junhost 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/jun.js +17 -0
- package/dist/index.js +38 -38
- package/dist/mcp-server.js +12 -12
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
2
|
+
var bO=Object.create;var{getPrototypeOf:qO,defineProperty:KH,getOwnPropertyNames:IO}=Object;var jO=Object.prototype.hasOwnProperty;function gO(N){return this[N]}var vO,hO,gY=(N,H,O)=>{var W=N!=null&&typeof N==="object";if(W){var Y=H?vO??=new WeakMap:hO??=new WeakMap,G=Y.get(N);if(G)return G}O=N!=null?bO(qO(N)):{};let $=H||!N||!N.__esModule?KH(O,"default",{value:N,enumerable:!0}):O;for(let U of IO(N))if(!jO.call($,U))KH($,U,{get:gO.bind(N,U),enumerable:!0});if(W)Y.set(N,$);return $};var vY=(N,H)=>()=>(H||N((H={exports:{}}).exports,H),H.exports);var mO=(N)=>N;function cO(N,H){this[N]=mO.bind(null,H)}var hY=(N,H)=>{for(var O in H)KH(N,O,{get:H[O],enumerable:!0,configurable:!0,set:cO.bind(H,O)})};import{existsSync as xO,watch as kY}from"fs";import{stat as kO}from"fs/promises";import k from"path";import{promises as a}from"fs";import u from"path";import{existsSync as sH,renameSync as lO}from"fs";import tH from"os";import S from"path";function y(N){return process.env[`JUN_${N}`]??process.env[`AGENTHOST_${N}`]}function uO(){let N=y("HOME");if(N)return N;let H=S.join(tH.homedir(),".jun"),O=S.join(tH.homedir(),".agenthost");if(!sH(H)&&sH(O))try{lO(O,H),console.log("[paths] migrated data dir ~/.agenthost -> ~/.jun")}catch(W){return console.warn("[paths] could not migrate ~/.agenthost -> ~/.jun (files in use?) \u2014 using legacy dir:",W),O}return H}var b=uO(),z="default",AH=y("HOST")??"127.0.0.1",lN=Number(y("PORT")??8787);function UN(){return S.join(b,"projects")}function r(N=z){return S.join(UN(),N)}function n(){return S.join(b,"runs")}function J(N=z){return S.join(r(N),"workspace")}function DN(){return S.join(b,"schedules")}function q(N=z){return S.join(r(N),"codex-home")}function rH(N=z){return S.join(r(N),"widgets")}function CN(N=z){return S.join(r(N),"browser")}function uN(N){let H=S.resolve(UN()),O=S.relative(H,S.resolve(N));if(!O||O.startsWith("..")||S.isAbsolute(O))return null;return O.split(S.sep)[0]||null}function l(N){return N.split(S.sep).join("/")}function JH(N){return u.join(r(N),"project.json")}var iO=["files","reports","downloads","screenshots","artifacts",".agents/skills"],pO=["profile","downloads","screenshots","recordings"],nO={projectId:z,defaultModel:"gpt-5.4",defaultSandbox:"workspaceWrite",defaultApprovalPolicy:"onRequest",host:"127.0.0.1",port:8787,browserProvider:"agent-browser"},aO={version:1,pages:[{id:"home",title:"Home",widgets:[]}]},oO='# Jun workspace\n\nYou are running inside JunHost \u2014 a self-hosted dashboard that supervises you.\nThis directory is your workspace; write outputs here.\n\n## Browsing the web \u2014 use the `agent-browser` CLI\n\nA shared, visible browser session is already running and wired to your\nenvironment. The user can watch it live and take manual control. Drive it ONLY\nthrough the `agent-browser` command-line tool. Do NOT connect to Chrome via\nraw CDP/DevTools, scrape the `/json` debugger endpoint, or open your own\nWebSocket \u2014 that bypasses the shared session the user is watching.\n\nCommon commands (the session is preconfigured \u2014 no flags needed):\n- `agent-browser open <url>` \u2014 navigate\n- `agent-browser snapshot -i` \u2014 accessibility tree with @refs (best for deciding what to click)\n- `agent-browser click @ref` \u2014 click an element from the snapshot\n- `agent-browser fill @ref "text"` \u2014 fill an input\n- `agent-browser get text @ref` \u2014 read text (use `get url`, `get title` for page info)\n- `agent-browser scroll down 800` \u2014 scroll\n- `agent-browser screenshot screenshots/<name>.png` \u2014 capture to the workspace\n- `agent-browser eval "<js>"` \u2014 run JS in the page when no command fits\n\nPrefer snapshot \u2192 ref-based actions over guessing selectors. Save screenshots\nand extracted notes under `reports/` and `screenshots/`.\n\n## Output locations\n- `reports/` \u2014 summaries and findings\n- `screenshots/` \u2014 captured images\n- `downloads/` \u2014 downloaded files\n',dO=`# Codex configuration for this Jun project.
|
|
3
3
|
# MCP servers are configured here, e.g.:
|
|
4
4
|
#
|
|
5
5
|
# [mcp_servers.context7]
|
|
6
6
|
# command = "npx"
|
|
7
7
|
# args = ["-y", "@upstash/context7-mcp"]
|
|
8
|
-
`;async function SN(N,H){try{await a.access(N)}catch{await a.mkdir(u.dirname(N),{recursive:!0}),await a.writeFile(N,H,"utf8")}}async function
|
|
9
|
-
`),await SN(u.join(r(N),"dashboard.json"),JSON.stringify(
|
|
10
|
-
`),await SN(u.join(q(N),"config.toml"),
|
|
11
|
-
`),await
|
|
8
|
+
`;async function SN(N,H){try{await a.access(N)}catch{await a.mkdir(u.dirname(N),{recursive:!0}),await a.writeFile(N,H,"utf8")}}async function BH(N,H){let O=J(N);for(let W of iO)await a.mkdir(u.join(O,W),{recursive:!0});for(let W of pO)await a.mkdir(u.join(CN(N),W),{recursive:!0});await a.mkdir(rH(N),{recursive:!0}),await a.mkdir(u.join(q(N),"logs"),{recursive:!0}),await SN(JH(N),JSON.stringify({id:N,name:H??N,createdAt:new Date().toISOString()},null,2)+`
|
|
9
|
+
`),await SN(u.join(r(N),"dashboard.json"),JSON.stringify(aO,null,2)+`
|
|
10
|
+
`),await SN(u.join(q(N),"config.toml"),dO),await SN(u.join(O,"AGENTS.md"),oO)}async function eH(){await a.mkdir(n(),{recursive:!0}),await SN(u.join(b,"config.json"),JSON.stringify(nO,null,2)+`
|
|
11
|
+
`),await BH(z,"Default")}import{promises as FN}from"fs";import pW from"path";/*!
|
|
12
12
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
13
13
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
14
14
|
*
|
|
@@ -34,9 +34,9 @@ var kO=Object.create;var{getPrototypeOf:yO,defineProperty:KH,getOwnPropertyNames
|
|
|
34
34
|
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
35
35
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
36
36
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
37
|
-
*/function
|
|
37
|
+
*/function sO(N,H){let O=N.slice(0,H).split(/\r\n|\n|\r/g);return[O.length,O.pop().length+1]}function tO(N,H,O){let W=N.split(/\r\n|\n|\r/g),Y="",G=(Math.log10(H+1)|0)+1;for(let $=H-1;$<=H+1;$++){let U=W[$-1];if(!U)continue;if(Y+=$.toString().padEnd(G," "),Y+=": ",Y+=U,Y+=`
|
|
38
38
|
`,$===H)Y+=" ".repeat(G+O+2),Y+=`^
|
|
39
|
-
`}return Y}class V extends Error{line;column;codeblock;constructor(N,H){let[O,W]=
|
|
39
|
+
`}return Y}class V extends Error{line;column;codeblock;constructor(N,H){let[O,W]=sO(H.toml,H.ptr),Y=tO(H.toml,O,W);super(`Invalid TOML document: ${N}
|
|
40
40
|
|
|
41
41
|
${Y}`,H);this.line=O,this.column=W,this.codeblock=Y}}/*!
|
|
42
42
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -64,14 +64,14 @@ ${Y}`,H);this.line=O,this.column=W,this.codeblock=Y}}/*!
|
|
|
64
64
|
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
65
65
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
66
66
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
67
|
-
*/function
|
|
67
|
+
*/function rO(N,H){let O=0;while(N[H-++O]==="\\");return--O&&O%2}function iN(N,H=0,O=N.length){let W=N.indexOf(`
|
|
68
68
|
`,H);if(N[W-1]==="\r")W--;return W<=O?W:-1}function QN(N,H){for(let O=H;O<N.length;O++){let W=N[O];if(W===`
|
|
69
69
|
`)return O;if(W==="\r"&&N[O+1]===`
|
|
70
70
|
`)return O+1;if(W<" "&&W!=="\t"||W==="\x7F")throw new V("control characters are not allowed in comments",{toml:N,ptr:H})}return N.length}function _(N,H,O,W){let Y;while(!0){while((Y=N[H])===" "||Y==="\t"||!O&&(Y===`
|
|
71
71
|
`||Y==="\r"&&N[H+1]===`
|
|
72
|
-
`))H++;if(W||Y!=="#")break;H=QN(N,H)}return H}function
|
|
72
|
+
`))H++;if(W||Y!=="#")break;H=QN(N,H)}return H}function N0(N,H,O,W,Y=!1){if(!W)return H=iN(N,H),H<0?N.length:H;for(let G=H;G<N.length;G++){let $=N[G];if($==="#")G=iN(N,G);else if($===O)return G+1;else if($===W||Y&&($===`
|
|
73
73
|
`||$==="\r"&&N[G+1]===`
|
|
74
|
-
`))return G}throw new V("cannot find end of structure",{toml:N,ptr:H})}function pN(N,H){let O=N[H],W=O===N[H+1]&&N[H+1]===N[H+2]?N.slice(H,H+3):O;H+=W.length-1;do H=N.indexOf(W,++H);while(H>-1&&O!=="'"&&
|
|
74
|
+
`))return G}throw new V("cannot find end of structure",{toml:N,ptr:H})}function pN(N,H){let O=N[H],W=O===N[H+1]&&N[H+1]===N[H+2]?N.slice(H,H+3):O;H+=W.length-1;do H=N.indexOf(W,++H);while(H>-1&&O!=="'"&&rO(N,H));if(H>-1){if(H+=W.length,W.length>1){if(N[H]===O)H++;if(N[H]===O)H++}}return H}/*!
|
|
75
75
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
76
76
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
77
77
|
*
|
|
@@ -97,7 +97,7 @@ ${Y}`,H);this.line=O,this.column=W,this.codeblock=Y}}/*!
|
|
|
97
97
|
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
98
98
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
99
99
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
100
|
-
*/var
|
|
100
|
+
*/var eO=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;class o extends Date{#H=!1;#O=!1;#N=null;constructor(N){let H=!0,O=!0,W="Z";if(typeof N==="string"){let Y=N.match(eO);if(Y){if(!Y[1])H=!1,N=`0000-01-01T${N}`;if(O=!!Y[2],O&&N[10]===" "&&(N=N.replace(" ","T")),Y[2]&&+Y[2]>23)N="";else if(W=Y[3]||null,N=N.toUpperCase(),!W&&O)N+="Z"}else N=""}super(N);if(!isNaN(this.getTime()))this.#H=H,this.#O=O,this.#N=W}isDateTime(){return this.#H&&this.#O}isLocal(){return!this.#H||!this.#O||!this.#N}isDate(){return this.#H&&!this.#O}isTime(){return this.#O&&!this.#H}isValid(){return this.#H||this.#O}toISOString(){let N=super.toISOString();if(this.isDate())return N.slice(0,10);if(this.isTime())return N.slice(11,23);if(this.#N===null)return N.slice(0,-1);if(this.#N==="Z")return N;let H=+this.#N.slice(1,3)*60+ +this.#N.slice(4,6);return H=this.#N[0]==="-"?H:-H,new Date(this.getTime()-H*60000).toISOString().slice(0,-1)+this.#N}static wrapAsOffsetDateTime(N,H="Z"){let O=new o(N);return O.#N=H,O}static wrapAsLocalDateTime(N){let H=new o(N);return H.#N=null,H}static wrapAsLocalDate(N){let H=new o(N);return H.#O=!1,H.#N=null,H}static wrapAsLocalTime(N){let H=new o(N);return H.#H=!1,H.#N=null,H}}/*!
|
|
101
101
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
102
102
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
103
103
|
*
|
|
@@ -123,13 +123,13 @@ ${Y}`,H);this.line=O,this.column=W,this.codeblock=Y}}/*!
|
|
|
123
123
|
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
124
124
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
125
125
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
126
|
-
*/var
|
|
126
|
+
*/var NW=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,HW=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,OW=/^[+-]?0[0-9_]/,WW=/^[0-9a-f]{2,8}$/i,H0={b:"\b",t:"\t",n:`
|
|
127
127
|
`,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function nN(N,H=0,O=N.length){let W=N[H]==="'",Y=N[H++]===N[H]&&N[H]===N[H+1];if(Y){if(O-=2,N[H+=2]==="\r")H++;if(N[H]===`
|
|
128
128
|
`)H++}let G=0,$,U="",Q=H;while(H<O-1){let X=N[H++];if(X===`
|
|
129
129
|
`||X==="\r"&&N[H]===`
|
|
130
|
-
`){if(!Y)throw new V("newlines are not allowed in strings",{toml:N,ptr:H-1})}else if(X<" "&&X!=="\t"||X==="\x7F")throw new V("control characters are not allowed in strings",{toml:N,ptr:H-1});if($){if($=!1,X==="x"||X==="u"||X==="U"){let F=N.slice(H,H+=X==="x"?2:X==="u"?4:8);if(!
|
|
130
|
+
`){if(!Y)throw new V("newlines are not allowed in strings",{toml:N,ptr:H-1})}else if(X<" "&&X!=="\t"||X==="\x7F")throw new V("control characters are not allowed in strings",{toml:N,ptr:H-1});if($){if($=!1,X==="x"||X==="u"||X==="U"){let F=N.slice(H,H+=X==="x"?2:X==="u"?4:8);if(!WW.test(F))throw new V("invalid unicode escape",{toml:N,ptr:G});try{U+=String.fromCodePoint(parseInt(F,16))}catch{throw new V("invalid unicode escape",{toml:N,ptr:G})}}else if(Y&&(X===`
|
|
131
131
|
`||X===" "||X==="\t"||X==="\r")){if(H=_(N,H-1,!0),N[H]!==`
|
|
132
|
-
`&&N[H]!=="\r")throw new V("invalid escape: only line-ending whitespace may be escaped",{toml:N,ptr:G});H=_(N,H)}else if(X in
|
|
132
|
+
`&&N[H]!=="\r")throw new V("invalid escape: only line-ending whitespace may be escaped",{toml:N,ptr:G});H=_(N,H)}else if(X in H0)U+=H0[X];else throw new V("unrecognized escape sequence",{toml:N,ptr:G});Q=H}else if(!W&&X==="\\")G=H-1,$=!0,U+=N.slice(Q,G)}return U+N.slice(Q,O-1)}function O0(N,H,O,W){if(N==="true")return!0;if(N==="false")return!1;if(N==="-inf")return-1/0;if(N==="inf"||N==="+inf")return 1/0;if(N==="nan"||N==="+nan"||N==="-nan")return NaN;if(N==="-0")return W?0n:0;let Y=NW.test(N);if(Y||HW.test(N)){if(OW.test(N))throw new V("leading zeroes are not allowed",{toml:H,ptr:O});N=N.replace(/_/g,"");let $=+N;if(isNaN($))throw new V("invalid number",{toml:H,ptr:O});if(Y){if((Y=!Number.isSafeInteger($))&&!W)throw new V("integer value cannot be represented losslessly",{toml:H,ptr:O});if(Y||W===!0)$=BigInt(N)}return $}let G=new o(N);if(!G.isValid())throw new V("invalid value",{toml:H,ptr:O});return G}/*!
|
|
133
133
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
134
134
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
135
135
|
*
|
|
@@ -155,8 +155,8 @@ ${Y}`,H);this.line=O,this.column=W,this.codeblock=Y}}/*!
|
|
|
155
155
|
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
156
156
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
157
157
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
158
|
-
*/function
|
|
159
|
-
`&&N[$]!=="\r")throw new V("unexpected character encountered",{toml:N,ptr:$});$+=+(N[$]===",")}return[Q,$]}$=
|
|
158
|
+
*/function YW(N,H,O){let W=N.slice(H,O),Y=W.indexOf("#");if(Y>-1)QN(N,Y),W=W.slice(0,Y);return[W.trimEnd(),Y]}function RN(N,H,O,W,Y){if(W===0)throw new V("document contains excessively nested structures. aborting.",{toml:N,ptr:H});let G=N[H];if(G==="["||G==="{"){let[Q,X]=G==="["?Y0(N,H,W,Y):W0(N,H,W,Y);if(O){if(X=_(N,X),N[X]===",")X++;else if(N[X]!==O)throw new V("expected comma or end of structure",{toml:N,ptr:X})}return[Q,X]}let $;if(G==='"'||G==="'"){$=pN(N,H);let Q=nN(N,H,$);if(O){if($=_(N,$),N[$]&&N[$]!==","&&N[$]!==O&&N[$]!==`
|
|
159
|
+
`&&N[$]!=="\r")throw new V("unexpected character encountered",{toml:N,ptr:$});$+=+(N[$]===",")}return[Q,$]}$=N0(N,H,",",O);let U=YW(N,H,$-+(N[$-1]===","));if(!U[0])throw new V("incomplete key-value declaration: no value specified",{toml:N,ptr:H});if(O&&U[1]>-1)$=_(N,H+U[1]),$+=+(N[$]===",");return[O0(U[0],N,H,Y),$]}/*!
|
|
160
160
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
161
161
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
162
162
|
*
|
|
@@ -182,8 +182,8 @@ ${Y}`,H);this.line=O,this.column=W,this.codeblock=Y}}/*!
|
|
|
182
182
|
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
183
183
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
184
184
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
185
|
-
*/var
|
|
186
|
-
`&&$!=="\r"){let U,Q=Y,X=!1,[F,
|
|
185
|
+
*/var GW=/^[a-zA-Z0-9-_]+[ \t]*$/;function aN(N,H,O="="){let W=H-1,Y=[],G=N.indexOf(O,H);if(G<0)throw new V("incomplete key-value: cannot find end of key",{toml:N,ptr:H});do{let $=N[H=++W];if($!==" "&&$!=="\t")if($==='"'||$==="'"){if($===N[H+1]&&$===N[H+2])throw new V("multiline strings are not allowed in keys",{toml:N,ptr:H});let U=pN(N,H);if(U<0)throw new V("unfinished string encountered",{toml:N,ptr:H});W=N.indexOf(".",U);let Q=N.slice(U,W<0||W>G?G:W),X=iN(Q);if(X>-1)throw new V("newlines are not allowed in keys",{toml:N,ptr:H+W+X});if(Q.trimStart())throw new V("found extra tokens after the string part",{toml:N,ptr:U});if(G<U){if(G=N.indexOf(O,U),G<0)throw new V("incomplete key-value: cannot find end of key",{toml:N,ptr:H})}Y.push(nN(N,H,U))}else{W=N.indexOf(".",H);let U=N.slice(H,W<0||W>G?G:W);if(!GW.test(U))throw new V("only letter, numbers, dashes and underscores are allowed in keys",{toml:N,ptr:H});Y.push(U.trimEnd())}}while(W+1&&W<G);return[Y,_(N,G+1,!0,!0)]}function W0(N,H,O,W){let Y={},G=new Set,$;H++;while(($=N[H++])!=="}"&&$)if($===",")throw new V("expected value, found comma",{toml:N,ptr:H-1});else if($==="#")H=QN(N,H);else if($!==" "&&$!=="\t"&&$!==`
|
|
186
|
+
`&&$!=="\r"){let U,Q=Y,X=!1,[F,K]=aN(N,H-1);for(let $N=0;$N<F.length;$N++){if($N)Q=X?Q[U]:Q[U]={};if(U=F[$N],(X=Object.hasOwn(Q,U))&&(typeof Q[U]!=="object"||G.has(Q[U])))throw new V("trying to redefine an already defined value",{toml:N,ptr:H});if(!X&&U==="__proto__")Object.defineProperty(Q,U,{enumerable:!0,configurable:!0,writable:!0})}if(X)throw new V("trying to redefine an already defined value",{toml:N,ptr:H});let[R,f]=RN(N,K,"}",O-1,W);G.add(R),Q[U]=R,H=f}if(!$)throw new V("unfinished table encountered",{toml:N,ptr:H});return[Y,H]}function Y0(N,H,O,W){let Y=[],G;H++;while((G=N[H++])!=="]"&&G)if(G===",")throw new V("expected value, found comma",{toml:N,ptr:H-1});else if(G==="#")H=QN(N,H);else if(G!==" "&&G!=="\t"&&G!==`
|
|
187
187
|
`&&G!=="\r"){let $=RN(N,H-1,"]",O-1,W);Y.push($[0]),H=$[1]}if(!G)throw new V("unfinished array encountered",{toml:N,ptr:H});return[Y,H]}/*!
|
|
188
188
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
189
189
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -210,7 +210,7 @@ ${Y}`,H);this.line=O,this.column=W,this.codeblock=Y}}/*!
|
|
|
210
210
|
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
211
211
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
212
212
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
213
|
-
*/function
|
|
213
|
+
*/function G0(N,H,O,W){let Y=H,G=O,$,U=!1,Q;for(let X=0;X<N.length;X++){if(X){if(Y=U?Y[$]:Y[$]={},G=(Q=G[$]).c,W===0&&(Q.t===1||Q.t===2))return null;if(Q.t===2){let F=Y.length-1;Y=Y[F],G=G[F].c}}if($=N[X],(U=Object.hasOwn(Y,$))&&G[$]?.t===0&&G[$]?.d)return null;if(!U){if($==="__proto__")Object.defineProperty(Y,$,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(G,$,{enumerable:!0,configurable:!0,writable:!0});G[$]={t:X<N.length-1&&W===2?3:W,d:!1,i:0,c:{}}}}if(Q=G[$],Q.t!==W&&!(W===1&&Q.t===3))return null;if(W===2){if(!Q.d)Q.d=!0,Y[$]=[];Y[$].push(Y={}),Q.c[Q.i++]=Q={t:1,d:!1,i:0,c:{}}}if(Q.d)return null;if(Q.d=!0,W===1)Y=U?Y[$]:Y[$]={};else if(W===0&&U)return null;return[$,Y,Q.c]}function c(N,{maxDepth:H=1000,integersAsBigInt:O}={}){let W={},Y={},G=W,$=Y;for(let U=_(N,0);U<N.length;){if(N[U]==="["){let Q=N[++U]==="[",X=aN(N,U+=+Q,"]");if(Q){if(N[X[1]-1]!=="]")throw new V("expected end of table declaration",{toml:N,ptr:X[1]-1});X[1]++}let F=G0(X[0],W,Y,Q?2:1);if(!F)throw new V("trying to redefine an already defined table or value",{toml:N,ptr:U});$=F[2],G=F[1],U=X[1]}else{let Q=aN(N,U),X=G0(Q[0],G,$,0);if(!X)throw new V("trying to redefine an already defined table or value",{toml:N,ptr:U});let F=RN(N,Q[1],void 0,H,O);X[1][X[0]]=F[0],U=F[1]}if(U=_(N,U,!0),N[U]&&N[U]!==`
|
|
214
214
|
`&&N[U]!=="\r")throw new V("each key-value declaration must be followed by an end-of-line",{toml:N,ptr:U});U=_(N,U)}return W}/*!
|
|
215
215
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
216
216
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -237,14 +237,14 @@ ${Y}`,H);this.line=O,this.column=W,this.codeblock=Y}}/*!
|
|
|
237
237
|
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
238
238
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
239
239
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
240
|
-
*/var
|
|
240
|
+
*/var $0=/^[a-z0-9-_]+$/i;function TN(N){let H=typeof N;if(H==="object"){if(Array.isArray(N))return"array";if(N instanceof Date)return"date"}return H}function $W(N){for(let H=0;H<N.length;H++)if(TN(N[H])!=="object")return!1;return N.length!=0}function DH(N){return JSON.stringify(N).replace(/\x7f/g,"\\u007f")}function CH(N,H,O,W){if(O===0)throw Error("Could not stringify the object: maximum object depth exceeded");if(H==="number"){if(isNaN(N))return"nan";if(N===1/0)return"inf";if(N===-1/0)return"-inf";if(W&&Number.isInteger(N))return N.toFixed(1);return N.toString()}if(H==="bigint"||H==="boolean")return N.toString();if(H==="string")return DH(N);if(H==="date"){if(isNaN(N.getTime()))throw TypeError("cannot serialize invalid date");return N.toISOString()}if(H==="object")return UW(N,O,W);if(H==="array")return QW(N,O,W)}function UW(N,H,O){let W=Object.keys(N);if(W.length===0)return"{}";let Y="{ ";for(let G=0;G<W.length;G++){let $=W[G];if(G)Y+=", ";Y+=$0.test($)?$:DH($),Y+=" = ",Y+=CH(N[$],TN(N[$]),H-1,O)}return Y+" }"}function QW(N,H,O){if(N.length===0)return"[]";let W="[ ";for(let Y=0;Y<N.length;Y++){if(Y)W+=", ";if(N[Y]===null||N[Y]===void 0)throw TypeError("arrays cannot contain null or undefined values");W+=CH(N[Y],TN(N[Y]),H-1,O)}return W+" ]"}function XW(N,H,O,W){if(O===0)throw Error("Could not stringify the object: maximum object depth exceeded");let Y="";for(let G=0;G<N.length;G++)Y+=`${Y&&`
|
|
241
241
|
`}[[${H}]]
|
|
242
|
-
`,Y+=
|
|
243
|
-
`)+
|
|
244
|
-
`)+
|
|
242
|
+
`,Y+=SH(0,N[G],H,O,W);return Y}function SH(N,H,O,W,Y){if(W===0)throw Error("Could not stringify the object: maximum object depth exceeded");let G="",$="",U=Object.keys(H);for(let Q=0;Q<U.length;Q++){let X=U[Q];if(H[X]!==null&&H[X]!==void 0){let F=TN(H[X]);if(F==="symbol"||F==="function")throw TypeError(`cannot serialize values of type '${F}'`);let K=$0.test(X)?X:DH(X);if(F==="array"&&$W(H[X]))$+=($&&`
|
|
243
|
+
`)+XW(H[X],O?`${O}.${K}`:K,W-1,Y);else if(F==="object"){let R=O?`${O}.${K}`:K;$+=($&&`
|
|
244
|
+
`)+SH(R,H[X],R,W-1,Y)}else G+=K,G+=" = ",G+=CH(H[X],F,W,Y),G+=`
|
|
245
245
|
`}}if(N&&(G||!$))G=G?`[${N}]
|
|
246
246
|
${G}`:`[${N}]`;return G&&$?`${G}
|
|
247
|
-
${$}`:G||$}function d(N,{maxDepth:H=1000,numbersAsFloat:O=!1}={}){if(TN(N)!=="object")throw TypeError("stringify can only be called with an object");let W=
|
|
247
|
+
${$}`:G||$}function d(N,{maxDepth:H=1000,numbersAsFloat:O=!1}={}){if(TN(N)!=="object")throw TypeError("stringify can only be called with an object");let W=SH(0,N,"",H,O);if(W[W.length-1]!==`
|
|
248
248
|
`)return W+`
|
|
249
249
|
`;return W}/*!
|
|
250
250
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -272,13 +272,13 @@ ${$}`:G||$}function d(N,{maxDepth:H=1000,numbersAsFloat:O=!1}={}){if(TN(N)!=="ob
|
|
|
272
272
|
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
273
273
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
274
274
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
275
|
-
*/function L(N,H=200){return new Response(JSON.stringify(N),{status:H,headers:{"content-type":"application/json"}})}function Z(N,H,O){return L({error:H,detail:O},N)}async function
|
|
276
|
-
`,"utf8")}async function
|
|
277
|
-
`,"utf8")}var
|
|
278
|
-
`);if(W.length>0&&W[W.length-1]==="")W.pop();let Y=W.length,G=Math.max(0,Math.min(H.before??Y,Y)),$=H.limit===void 0?0:Math.max(0,G-H.limit);if($>0){for(let Q=$;Q>=Math.max(0,$-
|
|
279
|
-
`,"utf8"),
|
|
280
|
-
`))!==-1){let G=H.slice(0,Y).replace(/\r$/,"");if(H=H.slice(Y+1),G.trim().length>0)N(G)}},flush(){let W=H.trim();if(H="",W.length>0)N(W)}}}class
|
|
281
|
-
`),O.stdin.flush()},{onNotification:(Y,G)=>this.handlers.onNotification(Y,G),onServerRequest:(Y,G,$)=>this.handlers.onServerRequest(Y,G,$)});let W=this.rpc;(async()=>{let Y=
|
|
275
|
+
*/function L(N,H=200){return new Response(JSON.stringify(N),{status:H,headers:{"content-type":"application/json"}})}function Z(N,H,O){return L({error:H,detail:O},N)}async function M(N){try{return await N.json()}catch{throw new B("Invalid JSON body")}}function A(N,H){if(typeof N!=="string"||N.length===0)throw new B(`Missing or invalid field: ${H}`);return N}class B extends Error{constructor(N){super(N);this.name="BadRequestError"}}import{promises as j}from"fs";import I from"path";import RH from"path";function e(N,H){let O=RH.resolve(N),W=RH.resolve(O,H||".");if(W!==O&&!W.startsWith(O+RH.sep))throw new oN(H);return W}class oN extends Error{constructor(N){super(`Path escapes workspace: ${N}`);this.name="PathEscapeError"}}var ZW=2097152,LW=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".bmp",".ico",".avif"]),FW=new Set([".zip",".tar",".gz",".7z",".exe",".dll",".so",".dylib",".pdf",".woff",".woff2",".ttf",".mp3",".mp4",".mov",".webm",".sqlite",".db",".bin"]);function zW(N){let H=I.extname(N).toLowerCase();if(H===".md"||H===".markdown")return"markdown";if(H===".json"||H===".jsonl")return"json";if(LW.has(H))return"image";if(FW.has(H))return"binary";return"text"}function s(N,H){return e(J(H),N)}function TH(N,H){let O=I.relative(J(H),N);return O===""?".":l(O)}async function U0(N,H){let O=await j.stat(N),W={name:I.basename(N)||".",path:TH(N,H),type:O.isDirectory()?"dir":"file",modifiedAt:O.mtime.toISOString()};if(W.type==="file")return W.size=O.size,W;let Y=await j.readdir(N,{withFileTypes:!0}),G=await Promise.all(Y.map(($)=>U0(I.join(N,$.name),H)));return G.sort(($,U)=>$.type!==U.type?$.type==="dir"?-1:1:$.name.localeCompare(U.name)),W.children=G,W}async function Q0(N=".",H=z){return U0(s(N,H),H)}async function X0(N,H=z){let O=s(N,H),W=await j.stat(O);if(W.isDirectory())throw Error(`Not a file: ${N}`);let Y=zW(O),G={path:TH(O,H),kind:Y,size:W.size,modifiedAt:W.mtime.toISOString()};if(Y==="image"||Y==="binary")return G;if(W.size>ZW)throw Error(`File too large to open (${W.size} bytes): ${N}`);return G.content=await j.readFile(O,"utf8"),G}async function Z0(N,H,O=z){let W=s(N,O);await j.mkdir(I.dirname(W),{recursive:!0}),await j.writeFile(W,H,"utf8")}async function L0(N,H=z){await j.mkdir(s(N,H),{recursive:!0})}async function F0(N,H=z){let O=s(N,H);if(O===I.resolve(J(H)))throw Error("Cannot delete the workspace root");await j.rm(O,{recursive:!0,force:!0})}async function z0(N,H,O=z){let W=s(N,O),Y=s(H,O);if(W===I.resolve(J(O)))throw Error("Cannot rename the workspace root");await j.mkdir(I.dirname(Y),{recursive:!0}),await j.rename(W,Y)}async function V0(N,H,O,W=z){let Y=I.basename(H);if(!Y||Y==="."||Y==="..")throw Error(`Invalid file name: ${H}`);let G=e(J(W),I.join(N||".",Y));return await j.mkdir(I.dirname(G),{recursive:!0}),await Bun.write(G,O),TH(G,W)}function dN(N,H=z){return s(N,H)}import{randomBytes as VW}from"crypto";function sN(N){return`${N}_${VW(6).toString("hex")}`}var EH=null;function K0(N){EH=N}function i(N,H){EH?.publish(N,JSON.stringify(H))}function A0(N,H){EH?.publish(N,H)}import{promises as EN}from"fs";import MW from"os";import _H from"path";var t=new Map,J0=!1;function wH(N){return _H.join(n(),N,"meta.json")}var B0=_H.join(MW.homedir(),".agenthost");function D0(N){let H=JSON.parse(N);if(H.cwd?.startsWith(B0))H.cwd=b+H.cwd.slice(B0.length);return H}async function C0(N){await EN.mkdir(_H.join(n(),N.id),{recursive:!0}),await EN.writeFile(wH(N.id),JSON.stringify(N,null,2)+`
|
|
276
|
+
`,"utf8")}async function KW(){if(J0)return;J0=!0;let N;try{N=await EN.readdir(n())}catch{return}for(let H of N){if(t.has(H))continue;try{let O=await EN.readFile(wH(H),"utf8"),W=D0(O);t.set(W.id,W)}catch{}}}async function S0(N){let H={id:sN("run"),projectId:N.projectId??z,prompt:N.prompt,status:"starting",startedAt:new Date().toISOString(),cwd:N.cwd,sandbox:N.sandbox,approvalPolicy:N.approvalPolicy,approvalsReviewer:N.approvalsReviewer,model:N.model,effort:N.effort,source:N.source,scheduleId:N.scheduleId,scheduleName:N.scheduleName};return t.set(H.id,H),await C0(H),H}async function NN(N,H){let O=await D(N);if(!O)return null;let W={...O,...H};return t.set(N,W),await C0(W),W}async function D(N){if(t.has(N))return t.get(N);try{let H=await EN.readFile(wH(N),"utf8"),O=D0(H);return t.set(N,O),O}catch{return null}}async function R0(N){await KW();let H=[...t.values()];return(N?H.filter((W)=>W.projectId===N):H).sort((W,Y)=>Y.startedAt.localeCompare(W.startedAt))}function g(N){return N==="queued"||N==="starting"||N==="running"||N==="waiting_approval"}import{promises as T0}from"fs";import AW from"path";function E0(N){return AW.join(n(),N,"events.jsonl")}async function _0(N){await T0.appendFile(E0(N.runId),JSON.stringify(N)+`
|
|
277
|
+
`,"utf8")}var JW=/"type":\s*"run\.(started|resumed|steered)"/,BW=400;async function w0(N,H={}){let O;try{O=await T0.readFile(E0(N),"utf8")}catch{return{events:[],offset:0,total:0}}let W=O.split(`
|
|
278
|
+
`);if(W.length>0&&W[W.length-1]==="")W.pop();let Y=W.length,G=Math.max(0,Math.min(H.before??Y,Y)),$=H.limit===void 0?0:Math.max(0,G-H.limit);if($>0){for(let Q=$;Q>=Math.max(0,$-BW);Q--)if(JW.test(W[Q])){$=Q;break}}let U=[];for(let Q=$;Q<G;Q++){let X=W[Q].trim();if(!X)continue;try{U.push(JSON.parse(X))}catch{}}return{events:U,offset:$,total:Y}}import{promises as O1}from"fs";import IW from"os";import W1 from"path";var f0={name:"junhost",version:"0.1.1",description:"Jun \u2014 a self-hosted dashboard that runs and supervises Codex as a 24/7 local/VPS agent: chat runs, workspace files, remote browser, skills, MCP, schedules.",type:"module",bin:{jun:"bin/jun.js"},files:["bin","dist","ui-dist","README.md"],engines:{bun:">=1.2.0"},keywords:["codex","agent","ai","dashboard","self-hosted","browser-automation","mcp"],license:"UNLICENSED",scripts:{dev:"bun --hot src/index.ts",start:"bun src/index.ts",build:"bun build src/index.ts src/mcp-server.ts --target=bun --minify --outdir=dist",typecheck:"bunx tsc --noEmit"},dependencies:{"agent-browser":"^0.27.1",cloakbrowser:"^0.3.31"},devDependencies:{"@junhost/shared":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@types/bun":"^1.2.0","smol-toml":"^1.6.1",typescript:"^5.6.3",zod:"3"}};var tN=f0.version;import TW from"os";import w from"path";import{existsSync as PN,readdirSync as EW}from"fs";import{mkdir as v0}from"fs/promises";import{randomUUID as _W}from"crypto";import{readFileSync as CW}from"fs";import{promises as SW}from"fs";import RW from"path";var x0=["browserProxy","browserNoProxy"];function k0(){return RW.join(b,"config.json")}var rN=null;function eN(){if(rN)return rN;let N={};try{N=JSON.parse(CW(k0(),"utf8"))}catch{}let H={};for(let O of x0){let W=N[O];if(typeof W==="string"&&W.length>0)H[O]=W}return rN=H,H}async function y0(N){let H={...eN()};for(let O of x0){if(!(O in N))continue;let W=N[O];if(typeof W==="string"&&W.trim().length>0)H[O]=W.trim();else delete H[O]}return await SW.writeFile(k0(),JSON.stringify(H,null,2)+`
|
|
279
|
+
`,"utf8"),rN=H,H}var wW="jun",b0=200,h0=process.platform==="win32"?"agent-browser.exe":"agent-browser";function m0(){let N=import.meta.dir;for(let H=0;H<8;H++){let O=w.join(N,"node_modules",".bin");if(PN(w.join(O,h0)))return O;let W=w.dirname(N);if(W===N)break;N=W}return null}function PW(N){let H=m0();if(H)return[w.join(H,h0),...N];return process.platform==="win32"?["cmd","/c","agent-browser",...N]:["agent-browser",...N]}var q0=Object.keys(process.env).find((N)=>N.toUpperCase()==="PATH")??"PATH",OH="agent",HH=null,NH=[];function c0(){let N=y("CLOAK_PATH");if(N&&PN(N))return N;let H=w.join(TW.homedir(),".cloakbrowser"),O;try{O=EW(H).filter((Y)=>Y.startsWith("chromium-"))}catch{return null}O.sort().reverse();let W=process.platform==="win32"?"chrome.exe":"chrome";for(let Y of O){let G=w.join(H,Y,W);if(PN(G))return G}return null}function fW(){let N=y("CHROME_PATH");if(N&&PN(N))return N;return(process.platform==="win32"?[`${process.env.ProgramFiles}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env["ProgramFiles(x86)"]}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env.LocalAppData}\\Google\\Chrome\\Application\\chrome.exe`]:process.platform==="darwin"?["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"]:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome"]).find((O)=>O&&PN(O))??null}function xH(){let N={AGENT_BROWSER_SESSION:wW,AGENT_BROWSER_PROFILE:w.join(CN(),"profile"),AGENT_BROWSER_DOWNLOAD_PATH:w.join(J(),"downloads"),AGENT_BROWSER_SCREENSHOT_DIR:w.join(J(),"screenshots"),AGENT_BROWSER_ARGS:"--disable-blink-features=AutomationControlled"},H=m0();if(H)N[q0]=`${H}${w.delimiter}${process.env[q0]??""}`;let O=c0();if(O)return N.AGENT_BROWSER_EXECUTABLE_PATH=O,N;let W=fW(),Y=process.platform!=="linux"||Boolean(process.env.DISPLAY),G=y("BROWSER_HEADED")!=="false"&&Y;if(process.platform==="linux"&&!process.env.DISPLAY&&y("BROWSER_HEADED")!=="false")console.warn("[browser] No cloakbrowser engine and no DISPLAY \u2014 running HEADLESS. Edge "+"WAFs (Reddit/Fastly) will block headless. Install cloakbrowser (works headless) or set up Xvfb + Google Chrome with DISPLAY for a VPS.");if(W&&G)N.AGENT_BROWSER_EXECUTABLE_PATH=W,N.AGENT_BROWSER_HEADED="true";else{if(W)N.AGENT_BROWSER_EXECUTABLE_PATH=W;N.AGENT_BROWSER_USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36"}return N}function xW(){return{...process.env,...xH()}}function kW(){let N=kH().value;if(!N)return[];let H=["--proxy",N],O=yH().value;if(O)H.push("--proxy-bypass",O);return H}function kH(){let N=eN().browserProxy;if(N)return{value:N,source:"settings"};let H=y("BROWSER_PROXY")?.trim();if(H)return{value:H,source:"env"};return{value:null,source:"none"}}function yH(){let N=eN().browserNoProxy;if(N)return{value:N,source:"settings"};let H=y("BROWSER_NO_PROXY")?.trim();if(H)return{value:H,source:"env"};return{value:null,source:"none"}}var fH=!1;function l0(N){if(fH)return;if(y("NO_CLOAK_DOWNLOAD")==="true")return;if(c0())return;fH=!0,console.log("[browser] cloakbrowser Stealth Chromium not found \u2014 downloading in background\u2026"),Bun.spawn([process.execPath,"x","cloakbrowser","install"],{cwd:N,stdout:"inherit",stderr:"inherit"}).exited.then((O)=>{if(fH=!1,O===0)console.log("[browser] cloakbrowser Stealth Chromium ready.");else console.warn(`[browser] cloakbrowser download exited with code ${O}.`)})}async function I0(N,H,O){if(!N)return"";let W=N.getReader(),Y=new TextDecoder,G="",$=Date.now()+O;try{while(Date.now()<$){let U=Math.min(H,$-Date.now()),Q=await Promise.race([W.read(),new Promise((X)=>setTimeout(()=>X("timeout"),U))]);if(Q==="timeout"||Q.done)break;G+=Y.decode(Q.value,{stream:!0})}}finally{W.releaseLock()}return G}async function v(N,H={}){let O=[...kW(),...N],W=H.json?[...O,"--json"]:O,Y=Bun.spawn(PW(W),{env:xW(),stdout:"pipe",stderr:"pipe"}),G=setTimeout(()=>Y.kill(),H.timeoutMs??120000),$=await Y.exited;clearTimeout(G);let[U,Q]=await Promise.all([I0(Y.stdout,80,1500),I0(Y.stderr,60,300)]),X,F;if(H.json)try{let K=JSON.parse(U);if(X=K.data??K,K.success===!1)F=typeof K.error==="string"?K.error:"command failed"}catch{}return{ok:$===0&&!F,stdout:U,stderr:Q,data:X,error:F}}function XN(N,H){if(NH.unshift({id:_W(),ts:new Date().toISOString(),kind:N,detail:H}),NH.length>b0)NH.length=b0}function u0(){return NH}function i0(){return OH}function p0(N){OH=N,XN("control",N)}function n0(){return HH}var a0=(N)=>typeof N==="object"&&N!==null?N:{};function j0(N){if(typeof N==="string")return N;let H=a0(N);for(let O of["url","title","value","text","result"])if(typeof H[O]==="string")return H[O];return null}var yW=2500,wN=null,_N=null;function HN(){wN=null}async function fN(){if(wN&&Date.now()-wN.at<yW)return{...wN.status,controller:OH};if(_N)return _N;return _N=bW().then((N)=>{return wN={at:Date.now(),status:N},N}).finally(()=>{_N=null}),_N}async function bW(){let N=await v(["stream","status"],{json:!0,timeoutMs:30000}),H=a0(N.data),O=N.ok&&H.connected===!0,W=O&&H.enabled===!0;HH=W&&typeof H.port==="number"?H.port:null;let Y=null,G=null;if(O){let[$,U]=await Promise.all([v(["get","url"],{json:!0,timeoutMs:30000}),v(["get","title"],{json:!0,timeoutMs:30000})]);Y=$.ok?j0($.data):null,G=U.ok?j0(U.data):null}return{running:O,streaming:W,streamPort:HH,url:Y,title:G,controller:OH}}var g0={width:1280,height:720};async function bH(){await v(["set","viewport",String(g0.width),String(g0.height)],{timeoutMs:30000})}async function o0(){await Promise.all(["screenshots","downloads","reports"].map((N)=>v0(w.join(J(),N),{recursive:!0})))}async function d0(N){await o0(),await v0(w.join(CN(),"profile"),{recursive:!0});let H=await v(["open",N??"about:blank"],{timeoutMs:180000});if(!H.ok)throw Error(`agent-browser open failed: ${H.stderr||H.stdout}`);return await bH(),await v(["stream","enable"],{json:!0,timeoutMs:30000}),XN("start",N??"about:blank"),HN(),fN()}async function s0(){await v(["close"],{timeoutMs:30000}),HH=null,HN(),XN("stop")}async function t0(N){let H=await v(["open",N],{timeoutMs:120000});if(!H.ok)throw Error(`Navigation failed: ${H.stderr||H.stdout}`);await bH(),HN(),XN("navigate",N)}async function r0(N){let H=await v([N],{timeoutMs:60000});if(!H.ok)throw Error(`${N} failed: ${H.stderr||H.stdout}`);await bH(),HN(),XN(N)}async function e0(N){let H=await v(["press",N],{timeoutMs:30000});if(!H.ok)throw Error(`Key press failed: ${H.stderr||H.stdout}`);HN()}async function N1(){await o0();let N=`browser-${new Date().toISOString().replace(/[:.]/g,"-")}.png`,H=w.join(J(),"screenshots",N),O=await v(["screenshot",H],{timeoutMs:60000});if(!O.ok)throw Error(`Screenshot failed: ${O.stderr||O.stdout}`);return XN("screenshot",`screenshots/${N}`),`screenshots/${N}`}class qH{send;handlers;nextId=1;pending=new Map;constructor(N,H){this.send=N;this.handlers=H}request(N,H){let O=this.nextId++,W=new Promise((Y,G)=>{this.pending.set(O,{method:N,resolve:Y,reject:G})});return this.send(JSON.stringify({jsonrpc:"2.0",id:O,method:N,params:H})),W}notify(N,H){this.send(JSON.stringify({jsonrpc:"2.0",method:N,params:H}))}respond(N,H){this.send(JSON.stringify({jsonrpc:"2.0",id:N,result:H}))}respondError(N,H,O){this.send(JSON.stringify({jsonrpc:"2.0",id:N,error:{code:H,message:O}}))}handleLine(N){let H;try{H=JSON.parse(N)}catch{console.warn("[codex] non-JSON line on stdout:",N.slice(0,200));return}if(H.method!==void 0){if(H.id!==void 0)this.handlers.onServerRequest(H.id,H.method,H.params);else this.handlers.onNotification(H.method,H.params);return}if(H.id===void 0)return;let O=this.pending.get(Number(H.id));if(!O)return;if(this.pending.delete(Number(H.id)),H.error)O.reject(Error(`${O.method} failed: ${H.error.message} (${H.error.code})`));else O.resolve(H.result)}failAll(N){for(let H of this.pending.values())H.reject(Error(`${H.method} failed: ${N}`));this.pending.clear()}}function H1(N){let H="",O=new TextDecoder;return{push(W){H+=O.decode(W,{stream:!0});let Y;while((Y=H.indexOf(`
|
|
280
|
+
`))!==-1){let G=H.slice(0,Y).replace(/\r$/,"");if(H=H.slice(Y+1),G.trim().length>0)N(G)}},flush(){let W=H.trim();if(H="",W.length>0)N(W)}}}class IH{handlers;proc=null;rpc=null;initialized=!1;constructor(N){this.handlers=N}get running(){return this.proc!==null}async start(){if(this.proc)return;await jW();let N=Bun.which("codex");if(!N)throw Error("codex binary not found in PATH. Install Codex CLI first.");let H=/\.(cmd|bat)$/i.test(N)?["cmd","/c",N,"app-server"]:[N,"app-server"],O=Bun.spawn(H,{cwd:J(),env:{...process.env,CODEX_HOME:q(),...xH()},stdin:"pipe",stdout:"pipe",stderr:"pipe",onExit:(Y,G)=>{console.log(`[codex] app-server exited (code ${G})`),this.rpc?.failAll(`codex app-server exited (code ${G})`),this.proc=null,this.rpc=null,this.initialized=!1,this.handlers.onExit(G)}});this.proc=O,this.rpc=new qH((Y)=>{O.stdin.write(Y+`
|
|
281
|
+
`),O.stdin.flush()},{onNotification:(Y,G)=>this.handlers.onNotification(Y,G),onServerRequest:(Y,G,$)=>this.handlers.onServerRequest(Y,G,$)});let W=this.rpc;(async()=>{let Y=H1((G)=>W.handleLine(G));for await(let G of O.stdout)Y.push(G);Y.flush()})(),(async()=>{let Y=new TextDecoder;for await(let G of O.stderr){let $=Y.decode(G).trimEnd();if($)console.error("[codex:stderr]",$)}})()}async initializeOnce(){if(this.initialized)return;await this.requireRpc().request("initialize",{clientInfo:{name:"jun",title:"Jun",version:tN},capabilities:{experimentalApi:!0}}),this.requireRpc().notify("initialized",{}),this.initialized=!0}request(N,H){return this.requireRpc().request(N,H)}respond(N,H){this.requireRpc().respond(N,H)}respondError(N,H,O){this.requireRpc().respondError(N,H,O)}requireRpc(){if(!this.rpc)throw Error("codex app-server is not running");return this.rpc}}async function jW(){let N=W1.join(q(),"auth.json");try{await O1.access(N);return}catch{}let H=W1.join(IW.homedir(),".codex","auth.json");try{await O1.copyFile(H,N),console.log("[codex] copied auth.json from ~/.codex into project codex-home")}catch{console.warn("[codex] no auth.json found in ~/.codex \u2014 runs may fail until `codex login` is run")}}var xN=null,WH=null;function YH(){return xN}function Y1(){return WH}function G1(N){if(xN=N,N)WH=null}function GH(){xN=null,WH=null}function $1(N){let H=N??{};if(WH={success:H.success===!0,error:H.error??null,at:new Date().toISOString()},!H.loginId||xN?.loginId===H.loginId)xN=null}var gW={"thread/started":"codex.thread.started","turn/started":"codex.turn.started","turn/completed":"codex.turn.completed","item/started":"codex.item.started","item/completed":"codex.item.completed","item/agentMessage/delta":"codex.message.delta","item/reasoning/textDelta":"codex.reasoning.delta","item/reasoning/summaryTextDelta":"codex.reasoning.summary.delta","item/commandExecution/outputDelta":"codex.command.output","item/fileChange/patchUpdated":"codex.file_change.patch",error:"codex.error"},vW={"item/commandExecution/requestApproval":"codex.approval.command","item/fileChange/requestApproval":"codex.approval.file_change","item/permissions/requestApproval":"codex.approval.permissions","item/tool/requestUserInput":"codex.approval.user_input","mcpServer/elicitation/request":"codex.approval.elicitation"};function U1(N){return gW[N]??`codex.${N.split("/").join(".")}`}function Q1(N){return vW[N]??null}function X1(N){return N==="item/commandExecution/requestApproval"||N==="item/fileChange/requestApproval"||N==="item/permissions/requestApproval"}function kN(N){if(typeof N!=="object"||N===null)return null;let H=N;if(typeof H.threadId==="string")return H.threadId;let O=H.thread;if(typeof O==="object"&&O!==null){let W=O.id;if(typeof W==="string")return W}return null}var Z1={readOnly:"read-only",workspaceWrite:"workspace-write",dangerFullAccess:"danger-full-access"},L1={readOnly:{type:"readOnly"},workspaceWrite:{type:"workspaceWrite"},dangerFullAccess:{type:"dangerFullAccess"}},jH={never:"never",onRequest:"on-request",onFailure:"on-failure",untrusted:"untrusted"},$H=`# Who you are
|
|
282
282
|
|
|
283
283
|
You are Jun. That's your name, use it if anyone asks. You live inside JunHost,
|
|
284
284
|
your own self-hosted dashboard that runs you as a long-running local/VPS assistant, and
|
|
@@ -319,20 +319,20 @@ model powers you; you're just Jun.
|
|
|
319
319
|
- Report outcomes honestly. If something failed, say so plainly with the actual
|
|
320
320
|
error; don't dress up a partial result as done.
|
|
321
321
|
- Per-workspace guidance lives in each workspace's AGENTS.md and takes
|
|
322
|
-
precedence over this general guidance when they differ.`,ON=new Map,WN=new Map,yN=new Map,
|
|
322
|
+
precedence over this general guidance when they differ.`,ON=new Map,WN=new Map,yN=new Map,F1=new Set,bN=new Map,ZN=new Map,gH="__default__";function hW(N){let H=N.error?.message;return typeof H==="string"&&H.includes("unsupported_parameter")&&H.includes("reasoning.summary")}async function z1(N,H,O){if(F1.has(H))O.summary="none";bN.set(N,O),await h().request("turn/start",O)}var IN=new Map,qN=null;function h(){if(!qN)qN=new IH({onNotification:mW,onServerRequest:cW,onExit:lW});return qN}async function T(N,H,O,W){let Y={id:sN("evt"),runId:N,ts:new Date().toISOString(),source:H,type:O,payload:W};return await _0(Y),i(`run:${N}`,Y),i("runs",{type:"run.event",runId:N,eventType:O}),Y}async function x(N,H){let O={status:H};if(H==="completed"||H==="failed"||H==="stopped")O.completedAt=new Date().toISOString();let W=await NN(N,O);if(W)i("runs",{type:"run.updated",run:W})}function mW(N,H){if(N==="account/login/completed"){$1(H);return}let O=kN(H),W=O?IN.get(O):void 0;if(W){if(N==="item/completed"){let G=H.item;if(G?.type==="agentMessage"&&typeof G.text==="string")W.text=G.text}else if(N==="turn/completed"||N==="error")W.done(W.text);return}let Y=O?ON.get(O):void 0;if(!Y)return;(async()=>{if(await T(Y,"codex",U1(N),H),N==="turn/started"){let G=H.turn?.id;if(typeof G==="string")yN.set(Y,G)}else if(N==="turn/completed"){let G=H.turn?.id;if(typeof G==="string"&&ZN.get(Y)===G){ZN.delete(Y);return}ZN.delete(Y),yN.delete(Y),bN.delete(Y);let $=await D(Y);if($&&g($.status))await x(Y,"completed");if(WN.delete(Y),$&&!$.title)iW(Y)}else if(N==="error"){let G=H.turnId;yN.delete(Y);let $=await D(Y),U=bN.get(Y);if($&&U&&U.summary&&U.summary!=="none"&&hW(H)){F1.add($.model??gH);let Q={...U,summary:"none"};console.warn(`[runs] ${$.model??"default model"} rejects reasoning.summary \u2014 retrying with summaries disabled`);try{if(typeof G==="string")ZN.set(Y,G);bN.set(Y,Q),await h().request("turn/start",Q);return}catch(X){ZN.delete(Y),console.warn(`[runs] summary-less retry failed for ${Y}:`,X)}}if($&&g($.status))await x(Y,"failed")}else if(N==="thread/name/updated"){let G=H.threadName;if(typeof G==="string"&&G.trim()){let $=await NN(Y,{title:G.trim()});if($)i("runs",{type:"run.updated",run:$})}}})()}function cW(N,H,O){let W=Q1(H),Y=kN(O),G=Y?ON.get(Y):void 0;if(!W||!G){if(console.warn(`[runs] auto-declining unroutable server request ${H} (id ${N})`),X1(H))h().respond(N,{decision:"decline"});else h().respondError(N,-32601,"Jun cannot handle this request yet");return}(async()=>{let $=WN.get(G)??[];$.push({requestId:N,method:H}),WN.set(G,$),await x(G,"waiting_approval"),await T(G,"codex",W,{requestId:N,method:H,params:O})})()}function lW(N){for(let O of IN.values())O.done(O.text);IN.clear();let H=[...ON.values()];ON.clear(),WN.clear(),yN.clear(),bN.clear(),ZN.clear();for(let O of H)(async()=>{let W=await D(O);if(!W||!g(W.status))return;await T(O,"daemon","run.failed",{reason:`codex app-server exited (code ${N})`}),await x(O,"failed")})()}function vH(N,H,O,W){let Y=(O??[]).filter((Q)=>Q.mediaType?.startsWith("image/")),G=(O??[]).filter((Q)=>!Q.mediaType?.startsWith("image/")),$=H;if(G.length>0)$+=`
|
|
323
323
|
|
|
324
324
|
Attached workspace files:
|
|
325
325
|
`+G.map((Q)=>`- ${Q.path}`).join(`
|
|
326
|
-
`);let U=[{type:"text",text:$}];if(W)U.push({type:"skill",name:W.name,path:W.path});for(let Q of Y)U.push({type:"localImage",path:dN(Q.path,N)});return U}function
|
|
327
|
-
`)[0].replace(/^["'`#*\s]+|["'`*\s]+$/g,"").replace(/\s+/g," ").trim();if(!H)return null;return H.length>60?H.slice(0,57).trimEnd()+"\u2026":H}async function
|
|
326
|
+
`);let U=[{type:"text",text:$}];if(W)U.push({type:"skill",name:W.name,path:W.path});for(let Q of Y)U.push({type:"localImage",path:dN(Q.path,N)});return U}function uW(N){if(!N)return null;let H=N.split(`
|
|
327
|
+
`)[0].replace(/^["'`#*\s]+|["'`*\s]+$/g,"").replace(/\s+/g," ").trim();if(!H)return null;return H.length>60?H.slice(0,57).trimEnd()+"\u2026":H}async function iW(N){let H=await D(N);if(!H||H.title||!H.codexThreadId)return;try{let O=h(),W=await O.request("thread/start",{cwd:H.cwd,ephemeral:!0,sandbox:"read-only",approvalPolicy:"never",serviceName:"jun"}),Y=kN(W);if(!Y)return;let G=await new Promise((Q)=>{let X=(K)=>{clearTimeout(F),IN.delete(Y),Q(K)},F=setTimeout(()=>X(null),30000);IN.set(Y,{text:null,done:X}),O.request("turn/start",{threadId:Y,input:[{type:"text",text:`Reply with ONLY a short title (3-6 words, no quotes, no punctuation at the end) summarizing this conversation opener:
|
|
328
328
|
|
|
329
|
-
`+H.prompt.slice(0,2000)}],effort:"low"}).catch(()=>X(null))}),$=mW(G);if(!$)return;await O.request("thread/name/set",{threadId:H.codexThreadId,name:$});let U=await NN(N,{title:$});if(U)i("runs",{type:"run.updated",run:U})}catch(O){console.warn(`[runs] title generation failed for ${N}:`,O)}}async function C(N,H){let O=h();return await O.start(),await O.initializeOnce(),O.request(N,H)}async function LN(N){let H=N.projectId??"default",O=N.cwd??J(H),W=await C0({prompt:N.prompt,cwd:O,projectId:H,sandbox:N.sandbox??"workspaceWrite",approvalPolicy:N.approvalPolicy??"onRequest",approvalsReviewer:N.approvalsReviewer??"user",model:N.model,effort:N.effort??"medium",source:N.source,scheduleId:N.scheduleId,scheduleName:N.scheduleName});return i("runs",{type:"run.updated",run:W}),await T(W.id,"daemon","run.started",{prompt:N.prompt,cwd:O,projectId:H,attachments:N.attachments??[]}),(async()=>{try{let Y=h();await Y.start(),await Y.initializeOnce();let G=await Y.request("thread/start",{cwd:O,model:N.model??null,sandbox:Q1[N.sandbox??"workspaceWrite"],approvalPolicy:IH[N.approvalPolicy??"onRequest"],...N.approvalsReviewer==="auto_review"?{approvalsReviewer:"auto_review"}:{},...GH?{developerInstructions:GH}:{},serviceName:"jun"}),$=kN(G)??(typeof G.threadId==="string"?G.threadId:null);if(!$)throw Error(`thread/start returned no thread id: ${JSON.stringify(G)}`);ON.set($,W.id),await NN(W.id,{codexThreadId:$}),await x(W.id,"running"),await L1(W.id,N.model??jH,{threadId:$,input:gH(H,N.prompt,N.attachments,N.skill),summary:"detailed",effort:N.effort??"medium",sandboxPolicy:X1[N.sandbox??"workspaceWrite"]})}catch(Y){let G=Y instanceof Error?Y.message:String(Y);await T(W.id,"daemon","run.failed",{reason:G}),await x(W.id,"failed")}})(),W}async function vH(N,H){let O=h();if(await O.start(),await O.initializeOnce(),ON.has(H))return{server:O,resumed:!1};let W=await D(N);return await O.request("thread/resume",{threadId:H,...W?.approvalPolicy?{approvalPolicy:IH[W.approvalPolicy]}:{},...W?.approvalsReviewer==="auto_review"?{approvalsReviewer:"auto_review"}:{},...W?.model?{model:W.model}:{},...W?.sandbox?{sandbox:Q1[W.sandbox]}:{},...GH?{developerInstructions:GH}:{}}),ON.set(H,N),{server:O,resumed:!0}}async function $H(N,H,O,W){let Y=await D(N);if(!Y)throw Error(`Run not found: ${N}`);if(g(Y.status))throw Error("Run is still active \u2014 wait for the current turn to finish");let G=Y.codexThreadId;if(!G)throw Error("Run has no Codex thread to resume");let $={};if(W?.sandbox&&W.sandbox!==Y.sandbox)$.sandbox=W.sandbox;if(W?.approvalPolicy&&W.approvalPolicy!==Y.approvalPolicy)$.approvalPolicy=W.approvalPolicy;if(W?.approvalsReviewer&&W.approvalsReviewer!==Y.approvalsReviewer)$.approvalsReviewer=W.approvalsReviewer;if(W?.model&&W.model!==Y.model)$.model=W.model;if(W?.effort&&W.effort!==Y.effort)$.effort=W.effort;if(Object.keys($).length>0){let U=await NN(N,$);if(U)i("runs",{type:"run.updated",run:U})}return await T(N,"daemon","run.resumed",{prompt:H,attachments:O??[],...Object.keys($).length>0?{modeChanges:$}:{}}),await x(N,"running"),(async()=>{try{await vH(N,G);let U=$.sandbox??Y.sandbox??"workspaceWrite",Q=$.approvalPolicy??Y.approvalPolicy??"onRequest",X=$.approvalsReviewer??Y.approvalsReviewer,F=$.model??Y.model,M=(await D(N))?.serviceTier;await L1(N,F??jH,{threadId:G,input:gH(Y.projectId,H,O),summary:"detailed",effort:$.effort??Y.effort??"medium",sandboxPolicy:X1[U],approvalPolicy:IH[Q],...X==="auto_review"?{approvalsReviewer:X}:{},...F?{model:F}:{},...M?{serviceTier:M}:{}})}catch(U){let Q=U instanceof Error?U.message:String(U);await T(N,"daemon","run.failed",{reason:Q}),await x(N,"failed")}})(),await D(N)}async function F1(N,H,O){let W=await D(N);if(!W)throw Error(`Run not found: ${N}`);if(!g(W.status))throw Error("Run is not active \u2014 send a follow-up message instead");let Y=W.codexThreadId,G=yN.get(N);if(!Y||!G)throw Error("No active turn to steer");await T(N,"daemon","run.steered",{prompt:H,attachments:O??[]}),await h().request("turn/steer",{threadId:Y,expectedTurnId:G,input:gH(W.projectId,H,O)})}async function z1(N,H){let O=await D(N);if(!O)throw Error(`Run not found: ${N}`);if(H){let G=((await C("model/list",{})).data??[]).find(($)=>O.model?$.model===O.model:$.isDefault);if(!G?.serviceTiers?.some(($)=>$.id==="priority"))throw Error(`Model ${G?.model??O.model??"unknown"} does not support fast mode`)}let W=await NN(N,{serviceTier:H?"priority":"standard"});if(W)i("runs",{type:"run.updated",run:W});return await T(N,"daemon","run.fast",{enabled:H}),W}async function V1(N){let H=await D(N);if(!H)throw Error(`Run not found: ${N}`);if(g(H.status))throw Error("Run is still active \u2014 wait for the current turn to finish");let O=H.codexThreadId;if(!O)throw Error("Run has no Codex thread");let{server:W}=await vH(N,O);await T(N,"daemon","run.compact.started",{}),await W.request("thread/compact/start",{threadId:O})}async function K1(N,H){let O=await D(N);if(!O)throw Error(`Run not found: ${N}`);if(g(O.status))throw Error("Run is still active \u2014 wait for the current turn to finish");let W=O.codexThreadId;if(!W)throw Error("Run has no Codex thread");let{server:Y}=await vH(N,W),G=H?.trim();await T(N,"daemon","run.review.started",{instructions:G??null}),await x(N,"running");try{await Y.request("review/start",{threadId:W,target:G?{type:"custom",instructions:G}:{type:"uncommittedChanges"},delivery:"inline"})}catch($){let U=$ instanceof Error?$.message:String($);throw await T(N,"daemon","run.failed",{reason:U}),await x(N,"failed"),$}return await D(N)}async function M1(N){let H=await D(N);if(!H||!g(H.status))return!1;if(H.codexThreadId&&qN?.running)try{await qN.request("turn/interrupt",{threadId:H.codexThreadId})}catch(O){console.warn(`[runs] turn/interrupt failed for ${N}:`,O)}return WN.delete(N),await T(N,"daemon","run.stopped",{}),await x(N,"stopped"),!0}async function A1(N,H,O){let W=WN.get(N)??[],Y=W.findIndex(($)=>String($.requestId)===String(H));if(Y===-1)return!1;let[G]=W.splice(Y,1);if(W.length===0)WN.delete(N);if(G.method==="mcpServer/elicitation/request"){let $=O==="decline"||O==="cancel"?O:"accept";h().respond(G.requestId,{action:$})}else h().respond(G.requestId,{decision:O});if(await T(N,"daemon","approval.resolved",{requestId:G.requestId,decision:O}),W.length===0)await x(N,"running");return!0}function zN(){return lW.join(q(),"config.toml")}async function p(){try{return await FN.readFile(zN(),"utf8")}catch{return""}}async function B1(N){try{c(N)}catch(H){throw new B(`Invalid TOML: ${H instanceof Error?H.message:String(H)}`)}await FN.writeFile(zN(),N,"utf8")}function uW(N){if(!N.trim())return{};let O=c(N).mcp_servers;if(typeof O!=="object"||O===null)return{};return O}async function iW(){let N=new Map;try{let H=await C("mcpServerStatus/list",{detail:"full"});for(let O of H.data??[]){let W=Object.entries(O.tools??{}).map(([Y,G])=>({name:Y,description:G?.description}));N.set(O.name,{startupState:O.serverInfo?"ready":"starting",authStatus:O.authStatus??null,tools:W})}}catch(H){console.warn("[mcp] mcpServerStatus/list failed:",H)}return N}async function D1(){let N=await p(),H=uW(N),O=await iW();return{servers:Object.entries(H).map(([Y,G])=>{let $=O.get(Y);return{name:Y,command:G.command,args:G.args,envKeys:G.env?Object.keys(G.env):void 0,url:G.url,enabled:G.enabled!==!1,startupState:$?.startupState??null,authStatus:$?.authStatus??null,tools:$?.tools??[],error:$?.error}})}}var pW=/^[A-Za-z0-9_-]+$/;async function C1(N){if(!pW.test(N.name))throw new B(`Invalid server name "${N.name}" \u2014 letters, digits, _ and - only`);if(!N.command&&!N.url)throw new B("Server needs either a command or a url");let H=await p(),O=H.trim()?c(H):{},W=O.mcp_servers??{},Y={};if(N.command)Y.command=N.command;if(N.args&&N.args.length>0)Y.args=N.args;if(N.env&&Object.keys(N.env).length>0)Y.env=N.env;if(N.url)Y.url=N.url;if(N.enabled===!1)Y.enabled=!1;W[N.name]=Y,O.mcp_servers=W,await FN.writeFile(zN(),d(O),"utf8")}async function S1(N){let H=await p();if(!H.trim())return!1;let O=c(H),W=O.mcp_servers;if(!W||!(N in W))return!1;return delete W[N],await FN.writeFile(zN(),d(O),"utf8"),!0}async function R1(N,H){let O=await p(),W=c(O||""),Y=W.mcp_servers??{};if(!Y[N])throw new B(`Server not found: ${N}`);Y[N].enabled=H,W.mcp_servers=Y,await FN.writeFile(zN(),d(W),"utf8")}async function T1(){await C("config/mcpServer/reload",{})}async function E1(N,H){let O=await p(),W=O.trim()?c(O):{},Y=W.mcp_servers??{},G={command:process.execPath,args:[N],env:{JUN_PORT:String(H)}},$=Y.jun;if($&&!Y.agenthost&&$.command===G.command&&JSON.stringify($.args)===JSON.stringify(G.args)&&$.env?.JUN_PORT===String(H))return;delete Y.agenthost,Y.jun=G,W.mcp_servers=Y,await FN.writeFile(zN(),d(W),"utf8")}var aW=Date.now();function _1(){return L({ok:!0})}function w1(){let N={ok:!0,name:"jun",version:"0.0.1",projectId:z,dataRoot:b,workspaceRoot:J(),uptimeSeconds:Math.round((Date.now()-aW)/1000)};return L(N)}import oW from"path";var UH={ok:!0};async function P1(N,H){let O=H.pathname.slice(11),W=H.searchParams.get("path")??".",Y=H.searchParams.get("project")??z;switch(`${N.method} ${O}`){case"GET tree":return L(await U0(W,Y));case"GET read":return L(await Q0(W,Y));case"GET download":{let G=dN(W,Y),$=Bun.file(G);if(!await $.exists())return Z(404,`File not found: ${W}`);return new Response($,{headers:{"content-disposition":`attachment; filename="${encodeURIComponent(oW.basename(G))}"`}})}case"POST write":{let G=await K(N);return await X0(A(G.path,"path"),typeof G.content==="string"?G.content:"",Y),L(UH)}case"POST mkdir":{let G=await K(N);return await Z0(A(G.path,"path"),Y),L(UH)}case"POST delete":{let G=await K(N);return await L0(A(G.path,"path"),Y),L(UH)}case"POST rename":{let G=await K(N);return await F0(A(G.from,"from"),A(G.to,"to"),Y),L(UH)}case"POST upload":{let G;try{G=await N.formData()}catch{throw new B("Expected multipart/form-data body")}let $=String(G.get("path")??"."),U=G.getAll("file").filter((X)=>X instanceof File);if(U.length===0)throw new B("No files in upload (field name: file)");let Q=[];for(let X of U)Q.push(await z0($,X.name,X,Y));return L({ok:!0,saved:Q})}default:return Z(404,`Unknown files endpoint: ${N.method} /api/files/${O}`)}}import{promises as f1}from"fs";function dW(N){return N.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}async function x1(N){try{let H=await f1.readFile(AH(N),"utf8"),O=JSON.parse(H);return{id:O.id??N,name:O.name??N,createdAt:O.createdAt??new Date(0).toISOString(),workspaceRoot:J(N)}}catch{return null}}async function k1(){let N;try{N=await f1.readdir(UN(),{withFileTypes:!0})}catch{return[]}let H=[];for(let O of N){if(!O.isDirectory())continue;let W=await x1(O.name);if(W)H.push(W)}return H.sort((O,W)=>{if(O.id===z)return-1;if(W.id===z)return 1;return W.createdAt.localeCompare(O.createdAt)}),H}async function jN(N){return x1(N)}async function y1(N){let H=N.trim();if(!H)throw Error("Project name is required");let O=dW(H);if(!O)throw Error("Project name must contain letters or numbers");if(await jN(O))throw Error(`A project named "${O}" already exists`);await JH(O,H);let W=await jN(O);if(!W)throw Error(`Failed to create project "${O}"`);return W}async function VN(N){return await jN(N)!==null}async function b1(N,H){let W=H.pathname.split("/").filter(Boolean)[2];if(!W){if(N.method==="GET"){let Y={projects:await k1()};return L(Y)}if(N.method==="POST"){let Y=await K(N);A(Y.name,"name");try{let $={project:await y1(Y.name)};return L($,201)}catch(G){let $=G instanceof Error?G.message:String(G),U=$.includes("already exists")?409:400;return Z(U,$)}}return Z(405,"Method not allowed")}if(N.method==="GET"){let Y=await jN(W);return Y?L({project:Y}):Z(404,`Project not found: ${W}`)}return Z(405,"Method not allowed")}var sW=new Set(["accept","acceptForSession","decline","cancel"]);async function q1(N,H,O){let W=H.pathname.split("/").filter(Boolean),Y=W[2],G=W[3];if(!Y){if(N.method==="GET"){let $=H.searchParams.get("project")??void 0,U={runs:await S0($)};return L(U)}if(N.method==="POST"){let $=await K(N);A($.prompt,"prompt");let Q={run:await LN($)};return L(Q,201)}return Z(405,"Method not allowed")}if(G==="events"){if(!await D(Y))return Z(404,`Run not found: ${Y}`);return O.upgrade(N,{data:{channel:`run:${Y}`}})?void 0:Z(400,"WebSocket upgrade required")}if(!G&&N.method==="GET"){let $=await D(Y);if(!$)return Z(404,`Run not found: ${Y}`);let U=Number(H.searchParams.get("tail")??NaN),Q=Number(H.searchParams.get("before")??NaN),X=await _0(Y,{limit:Number.isFinite(U)&&U>0?U:void 0,before:Number.isFinite(Q)&&Q>=0?Q:void 0}),F={run:$,events:X.events,eventsOffset:X.offset,totalEvents:X.total};return L(F)}if(N.method!=="POST")return Z(405,"Method not allowed");switch(G){case"stop":return await M1(Y)?L({ok:!0}):Z(409,"Run is not active");case"resume":{let $=await K(N);A($.prompt,"prompt");try{let U=await $H(Y,$.prompt,Array.isArray($.attachments)?$.attachments:void 0,{sandbox:$.sandbox,approvalPolicy:$.approvalPolicy,approvalsReviewer:$.approvalsReviewer,model:$.model,effort:$.effort});return L({run:U})}catch(U){let Q=U instanceof Error?U.message:String(U),X=Q.includes("not found")?404:Q.includes("still active")?409:400;return Z(X,Q)}}case"steer":{let $=await K(N);A($.prompt,"prompt");try{return await F1(Y,$.prompt,Array.isArray($.attachments)?$.attachments:void 0),L({ok:!0})}catch(U){let Q=U instanceof Error?U.message:String(U),X=Q.includes("not found")?404:Q.includes("not active")||Q.includes("No active turn")?409:400;return Z(X,Q)}}case"fast":{let $=await K(N);if(typeof $.enabled!=="boolean")return Z(400,"Missing or invalid field: enabled");try{let U=await z1(Y,$.enabled);return L({run:U})}catch(U){let Q=U instanceof Error?U.message:String(U),X=Q.includes("not found")?404:Q.includes("does not support")?400:500;return Z(X,Q)}}case"compact":try{return await V1(Y),L({ok:!0})}catch($){let U=$ instanceof Error?$.message:String($),Q=U.includes("not found")?404:U.includes("still active")?409:400;return Z(Q,U)}case"review":{let $=await K(N);try{let U=await K1(Y,$.instructions);return L({run:U})}catch(U){let Q=U instanceof Error?U.message:String(U),X=Q.includes("not found")?404:Q.includes("still active")?409:400;return Z(X,Q)}}case"approve":{let $=await K(N);if(!sW.has(String($.decision)))return Z(400,`Invalid decision: ${String($.decision)}`);if($.requestId===void 0||$.requestId===null)return Z(400,"Missing field: requestId");return await A1(Y,$.requestId,$.decision)?L({ok:!0}):Z(404,"No matching pending approval")}default:return Z(404,`Unknown runs endpoint: ${H.pathname}`)}}var YN="browser-stream",m=null,I1=null,KN=0,MN=null,mH=null;function tW(N){if(m&&I1===N&&m.readyState<=WebSocket.OPEN)return;m?.close(),I1=N;let H=new WebSocket(`ws://127.0.0.1:${N}`);m=H,H.onmessage=(O)=>{let W=String(O.data);if(W.includes('"type":"frame"'))mH=W;M0(YN,W)},H.onclose=()=>{if(m===H)m=null,mH=null,j1()},H.onerror=()=>{}}function j1(){if(MN||KN===0)return;MN=setTimeout(()=>{MN=null,gN(!0)},2000)}async function gN(N=!1){if(KN===0)return;let H=N?null:i0();if(H===null){if(N)HN();H=(await fN()).streamPort}if(H!==null)tW(H);else j1()}function g1(){KN+=1,gN()}function v1(){return mH}function h1(){if(KN=Math.max(0,KN-1),KN===0){if(m?.close(),m=null,MN)clearTimeout(MN),MN=null}}var rW=new Set(["input_mouse","input_keyboard","input_touch"]);function m1(N){if(l0()!=="user")return;if(!m||m.readyState!==WebSocket.OPEN)return;let H=typeof N==="string"?N:N.toString("utf8");try{let O=JSON.parse(H);if(typeof O.type==="string"&&rW.has(O.type))m.send(H)}catch{}}var eW=new Set(["user","agent","paused"]);async function c1(N,H,O){let Y=H.pathname.split("/").filter(Boolean)[2];if(Y==="stream")return O.upgrade(N,{data:{channel:YN}})?void 0:Z(400,"WebSocket upgrade required");if(N.method==="GET")switch(Y){case"status":{let G=await fN();if(G.streaming)gN();return L({status:G})}case"actions":{let G={actions:c0()};return L(G)}default:return Z(404,`Unknown browser endpoint: ${H.pathname}`)}if(N.method!=="POST")return Z(405,"Method not allowed");switch(Y){case"start":{let G=await K(N).catch(()=>({})),$=await a0(typeof G.url==="string"&&G.url.length>0?G.url:void 0);return gN(),L({status:$})}case"stop":return await o0(),L({ok:!0});case"navigate":{let G=await K(N);return A(G.url,"url"),await d0(G.url),L({ok:!0})}case"key":{let G=await K(N);return A(G.key,"key"),await t0(G.key),L({ok:!0})}case"back":case"forward":case"reload":return await s0(Y),L({ok:!0});case"screenshot":{let $={path:await r0()};return L($)}case"control":{let G=await K(N);if(!eW.has(String(G.controller)))return Z(400,`Invalid controller: ${String(G.controller)}`);return u0(G.controller),L({ok:!0})}default:return Z(404,`Unknown browser endpoint: ${H.pathname}`)}}import{promises as P}from"fs";import E from"path";var i1=".agents/skills";function AN(N){return E.join(J(N),i1)}var NY=/^[a-z0-9][a-z0-9-]*$/,HY=new Set(["registry","install"]);function JN(N,H){if(!NY.test(N))throw new B(`Invalid skill id "${N}" \u2014 use lowercase letters, digits and dashes`);return E.join(AN(H),N)}function l1(N){return N.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"")}async function p1(N,H,O=120000){let W=Bun.spawn([process.execPath,"x","skills",...N],{cwd:H,env:{...process.env,DISABLE_TELEMETRY:"1",DO_NOT_TRACK:"1"},stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>W.kill(),O);try{let[G,$,U]=await Promise.all([new Response(W.stdout).text(),new Response(W.stderr).text(),W.exited]);return{stdout:l1(G),stderr:l1($),code:U}}finally{clearTimeout(Y)}}function OY(N){let H=[],O=null;for(let W of N.split(/\r?\n/)){let Y=W.trim(),G=/^(\S+@\S+)\s+([\d.]+[KMB]?)\s+installs\b/.exec(Y);if(G){let U=G[1],Q=U.indexOf("@");O={source:U,repo:U.slice(0,Q),name:U.slice(Q+1),installs:G[2]},H.push(O);continue}let $=/^[\u2514\u2570]\s*(https?:\/\/\S+)/.exec(Y);if($&&O)O.url=$[1],O=null}return H}function WY(N){let H=[],O=/^---\r?\n([\s\S]*?)\r?\n---/.exec(N.replace(/^\uFEFF/,""));if(!O)return{errors:["Missing YAML frontmatter (--- name/description ---)"]};let W={};for(let Y of O[1].split(/\r?\n/)){let G=/^([A-Za-z_][\w-]*):\s*(.*)$/.exec(Y);if(G)W[G[1].toLowerCase()]=G[2].trim().replace(/^["']|["']$/g,"")}if(!W.name)H.push("Frontmatter is missing required field: name");if(!W.description)H.push("Frontmatter is missing required field: description");return{name:W.name,description:W.description,errors:H}}var YY=15000,lH=new Map,cH=new Map;function vN(N){lH.delete(N)}async function GY(N){let H=lH.get(N);if(H&&Date.now()-H.at<YY)return H.view;let O=cH.get(N);if(O)return O;let W=$Y(N).then((Y)=>{return lH.set(N,{at:Date.now(),view:Y}),Y}).finally(()=>{cH.delete(N)});return cH.set(N,W),W}async function $Y(N){let H=new Map,O=[];try{let W=await C("skills/list",{cwds:[J(N)],forceReload:!0});for(let Y of W.data??[]){for(let G of Y.errors??[])O.push(G);for(let G of Y.skills??[]){let $=E.basename(E.dirname(G.path));H.set($,G)}}}catch(W){console.warn("[skills] skills/list failed:",W)}return{byDir:H,errors:O}}async function QH(N=z){await P.mkdir(AN(N),{recursive:!0});let O=(await P.readdir(AN(N),{withFileTypes:!0})).filter((U)=>U.isDirectory()).map((U)=>U.name),{byDir:W,errors:Y}=await GY(N),G=[];for(let U of O){let Q=E.join(AN(N),U,"SKILL.md"),X=null;try{X=await P.readFile(Q,"utf8")}catch{G.push({id:U,name:U,description:"",enabled:!1,errors:["Missing SKILL.md"]});continue}let F=WY(X),M=W.get(U),R=Y.filter((f)=>l(f.path).includes(`/${U}/`)||E.basename(E.dirname(f.path))===U).map((f)=>f.message);G.push({id:U,name:M?.name??F.name??U,description:M?.description??F.description??"",enabled:M?.enabled??!0,errors:[...new Set([...F.errors,...R])]})}let $=Y.filter((U)=>!O.some((Q)=>l(U.path).includes(`/${Q}/`)));return{skills:G,errors:$}}async function hN(N,H=z){let O=JN(N,H),W;try{W=await P.readFile(E.join(O,"SKILL.md"),"utf8")}catch{return null}let{skills:Y}=await QH(H),G=Y.find((Q)=>Q.id===N)??{id:N,name:N,description:"",enabled:!0,errors:[]},$=[],U=async(Q)=>{let X=await P.readdir(E.join(O,Q),{withFileTypes:!0});for(let F of X){let M=Q?`${Q}/${F.name}`:F.name;if(F.isDirectory())await U(M);else if(M!=="SKILL.md")$.push(`${i1}/${N}/${M}`)}};return await U(""),{info:G,content:W,files:$}}async function n1(N,H=z){let O=N.name.trim().toLowerCase().replace(/\s+/g,"-");if(HY.has(O))throw new B(`"${O}" is a reserved name \u2014 pick another`);let W=JN(O,H);try{throw await P.access(E.join(W,"SKILL.md")),new B(`Skill "${O}" already exists`)}catch(G){if(G instanceof B)throw G}let Y=`---
|
|
329
|
+
`+H.prompt.slice(0,2000)}],effort:"low"}).catch(()=>X(null))}),$=uW(G);if(!$)return;await O.request("thread/name/set",{threadId:H.codexThreadId,name:$});let U=await NN(N,{title:$});if(U)i("runs",{type:"run.updated",run:U})}catch(O){console.warn(`[runs] title generation failed for ${N}:`,O)}}async function C(N,H){let O=h();return await O.start(),await O.initializeOnce(),O.request(N,H)}async function LN(N){let H=N.projectId??"default",O=N.cwd??J(H),W=await S0({prompt:N.prompt,cwd:O,projectId:H,sandbox:N.sandbox??"workspaceWrite",approvalPolicy:N.approvalPolicy??"onRequest",approvalsReviewer:N.approvalsReviewer??"user",model:N.model,effort:N.effort??"medium",source:N.source,scheduleId:N.scheduleId,scheduleName:N.scheduleName});return i("runs",{type:"run.updated",run:W}),await T(W.id,"daemon","run.started",{prompt:N.prompt,cwd:O,projectId:H,attachments:N.attachments??[]}),(async()=>{try{let Y=h();await Y.start(),await Y.initializeOnce();let G=await Y.request("thread/start",{cwd:O,model:N.model??null,sandbox:Z1[N.sandbox??"workspaceWrite"],approvalPolicy:jH[N.approvalPolicy??"onRequest"],...N.approvalsReviewer==="auto_review"?{approvalsReviewer:"auto_review"}:{},...$H?{developerInstructions:$H}:{},serviceName:"jun"}),$=kN(G)??(typeof G.threadId==="string"?G.threadId:null);if(!$)throw Error(`thread/start returned no thread id: ${JSON.stringify(G)}`);ON.set($,W.id),await NN(W.id,{codexThreadId:$}),await x(W.id,"running"),await z1(W.id,N.model??gH,{threadId:$,input:vH(H,N.prompt,N.attachments,N.skill),summary:"detailed",effort:N.effort??"medium",sandboxPolicy:L1[N.sandbox??"workspaceWrite"]})}catch(Y){let G=Y instanceof Error?Y.message:String(Y);await T(W.id,"daemon","run.failed",{reason:G}),await x(W.id,"failed")}})(),W}async function hH(N,H){let O=h();if(await O.start(),await O.initializeOnce(),ON.has(H))return{server:O,resumed:!1};let W=await D(N);return await O.request("thread/resume",{threadId:H,...W?.approvalPolicy?{approvalPolicy:jH[W.approvalPolicy]}:{},...W?.approvalsReviewer==="auto_review"?{approvalsReviewer:"auto_review"}:{},...W?.model?{model:W.model}:{},...W?.sandbox?{sandbox:Z1[W.sandbox]}:{},...$H?{developerInstructions:$H}:{}}),ON.set(H,N),{server:O,resumed:!0}}async function UH(N,H,O,W){let Y=await D(N);if(!Y)throw Error(`Run not found: ${N}`);if(g(Y.status))throw Error("Run is still active \u2014 wait for the current turn to finish");let G=Y.codexThreadId;if(!G)throw Error("Run has no Codex thread to resume");let $={};if(W?.sandbox&&W.sandbox!==Y.sandbox)$.sandbox=W.sandbox;if(W?.approvalPolicy&&W.approvalPolicy!==Y.approvalPolicy)$.approvalPolicy=W.approvalPolicy;if(W?.approvalsReviewer&&W.approvalsReviewer!==Y.approvalsReviewer)$.approvalsReviewer=W.approvalsReviewer;if(W?.model&&W.model!==Y.model)$.model=W.model;if(W?.effort&&W.effort!==Y.effort)$.effort=W.effort;if(Object.keys($).length>0){let U=await NN(N,$);if(U)i("runs",{type:"run.updated",run:U})}return await T(N,"daemon","run.resumed",{prompt:H,attachments:O??[],...Object.keys($).length>0?{modeChanges:$}:{}}),await x(N,"running"),(async()=>{try{await hH(N,G);let U=$.sandbox??Y.sandbox??"workspaceWrite",Q=$.approvalPolicy??Y.approvalPolicy??"onRequest",X=$.approvalsReviewer??Y.approvalsReviewer,F=$.model??Y.model,K=(await D(N))?.serviceTier;await z1(N,F??gH,{threadId:G,input:vH(Y.projectId,H,O),summary:"detailed",effort:$.effort??Y.effort??"medium",sandboxPolicy:L1[U],approvalPolicy:jH[Q],...X==="auto_review"?{approvalsReviewer:X}:{},...F?{model:F}:{},...K?{serviceTier:K}:{}})}catch(U){let Q=U instanceof Error?U.message:String(U);await T(N,"daemon","run.failed",{reason:Q}),await x(N,"failed")}})(),await D(N)}async function V1(N,H,O){let W=await D(N);if(!W)throw Error(`Run not found: ${N}`);if(!g(W.status))throw Error("Run is not active \u2014 send a follow-up message instead");let Y=W.codexThreadId,G=yN.get(N);if(!Y||!G)throw Error("No active turn to steer");await T(N,"daemon","run.steered",{prompt:H,attachments:O??[]}),await h().request("turn/steer",{threadId:Y,expectedTurnId:G,input:vH(W.projectId,H,O)})}async function M1(N,H){let O=await D(N);if(!O)throw Error(`Run not found: ${N}`);if(H){let G=((await C("model/list",{})).data??[]).find(($)=>O.model?$.model===O.model:$.isDefault);if(!G?.serviceTiers?.some(($)=>$.id==="priority"))throw Error(`Model ${G?.model??O.model??"unknown"} does not support fast mode`)}let W=await NN(N,{serviceTier:H?"priority":"standard"});if(W)i("runs",{type:"run.updated",run:W});return await T(N,"daemon","run.fast",{enabled:H}),W}async function K1(N){let H=await D(N);if(!H)throw Error(`Run not found: ${N}`);if(g(H.status))throw Error("Run is still active \u2014 wait for the current turn to finish");let O=H.codexThreadId;if(!O)throw Error("Run has no Codex thread");let{server:W}=await hH(N,O);await T(N,"daemon","run.compact.started",{}),await W.request("thread/compact/start",{threadId:O})}async function A1(N,H){let O=await D(N);if(!O)throw Error(`Run not found: ${N}`);if(g(O.status))throw Error("Run is still active \u2014 wait for the current turn to finish");let W=O.codexThreadId;if(!W)throw Error("Run has no Codex thread");let{server:Y}=await hH(N,W),G=H?.trim();await T(N,"daemon","run.review.started",{instructions:G??null}),await x(N,"running");try{await Y.request("review/start",{threadId:W,target:G?{type:"custom",instructions:G}:{type:"uncommittedChanges"},delivery:"inline"})}catch($){let U=$ instanceof Error?$.message:String($);throw await T(N,"daemon","run.failed",{reason:U}),await x(N,"failed"),$}return await D(N)}async function J1(N){let H=await D(N);if(!H||!g(H.status))return!1;if(H.codexThreadId&&qN?.running)try{await qN.request("turn/interrupt",{threadId:H.codexThreadId})}catch(O){console.warn(`[runs] turn/interrupt failed for ${N}:`,O)}return WN.delete(N),await T(N,"daemon","run.stopped",{}),await x(N,"stopped"),!0}async function B1(N,H,O){let W=WN.get(N)??[],Y=W.findIndex(($)=>String($.requestId)===String(H));if(Y===-1)return!1;let[G]=W.splice(Y,1);if(W.length===0)WN.delete(N);if(G.method==="mcpServer/elicitation/request"){let $=O==="decline"||O==="cancel"?O:"accept";h().respond(G.requestId,{action:$})}else h().respond(G.requestId,{decision:O});if(await T(N,"daemon","approval.resolved",{requestId:G.requestId,decision:O}),W.length===0)await x(N,"running");return!0}function zN(){return pW.join(q(),"config.toml")}async function p(){try{return await FN.readFile(zN(),"utf8")}catch{return""}}async function C1(N){try{c(N)}catch(H){throw new B(`Invalid TOML: ${H instanceof Error?H.message:String(H)}`)}await FN.writeFile(zN(),N,"utf8")}function nW(N){if(!N.trim())return{};let O=c(N).mcp_servers;if(typeof O!=="object"||O===null)return{};return O}async function aW(){let N=new Map;try{let H=await C("mcpServerStatus/list",{detail:"full"});for(let O of H.data??[]){let W=Object.entries(O.tools??{}).map(([Y,G])=>({name:Y,description:G?.description}));N.set(O.name,{startupState:O.serverInfo?"ready":"starting",authStatus:O.authStatus??null,tools:W})}}catch(H){console.warn("[mcp] mcpServerStatus/list failed:",H)}return N}async function S1(){let N=await p(),H=nW(N),O=await aW();return{servers:Object.entries(H).map(([Y,G])=>{let $=O.get(Y);return{name:Y,command:G.command,args:G.args,envKeys:G.env?Object.keys(G.env):void 0,url:G.url,enabled:G.enabled!==!1,startupState:$?.startupState??null,authStatus:$?.authStatus??null,tools:$?.tools??[],error:$?.error}})}}var oW=/^[A-Za-z0-9_-]+$/;async function R1(N){if(!oW.test(N.name))throw new B(`Invalid server name "${N.name}" \u2014 letters, digits, _ and - only`);if(!N.command&&!N.url)throw new B("Server needs either a command or a url");let H=await p(),O=H.trim()?c(H):{},W=O.mcp_servers??{},Y={};if(N.command)Y.command=N.command;if(N.args&&N.args.length>0)Y.args=N.args;if(N.env&&Object.keys(N.env).length>0)Y.env=N.env;if(N.url)Y.url=N.url;if(N.enabled===!1)Y.enabled=!1;W[N.name]=Y,O.mcp_servers=W,await FN.writeFile(zN(),d(O),"utf8")}async function T1(N){let H=await p();if(!H.trim())return!1;let O=c(H),W=O.mcp_servers;if(!W||!(N in W))return!1;return delete W[N],await FN.writeFile(zN(),d(O),"utf8"),!0}async function E1(N,H){let O=await p(),W=c(O||""),Y=W.mcp_servers??{};if(!Y[N])throw new B(`Server not found: ${N}`);Y[N].enabled=H,W.mcp_servers=Y,await FN.writeFile(zN(),d(W),"utf8")}async function _1(){await C("config/mcpServer/reload",{})}async function w1(N,H){let O=await p(),W=O.trim()?c(O):{},Y=W.mcp_servers??{},G={command:process.execPath,args:[N],env:{JUN_PORT:String(H)}},$=Y.jun;if($&&!Y.agenthost&&$.command===G.command&&JSON.stringify($.args)===JSON.stringify(G.args)&&$.env?.JUN_PORT===String(H))return;delete Y.agenthost,Y.jun=G,W.mcp_servers=Y,await FN.writeFile(zN(),d(W),"utf8")}var sW=Date.now();function P1(){return L({ok:!0})}function f1(){let N={ok:!0,name:"jun",version:tN,projectId:z,dataRoot:b,workspaceRoot:J(),uptimeSeconds:Math.round((Date.now()-sW)/1000)};return L(N)}import tW from"path";var QH={ok:!0};async function x1(N,H){let O=H.pathname.slice(11),W=H.searchParams.get("path")??".",Y=H.searchParams.get("project")??z;switch(`${N.method} ${O}`){case"GET tree":return L(await Q0(W,Y));case"GET read":return L(await X0(W,Y));case"GET download":{let G=dN(W,Y),$=Bun.file(G);if(!await $.exists())return Z(404,`File not found: ${W}`);return new Response($,{headers:{"content-disposition":`attachment; filename="${encodeURIComponent(tW.basename(G))}"`}})}case"POST write":{let G=await M(N);return await Z0(A(G.path,"path"),typeof G.content==="string"?G.content:"",Y),L(QH)}case"POST mkdir":{let G=await M(N);return await L0(A(G.path,"path"),Y),L(QH)}case"POST delete":{let G=await M(N);return await F0(A(G.path,"path"),Y),L(QH)}case"POST rename":{let G=await M(N);return await z0(A(G.from,"from"),A(G.to,"to"),Y),L(QH)}case"POST upload":{let G;try{G=await N.formData()}catch{throw new B("Expected multipart/form-data body")}let $=String(G.get("path")??"."),U=G.getAll("file").filter((X)=>X instanceof File);if(U.length===0)throw new B("No files in upload (field name: file)");let Q=[];for(let X of U)Q.push(await V0($,X.name,X,Y));return L({ok:!0,saved:Q})}default:return Z(404,`Unknown files endpoint: ${N.method} /api/files/${O}`)}}import{promises as k1}from"fs";function rW(N){return N.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}async function y1(N){try{let H=await k1.readFile(JH(N),"utf8"),O=JSON.parse(H);return{id:O.id??N,name:O.name??N,createdAt:O.createdAt??new Date(0).toISOString(),workspaceRoot:J(N)}}catch{return null}}async function b1(){let N;try{N=await k1.readdir(UN(),{withFileTypes:!0})}catch{return[]}let H=[];for(let O of N){if(!O.isDirectory())continue;let W=await y1(O.name);if(W)H.push(W)}return H.sort((O,W)=>{if(O.id===z)return-1;if(W.id===z)return 1;return W.createdAt.localeCompare(O.createdAt)}),H}async function jN(N){return y1(N)}async function q1(N){let H=N.trim();if(!H)throw Error("Project name is required");let O=rW(H);if(!O)throw Error("Project name must contain letters or numbers");if(await jN(O))throw Error(`A project named "${O}" already exists`);await BH(O,H);let W=await jN(O);if(!W)throw Error(`Failed to create project "${O}"`);return W}async function VN(N){return await jN(N)!==null}async function I1(N,H){let W=H.pathname.split("/").filter(Boolean)[2];if(!W){if(N.method==="GET"){let Y={projects:await b1()};return L(Y)}if(N.method==="POST"){let Y=await M(N);A(Y.name,"name");try{let $={project:await q1(Y.name)};return L($,201)}catch(G){let $=G instanceof Error?G.message:String(G),U=$.includes("already exists")?409:400;return Z(U,$)}}return Z(405,"Method not allowed")}if(N.method==="GET"){let Y=await jN(W);return Y?L({project:Y}):Z(404,`Project not found: ${W}`)}return Z(405,"Method not allowed")}var eW=new Set(["accept","acceptForSession","decline","cancel"]);async function j1(N,H,O){let W=H.pathname.split("/").filter(Boolean),Y=W[2],G=W[3];if(!Y){if(N.method==="GET"){let $=H.searchParams.get("project")??void 0,U={runs:await R0($)};return L(U)}if(N.method==="POST"){let $=await M(N);A($.prompt,"prompt");let Q={run:await LN($)};return L(Q,201)}return Z(405,"Method not allowed")}if(G==="events"){if(!await D(Y))return Z(404,`Run not found: ${Y}`);return O.upgrade(N,{data:{channel:`run:${Y}`}})?void 0:Z(400,"WebSocket upgrade required")}if(!G&&N.method==="GET"){let $=await D(Y);if(!$)return Z(404,`Run not found: ${Y}`);let U=Number(H.searchParams.get("tail")??NaN),Q=Number(H.searchParams.get("before")??NaN),X=await w0(Y,{limit:Number.isFinite(U)&&U>0?U:void 0,before:Number.isFinite(Q)&&Q>=0?Q:void 0}),F={run:$,events:X.events,eventsOffset:X.offset,totalEvents:X.total};return L(F)}if(N.method!=="POST")return Z(405,"Method not allowed");switch(G){case"stop":return await J1(Y)?L({ok:!0}):Z(409,"Run is not active");case"resume":{let $=await M(N);A($.prompt,"prompt");try{let U=await UH(Y,$.prompt,Array.isArray($.attachments)?$.attachments:void 0,{sandbox:$.sandbox,approvalPolicy:$.approvalPolicy,approvalsReviewer:$.approvalsReviewer,model:$.model,effort:$.effort});return L({run:U})}catch(U){let Q=U instanceof Error?U.message:String(U),X=Q.includes("not found")?404:Q.includes("still active")?409:400;return Z(X,Q)}}case"steer":{let $=await M(N);A($.prompt,"prompt");try{return await V1(Y,$.prompt,Array.isArray($.attachments)?$.attachments:void 0),L({ok:!0})}catch(U){let Q=U instanceof Error?U.message:String(U),X=Q.includes("not found")?404:Q.includes("not active")||Q.includes("No active turn")?409:400;return Z(X,Q)}}case"fast":{let $=await M(N);if(typeof $.enabled!=="boolean")return Z(400,"Missing or invalid field: enabled");try{let U=await M1(Y,$.enabled);return L({run:U})}catch(U){let Q=U instanceof Error?U.message:String(U),X=Q.includes("not found")?404:Q.includes("does not support")?400:500;return Z(X,Q)}}case"compact":try{return await K1(Y),L({ok:!0})}catch($){let U=$ instanceof Error?$.message:String($),Q=U.includes("not found")?404:U.includes("still active")?409:400;return Z(Q,U)}case"review":{let $=await M(N);try{let U=await A1(Y,$.instructions);return L({run:U})}catch(U){let Q=U instanceof Error?U.message:String(U),X=Q.includes("not found")?404:Q.includes("still active")?409:400;return Z(X,Q)}}case"approve":{let $=await M(N);if(!eW.has(String($.decision)))return Z(400,`Invalid decision: ${String($.decision)}`);if($.requestId===void 0||$.requestId===null)return Z(400,"Missing field: requestId");return await B1(Y,$.requestId,$.decision)?L({ok:!0}):Z(404,"No matching pending approval")}default:return Z(404,`Unknown runs endpoint: ${H.pathname}`)}}var YN="browser-stream",m=null,g1=null,MN=0,KN=null,cH=null;function NY(N){if(m&&g1===N&&m.readyState<=WebSocket.OPEN)return;m?.close(),g1=N;let H=new WebSocket(`ws://127.0.0.1:${N}`);m=H,H.onmessage=(O)=>{let W=String(O.data);if(W.includes('"type":"frame"'))cH=W;A0(YN,W)},H.onclose=()=>{if(m===H)m=null,cH=null,v1()},H.onerror=()=>{}}function v1(){if(KN||MN===0)return;KN=setTimeout(()=>{KN=null,gN(!0)},2000)}async function gN(N=!1){if(MN===0)return;let H=N?null:n0();if(H===null){if(N)HN();H=(await fN()).streamPort}if(H!==null)NY(H);else v1()}function h1(){MN+=1,gN()}function m1(){return cH}function c1(){if(MN=Math.max(0,MN-1),MN===0){if(m?.close(),m=null,KN)clearTimeout(KN),KN=null}}var HY=new Set(["input_mouse","input_keyboard","input_touch"]);function l1(N){if(i0()!=="user")return;if(!m||m.readyState!==WebSocket.OPEN)return;let H=typeof N==="string"?N:N.toString("utf8");try{let O=JSON.parse(H);if(typeof O.type==="string"&&HY.has(O.type))m.send(H)}catch{}}var OY=new Set(["user","agent","paused"]);async function u1(N,H,O){let Y=H.pathname.split("/").filter(Boolean)[2];if(Y==="stream")return O.upgrade(N,{data:{channel:YN}})?void 0:Z(400,"WebSocket upgrade required");if(N.method==="GET")switch(Y){case"status":{let G=await fN();if(G.streaming)gN();return L({status:G})}case"actions":{let G={actions:u0()};return L(G)}default:return Z(404,`Unknown browser endpoint: ${H.pathname}`)}if(N.method!=="POST")return Z(405,"Method not allowed");switch(Y){case"start":{let G=await M(N).catch(()=>({})),$=await d0(typeof G.url==="string"&&G.url.length>0?G.url:void 0);return gN(),L({status:$})}case"stop":return await s0(),L({ok:!0});case"navigate":{let G=await M(N);return A(G.url,"url"),await t0(G.url),L({ok:!0})}case"key":{let G=await M(N);return A(G.key,"key"),await e0(G.key),L({ok:!0})}case"back":case"forward":case"reload":return await r0(Y),L({ok:!0});case"screenshot":{let $={path:await N1()};return L($)}case"control":{let G=await M(N);if(!OY.has(String(G.controller)))return Z(400,`Invalid controller: ${String(G.controller)}`);return p0(G.controller),L({ok:!0})}default:return Z(404,`Unknown browser endpoint: ${H.pathname}`)}}import{promises as P}from"fs";import E from"path";var n1=".agents/skills";function AN(N){return E.join(J(N),n1)}var WY=/^[a-z0-9][a-z0-9-]*$/,YY=new Set(["registry","install"]);function JN(N,H){if(!WY.test(N))throw new B(`Invalid skill id "${N}" \u2014 use lowercase letters, digits and dashes`);return E.join(AN(H),N)}function i1(N){return N.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"")}async function a1(N,H,O=120000){let W=Bun.spawn([process.execPath,"x","skills",...N],{cwd:H,env:{...process.env,DISABLE_TELEMETRY:"1",DO_NOT_TRACK:"1"},stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>W.kill(),O);try{let[G,$,U]=await Promise.all([new Response(W.stdout).text(),new Response(W.stderr).text(),W.exited]);return{stdout:i1(G),stderr:i1($),code:U}}finally{clearTimeout(Y)}}function GY(N){let H=[],O=null;for(let W of N.split(/\r?\n/)){let Y=W.trim(),G=/^(\S+@\S+)\s+([\d.]+[KMB]?)\s+installs\b/.exec(Y);if(G){let U=G[1],Q=U.indexOf("@");O={source:U,repo:U.slice(0,Q),name:U.slice(Q+1),installs:G[2]},H.push(O);continue}let $=/^[\u2514\u2570]\s*(https?:\/\/\S+)/.exec(Y);if($&&O)O.url=$[1],O=null}return H}function $Y(N){let H=[],O=/^---\r?\n([\s\S]*?)\r?\n---/.exec(N.replace(/^\uFEFF/,""));if(!O)return{errors:["Missing YAML frontmatter (--- name/description ---)"]};let W={};for(let Y of O[1].split(/\r?\n/)){let G=/^([A-Za-z_][\w-]*):\s*(.*)$/.exec(Y);if(G)W[G[1].toLowerCase()]=G[2].trim().replace(/^["']|["']$/g,"")}if(!W.name)H.push("Frontmatter is missing required field: name");if(!W.description)H.push("Frontmatter is missing required field: description");return{name:W.name,description:W.description,errors:H}}var UY=15000,uH=new Map,lH=new Map;function vN(N){uH.delete(N)}async function QY(N){let H=uH.get(N);if(H&&Date.now()-H.at<UY)return H.view;let O=lH.get(N);if(O)return O;let W=XY(N).then((Y)=>{return uH.set(N,{at:Date.now(),view:Y}),Y}).finally(()=>{lH.delete(N)});return lH.set(N,W),W}async function XY(N){let H=new Map,O=[];try{let W=await C("skills/list",{cwds:[J(N)],forceReload:!0});for(let Y of W.data??[]){for(let G of Y.errors??[])O.push(G);for(let G of Y.skills??[]){let $=E.basename(E.dirname(G.path));H.set($,G)}}}catch(W){console.warn("[skills] skills/list failed:",W)}return{byDir:H,errors:O}}async function XH(N=z){await P.mkdir(AN(N),{recursive:!0});let O=(await P.readdir(AN(N),{withFileTypes:!0})).filter((U)=>U.isDirectory()).map((U)=>U.name),{byDir:W,errors:Y}=await QY(N),G=[];for(let U of O){let Q=E.join(AN(N),U,"SKILL.md"),X=null;try{X=await P.readFile(Q,"utf8")}catch{G.push({id:U,name:U,description:"",enabled:!1,errors:["Missing SKILL.md"]});continue}let F=$Y(X),K=W.get(U),R=Y.filter((f)=>l(f.path).includes(`/${U}/`)||E.basename(E.dirname(f.path))===U).map((f)=>f.message);G.push({id:U,name:K?.name??F.name??U,description:K?.description??F.description??"",enabled:K?.enabled??!0,errors:[...new Set([...F.errors,...R])]})}let $=Y.filter((U)=>!O.some((Q)=>l(U.path).includes(`/${Q}/`)));return{skills:G,errors:$}}async function hN(N,H=z){let O=JN(N,H),W;try{W=await P.readFile(E.join(O,"SKILL.md"),"utf8")}catch{return null}let{skills:Y}=await XH(H),G=Y.find((Q)=>Q.id===N)??{id:N,name:N,description:"",enabled:!0,errors:[]},$=[],U=async(Q)=>{let X=await P.readdir(E.join(O,Q),{withFileTypes:!0});for(let F of X){let K=Q?`${Q}/${F.name}`:F.name;if(F.isDirectory())await U(K);else if(K!=="SKILL.md")$.push(`${n1}/${N}/${K}`)}};return await U(""),{info:G,content:W,files:$}}async function o1(N,H=z){let O=N.name.trim().toLowerCase().replace(/\s+/g,"-");if(YY.has(O))throw new B(`"${O}" is a reserved name \u2014 pick another`);let W=JN(O,H);try{throw await P.access(E.join(W,"SKILL.md")),new B(`Skill "${O}" already exists`)}catch(G){if(G instanceof B)throw G}let Y=`---
|
|
330
330
|
name: ${O}
|
|
331
331
|
description: ${N.description.trim()}
|
|
332
332
|
---
|
|
333
333
|
|
|
334
334
|
${N.instructions?.trim()??"Describe when and how to use this skill."}
|
|
335
|
-
`;return await P.mkdir(W,{recursive:!0}),await P.writeFile(E.join(W,"SKILL.md"),Y,"utf8"),vN(H),await hN(O,H)}async function
|
|
335
|
+
`;return await P.mkdir(W,{recursive:!0}),await P.writeFile(E.join(W,"SKILL.md"),Y,"utf8"),vN(H),await hN(O,H)}async function d1(N,H,O=z){let W=JN(N,O);try{await P.access(W)}catch{throw new B(`Skill not found: ${N}`)}return await P.writeFile(E.join(W,"SKILL.md"),H,"utf8"),vN(O),await hN(N,O)}async function s1(N,H=z){let O=JN(N,H);try{return await P.rm(O,{recursive:!0,force:!1}),vN(H),!0}catch{return!1}}async function t1(N,H,O=z){let W=E.join(JN(N,O),"SKILL.md");await C("skills/config/write",{path:W,enabled:H,name:null}),vN(O)}async function r1(N){let H=N.trim();if(!H)return[];let{stdout:O}=await a1(["find",H],J(z),30000);return GY(O)}async function p1(N){await P.mkdir(AN(N),{recursive:!0});let H=await P.readdir(AN(N),{withFileTypes:!0});return new Set(H.filter((O)=>O.isDirectory()).map((O)=>O.name))}async function e1(N,H=z){let O=N.trim();if(!O)throw new B("Missing skill source");if(/[\s;&|`$(){}<>]/.test(O))throw new B("Invalid source \u2014 expected owner/repo[@skill] or a URL");let W=J(H),Y=await p1(H),{stdout:G,stderr:$}=await a1(["add",O,"-a","codex","--copy","-y"],W);vN(H);let Q=[...await p1(H)].filter((F)=>!Y.has(F));if(Q.length===0){let F=[G,$].filter(Boolean).join(`
|
|
336
336
|
`).trim();throw new B(`No skill installed from "${O}".${F?`
|
|
337
|
-
${F}`:""}`)}let{skills:X}=await
|
|
338
|
-
`).trim()}}async function r1(N,H,O=z){let W=await hN(N,O);if(!W)throw new B(`Skill not found: ${N}`);let Y={prompt:H?.trim()||`Use the "${W.info.name}" skill to demonstrate what it does. Follow its instructions and report the result.`,projectId:O,skill:{name:W.info.name,path:E.join(JN(N,O),"SKILL.md")}};return LN(Y)}async function QY(N){let H=N.searchParams.get("project");if(H)return H;let O=N.searchParams.get("cwd");if(O){let W=uN(O);if(W&&await VN(W))return W}return z}async function e1(N,H){let O=H.pathname.split("/").filter(Boolean),W=O[2],Y=O[3],G=await QY(H);if(W==="registry"){if(Y==="search"&&N.method==="GET"){let $=H.searchParams.get("q")??"",U=await s1($);return L({results:U})}if(Y==="install"&&N.method==="POST"){let $=await K(N);A($.source,"source");let U=await t1($.source,G);return L(U,201)}return Z(404,`Unknown skills endpoint: ${H.pathname}`)}if(!W){if(N.method==="GET")return L(await QH(G));if(N.method==="POST"){let $=await K(N);A($.name,"name"),A($.description,"description");let U=await n1($,G);return L({skill:U},201)}return Z(405,"Method not allowed")}if(!Y)switch(N.method){case"GET":{let $=await hN(W,G);return $?L({skill:$}):Z(404,`Skill not found: ${W}`)}case"PUT":{let $=await K(N);A($.content,"content");let U=await a1(W,$.content,G);return L({skill:U})}case"DELETE":return await o1(W,G)?L({ok:!0}):Z(404,`Skill not found: ${W}`);default:return Z(405,"Method not allowed")}if(N.method!=="POST")return Z(405,"Method not allowed");switch(Y){case"enable":{let $=await K(N);if(typeof $.enabled!=="boolean")return Z(400,"Missing or invalid field: enabled");return await d1(W,$.enabled,G),L({ok:!0})}case"test":{let $=await K(N).catch(()=>({})),U=await r1(W,$.prompt,G);return L({run:U},201)}default:return Z(404,`Unknown skills endpoint: ${H.pathname}`)}}async function NO(N,H){let O=H.pathname.split("/").filter(Boolean),W=O[2];if(!W){if(N.method==="GET")return L(await D1());return Z(405,"Method not allowed")}if(W==="config"){if(N.method==="GET"){let Y={toml:await p()};return L(Y)}if(N.method==="PUT"){let Y=await K(N);return A(Y.toml,"toml"),await B1(Y.toml),L({ok:!0})}return Z(405,"Method not allowed")}if(W==="reload"&&N.method==="POST")return await T1(),L({ok:!0});if(W==="servers"){let Y=O[3];if(!Y){if(N.method==="POST"){let $=await K(N);return A($.name,"name"),await C1($),L({ok:!0},201)}return Z(405,"Method not allowed")}let G=O[4];if(G==="enable"&&N.method==="POST"){let $=await K(N);if(typeof $.enabled!=="boolean")return Z(400,"Missing or invalid field: enabled");return await R1(Y,$.enabled),L({ok:!0})}if(!G&&N.method==="DELETE")return await S1(Y)?L({ok:!0}):Z(404,`Server not found: ${Y}`);return Z(405,"Method not allowed")}return Z(404,`Unknown MCP endpoint: ${H.pathname}`)}import{promises as GN}from"fs";import mN from"path";function XY(){return mN.join(q(),"config.toml")}function ZH(){return mN.join(q(),"memories")}async function HO(){let N=await p();return N.trim()?c(N):{}}function XH(N){return typeof N==="object"&&N!==null?N:{}}function ZY(N){let H=XH(N.memories),O={};if(typeof H.generate_memories==="boolean")O.generateMemories=H.generate_memories;if(typeof H.use_memories==="boolean")O.useMemories=H.use_memories;if(typeof H.disable_on_external_context==="boolean")O.disableOnExternalContext=H.disable_on_external_context;if(typeof H.min_rate_limit_remaining_percent==="number")O.minRateLimitRemainingPercent=H.min_rate_limit_remaining_percent;return O}async function LY(){let N=ZH(),H=[];async function O(W){let Y;try{Y=await GN.readdir(W,{withFileTypes:!0})}catch{return}for(let G of Y){let $=mN.join(W,G.name);if(G.isDirectory()){if(G.name===".git")continue;await O($)}else if(G.isFile()){let U=await GN.stat($);H.push({path:l(mN.relative(N,$)),name:G.name,size:U.size,modifiedAt:U.mtime.toISOString()})}}}return await O(N),H.sort((W,Y)=>Y.modifiedAt.localeCompare(W.modifiedAt)),H}async function FY(){try{let H=((await C("experimentalFeature/list",{})).data??[]).find((O)=>O.name==="memories");return H?H.enabled:null}catch(N){return console.warn("[memories] experimentalFeature/list failed:",N),null}}async function OO(){let N=await HO();return{enabled:XH(N.features).memories===!0,liveEnabled:await FY(),settings:ZY(N),files:await LY()}}async function WO(N){let H=await HO();if(typeof N.enabled==="boolean"){let O=XH(H.features);O.memories=N.enabled,H.features=O}if(N.settings){let O=XH(H.memories),W=N.settings;if(typeof W.generateMemories==="boolean")O.generate_memories=W.generateMemories;if(typeof W.useMemories==="boolean")O.use_memories=W.useMemories;if(typeof W.disableOnExternalContext==="boolean")O.disable_on_external_context=W.disableOnExternalContext;if(typeof W.minRateLimitRemainingPercent==="number")O.min_rate_limit_remaining_percent=W.minRateLimitRemainingPercent;H.memories=O}if(await GN.writeFile(XY(),d(H),"utf8"),typeof N.enabled==="boolean")try{await C("experimentalFeature/enablement/set",{enablement:{memories:N.enabled}})}catch(O){console.warn("[memories] live enablement/set failed (applies on restart):",O)}}async function YO(N){let H=e(ZH(),N);return GN.readFile(H,"utf8")}async function GO(N,H){let O=e(ZH(),N);await GN.mkdir(mN.dirname(O),{recursive:!0}),await GN.writeFile(O,H,"utf8")}async function $O(N){let H=e(ZH(),N);await GN.rm(H)}async function UO(N,H){let W=H.pathname.split("/").filter(Boolean)[2];if(!W){if(N.method==="GET")return L(await OO());return Z(405,"Method not allowed")}if(W==="config"){if(N.method==="PUT"){let Y=await K(N);if(typeof Y.enabled!=="boolean"&&!Y.settings)return Z(400,"Nothing to update: pass enabled and/or settings");return await WO(Y),L({ok:!0})}return Z(405,"Method not allowed")}if(W==="file"){if(N.method==="GET"){let Y=A(H.searchParams.get("path"),"path"),G={path:Y,content:await YO(Y)};return L(G)}if(N.method==="PUT"){let Y=await K(N);if(A(Y.path,"path"),typeof Y.content!=="string")return Z(400,"Missing or invalid field: content");return await GO(Y.path,Y.content),L({ok:!0})}if(N.method==="DELETE"){let Y=A(H.searchParams.get("path"),"path");return await $O(Y),L({ok:!0})}return Z(405,"Method not allowed")}return Z(404,`Unknown memories endpoint: ${H.pathname}`)}var VY=300000,LH=null;async function QO(N){if(N.method!=="GET")return Z(405,"Method not allowed");if(LH&&Date.now()-LH.at<VY)return L({models:LH.models});let O=((await C("model/list",{})).data??[]).filter((Y)=>!Y.hidden).map((Y)=>({id:Y.id,model:Y.model,displayName:Y.displayName,description:Y.description,isDefault:Y.isDefault,defaultReasoningEffort:Y.defaultReasoningEffort,supportedReasoningEfforts:Y.supportedReasoningEfforts??[]}));return LH={at:Date.now(),models:O},L({models:O})}async function FH(){let N=await C("account/read",{});return{account:N.account??null,requiresOpenaiAuth:N.requiresOpenaiAuth,pendingLogin:WH(),lastLoginResult:O1()}}async function XO(N,H){if(H.pathname==="/api/account"){if(N.method!=="GET")return Z(405,"Method not allowed");return L(await FH())}if(H.pathname==="/api/account/login"&&N.method==="POST"){let O=await K(N),W;if(O.type==="chatgpt"||O.type==="chatgptDeviceCode")W={type:O.type};else if(O.type==="apiKey")W={type:"apiKey",apiKey:A(O.apiKey,"apiKey")};else throw new B("type must be one of: chatgpt, chatgptDeviceCode, apiKey");let Y=WH();if(Y)await C("account/login/cancel",{loginId:Y.loginId}).catch(()=>{});YH();let G=await C("account/login/start",W);if((G.type==="chatgpt"||G.type==="chatgptDeviceCode")&&G.loginId){let $={loginId:G.loginId,type:G.type,authUrl:G.authUrl,userCode:G.userCode,verificationUrl:G.verificationUrl,startedAt:new Date().toISOString()};W1($)}return L(await FH())}if(H.pathname==="/api/account/login/cancel"&&N.method==="POST"){let O=WH();if(O)await C("account/login/cancel",{loginId:O.loginId}).catch(()=>{});return YH(),L(await FH())}if(H.pathname==="/api/account/logout"&&N.method==="POST")return await C("account/logout",{}),YH(),L(await FH());return Z(404,`Not found: ${H.pathname}`)}function KY(N){if(!N)return null;return N.replace(/^([a-z0-9+.-]+:\/\/[^:@/]+):[^@/]+@/i,"$1:\u2022\u2022\u2022\u2022@")}function ZO(){let N=xH(),H=kH();return{browserProxy:{proxyUrl:KY(N.value),source:N.source,noProxy:H.value,noProxySource:H.source}}}async function LO(N,H){if(H.pathname==="/api/settings"&&N.method==="GET")return L(ZO());if(H.pathname==="/api/settings/browser-proxy"&&N.method==="PUT"){let O=await K(N);if(O.proxyUrl!==void 0&&O.proxyUrl!==null&&O.proxyUrl.trim())try{if(!new URL(O.proxyUrl.trim()).hostname)throw Error("missing host")}catch{return Z(400,"Invalid proxy URL \u2014 expected e.g. http://user:pass@host:port")}return await x0({...O.proxyUrl!==void 0?{browserProxy:O.proxyUrl}:{},...O.noProxy!==void 0?{browserNoProxy:O.noProxy}:{}}),L(ZO())}if(N.method!=="GET"&&N.method!=="PUT")return Z(405,"Method not allowed");return Z(404,`Unknown settings endpoint: ${H.pathname}`)}import{promises as BN}from"fs";import JO from"path";import{randomUUID as SY}from"crypto";function cN(N,H,O,W){let Y=new Set,G=N.trim()!=="*";for(let $ of N.split(",")){let U=$.trim();if(!U)throw Error(`Invalid ${W} field: empty term`);let Q=U,X=1,F=U.indexOf("/");if(F!==-1){if(Q=U.slice(0,F),X=Number(U.slice(F+1)),!Number.isInteger(X)||X<=0)throw Error(`Invalid step in ${W}: ${U}`)}let M,R;if(Q==="*")M=H,R=O;else if(Q.includes("-")){let[f,$N]=Q.split("-");M=Number(f),R=Number($N)}else M=Number(Q),R=M;if(!Number.isInteger(M)||!Number.isInteger(R))throw Error(`Invalid ${W} value: ${U}`);if(M<H||R>O||M>R)throw Error(`${W} out of range (${H}-${O}): ${U}`);for(let f=M;f<=R;f+=X)Y.add(f)}return{set:Y,restricted:G}}function VO(N){let H=N.trim().split(/\s+/);if(H.length!==5)throw Error(`Cron must have 5 fields (min hour dom month dow); got ${H.length}`);let O=cN(H[0],0,59,"minute"),W=cN(H[1],0,23,"hour"),Y=cN(H[2],1,31,"day-of-month"),G=cN(H[3],1,12,"month"),$=cN(H[4],0,7,"day-of-week"),U=new Set;for(let Q of $.set)U.add(Q===7?0:Q);return{minute:O.set,hour:W.set,dom:Y.set,month:G.set,dow:U,domRestricted:Y.restricted,dowRestricted:$.restricted}}function KO(N){try{return VO(N),null}catch(H){return H instanceof Error?H.message:"Invalid cron expression"}}function MY(N){return new Intl.DateTimeFormat("en-US",{timeZone:N,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"})}function MO(N,H){if(!H)return{year:N.getFullYear(),month:N.getMonth()+1,day:N.getDate(),hour:N.getHours(),minute:N.getMinutes(),second:N.getSeconds()};let O={};for(let W of MY(H).formatToParts(N))if(W.type!=="literal")O[W.type]=Number(W.value);return{year:O.year,month:O.month,day:O.day,hour:O.hour,minute:O.minute,second:O.second}}function AY(N,H){return new Date(Date.UTC(N,H,0)).getUTCDate()}function JY(N){return new Date(Date.UTC(N.year,N.month-1,N.day)).getUTCDay()}function FO(N){if(N.minute++,N.minute<60)return;if(N.minute=0,N.hour++,N.hour<24)return;if(N.hour=0,N.day++,N.day<=AY(N.year,N.month))return;if(N.day=1,N.month++,N.month<=12)return;N.month=1,N.year++}function BY(N,H){if(!N.minute.has(H.minute))return!1;if(!N.hour.has(H.hour))return!1;if(!N.month.has(H.month))return!1;let O=N.dom.has(H.day),W=N.dow.has(JY(H));if(N.domRestricted&&N.dowRestricted)return O||W;if(N.domRestricted)return O;if(N.dowRestricted)return W;return!0}function zO(N,H){let O=MO(N,H);return Date.UTC(O.year,O.month-1,O.day,O.hour,O.minute,O.second)-N.getTime()}function DY(N,H){if(!H)return new Date(N.year,N.month-1,N.day,N.hour,N.minute,0,0);let O=Date.UTC(N.year,N.month-1,N.day,N.hour,N.minute,0),W=zO(new Date(O),H),Y=O-W,G=zO(new Date(Y),H);if(G!==W)Y=O-G;return new Date(Y)}var CY=4216320;function AO(N,H,O){let W=VO(N),Y=MO(H,O),G={year:Y.year,month:Y.month,day:Y.day,hour:Y.hour,minute:Y.minute};FO(G);for(let $=0;$<CY;$++){if(BY(W,G))return DY(G,O);FO(G)}return null}var RY={sandbox:"workspaceWrite",approvalPolicy:"onRequest",approvalsReviewer:"auto_review",effort:"medium"};function TY(N){return N.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}function iH(N){return JO.join(DN(),`${N}.json`)}async function BO(){await BN.mkdir(DN(),{recursive:!0})}async function pH(N){await BO(),await BN.writeFile(iH(N.id),JSON.stringify(N,null,2),"utf8")}function nH(N,H){if(!N.enabled)return null;if(N.kind==="once"){if(!N.runAt)return null;let W=new Date(N.runAt);if(Number.isNaN(W.getTime()))return null;if(N.lastRunAt)return null;return W.toISOString()}if(!N.cron)return null;let O=AO(N.cron,H,N.tz);return O?O.toISOString():null}function DO(N,H){if(H==="cron"){if(!N.cron)throw Error("cron expression is required for a cron schedule");let O=KO(N.cron);if(O)throw Error(`Invalid cron expression: ${O}`)}else{if(!N.runAt)throw Error("runAt is required for a one-off schedule");if(Number.isNaN(new Date(N.runAt).getTime()))throw Error("runAt is not a valid datetime")}if(N.tz)try{new Intl.DateTimeFormat("en-US",{timeZone:N.tz})}catch{throw Error(`Unknown timezone: ${N.tz}`)}}async function aH(N){await BO();let H;try{H=await BN.readdir(DN())}catch{return[]}let O=[];for(let W of H){if(!W.endsWith(".json"))continue;try{let Y=await BN.readFile(JO.join(DN(),W),"utf8"),G=JSON.parse(Y);if(N&&G.projectId!==N)continue;O.push(G)}catch{}}return O.sort((W,Y)=>Y.createdAt.localeCompare(W.createdAt)),O}async function zH(N){try{let H=await BN.readFile(iH(N),"utf8");return JSON.parse(H)}catch{return null}}async function CO(N){let H=N.name?.trim();if(!H)throw Error("Schedule name is required");if(!N.prompt?.trim())throw Error("Schedule prompt is required");let O=N.projectId??"default";if(!await VN(O))throw Error(`Unknown project: ${O}`);let W=N.kind??"cron";DO(N,W);let Y=`${TY(H)||"schedule"}-${SY().slice(0,8)}`,G=new Date,$={id:Y,name:H,projectId:O,prompt:N.prompt,kind:W,cron:W==="cron"?N.cron:void 0,runAt:W==="once"?new Date(N.runAt).toISOString():void 0,tz:N.tz,mode:{...RY,...N.mode??{}},resume:N.resume??!1,threadRunId:null,enabled:N.enabled??!0,createdAt:G.toISOString(),lastRunAt:null,lastRunId:null,lastError:null,nextRunAt:null};return $.nextRunAt=nH($,G),await pH($),$}async function SO(N,H){let O=await zH(N);if(!O)return null;let W=H.kind??O.kind,Y={...O,name:H.name?.trim()||O.name,prompt:H.prompt??O.prompt,kind:W,cron:W==="cron"?H.cron??O.cron:void 0,runAt:W==="once"?H.runAt?new Date(H.runAt).toISOString():O.runAt:void 0,tz:H.tz!==void 0?H.tz||void 0:O.tz,mode:H.mode?{...O.mode,...H.mode}:O.mode,resume:H.resume??O.resume,enabled:H.enabled??O.enabled};if(DO(Y,W),W==="once"&&H.runAt&&Y.runAt!==O.runAt)Y.lastRunAt=null;return Y.nextRunAt=nH(Y,new Date),await pH(Y),Y}async function RO(N){try{return await BN.unlink(iH(N)),!0}catch{return!1}}function EY(N){return{sandbox:N.sandbox,approvalPolicy:N.approvalPolicy,approvalsReviewer:N.approvalsReviewer,model:N.model,effort:N.effort}}async function oH(N,H){let O=N.lastRunId??null,W=null,Y=N.threadRunId??null;try{let $=N.mode;if(N.resume&&Y&&await D(Y)){let U=await D(Y);if(U&&g(U.status))throw Error("previous run still active \u2014 skipped this fire");O=(await $H(Y,N.prompt,[],EY($))).id}else{let U=await LN({prompt:N.prompt,projectId:N.projectId,sandbox:$.sandbox,approvalPolicy:$.approvalPolicy,approvalsReviewer:$.approvalsReviewer,model:$.model,effort:$.effort,source:"schedule",scheduleId:N.id,scheduleName:N.name});if(O=U.id,N.resume)Y=U.id}}catch($){W=$ instanceof Error?$.message:String($)}let G={...N,lastRunAt:H.toISOString(),lastRunId:O,lastError:W,threadRunId:Y};return G.nextRunAt=nH(G,H),await pH(G),G}var uH=!1;async function TO(N=new Date){if(uH)return;uH=!0;try{let H=await aH();for(let O of H){if(!O.enabled||!O.nextRunAt)continue;let W=new Date(O.nextRunAt);if(Number.isNaN(W.getTime())||W.getTime()>N.getTime())continue;try{await oH(O,N)}catch(Y){console.error(`[schedules] fire failed for ${O.id}:`,Y)}}}catch(H){console.error("[schedules] tick failed:",H)}finally{uH=!1}}async function EO(N){let H=N.searchParams.get("project");if(H)return H;let O=N.searchParams.get("cwd");if(O){let W=uN(O);if(W&&await VN(W))return W;return z}return}async function _O(N,H){let O=H.pathname.split("/").filter(Boolean),W=O[2],Y=O[3];if(!W){if(N.method==="GET"){let G=await EO(H),$={schedules:await aH(G)};return L($)}if(N.method==="POST"){let G=await K(N);if(!G.projectId){let $=await EO(H);if($)G.projectId=$}try{let U={schedule:await CO(G)};return L(U,201)}catch($){return Z(400,$ instanceof Error?$.message:String($))}}return Z(405,"Method not allowed")}if(Y==="run"&&N.method==="POST"){let G=await zH(W);if(!G)return Z(404,`Schedule not found: ${W}`);let U={schedule:await oH(G,new Date)};return L(U)}if(Y)return Z(404,`Not found: ${H.pathname}`);if(N.method==="GET"){let G=await zH(W);return G?L({schedule:G}):Z(404,`Schedule not found: ${W}`)}if(N.method==="PUT"){let G=await K(N);try{let $=await SO(W,G);return $?L({schedule:$}):Z(404,`Schedule not found: ${W}`)}catch($){return Z(400,$ instanceof Error?$.message:String($))}}if(N.method==="DELETE")return await RO(W)?L({ok:!0}):Z(404,`Schedule not found: ${W}`);return Z(405,"Method not allowed")}async function wO(N,H){let O=new URL(N.url);try{if(O.pathname==="/api/health")return _1();if(O.pathname==="/api/status")return w1();if(O.pathname==="/api/files/watch")return H.upgrade(N,{data:{channel:"files"}})?void 0:Z(400,"WebSocket upgrade required");if(O.pathname.startsWith("/api/files/"))return await P1(N,O);if(O.pathname==="/api/projects"||O.pathname.startsWith("/api/projects/"))return await b1(N,O);if(O.pathname==="/api/runs"||O.pathname.startsWith("/api/runs/"))return await q1(N,O,H);if(O.pathname.startsWith("/api/browser/"))return await c1(N,O,H);if(O.pathname==="/api/skills"||O.pathname.startsWith("/api/skills/"))return await e1(N,O);if(O.pathname==="/api/mcp"||O.pathname.startsWith("/api/mcp/"))return await NO(N,O);if(O.pathname==="/api/memories"||O.pathname.startsWith("/api/memories/"))return await UO(N,O);if(O.pathname==="/api/models")return await QO(N);if(O.pathname==="/api/account"||O.pathname.startsWith("/api/account/"))return await XO(N,O);if(O.pathname==="/api/settings"||O.pathname.startsWith("/api/settings/"))return await LO(N,O);if(O.pathname==="/api/schedules"||O.pathname.startsWith("/api/schedules/"))return await _O(N,O);return Z(404,`Not found: ${O.pathname}`)}catch(W){if(W instanceof oN)return Z(400,W.message);if(W instanceof B)return Z(400,W.message);if(wY(W))return Z(404,`Not found: ${O.searchParams.get("path")??O.pathname}`);return console.error(`[api] ${N.method} ${O.pathname} failed:`,W),Z(500,W instanceof Error?W.message:"Internal error")}}function wY(N){return typeof N==="object"&&N!==null&&"code"in N&&N.code==="ENOENT"}await rH();var VH=[k.resolve(import.meta.dir,"../ui-dist"),k.resolve(import.meta.dir,"../../ui/dist")].find((N)=>PO(k.join(N,"index.html")))??k.resolve(import.meta.dir,"../../ui/dist");try{let N=["mcp-server.ts","mcp-server.js"].map((H)=>k.join(import.meta.dir,H)).find((H)=>PO(H));if(N)await E1(N,lN);else console.warn("[daemon] mcp-server script not found next to daemon entry")}catch(N){console.warn("[daemon] could not register Jun MCP server:",N)}m0(k.join(import.meta.dir,".."));var xO=Bun.serve({hostname:MH,port:lN,async fetch(N,H){let O=new URL(N.url);if(O.pathname.startsWith("/api/"))return wO(N,H);let W=await xY(O.pathname);if(W)return W;return new Response("Jun daemon is running. Build the UI to enable the dashboard.",{status:200})},websocket:{idleTimeout:960,open(N){if(N.subscribe(N.data.channel),N.data.channel===YN){g1();let H=v1();if(H)N.send(H)}},message(N,H){if(N.data.channel===YN)m1(H)},close(N){if(N.unsubscribe(N.data.channel),N.data.channel===YN)h1()}}});K0(xO);try{PY(UN(),{recursive:!0},(N,H)=>{let O={type:"fs.changed",path:H?l(String(H)):null,ts:new Date().toISOString()};xO.publish("files",JSON.stringify(O))})}catch(N){console.warn("[daemon] workspace watcher unavailable:",N)}var fY=30000;setInterval(()=>{TO()},fY);console.log(`Jun daemon running at http://${MH}:${lN}`);console.log(`Workspace: ${k.resolve(J())}`);async function xY(N){let H=k.join(VH,"index.html");if(!await kY(H))return null;let O=k.normalize(decodeURIComponent(N)).replace(/^[/\\]+/,""),W=k.resolve(VH,O||"index.html"),Y=`${VH}${k.sep}`;if(W!==VH&&!W.startsWith(Y))return new Response("Not found",{status:404});if(await yY(W))return new Response(Bun.file(W),{headers:{"content-type":bY(W)}});return new Response(Bun.file(H),{headers:{"content-type":"text/html; charset=utf-8"}})}async function kY(N){try{return await fO(N),!0}catch{return!1}}async function yY(N){try{return(await fO(N)).isFile()}catch{return!1}}function bY(N){switch(k.extname(N)){case".css":return"text/css; charset=utf-8";case".html":return"text/html; charset=utf-8";case".js":return"text/javascript; charset=utf-8";case".json":return"application/json; charset=utf-8";case".svg":return"image/svg+xml";case".webp":return"image/webp";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".ico":return"image/x-icon";default:return"application/octet-stream"}}
|
|
337
|
+
${F}`:""}`)}let{skills:X}=await XH(H);return{installed:Q,skills:X,log:[G,$].filter(Boolean).join(`
|
|
338
|
+
`).trim()}}async function NO(N,H,O=z){let W=await hN(N,O);if(!W)throw new B(`Skill not found: ${N}`);let Y={prompt:H?.trim()||`Use the "${W.info.name}" skill to demonstrate what it does. Follow its instructions and report the result.`,projectId:O,skill:{name:W.info.name,path:E.join(JN(N,O),"SKILL.md")}};return LN(Y)}async function LY(N){let H=N.searchParams.get("project");if(H)return H;let O=N.searchParams.get("cwd");if(O){let W=uN(O);if(W&&await VN(W))return W}return z}async function HO(N,H){let O=H.pathname.split("/").filter(Boolean),W=O[2],Y=O[3],G=await LY(H);if(W==="registry"){if(Y==="search"&&N.method==="GET"){let $=H.searchParams.get("q")??"",U=await r1($);return L({results:U})}if(Y==="install"&&N.method==="POST"){let $=await M(N);A($.source,"source");let U=await e1($.source,G);return L(U,201)}return Z(404,`Unknown skills endpoint: ${H.pathname}`)}if(!W){if(N.method==="GET")return L(await XH(G));if(N.method==="POST"){let $=await M(N);A($.name,"name"),A($.description,"description");let U=await o1($,G);return L({skill:U},201)}return Z(405,"Method not allowed")}if(!Y)switch(N.method){case"GET":{let $=await hN(W,G);return $?L({skill:$}):Z(404,`Skill not found: ${W}`)}case"PUT":{let $=await M(N);A($.content,"content");let U=await d1(W,$.content,G);return L({skill:U})}case"DELETE":return await s1(W,G)?L({ok:!0}):Z(404,`Skill not found: ${W}`);default:return Z(405,"Method not allowed")}if(N.method!=="POST")return Z(405,"Method not allowed");switch(Y){case"enable":{let $=await M(N);if(typeof $.enabled!=="boolean")return Z(400,"Missing or invalid field: enabled");return await t1(W,$.enabled,G),L({ok:!0})}case"test":{let $=await M(N).catch(()=>({})),U=await NO(W,$.prompt,G);return L({run:U},201)}default:return Z(404,`Unknown skills endpoint: ${H.pathname}`)}}async function OO(N,H){let O=H.pathname.split("/").filter(Boolean),W=O[2];if(!W){if(N.method==="GET")return L(await S1());return Z(405,"Method not allowed")}if(W==="config"){if(N.method==="GET"){let Y={toml:await p()};return L(Y)}if(N.method==="PUT"){let Y=await M(N);return A(Y.toml,"toml"),await C1(Y.toml),L({ok:!0})}return Z(405,"Method not allowed")}if(W==="reload"&&N.method==="POST")return await _1(),L({ok:!0});if(W==="servers"){let Y=O[3];if(!Y){if(N.method==="POST"){let $=await M(N);return A($.name,"name"),await R1($),L({ok:!0},201)}return Z(405,"Method not allowed")}let G=O[4];if(G==="enable"&&N.method==="POST"){let $=await M(N);if(typeof $.enabled!=="boolean")return Z(400,"Missing or invalid field: enabled");return await E1(Y,$.enabled),L({ok:!0})}if(!G&&N.method==="DELETE")return await T1(Y)?L({ok:!0}):Z(404,`Server not found: ${Y}`);return Z(405,"Method not allowed")}return Z(404,`Unknown MCP endpoint: ${H.pathname}`)}import{promises as GN}from"fs";import mN from"path";function FY(){return mN.join(q(),"config.toml")}function LH(){return mN.join(q(),"memories")}async function WO(){let N=await p();return N.trim()?c(N):{}}function ZH(N){return typeof N==="object"&&N!==null?N:{}}function zY(N){let H=ZH(N.memories),O={};if(typeof H.generate_memories==="boolean")O.generateMemories=H.generate_memories;if(typeof H.use_memories==="boolean")O.useMemories=H.use_memories;if(typeof H.disable_on_external_context==="boolean")O.disableOnExternalContext=H.disable_on_external_context;if(typeof H.min_rate_limit_remaining_percent==="number")O.minRateLimitRemainingPercent=H.min_rate_limit_remaining_percent;return O}async function VY(){let N=LH(),H=[];async function O(W){let Y;try{Y=await GN.readdir(W,{withFileTypes:!0})}catch{return}for(let G of Y){let $=mN.join(W,G.name);if(G.isDirectory()){if(G.name===".git")continue;await O($)}else if(G.isFile()){let U=await GN.stat($);H.push({path:l(mN.relative(N,$)),name:G.name,size:U.size,modifiedAt:U.mtime.toISOString()})}}}return await O(N),H.sort((W,Y)=>Y.modifiedAt.localeCompare(W.modifiedAt)),H}async function MY(){try{let H=((await C("experimentalFeature/list",{})).data??[]).find((O)=>O.name==="memories");return H?H.enabled:null}catch(N){return console.warn("[memories] experimentalFeature/list failed:",N),null}}async function YO(){let N=await WO();return{enabled:ZH(N.features).memories===!0,liveEnabled:await MY(),settings:zY(N),files:await VY()}}async function GO(N){let H=await WO();if(typeof N.enabled==="boolean"){let O=ZH(H.features);O.memories=N.enabled,H.features=O}if(N.settings){let O=ZH(H.memories),W=N.settings;if(typeof W.generateMemories==="boolean")O.generate_memories=W.generateMemories;if(typeof W.useMemories==="boolean")O.use_memories=W.useMemories;if(typeof W.disableOnExternalContext==="boolean")O.disable_on_external_context=W.disableOnExternalContext;if(typeof W.minRateLimitRemainingPercent==="number")O.min_rate_limit_remaining_percent=W.minRateLimitRemainingPercent;H.memories=O}if(await GN.writeFile(FY(),d(H),"utf8"),typeof N.enabled==="boolean")try{await C("experimentalFeature/enablement/set",{enablement:{memories:N.enabled}})}catch(O){console.warn("[memories] live enablement/set failed (applies on restart):",O)}}async function $O(N){let H=e(LH(),N);return GN.readFile(H,"utf8")}async function UO(N,H){let O=e(LH(),N);await GN.mkdir(mN.dirname(O),{recursive:!0}),await GN.writeFile(O,H,"utf8")}async function QO(N){let H=e(LH(),N);await GN.rm(H)}async function XO(N,H){let W=H.pathname.split("/").filter(Boolean)[2];if(!W){if(N.method==="GET")return L(await YO());return Z(405,"Method not allowed")}if(W==="config"){if(N.method==="PUT"){let Y=await M(N);if(typeof Y.enabled!=="boolean"&&!Y.settings)return Z(400,"Nothing to update: pass enabled and/or settings");return await GO(Y),L({ok:!0})}return Z(405,"Method not allowed")}if(W==="file"){if(N.method==="GET"){let Y=A(H.searchParams.get("path"),"path"),G={path:Y,content:await $O(Y)};return L(G)}if(N.method==="PUT"){let Y=await M(N);if(A(Y.path,"path"),typeof Y.content!=="string")return Z(400,"Missing or invalid field: content");return await UO(Y.path,Y.content),L({ok:!0})}if(N.method==="DELETE"){let Y=A(H.searchParams.get("path"),"path");return await QO(Y),L({ok:!0})}return Z(405,"Method not allowed")}return Z(404,`Unknown memories endpoint: ${H.pathname}`)}var AY=300000,FH=null;async function ZO(N){if(N.method!=="GET")return Z(405,"Method not allowed");if(FH&&Date.now()-FH.at<AY)return L({models:FH.models});let O=((await C("model/list",{})).data??[]).filter((Y)=>!Y.hidden).map((Y)=>({id:Y.id,model:Y.model,displayName:Y.displayName,description:Y.description,isDefault:Y.isDefault,defaultReasoningEffort:Y.defaultReasoningEffort,supportedReasoningEfforts:Y.supportedReasoningEfforts??[]}));return FH={at:Date.now(),models:O},L({models:O})}async function zH(){let N=await C("account/read",{});return{account:N.account??null,requiresOpenaiAuth:N.requiresOpenaiAuth,pendingLogin:YH(),lastLoginResult:Y1()}}async function LO(N,H){if(H.pathname==="/api/account"){if(N.method!=="GET")return Z(405,"Method not allowed");return L(await zH())}if(H.pathname==="/api/account/login"&&N.method==="POST"){let O=await M(N),W;if(O.type==="chatgpt"||O.type==="chatgptDeviceCode")W={type:O.type};else if(O.type==="apiKey")W={type:"apiKey",apiKey:A(O.apiKey,"apiKey")};else throw new B("type must be one of: chatgpt, chatgptDeviceCode, apiKey");let Y=YH();if(Y)await C("account/login/cancel",{loginId:Y.loginId}).catch(()=>{});GH();let G=await C("account/login/start",W);if((G.type==="chatgpt"||G.type==="chatgptDeviceCode")&&G.loginId){let $={loginId:G.loginId,type:G.type,authUrl:G.authUrl,userCode:G.userCode,verificationUrl:G.verificationUrl,startedAt:new Date().toISOString()};G1($)}return L(await zH())}if(H.pathname==="/api/account/login/cancel"&&N.method==="POST"){let O=YH();if(O)await C("account/login/cancel",{loginId:O.loginId}).catch(()=>{});return GH(),L(await zH())}if(H.pathname==="/api/account/logout"&&N.method==="POST")return await C("account/logout",{}),GH(),L(await zH());return Z(404,`Not found: ${H.pathname}`)}function JY(N){if(!N)return null;return N.replace(/^([a-z0-9+.-]+:\/\/[^:@/]+):[^@/]+@/i,"$1:\u2022\u2022\u2022\u2022@")}function FO(){let N=kH(),H=yH();return{browserProxy:{proxyUrl:JY(N.value),source:N.source,noProxy:H.value,noProxySource:H.source}}}async function zO(N,H){if(H.pathname==="/api/settings"&&N.method==="GET")return L(FO());if(H.pathname==="/api/settings/browser-proxy"&&N.method==="PUT"){let O=await M(N);if(O.proxyUrl!==void 0&&O.proxyUrl!==null&&O.proxyUrl.trim())try{if(!new URL(O.proxyUrl.trim()).hostname)throw Error("missing host")}catch{return Z(400,"Invalid proxy URL \u2014 expected e.g. http://user:pass@host:port")}return await y0({...O.proxyUrl!==void 0?{browserProxy:O.proxyUrl}:{},...O.noProxy!==void 0?{browserNoProxy:O.noProxy}:{}}),L(FO())}if(N.method!=="GET"&&N.method!=="PUT")return Z(405,"Method not allowed");return Z(404,`Unknown settings endpoint: ${H.pathname}`)}import{promises as BN}from"fs";import DO from"path";import{randomUUID as EY}from"crypto";function cN(N,H,O,W){let Y=new Set,G=N.trim()!=="*";for(let $ of N.split(",")){let U=$.trim();if(!U)throw Error(`Invalid ${W} field: empty term`);let Q=U,X=1,F=U.indexOf("/");if(F!==-1){if(Q=U.slice(0,F),X=Number(U.slice(F+1)),!Number.isInteger(X)||X<=0)throw Error(`Invalid step in ${W}: ${U}`)}let K,R;if(Q==="*")K=H,R=O;else if(Q.includes("-")){let[f,$N]=Q.split("-");K=Number(f),R=Number($N)}else K=Number(Q),R=K;if(!Number.isInteger(K)||!Number.isInteger(R))throw Error(`Invalid ${W} value: ${U}`);if(K<H||R>O||K>R)throw Error(`${W} out of range (${H}-${O}): ${U}`);for(let f=K;f<=R;f+=X)Y.add(f)}return{set:Y,restricted:G}}function KO(N){let H=N.trim().split(/\s+/);if(H.length!==5)throw Error(`Cron must have 5 fields (min hour dom month dow); got ${H.length}`);let O=cN(H[0],0,59,"minute"),W=cN(H[1],0,23,"hour"),Y=cN(H[2],1,31,"day-of-month"),G=cN(H[3],1,12,"month"),$=cN(H[4],0,7,"day-of-week"),U=new Set;for(let Q of $.set)U.add(Q===7?0:Q);return{minute:O.set,hour:W.set,dom:Y.set,month:G.set,dow:U,domRestricted:Y.restricted,dowRestricted:$.restricted}}function AO(N){try{return KO(N),null}catch(H){return H instanceof Error?H.message:"Invalid cron expression"}}function BY(N){return new Intl.DateTimeFormat("en-US",{timeZone:N,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"})}function JO(N,H){if(!H)return{year:N.getFullYear(),month:N.getMonth()+1,day:N.getDate(),hour:N.getHours(),minute:N.getMinutes(),second:N.getSeconds()};let O={};for(let W of BY(H).formatToParts(N))if(W.type!=="literal")O[W.type]=Number(W.value);return{year:O.year,month:O.month,day:O.day,hour:O.hour,minute:O.minute,second:O.second}}function DY(N,H){return new Date(Date.UTC(N,H,0)).getUTCDate()}function CY(N){return new Date(Date.UTC(N.year,N.month-1,N.day)).getUTCDay()}function VO(N){if(N.minute++,N.minute<60)return;if(N.minute=0,N.hour++,N.hour<24)return;if(N.hour=0,N.day++,N.day<=DY(N.year,N.month))return;if(N.day=1,N.month++,N.month<=12)return;N.month=1,N.year++}function SY(N,H){if(!N.minute.has(H.minute))return!1;if(!N.hour.has(H.hour))return!1;if(!N.month.has(H.month))return!1;let O=N.dom.has(H.day),W=N.dow.has(CY(H));if(N.domRestricted&&N.dowRestricted)return O||W;if(N.domRestricted)return O;if(N.dowRestricted)return W;return!0}function MO(N,H){let O=JO(N,H);return Date.UTC(O.year,O.month-1,O.day,O.hour,O.minute,O.second)-N.getTime()}function RY(N,H){if(!H)return new Date(N.year,N.month-1,N.day,N.hour,N.minute,0,0);let O=Date.UTC(N.year,N.month-1,N.day,N.hour,N.minute,0),W=MO(new Date(O),H),Y=O-W,G=MO(new Date(Y),H);if(G!==W)Y=O-G;return new Date(Y)}var TY=4216320;function BO(N,H,O){let W=KO(N),Y=JO(H,O),G={year:Y.year,month:Y.month,day:Y.day,hour:Y.hour,minute:Y.minute};VO(G);for(let $=0;$<TY;$++){if(SY(W,G))return RY(G,O);VO(G)}return null}var _Y={sandbox:"workspaceWrite",approvalPolicy:"onRequest",approvalsReviewer:"auto_review",effort:"medium"};function wY(N){return N.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}function pH(N){return DO.join(DN(),`${N}.json`)}async function CO(){await BN.mkdir(DN(),{recursive:!0})}async function nH(N){await CO(),await BN.writeFile(pH(N.id),JSON.stringify(N,null,2),"utf8")}function aH(N,H){if(!N.enabled)return null;if(N.kind==="once"){if(!N.runAt)return null;let W=new Date(N.runAt);if(Number.isNaN(W.getTime()))return null;if(N.lastRunAt)return null;return W.toISOString()}if(!N.cron)return null;let O=BO(N.cron,H,N.tz);return O?O.toISOString():null}function SO(N,H){if(H==="cron"){if(!N.cron)throw Error("cron expression is required for a cron schedule");let O=AO(N.cron);if(O)throw Error(`Invalid cron expression: ${O}`)}else{if(!N.runAt)throw Error("runAt is required for a one-off schedule");if(Number.isNaN(new Date(N.runAt).getTime()))throw Error("runAt is not a valid datetime")}if(N.tz)try{new Intl.DateTimeFormat("en-US",{timeZone:N.tz})}catch{throw Error(`Unknown timezone: ${N.tz}`)}}async function oH(N){await CO();let H;try{H=await BN.readdir(DN())}catch{return[]}let O=[];for(let W of H){if(!W.endsWith(".json"))continue;try{let Y=await BN.readFile(DO.join(DN(),W),"utf8"),G=JSON.parse(Y);if(N&&G.projectId!==N)continue;O.push(G)}catch{}}return O.sort((W,Y)=>Y.createdAt.localeCompare(W.createdAt)),O}async function VH(N){try{let H=await BN.readFile(pH(N),"utf8");return JSON.parse(H)}catch{return null}}async function RO(N){let H=N.name?.trim();if(!H)throw Error("Schedule name is required");if(!N.prompt?.trim())throw Error("Schedule prompt is required");let O=N.projectId??"default";if(!await VN(O))throw Error(`Unknown project: ${O}`);let W=N.kind??"cron";SO(N,W);let Y=`${wY(H)||"schedule"}-${EY().slice(0,8)}`,G=new Date,$={id:Y,name:H,projectId:O,prompt:N.prompt,kind:W,cron:W==="cron"?N.cron:void 0,runAt:W==="once"?new Date(N.runAt).toISOString():void 0,tz:N.tz,mode:{..._Y,...N.mode??{}},resume:N.resume??!1,threadRunId:null,enabled:N.enabled??!0,createdAt:G.toISOString(),lastRunAt:null,lastRunId:null,lastError:null,nextRunAt:null};return $.nextRunAt=aH($,G),await nH($),$}async function TO(N,H){let O=await VH(N);if(!O)return null;let W=H.kind??O.kind,Y={...O,name:H.name?.trim()||O.name,prompt:H.prompt??O.prompt,kind:W,cron:W==="cron"?H.cron??O.cron:void 0,runAt:W==="once"?H.runAt?new Date(H.runAt).toISOString():O.runAt:void 0,tz:H.tz!==void 0?H.tz||void 0:O.tz,mode:H.mode?{...O.mode,...H.mode}:O.mode,resume:H.resume??O.resume,enabled:H.enabled??O.enabled};if(SO(Y,W),W==="once"&&H.runAt&&Y.runAt!==O.runAt)Y.lastRunAt=null;return Y.nextRunAt=aH(Y,new Date),await nH(Y),Y}async function EO(N){try{return await BN.unlink(pH(N)),!0}catch{return!1}}function PY(N){return{sandbox:N.sandbox,approvalPolicy:N.approvalPolicy,approvalsReviewer:N.approvalsReviewer,model:N.model,effort:N.effort}}async function dH(N,H){let O=N.lastRunId??null,W=null,Y=N.threadRunId??null;try{let $=N.mode;if(N.resume&&Y&&await D(Y)){let U=await D(Y);if(U&&g(U.status))throw Error("previous run still active \u2014 skipped this fire");O=(await UH(Y,N.prompt,[],PY($))).id}else{let U=await LN({prompt:N.prompt,projectId:N.projectId,sandbox:$.sandbox,approvalPolicy:$.approvalPolicy,approvalsReviewer:$.approvalsReviewer,model:$.model,effort:$.effort,source:"schedule",scheduleId:N.id,scheduleName:N.name});if(O=U.id,N.resume)Y=U.id}}catch($){W=$ instanceof Error?$.message:String($)}let G={...N,lastRunAt:H.toISOString(),lastRunId:O,lastError:W,threadRunId:Y};return G.nextRunAt=aH(G,H),await nH(G),G}var iH=!1;async function _O(N=new Date){if(iH)return;iH=!0;try{let H=await oH();for(let O of H){if(!O.enabled||!O.nextRunAt)continue;let W=new Date(O.nextRunAt);if(Number.isNaN(W.getTime())||W.getTime()>N.getTime())continue;try{await dH(O,N)}catch(Y){console.error(`[schedules] fire failed for ${O.id}:`,Y)}}}catch(H){console.error("[schedules] tick failed:",H)}finally{iH=!1}}async function wO(N){let H=N.searchParams.get("project");if(H)return H;let O=N.searchParams.get("cwd");if(O){let W=uN(O);if(W&&await VN(W))return W;return z}return}async function PO(N,H){let O=H.pathname.split("/").filter(Boolean),W=O[2],Y=O[3];if(!W){if(N.method==="GET"){let G=await wO(H),$={schedules:await oH(G)};return L($)}if(N.method==="POST"){let G=await M(N);if(!G.projectId){let $=await wO(H);if($)G.projectId=$}try{let U={schedule:await RO(G)};return L(U,201)}catch($){return Z(400,$ instanceof Error?$.message:String($))}}return Z(405,"Method not allowed")}if(Y==="run"&&N.method==="POST"){let G=await VH(W);if(!G)return Z(404,`Schedule not found: ${W}`);let U={schedule:await dH(G,new Date)};return L(U)}if(Y)return Z(404,`Not found: ${H.pathname}`);if(N.method==="GET"){let G=await VH(W);return G?L({schedule:G}):Z(404,`Schedule not found: ${W}`)}if(N.method==="PUT"){let G=await M(N);try{let $=await TO(W,G);return $?L({schedule:$}):Z(404,`Schedule not found: ${W}`)}catch($){return Z(400,$ instanceof Error?$.message:String($))}}if(N.method==="DELETE")return await EO(W)?L({ok:!0}):Z(404,`Schedule not found: ${W}`);return Z(405,"Method not allowed")}async function fO(N,H){let O=new URL(N.url);try{if(O.pathname==="/api/health")return P1();if(O.pathname==="/api/status")return f1();if(O.pathname==="/api/files/watch")return H.upgrade(N,{data:{channel:"files"}})?void 0:Z(400,"WebSocket upgrade required");if(O.pathname.startsWith("/api/files/"))return await x1(N,O);if(O.pathname==="/api/projects"||O.pathname.startsWith("/api/projects/"))return await I1(N,O);if(O.pathname==="/api/runs"||O.pathname.startsWith("/api/runs/"))return await j1(N,O,H);if(O.pathname.startsWith("/api/browser/"))return await u1(N,O,H);if(O.pathname==="/api/skills"||O.pathname.startsWith("/api/skills/"))return await HO(N,O);if(O.pathname==="/api/mcp"||O.pathname.startsWith("/api/mcp/"))return await OO(N,O);if(O.pathname==="/api/memories"||O.pathname.startsWith("/api/memories/"))return await XO(N,O);if(O.pathname==="/api/models")return await ZO(N);if(O.pathname==="/api/account"||O.pathname.startsWith("/api/account/"))return await LO(N,O);if(O.pathname==="/api/settings"||O.pathname.startsWith("/api/settings/"))return await zO(N,O);if(O.pathname==="/api/schedules"||O.pathname.startsWith("/api/schedules/"))return await PO(N,O);return Z(404,`Not found: ${O.pathname}`)}catch(W){if(W instanceof oN)return Z(400,W.message);if(W instanceof B)return Z(400,W.message);if(xY(W))return Z(404,`Not found: ${O.searchParams.get("path")??O.pathname}`);return console.error(`[api] ${N.method} ${O.pathname} failed:`,W),Z(500,W instanceof Error?W.message:"Internal error")}}function xY(N){return typeof N==="object"&&N!==null&&"code"in N&&N.code==="ENOENT"}await eH();var MH=[k.resolve(import.meta.dir,"../ui-dist"),k.resolve(import.meta.dir,"../../ui/dist")].find((N)=>xO(k.join(N,"index.html")))??k.resolve(import.meta.dir,"../../ui/dist");try{let N=["mcp-server.ts","mcp-server.js"].map((H)=>k.join(import.meta.dir,H)).find((H)=>xO(H));if(N)await w1(N,lN);else console.warn("[daemon] mcp-server script not found next to daemon entry")}catch(N){console.warn("[daemon] could not register Jun MCP server:",N)}l0(k.join(import.meta.dir,".."));var yO=Bun.serve({hostname:AH,port:lN,async fetch(N,H){let O=new URL(N.url);if(O.pathname.startsWith("/api/"))return fO(N,H);let W=await bY(O.pathname);if(W)return W;return new Response("Jun daemon is running. Build the UI to enable the dashboard.",{status:200})},websocket:{idleTimeout:960,open(N){if(N.subscribe(N.data.channel),N.data.channel===YN){h1();let H=m1();if(H)N.send(H)}},message(N,H){if(N.data.channel===YN)l1(H)},close(N){if(N.unsubscribe(N.data.channel),N.data.channel===YN)c1()}}});K0(yO);try{kY(UN(),{recursive:!0},(N,H)=>{let O={type:"fs.changed",path:H?l(String(H)):null,ts:new Date().toISOString()};yO.publish("files",JSON.stringify(O))})}catch(N){console.warn("[daemon] workspace watcher unavailable:",N)}var yY=30000;setInterval(()=>{_O()},yY);console.log(`Jun daemon running at http://${AH}:${lN}`);console.log(`Workspace: ${k.resolve(J())}`);async function bY(N){let H=k.join(MH,"index.html");if(!await qY(H))return null;let O=k.normalize(decodeURIComponent(N)).replace(/^[/\\]+/,""),W=k.resolve(MH,O||"index.html"),Y=`${MH}${k.sep}`;if(W!==MH&&!W.startsWith(Y))return new Response("Not found",{status:404});if(await IY(W))return new Response(Bun.file(W),{headers:{"content-type":jY(W)}});return new Response(Bun.file(H),{headers:{"content-type":"text/html; charset=utf-8"}})}async function qY(N){try{return await kO(N),!0}catch{return!1}}async function IY(N){try{return(await kO(N)).isFile()}catch{return!1}}function jY(N){switch(k.extname(N)){case".css":return"text/css; charset=utf-8";case".html":return"text/html; charset=utf-8";case".js":return"text/javascript; charset=utf-8";case".json":return"application/json; charset=utf-8";case".svg":return"image/svg+xml";case".webp":return"image/webp";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".ico":return"image/x-icon";default:return"application/octet-stream"}}
|