palmagent 0.0.1-alpha.0 → 0.1.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +32 -5
- package/build-info.json +5 -0
- package/cli.js +182 -14
- package/package.json +39 -10
- package/runner-daemon.js +4 -0
- package/server.js +140 -0
- package/web/apple-touch-icon.png +0 -0
- package/web/assets/index-BNAED-_N.css +1 -0
- package/web/assets/index-BTRpL0qQ.js +352 -0
- package/web/assets/workbox-window.prod.es5-BBnX5xw4.js +2 -0
- package/web/favicon.svg +11 -0
- package/web/icon-192.png +0 -0
- package/web/icon-512-maskable.png +0 -0
- package/web/icon-512.png +0 -0
- package/web/index.html +57 -0
- package/web/manifest.webmanifest +1 -0
- package/web/sw.js +2 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Palmagent
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,8 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Palmagent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Self-hosted dispatcher that drives the Claude Code and Codex CLIs headless on your own
|
|
4
|
+
host, normalizes their two event streams into one schema, and serves an installable,
|
|
5
|
+
mobile-first PWA over SSE (read) + REST (control).
|
|
4
6
|
|
|
5
|
-
|
|
6
|
-
The real tool isn't published yet — there's nothing to install or run for now.
|
|
7
|
+
## Requirements
|
|
7
8
|
|
|
8
|
-
|
|
9
|
+
- Node.js >= 22
|
|
10
|
+
- At least one of the `claude` or `codex` CLIs on PATH and authenticated
|
|
11
|
+
- A public domain pointing at this host (TLS + passkey auth need a real https origin)
|
|
12
|
+
- Linux with systemd + nginx and sudo (the installer writes units + an nginx vhost)
|
|
13
|
+
|
|
14
|
+
## Quickstart
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npm i -g palmagent@next
|
|
18
|
+
palmagent install --domain your.domain.example # systemd units, nginx, TLS, first passkey
|
|
19
|
+
palmagent doctor # diagnose a running instance
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Run the CLI as the unprivileged account that should own the agent processes; do not
|
|
23
|
+
prefix the whole command with sudo. If you install with `--data-dir`, pass that same
|
|
24
|
+
option to later setup, doctor, update, passkey, and uninstall commands.
|
|
25
|
+
|
|
26
|
+
## Commands
|
|
27
|
+
|
|
28
|
+
- `palmagent install` First-run setup: systemd units, nginx, TLS (certbot), first passkey
|
|
29
|
+
- `palmagent setup` Reconfigure an existing install + re-render units/nginx
|
|
30
|
+
- `palmagent doctor` Diagnose a running instance + suggest fixes
|
|
31
|
+
- `palmagent update` Apply config; `--pull` updates an npm install on its release channel
|
|
32
|
+
- `palmagent uninstall` Remove the units + nginx vhost (data preserved unless `--purge`)
|
|
33
|
+
- `palmagent passkey` Mint a fresh device-enroll link
|
|
34
|
+
|
|
35
|
+
Run `palmagent --help` for the full option list.
|
package/build-info.json
ADDED
package/cli.js
CHANGED
|
@@ -1,15 +1,183 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// palmagent — placeholder binary. Reserves the npm name; the real tool isn't
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
2
|
+
var es=Object.defineProperty;var R=(t,e)=>()=>(t&&(e=t(t=0)),e);var Lt=(t,e)=>{for(var n in e)es(t,n,{get:e[n],enumerable:!0})};var Tn=R(()=>{});function ns(t){let e=ts.exec(t);return e?{repo:e[1],number:Number(e[2])}:null}function Ut(t){let e=ns(t);return e?{url:t,number:e.number,repo:e.repo,status:"open",checks:"unknown"}:null}var ts,En=R(()=>{ts=/^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)/});var Mt,xn=R(()=>{Mt={claude:"acceptEdits",codex:"workspace-write"}});var Rn=R(()=>{});var _,wn=R(()=>{_={productName:"Palmagent",displayName:"PalmAgent",packageName:"palmagent",cliName:"palmagent",unitBase:"palmagent",stateDirName:"palmagent"}});var W=R(()=>{"use strict";Tn();En();xn();Rn();wn()});import{chmodSync as Sn,mkdirSync as An}from"node:fs";function Me(t){An(t,{recursive:!0,mode:448}),Sn(t,448)}function In(t){An(t,{recursive:!0,mode:448})}function je(t){Sn(t,384)}var Qe=R(()=>{});var E,jt,m,Y,et=R(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{let i={};for(let a of s)i[a]=a;return i},t.getValidEnumValues=s=>{let i=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(let o of i)a[o]=s[o];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(let a of s)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(E||(E={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(jt||(jt={}));m=E.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Y=t=>{switch(typeof t){case"undefined":return m.undefined;case"string":return m.string;case"number":return Number.isNaN(t)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(t)?m.array:t===null?m.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?m.promise:typeof Map<"u"&&t instanceof Map?m.map:typeof Set<"u"&&t instanceof Set?m.set:typeof Date<"u"&&t instanceof Date?m.date:m.object;default:return m.unknown}}});var c,rs,j,lt=R(()=>{et();c=E.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),rs=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),j=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let o=r,u=0;for(;u<a.path.length;){let d=a.path[u];u===a.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(n(a))):o[d]=o[d]||{_errors:[]},o=o[d],u++}}};return s(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,E.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};j.create=t=>new j(t)});var ss,te,Ft=R(()=>{lt();et();ss=(t,e)=>{let n;switch(t.code){case c.invalid_type:t.received===m.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case c.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,E.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:n=`Unrecognized key(s) in object: ${E.joinValues(t.keys,", ")}`;break;case c.invalid_union:n="Invalid input";break;case c.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${E.joinValues(t.options)}`;break;case c.invalid_enum_value:n=`Invalid enum value. Expected ${E.joinValues(t.options)}, received '${t.received}'`;break;case c.invalid_arguments:n="Invalid function arguments";break;case c.invalid_return_type:n="Invalid function return type";break;case c.invalid_date:n="Invalid date";break;case c.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:E.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case c.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case c.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case c.custom:n="Invalid input";break;case c.invalid_intersection_types:n="Intersection results could not be merged";break;case c.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case c.not_finite:n="Number must be finite";break;default:n=e.defaultError,E.assertNever(t)}return{message:n}},te=ss});function is(t){Nn=t}function Fe(){return Nn}var Nn,pt=R(()=>{Ft();Nn=te});function l(t,e){let n=Fe(),r=tt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===te?void 0:te].filter(s=>!!s)});t.common.issues.push(r)}var tt,as,L,y,me,U,ft,mt,oe,He,Ht=R(()=>{pt();Ft();tt=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let o="",u=r.filter(d=>!!d).slice().reverse();for(let d of u)o=d(a,{data:e,defaultError:o}).message;return{...s,path:i,message:o}},as=[];L=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return y;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let i=await s.key,a=await s.value;r.push({key:i,value:a})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return y;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}},y=Object.freeze({status:"aborted"}),me=t=>({status:"dirty",value:t}),U=t=>({status:"valid",value:t}),ft=t=>t.status==="aborted",mt=t=>t.status==="dirty",oe=t=>t.status==="valid",He=t=>typeof Promise<"u"&&t instanceof Promise});var Cn=R(()=>{});var h,On=R(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}))});function k(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{let{message:u}=t;return a.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??r??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:u??n??o.defaultError}},description:s}}function Ln(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Es(t){return new RegExp(`^${Ln(t)}$`)}function Un(t){let e=`${$n}T${Ln(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function xs(t,e){return!!((e==="v4"||!e)&&gs.test(t)||(e==="v6"||!e)&&ys.test(t))}function Rs(t,e){if(!ps.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function ws(t,e){return!!((e==="v4"||!e)&&_s.test(t)||(e==="v6"||!e)&&vs.test(t))}function Ss(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}function qe(t){if(t instanceof F){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=G.create(qe(r))}return new F({...t._def,shape:()=>e})}else return t instanceof se?new se({...t._def,type:qe(t.element)}):t instanceof G?G.create(qe(t.unwrap())):t instanceof ee?ee.create(qe(t.unwrap())):t instanceof Q?Q.create(t.items.map(e=>qe(e))):t}function Bt(t,e){let n=Y(t),r=Y(e);if(t===e)return{valid:!0,data:t};if(n===m.object&&r===m.object){let s=E.objectKeys(e),i=E.objectKeys(t).filter(o=>s.indexOf(o)!==-1),a={...t,...e};for(let o of i){let u=Bt(t[o],e[o]);if(!u.valid)return{valid:!1};a[o]=u.data}return{valid:!0,data:a}}else if(n===m.array&&r===m.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<t.length;i++){let a=t[i],o=e[i],u=Bt(a,o);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return n===m.date&&r===m.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Mn(t,e){return new Re({values:t,typeName:v.ZodEnum,...k(e)})}function Pn(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function jn(t,e={},n){return t?de.create().superRefine((r,s)=>{let i=t(r);if(i instanceof Promise)return i.then(a=>{if(!a){let o=Pn(e,r),u=o.fatal??n??!0;s.addIssue({code:"custom",...o,fatal:u})}});if(!i){let a=Pn(e,r),o=a.fatal??n??!0;s.addIssue({code:"custom",...a,fatal:o})}}):de.create()}var V,Dn,T,os,us,ds,cs,ls,ps,fs,ms,hs,qt,gs,_s,ys,vs,bs,ks,$n,Ts,ue,he,ge,_e,ye,Be,ve,be,de,re,J,We,se,F,ke,ne,ht,Te,Q,gt,Ge,Ve,_t,Ee,xe,Re,we,ce,X,G,ee,Se,Ae,Xe,As,nt,rt,Ie,Is,v,Ns,Fn,Hn,Cs,Os,qn,Ds,Ps,$s,Ls,Us,Ms,js,Fs,Hs,qs,Bs,Ws,Gs,Vs,Xs,Ks,Zs,zs,Js,Ys,Qs,ei,ti,ni,ri,si,ii,ai,oi,ui,di,ci,li,pi,Bn=R(()=>{lt();pt();On();Ht();et();V=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Dn=(t,e)=>{if(oe(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new j(t.common.issues);return this._error=n,this._error}}};T=class{get description(){return this._def.description}_getType(e){return Y(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Y(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new L,ctx:{common:e.parent.common,data:e.data,parsedType:Y(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(He(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Y(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Dn(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Y(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return oe(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>oe(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Y(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(He(s)?s:Promise.resolve(s));return Dn(r,i)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{let a=e(s),o=()=>i.addIssue({code:c.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new X({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return G.create(this,this._def)}nullable(){return ee.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return se.create(this)}promise(){return ce.create(this,this._def)}or(e){return ke.create([this,e],this._def)}and(e){return Te.create(this,e,this._def)}transform(e){return new X({...k(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Se({...k(this._def),innerType:this,defaultValue:n,typeName:v.ZodDefault})}brand(){return new nt({typeName:v.ZodBranded,type:this,...k(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Ae({...k(this._def),innerType:this,catchValue:n,typeName:v.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return rt.create(this,e)}readonly(){return Ie.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},os=/^c[^\s-]{8,}$/i,us=/^[0-9a-z]+$/,ds=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cs=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ls=/^[a-z0-9_-]{21}$/i,ps=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fs=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ms=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,hs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gs=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_s=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ys=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,vs=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ks=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$n="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ts=new RegExp(`^${$n}$`);ue=class t extends T{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_type,expected:m.string,received:i.parsedType}),y}let r=new L,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?l(s,{code:c.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&l(s,{code:c.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")ms.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"email",code:c.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")qt||(qt=new RegExp(hs,"u")),qt.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"emoji",code:c.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")cs.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"uuid",code:c.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")ls.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"nanoid",code:c.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")os.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"cuid",code:c.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")us.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"cuid2",code:c.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")ds.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"ulid",code:c.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),l(s,{validation:"url",code:c.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"regex",code:c.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Un(i).test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Ts.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Es(i).test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{code:c.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?fs.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"duration",code:c.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?xs(e.data,i.version)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"ip",code:c.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Rs(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"jwt",code:c.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?ws(e.data,i.version)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"cidr",code:c.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?bs.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"base64",code:c.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?ks.test(e.data)||(s=this._getOrReturnCtx(e,s),l(s,{validation:"base64url",code:c.invalid_string,message:i.message}),r.dirty()):E.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:c.invalid_string,...h.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...h.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...h.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...h.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...h.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...h.errToObj(n)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};ue.create=t=>new ue({checks:[],typeName:v.ZodString,coerce:t?.coerce??!1,...k(t)});he=class t extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==m.number){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_type,expected:m.number,received:i.parsedType}),y}let r,s=new L;for(let i of this._def.checks)i.kind==="int"?E.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{code:c.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:c.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:c.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?Ss(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),l(r,{code:c.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),l(r,{code:c.not_finite,message:i.message}),s.dirty()):E.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,h.toString(n))}gt(e,n){return this.setLimit("min",e,!1,h.toString(n))}lte(e,n){return this.setLimit("max",e,!0,h.toString(n))}lt(e,n){return this.setLimit("max",e,!1,h.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&E.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};he.create=t=>new he({checks:[],typeName:v.ZodNumber,coerce:t?.coerce||!1,...k(t)});ge=class t extends T{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==m.bigint)return this._getInvalidInput(e);let r,s=new L;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:c.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),l(r,{code:c.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),l(r,{code:c.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):E.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:m.bigint,received:n.parsedType}),y}gte(e,n){return this.setLimit("min",e,!0,h.toString(n))}gt(e,n){return this.setLimit("min",e,!1,h.toString(n))}lte(e,n){return this.setLimit("max",e,!0,h.toString(n))}lt(e,n){return this.setLimit("max",e,!1,h.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};ge.create=t=>new ge({checks:[],typeName:v.ZodBigInt,coerce:t?.coerce??!1,...k(t)});_e=class extends T{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){let r=this._getOrReturnCtx(e);return l(r,{code:c.invalid_type,expected:m.boolean,received:r.parsedType}),y}return U(e.data)}};_e.create=t=>new _e({typeName:v.ZodBoolean,coerce:t?.coerce||!1,...k(t)});ye=class t extends T{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_type,expected:m.date,received:i.parsedType}),y}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return l(i,{code:c.invalid_date}),y}let r=new L,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),l(s,{code:c.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):E.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};ye.create=t=>new ye({checks:[],coerce:t?.coerce||!1,typeName:v.ZodDate,...k(t)});Be=class extends T{_parse(e){if(this._getType(e)!==m.symbol){let r=this._getOrReturnCtx(e);return l(r,{code:c.invalid_type,expected:m.symbol,received:r.parsedType}),y}return U(e.data)}};Be.create=t=>new Be({typeName:v.ZodSymbol,...k(t)});ve=class extends T{_parse(e){if(this._getType(e)!==m.undefined){let r=this._getOrReturnCtx(e);return l(r,{code:c.invalid_type,expected:m.undefined,received:r.parsedType}),y}return U(e.data)}};ve.create=t=>new ve({typeName:v.ZodUndefined,...k(t)});be=class extends T{_parse(e){if(this._getType(e)!==m.null){let r=this._getOrReturnCtx(e);return l(r,{code:c.invalid_type,expected:m.null,received:r.parsedType}),y}return U(e.data)}};be.create=t=>new be({typeName:v.ZodNull,...k(t)});de=class extends T{constructor(){super(...arguments),this._any=!0}_parse(e){return U(e.data)}};de.create=t=>new de({typeName:v.ZodAny,...k(t)});re=class extends T{constructor(){super(...arguments),this._unknown=!0}_parse(e){return U(e.data)}};re.create=t=>new re({typeName:v.ZodUnknown,...k(t)});J=class extends T{_parse(e){let n=this._getOrReturnCtx(e);return l(n,{code:c.invalid_type,expected:m.never,received:n.parsedType}),y}};J.create=t=>new J({typeName:v.ZodNever,...k(t)});We=class extends T{_parse(e){if(this._getType(e)!==m.undefined){let r=this._getOrReturnCtx(e);return l(r,{code:c.invalid_type,expected:m.void,received:r.parsedType}),y}return U(e.data)}};We.create=t=>new We({typeName:v.ZodVoid,...k(t)});se=class t extends T{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==m.array)return l(n,{code:c.invalid_type,expected:m.array,received:n.parsedType}),y;if(s.exactLength!==null){let a=n.data.length>s.exactLength.value,o=n.data.length<s.exactLength.value;(a||o)&&(l(n,{code:a?c.too_big:c.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(l(n,{code:c.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(l(n,{code:c.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,o)=>s.type._parseAsync(new V(n,a,n.path,o)))).then(a=>L.mergeArray(r,a));let i=[...n.data].map((a,o)=>s.type._parseSync(new V(n,a,n.path,o)));return L.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:h.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:h.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:h.toString(n)}})}nonempty(e){return this.min(1,e)}};se.create=(t,e)=>new se({type:t,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...k(e)});F=class t extends T{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=E.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==m.object){let d=this._getOrReturnCtx(e);return l(d,{code:c.invalid_type,expected:m.object,received:d.parsedType}),y}let{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof J&&this._def.unknownKeys==="strip"))for(let d in s.data)a.includes(d)||o.push(d);let u=[];for(let d of a){let p=i[d],b=s.data[d];u.push({key:{status:"valid",value:d},value:p._parse(new V(s,b,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof J){let d=this._def.unknownKeys;if(d==="passthrough")for(let p of o)u.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")o.length>0&&(l(s,{code:c.unrecognized_keys,keys:o}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let p of o){let b=s.data[p];u.push({key:{status:"valid",value:p},value:d._parse(new V(s,b,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let p of u){let b=await p.key,A=await p.value;d.push({key:b,value:A,alwaysSet:p.alwaysSet})}return d}).then(d=>L.mergeObjectSync(r,d)):L.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of E.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of E.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return qe(this)}partial(e){let n={};for(let r of E.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of E.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof G;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Mn(E.objectKeys(this.shape))}};F.create=(t,e)=>new F({shape:()=>t,unknownKeys:"strip",catchall:J.create(),typeName:v.ZodObject,...k(e)});F.strictCreate=(t,e)=>new F({shape:()=>t,unknownKeys:"strict",catchall:J.create(),typeName:v.ZodObject,...k(e)});F.lazycreate=(t,e)=>new F({shape:t,unknownKeys:"strip",catchall:J.create(),typeName:v.ZodObject,...k(e)});ke=class extends T{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(let o of i)if(o.result.status==="valid")return o.result;for(let o of i)if(o.result.status==="dirty")return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(o=>new j(o.ctx.common.issues));return l(n,{code:c.invalid_union,unionErrors:a}),y}if(n.common.async)return Promise.all(r.map(async i=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i,a=[];for(let u of r){let d={...n,common:{...n.common,issues:[]},parent:null},p=u._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let o=a.map(u=>new j(u));return l(n,{code:c.invalid_union,unionErrors:o}),y}}get options(){return this._def.options}};ke.create=(t,e)=>new ke({options:t,typeName:v.ZodUnion,...k(e)});ne=t=>t instanceof Ee?ne(t.schema):t instanceof X?ne(t.innerType()):t instanceof xe?[t.value]:t instanceof Re?t.options:t instanceof we?E.objectValues(t.enum):t instanceof Se?ne(t._def.innerType):t instanceof ve?[void 0]:t instanceof be?[null]:t instanceof G?[void 0,...ne(t.unwrap())]:t instanceof ee?[null,...ne(t.unwrap())]:t instanceof nt||t instanceof Ie?ne(t.unwrap()):t instanceof Ae?ne(t._def.innerType):[],ht=class t extends T{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==m.object)return l(n,{code:c.invalid_type,expected:m.object,received:n.parsedType}),y;let r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(l(n,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let i of n){let a=ne(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,i)}}return new t({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...k(r)})}};Te=class extends T{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(i,a)=>{if(ft(i)||ft(a))return y;let o=Bt(i.value,a.value);return o.valid?((mt(i)||mt(a))&&n.dirty(),{status:n.value,value:o.data}):(l(r,{code:c.invalid_intersection_types}),y)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Te.create=(t,e,n)=>new Te({left:t,right:e,typeName:v.ZodIntersection,...k(n)});Q=class t extends T{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.array)return l(r,{code:c.invalid_type,expected:m.array,received:r.parsedType}),y;if(r.data.length<this._def.items.length)return l(r,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),y;!this._def.rest&&r.data.length>this._def.items.length&&(l(r,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((a,o)=>{let u=this._def.items[o]||this._def.rest;return u?u._parse(new V(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>L.mergeArray(n,a)):L.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Q.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Q({items:t,typeName:v.ZodTuple,rest:null,...k(e)})};gt=class t extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.object)return l(r,{code:c.invalid_type,expected:m.object,received:r.parsedType}),y;let s=[],i=this._def.keyType,a=this._def.valueType;for(let o in r.data)s.push({key:i._parse(new V(r,o,r.path,o)),value:a._parse(new V(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?L.mergeObjectAsync(n,s):L.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof T?new t({keyType:e,valueType:n,typeName:v.ZodRecord,...k(r)}):new t({keyType:ue.create(),valueType:e,typeName:v.ZodRecord,...k(n)})}},Ge=class extends T{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.map)return l(r,{code:c.invalid_type,expected:m.map,received:r.parsedType}),y;let s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([o,u],d)=>({key:s._parse(new V(r,o,r.path,[d,"key"])),value:i._parse(new V(r,u,r.path,[d,"value"]))}));if(r.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let u of a){let d=await u.key,p=await u.value;if(d.status==="aborted"||p.status==="aborted")return y;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),o.set(d.value,p.value)}return{status:n.value,value:o}})}else{let o=new Map;for(let u of a){let d=u.key,p=u.value;if(d.status==="aborted"||p.status==="aborted")return y;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),o.set(d.value,p.value)}return{status:n.value,value:o}}}};Ge.create=(t,e,n)=>new Ge({valueType:e,keyType:t,typeName:v.ZodMap,...k(n)});Ve=class t extends T{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==m.set)return l(r,{code:c.invalid_type,expected:m.set,received:r.parsedType}),y;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(l(r,{code:c.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(l(r,{code:c.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let i=this._def.valueType;function a(u){let d=new Set;for(let p of u){if(p.status==="aborted")return y;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}let o=[...r.data.values()].map((u,d)=>i._parse(new V(r,u,r.path,d)));return r.common.async?Promise.all(o).then(u=>a(u)):a(o)}min(e,n){return new t({...this._def,minSize:{value:e,message:h.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:h.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Ve.create=(t,e)=>new Ve({valueType:t,minSize:null,maxSize:null,typeName:v.ZodSet,...k(e)});_t=class t extends T{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==m.function)return l(n,{code:c.invalid_type,expected:m.function,received:n.parsedType}),y;function r(o,u){return tt({data:o,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Fe(),te].filter(d=>!!d),issueData:{code:c.invalid_arguments,argumentsError:u}})}function s(o,u){return tt({data:o,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Fe(),te].filter(d=>!!d),issueData:{code:c.invalid_return_type,returnTypeError:u}})}let i={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof ce){let o=this;return U(async function(...u){let d=new j([]),p=await o._def.args.parseAsync(u,i).catch(D=>{throw d.addIssue(r(u,D)),d}),b=await Reflect.apply(a,this,p);return await o._def.returns._def.type.parseAsync(b,i).catch(D=>{throw d.addIssue(s(b,D)),d})})}else{let o=this;return U(function(...u){let d=o._def.args.safeParse(u,i);if(!d.success)throw new j([r(u,d.error)]);let p=Reflect.apply(a,this,d.data),b=o._def.returns.safeParse(p,i);if(!b.success)throw new j([s(p,b.error)]);return b.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Q.create(e).rest(re.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Q.create([]).rest(re.create()),returns:n||re.create(),typeName:v.ZodFunction,...k(r)})}},Ee=class extends T{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ee.create=(t,e)=>new Ee({getter:t,typeName:v.ZodLazy,...k(e)});xe=class extends T{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return l(n,{received:n.data,code:c.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}};xe.create=(t,e)=>new xe({value:t,typeName:v.ZodLiteral,...k(e)});Re=class t extends T{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return l(n,{expected:E.joinValues(r),received:n.parsedType,code:c.invalid_type}),y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return l(n,{received:n.data,code:c.invalid_enum_value,options:r}),y}return U(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Re.create=Mn;we=class extends T{_parse(e){let n=E.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==m.string&&r.parsedType!==m.number){let s=E.objectValues(n);return l(r,{expected:E.joinValues(s),received:r.parsedType,code:c.invalid_type}),y}if(this._cache||(this._cache=new Set(E.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=E.objectValues(n);return l(r,{received:r.data,code:c.invalid_enum_value,options:s}),y}return U(e.data)}get enum(){return this._def.values}};we.create=(t,e)=>new we({values:t,typeName:v.ZodNativeEnum,...k(e)});ce=class extends T{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==m.promise&&n.common.async===!1)return l(n,{code:c.invalid_type,expected:m.promise,received:n.parsedType}),y;let r=n.parsedType===m.promise?n.data:Promise.resolve(n.data);return U(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};ce.create=(t,e)=>new ce({type:t,typeName:v.ZodPromise,...k(e)});X=class extends T{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{l(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async o=>{if(n.value==="aborted")return y;let u=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return u.status==="aborted"?y:u.status==="dirty"?me(u.value):n.value==="dirty"?me(u.value):u});{if(n.value==="aborted")return y;let o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?y:o.status==="dirty"?me(o.value):n.value==="dirty"?me(o.value):o}}if(s.type==="refinement"){let a=o=>{let u=s.refinement(o,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?y:(o.status==="dirty"&&n.dirty(),a(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?y:(o.status==="dirty"&&n.dirty(),a(o.value).then(()=>({status:n.value,value:o.value}))))}if(s.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!oe(a))return y;let o=s.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>oe(a)?Promise.resolve(s.transform(a.value,i)).then(o=>({status:n.value,value:o})):y);E.assertNever(s)}};X.create=(t,e,n)=>new X({schema:t,typeName:v.ZodEffects,effect:e,...k(n)});X.createWithPreprocess=(t,e,n)=>new X({schema:e,effect:{type:"preprocess",transform:t},typeName:v.ZodEffects,...k(n)});G=class extends T{_parse(e){return this._getType(e)===m.undefined?U(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};G.create=(t,e)=>new G({innerType:t,typeName:v.ZodOptional,...k(e)});ee=class extends T{_parse(e){return this._getType(e)===m.null?U(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ee.create=(t,e)=>new ee({innerType:t,typeName:v.ZodNullable,...k(e)});Se=class extends T{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===m.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Se.create=(t,e)=>new Se({innerType:t,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...k(e)});Ae=class extends T{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return He(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new j(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new j(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ae.create=(t,e)=>new Ae({innerType:t,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...k(e)});Xe=class extends T{_parse(e){if(this._getType(e)!==m.nan){let r=this._getOrReturnCtx(e);return l(r,{code:c.invalid_type,expected:m.nan,received:r.parsedType}),y}return{status:"valid",value:e.data}}};Xe.create=t=>new Xe({typeName:v.ZodNaN,...k(t)});As=Symbol("zod_brand"),nt=class extends T{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},rt=class t extends T{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?y:i.status==="dirty"?(n.dirty(),me(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?y:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:v.ZodPipeline})}},Ie=class extends T{_parse(e){let n=this._def.innerType._parse(e),r=s=>(oe(s)&&(s.value=Object.freeze(s.value)),s);return He(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Ie.create=(t,e)=>new Ie({innerType:t,typeName:v.ZodReadonly,...k(e)});Is={object:F.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(v||(v={}));Ns=(t,e={message:`Input not instance of ${t.name}`})=>jn(n=>n instanceof t,e),Fn=ue.create,Hn=he.create,Cs=Xe.create,Os=ge.create,qn=_e.create,Ds=ye.create,Ps=Be.create,$s=ve.create,Ls=be.create,Us=de.create,Ms=re.create,js=J.create,Fs=We.create,Hs=se.create,qs=F.create,Bs=F.strictCreate,Ws=ke.create,Gs=ht.create,Vs=Te.create,Xs=Q.create,Ks=gt.create,Zs=Ge.create,zs=Ve.create,Js=_t.create,Ys=Ee.create,Qs=xe.create,ei=Re.create,ti=we.create,ni=ce.create,ri=X.create,si=G.create,ii=ee.create,ai=X.createWithPreprocess,oi=rt.create,ui=()=>Fn().optional(),di=()=>Hn().optional(),ci=()=>qn().optional(),li={string:t=>ue.create({...t,coerce:!0}),number:t=>he.create({...t,coerce:!0}),boolean:t=>_e.create({...t,coerce:!0}),bigint:t=>ge.create({...t,coerce:!0}),date:t=>ye.create({...t,coerce:!0})},pi=y});var g={};Lt(g,{BRAND:()=>As,DIRTY:()=>me,EMPTY_PATH:()=>as,INVALID:()=>y,NEVER:()=>pi,OK:()=>U,ParseStatus:()=>L,Schema:()=>T,ZodAny:()=>de,ZodArray:()=>se,ZodBigInt:()=>ge,ZodBoolean:()=>_e,ZodBranded:()=>nt,ZodCatch:()=>Ae,ZodDate:()=>ye,ZodDefault:()=>Se,ZodDiscriminatedUnion:()=>ht,ZodEffects:()=>X,ZodEnum:()=>Re,ZodError:()=>j,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>_t,ZodIntersection:()=>Te,ZodIssueCode:()=>c,ZodLazy:()=>Ee,ZodLiteral:()=>xe,ZodMap:()=>Ge,ZodNaN:()=>Xe,ZodNativeEnum:()=>we,ZodNever:()=>J,ZodNull:()=>be,ZodNullable:()=>ee,ZodNumber:()=>he,ZodObject:()=>F,ZodOptional:()=>G,ZodParsedType:()=>m,ZodPipeline:()=>rt,ZodPromise:()=>ce,ZodReadonly:()=>Ie,ZodRecord:()=>gt,ZodSchema:()=>T,ZodSet:()=>Ve,ZodString:()=>ue,ZodSymbol:()=>Be,ZodTransformer:()=>X,ZodTuple:()=>Q,ZodType:()=>T,ZodUndefined:()=>ve,ZodUnion:()=>ke,ZodUnknown:()=>re,ZodVoid:()=>We,addIssueToContext:()=>l,any:()=>Us,array:()=>Hs,bigint:()=>Os,boolean:()=>qn,coerce:()=>li,custom:()=>jn,date:()=>Ds,datetimeRegex:()=>Un,defaultErrorMap:()=>te,discriminatedUnion:()=>Gs,effect:()=>ri,enum:()=>ei,function:()=>Js,getErrorMap:()=>Fe,getParsedType:()=>Y,instanceof:()=>Ns,intersection:()=>Vs,isAborted:()=>ft,isAsync:()=>He,isDirty:()=>mt,isValid:()=>oe,late:()=>Is,lazy:()=>Ys,literal:()=>Qs,makeIssue:()=>tt,map:()=>Zs,nan:()=>Cs,nativeEnum:()=>ti,never:()=>js,null:()=>Ls,nullable:()=>ii,number:()=>Hn,object:()=>qs,objectUtil:()=>jt,oboolean:()=>ci,onumber:()=>di,optional:()=>si,ostring:()=>ui,pipeline:()=>oi,preprocess:()=>ai,promise:()=>ni,quotelessJson:()=>rs,record:()=>Ks,set:()=>zs,setErrorMap:()=>is,strictObject:()=>Bs,string:()=>Fn,symbol:()=>Ps,transformer:()=>ri,tuple:()=>Xs,undefined:()=>$s,union:()=>Ws,unknown:()=>Ms,util:()=>E,void:()=>Fs});var Wt=R(()=>{pt();Ht();Cn();et();Bn();lt()});var Gt=R(()=>{Wt();Wt()});var yr={};Lt(yr,{Db:()=>tn});import Hi from"better-sqlite3";import{dirname as qi}from"node:path";function pr(t){return{credentialId:t.credential_id,publicKey:t.public_key,counter:t.counter,transports:t.transports?JSON.parse(t.transports):void 0,label:t.label,createdAt:t.created_at,lastUsedAt:t.last_used_at}}function fr(t){return{id:t.id,name:t.name,path:t.path,vcs:t.vcs==="none"?"none":"git",defaultBaseRef:t.default_base_ref,createdAt:t.created_at}}function Bi(t){if(t.pr_urls)try{let e=JSON.parse(t.pr_urls);if(Array.isArray(e)&&e.length)return e}catch{}if(t.pr_url){let e=Ut(t.pr_url);if(e)return[e]}}function mr(t){return{taskId:t.id,repoId:t.repo_id,agent:t.agent,title:t.title??void 0,prompt:t.prompt,status:t.status,interrupted:t.interrupted===1,sessionId:t.session_id??void 0,branch:t.branch??void 0,worktreePath:t.worktree_path??void 0,permission:t.permission,model:t.model??void 0,effort:t.effort??void 0,prs:Bi(t),prUrl:t.pr_url??void 0,pendingInput:t.pending_input?JSON.parse(t.pending_input):void 0,createdAt:t.created_at,updatedAt:t.updated_at,lastActivityAt:t.last_activity_at}}function Wi(t){return{id:t.taskId,repo_id:t.repoId,agent:t.agent,title:t.title??null,prompt:t.prompt,status:t.status,interrupted:t.interrupted?1:0,session_id:t.sessionId??null,branch:t.branch??null,worktree_path:t.worktreePath??null,permission:t.permission,model:t.model??null,effort:t.effort??null,pr_url:t.prs?.[0]?.url??t.prUrl??null,pr_urls:t.prs&&t.prs.length?JSON.stringify(t.prs):null,pending_input:t.pendingInput?JSON.stringify(t.pendingInput):null,created_at:t.createdAt,updated_at:t.updatedAt,last_activity_at:t.lastActivityAt}}function hr(t){return{id:t.id,repoId:t.repo_id,agent:t.agent,title:t.title??void 0,prompt:t.prompt,permission:t.permission,model:t.model??void 0,effort:t.effort??void 0,preset:t.preset??"custom",schedule:t.schedule,enabled:t.enabled===1,lastRunAt:t.last_run_at??void 0,nextRunAt:t.next_run_at??void 0,createdAt:t.created_at,updatedAt:t.updated_at}}function Gi(t){return{id:t.id,routineId:t.routine_id,firedAt:t.fired_at,status:t.status,taskId:t.task_id??void 0,note:t.note??void 0}}function gr(t){return{id:t.id,repo_id:t.repoId,agent:t.agent,title:t.title??null,prompt:t.prompt,permission:t.permission,model:t.model??null,effort:t.effort??null,preset:t.preset,schedule:t.schedule,enabled:t.enabled?1:0,last_run_at:t.lastRunAt??null,next_run_at:t.nextRunAt??null,created_at:t.createdAt,updated_at:t.updatedAt}}function _r(t){return{id:t.id,seq:t.seq,event:{taskId:t.task_id,agent:t.agent,kind:t.kind,sessionId:t.session_id??void 0,payload:JSON.parse(t.payload_json),ts:t.ts}}}var tn,vr=R(()=>{W();Qe();tn=class{db;insertEventStmt;getSeqStmt;constructor(e){In(qi(e)),this.db=new Hi(e),je(e),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.migrate(),this.insertEventStmt=this.db.prepare(`INSERT INTO events (task_id, seq, kind, payload_json, ts)
|
|
3
|
+
VALUES (?, (SELECT COALESCE(MAX(seq),0)+1 FROM events WHERE task_id = ?), ?, ?, ?)`),this.getSeqStmt=this.db.prepare("SELECT seq FROM events WHERE id = ?")}migrate(){this.db.exec(`
|
|
4
|
+
CREATE TABLE IF NOT EXISTS repos (
|
|
5
|
+
id TEXT PRIMARY KEY,
|
|
6
|
+
name TEXT NOT NULL,
|
|
7
|
+
path TEXT NOT NULL,
|
|
8
|
+
default_base_ref TEXT NOT NULL,
|
|
9
|
+
created_at INTEGER NOT NULL
|
|
10
|
+
);
|
|
11
|
+
CREATE TABLE IF NOT EXISTS tasks (
|
|
12
|
+
id TEXT PRIMARY KEY,
|
|
13
|
+
repo_id TEXT NOT NULL REFERENCES repos(id),
|
|
14
|
+
agent TEXT NOT NULL,
|
|
15
|
+
title TEXT,
|
|
16
|
+
prompt TEXT NOT NULL,
|
|
17
|
+
status TEXT NOT NULL,
|
|
18
|
+
interrupted INTEGER NOT NULL DEFAULT 0,
|
|
19
|
+
session_id TEXT,
|
|
20
|
+
branch TEXT,
|
|
21
|
+
worktree_path TEXT,
|
|
22
|
+
permission TEXT NOT NULL,
|
|
23
|
+
model TEXT,
|
|
24
|
+
effort TEXT,
|
|
25
|
+
created_at INTEGER NOT NULL,
|
|
26
|
+
updated_at INTEGER NOT NULL,
|
|
27
|
+
last_activity_at INTEGER NOT NULL
|
|
28
|
+
);
|
|
29
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
30
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
31
|
+
task_id TEXT NOT NULL,
|
|
32
|
+
seq INTEGER NOT NULL,
|
|
33
|
+
kind TEXT NOT NULL,
|
|
34
|
+
payload_json TEXT NOT NULL,
|
|
35
|
+
ts INTEGER NOT NULL
|
|
36
|
+
);
|
|
37
|
+
CREATE INDEX IF NOT EXISTS idx_events_task_seq ON events(task_id, seq);
|
|
38
|
+
CREATE TABLE IF NOT EXISTS approvals (
|
|
39
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
40
|
+
task_id TEXT NOT NULL,
|
|
41
|
+
event_id INTEGER,
|
|
42
|
+
request_json TEXT,
|
|
43
|
+
decision TEXT,
|
|
44
|
+
decided_at INTEGER
|
|
45
|
+
);
|
|
46
|
+
CREATE TABLE IF NOT EXISTS push_subs (
|
|
47
|
+
endpoint TEXT PRIMARY KEY,
|
|
48
|
+
subscription_json TEXT NOT NULL,
|
|
49
|
+
created_at INTEGER NOT NULL
|
|
50
|
+
);
|
|
51
|
+
CREATE TABLE IF NOT EXISTS routines (
|
|
52
|
+
id TEXT PRIMARY KEY,
|
|
53
|
+
repo_id TEXT NOT NULL REFERENCES repos(id),
|
|
54
|
+
agent TEXT NOT NULL,
|
|
55
|
+
title TEXT,
|
|
56
|
+
prompt TEXT NOT NULL,
|
|
57
|
+
permission TEXT NOT NULL,
|
|
58
|
+
model TEXT,
|
|
59
|
+
effort TEXT,
|
|
60
|
+
preset TEXT NOT NULL DEFAULT 'custom',
|
|
61
|
+
schedule TEXT NOT NULL,
|
|
62
|
+
enabled INTEGER NOT NULL DEFAULT 1,
|
|
63
|
+
last_run_at INTEGER,
|
|
64
|
+
next_run_at INTEGER,
|
|
65
|
+
created_at INTEGER NOT NULL,
|
|
66
|
+
updated_at INTEGER NOT NULL
|
|
67
|
+
);
|
|
68
|
+
-- Run history: one row per fire / run-now / skipped-while-down (no catch-up).
|
|
69
|
+
CREATE TABLE IF NOT EXISTS routine_runs (
|
|
70
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
71
|
+
routine_id TEXT NOT NULL,
|
|
72
|
+
fired_at INTEGER NOT NULL,
|
|
73
|
+
status TEXT NOT NULL,
|
|
74
|
+
task_id TEXT,
|
|
75
|
+
note TEXT
|
|
76
|
+
);
|
|
77
|
+
CREATE INDEX IF NOT EXISTS idx_routine_runs ON routine_runs(routine_id, fired_at);
|
|
78
|
+
-- In-app WebAuthn auth. One logical
|
|
79
|
+
-- user, N passkeys (one row per device). Sessions are opaque random tokens;
|
|
80
|
+
-- enroll_tokens are short-lived, host-CLI-minted, single-use registration grants.
|
|
81
|
+
CREATE TABLE IF NOT EXISTS webauthn_credentials (
|
|
82
|
+
credential_id TEXT PRIMARY KEY,
|
|
83
|
+
public_key TEXT NOT NULL,
|
|
84
|
+
counter INTEGER NOT NULL,
|
|
85
|
+
transports TEXT,
|
|
86
|
+
label TEXT,
|
|
87
|
+
created_at INTEGER NOT NULL,
|
|
88
|
+
last_used_at INTEGER
|
|
89
|
+
);
|
|
90
|
+
CREATE TABLE IF NOT EXISTS auth_sessions (
|
|
91
|
+
token TEXT PRIMARY KEY,
|
|
92
|
+
created_at INTEGER NOT NULL,
|
|
93
|
+
expires_at INTEGER NOT NULL,
|
|
94
|
+
label TEXT
|
|
95
|
+
);
|
|
96
|
+
CREATE TABLE IF NOT EXISTS enroll_tokens (
|
|
97
|
+
token TEXT PRIMARY KEY,
|
|
98
|
+
expires_at INTEGER NOT NULL,
|
|
99
|
+
used_at INTEGER
|
|
100
|
+
);
|
|
101
|
+
`);let e=this.db.pragma("table_info(tasks)").map(s=>s.name);e.includes("pr_url")||this.db.exec("ALTER TABLE tasks ADD COLUMN pr_url TEXT"),e.includes("effort")||this.db.exec("ALTER TABLE tasks ADD COLUMN effort TEXT"),e.includes("last_raw_seq")||this.db.exec("ALTER TABLE tasks ADD COLUMN last_raw_seq INTEGER NOT NULL DEFAULT 0"),e.includes("pending_input")||this.db.exec("ALTER TABLE tasks ADD COLUMN pending_input TEXT"),e.includes("pr_urls")||this.db.exec("ALTER TABLE tasks ADD COLUMN pr_urls TEXT");let n=this.db.pragma("table_info(routines)").map(s=>s.name);n.includes("effort")||this.db.exec("ALTER TABLE routines ADD COLUMN effort TEXT"),n.includes("preset")||this.db.exec("ALTER TABLE routines ADD COLUMN preset TEXT NOT NULL DEFAULT 'custom'"),this.db.pragma("table_info(repos)").map(s=>s.name).includes("vcs")||this.db.exec("ALTER TABLE repos ADD COLUMN vcs TEXT NOT NULL DEFAULT 'git'")}insertRepo(e){this.db.prepare("INSERT INTO repos (id, name, path, vcs, default_base_ref, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.path,e.vcs,e.defaultBaseRef,e.createdAt)}getRepo(e){let n=this.db.prepare("SELECT * FROM repos WHERE id = ?").get(e);return n&&fr(n)}listRepos(){return this.db.prepare("SELECT * FROM repos ORDER BY created_at").all().map(fr)}deleteRepo(e){this.db.transaction(n=>{let r=this.db.prepare("SELECT id FROM tasks WHERE repo_id = ?").all(n).map(u=>u.id),s=this.db.prepare("DELETE FROM events WHERE task_id = ?"),i=this.db.prepare("DELETE FROM approvals WHERE task_id = ?");for(let u of r)s.run(u),i.run(u);this.db.prepare("DELETE FROM tasks WHERE repo_id = ?").run(n);let a=this.db.prepare("SELECT id FROM routines WHERE repo_id = ?").all(n).map(u=>u.id),o=this.db.prepare("DELETE FROM routine_runs WHERE routine_id = ?");for(let u of a)o.run(u);this.db.prepare("DELETE FROM routines WHERE repo_id = ?").run(n),this.db.prepare("DELETE FROM repos WHERE id = ?").run(n)})(e)}insertTask(e){this.db.prepare(`INSERT INTO tasks (id, repo_id, agent, title, prompt, status, interrupted, session_id,
|
|
102
|
+
branch, worktree_path, permission, model, effort, pr_url, pr_urls, pending_input, created_at, updated_at, last_activity_at)
|
|
103
|
+
VALUES (@id, @repo_id, @agent, @title, @prompt, @status, @interrupted, @session_id,
|
|
104
|
+
@branch, @worktree_path, @permission, @model, @effort, @pr_url, @pr_urls, @pending_input, @created_at, @updated_at, @last_activity_at)`).run(Wi(e))}getTask(e){let n=this.db.prepare("SELECT * FROM tasks WHERE id = ?").get(e);return n&&mr(n)}listTasks(e){return(e?this.db.prepare("SELECT * FROM tasks WHERE status = ? ORDER BY created_at").all(e):this.db.prepare("SELECT * FROM tasks ORDER BY created_at").all()).map(mr)}setTaskStatus(e,n,r,s){this.db.prepare("UPDATE tasks SET status = ?, interrupted = ?, updated_at = ? WHERE id = ?").run(n,r?1:0,s,e)}setTaskSession(e,n,r){this.db.prepare("UPDATE tasks SET session_id = ?, updated_at = ? WHERE id = ?").run(n,r,e)}setTaskSettings(e,n,r,s,i){this.db.prepare("UPDATE tasks SET model = ?, effort = ?, permission = ?, updated_at = ? WHERE id = ?").run(n??null,r??null,s,i,e)}setTaskWorktree(e,n,r,s){this.db.prepare("UPDATE tasks SET branch = ?, worktree_path = ?, updated_at = ? WHERE id = ?").run(n,r,s,e)}touchTask(e,n){this.db.prepare("UPDATE tasks SET last_activity_at = ? WHERE id = ?").run(n,e)}setTaskPrs(e,n,r){this.db.prepare("UPDATE tasks SET pr_urls = ?, pr_url = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(n),n[0]?.url??null,r,e)}setTaskPendingInput(e,n,r){this.db.prepare("UPDATE tasks SET pending_input = ?, updated_at = ? WHERE id = ?").run(n?JSON.stringify(n):null,r,e)}setTaskRawSeq(e,n){this.db.prepare("UPDATE tasks SET last_raw_seq = ? WHERE id = ?").run(n,e)}getTaskRawSeq(e){return this.db.prepare("SELECT last_raw_seq FROM tasks WHERE id = ?").get(e)?.last_raw_seq??0}inFlightTaskIds(){return this.db.prepare("SELECT id FROM tasks WHERE status IN ('running','awaiting_approval','awaiting_input','queued')").all().map(e=>e.id)}recoverInFlight(e,n){let r=this.inFlightTaskIds().filter(a=>!n?.has(a)),s=this.db.prepare("UPDATE tasks SET status='idle', interrupted=1, pending_input=NULL, updated_at=? WHERE id=?"),i=this.db.transaction(a=>{for(let o of a)s.run(e,o)});return r.length&&i(r),r}insertEvent(e,n,r,s){let i=this.insertEventStmt.run(e,e,n,JSON.stringify(r??null),s),a=Number(i.lastInsertRowid),{seq:o}=this.getSeqStmt.get(a);return{id:a,seq:o}}eventsAfterGlobal(e,n=5e3){return this.db.prepare(`SELECT e.id, e.seq, e.task_id, e.kind, e.payload_json, e.ts, t.agent, t.session_id
|
|
105
|
+
FROM events e JOIN tasks t ON t.id = e.task_id
|
|
106
|
+
WHERE e.id > ? ORDER BY e.id LIMIT ?`).all(e,n).map(_r)}eventsAfterSeq(e,n,r=5e3){return this.db.prepare(`SELECT e.id, e.seq, e.task_id, e.kind, e.payload_json, e.ts, t.agent, t.session_id
|
|
107
|
+
FROM events e JOIN tasks t ON t.id = e.task_id
|
|
108
|
+
WHERE e.task_id = ? AND e.seq > ? ORDER BY e.seq LIMIT ?`).all(e,n,r).map(_r)}usageByAgent(){let e=new Map,n=i=>{let a=e.get(i);return a||(a={agent:i,taskCount:0,turnCount:0,totalCostUsd:0,durationMs:0,inputTokens:0,cachedInputTokens:0,outputTokens:0,reasoningOutputTokens:0},e.set(i,a)),a};for(let i of this.db.prepare("SELECT agent, COUNT(*) AS n FROM tasks GROUP BY agent").all())n(i.agent).taskCount=i.n;let r=this.db.prepare(`SELECT t.agent AS agent, e.payload_json AS payload_json
|
|
109
|
+
FROM events e JOIN tasks t ON t.id = e.task_id
|
|
110
|
+
WHERE e.kind = 'result'`).all(),s=i=>typeof i=="number"&&Number.isFinite(i)?i:0;for(let i of r){let a=n(i.agent);a.turnCount+=1;let o;try{o=JSON.parse(i.payload_json)}catch{continue}if(!o||typeof o!="object")continue;let u=o;a.totalCostUsd+=s(u.total_cost_usd),a.durationMs+=s(u.duration_ms);let d=u.usage;if(d&&typeof d=="object"){let p=d;a.inputTokens+=s(p.input_tokens),a.cachedInputTokens+=s(p.cached_input_tokens),a.outputTokens+=s(p.output_tokens),a.reasoningOutputTokens+=s(p.reasoning_output_tokens)}}return[...e.values()].sort((i,a)=>i.agent.localeCompare(a.agent))}insertApproval(e,n,r,s,i){this.db.prepare("INSERT INTO approvals (task_id, event_id, request_json, decision, decided_at) VALUES (?, ?, ?, ?, ?)").run(e,n,r,s,i)}upsertPushSub(e,n){this.db.prepare(`INSERT INTO push_subs (endpoint, subscription_json, created_at) VALUES (?, ?, ?)
|
|
111
|
+
ON CONFLICT(endpoint) DO UPDATE SET subscription_json = excluded.subscription_json`).run(e.endpoint,JSON.stringify(e),n)}deletePushSub(e){this.db.prepare("DELETE FROM push_subs WHERE endpoint = ?").run(e)}listPushSubs(){return this.db.prepare("SELECT subscription_json FROM push_subs").all().map(n=>JSON.parse(n.subscription_json))}insertRoutine(e){this.db.prepare(`INSERT INTO routines (id, repo_id, agent, title, prompt, permission, model, effort, preset, schedule,
|
|
112
|
+
enabled, last_run_at, next_run_at, created_at, updated_at)
|
|
113
|
+
VALUES (@id, @repo_id, @agent, @title, @prompt, @permission, @model, @effort, @preset, @schedule,
|
|
114
|
+
@enabled, @last_run_at, @next_run_at, @created_at, @updated_at)`).run(gr(e))}updateRoutine(e){this.db.prepare(`UPDATE routines SET repo_id=@repo_id, agent=@agent, title=@title, prompt=@prompt,
|
|
115
|
+
permission=@permission, model=@model, effort=@effort, preset=@preset, schedule=@schedule, enabled=@enabled,
|
|
116
|
+
last_run_at=@last_run_at, next_run_at=@next_run_at, updated_at=@updated_at
|
|
117
|
+
WHERE id=@id`).run(gr(e))}deleteRoutine(e){this.db.transaction(n=>{this.db.prepare("DELETE FROM routine_runs WHERE routine_id = ?").run(n),this.db.prepare("DELETE FROM routines WHERE id = ?").run(n)})(e)}getRoutine(e){let n=this.db.prepare("SELECT * FROM routines WHERE id = ?").get(e);return n&&hr(n)}listRoutines(){return this.db.prepare("SELECT * FROM routines ORDER BY created_at").all().map(hr)}insertRoutineRun(e){this.db.prepare(`INSERT INTO routine_runs (routine_id, fired_at, status, task_id, note)
|
|
118
|
+
VALUES (@routine_id, @fired_at, @status, @task_id, @note)`).run({routine_id:e.routineId,fired_at:e.firedAt,status:e.status,task_id:e.taskId??null,note:e.note??null})}listRoutineRuns(e,n=20){return this.db.prepare("SELECT * FROM routine_runs WHERE routine_id = ? ORDER BY fired_at DESC, id DESC LIMIT ?").all(e,n).map(Gi)}insertCredential(e){this.db.prepare(`INSERT INTO webauthn_credentials (credential_id, public_key, counter, transports, label, created_at, last_used_at)
|
|
119
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(e.credentialId,e.publicKey,e.counter,e.transports?JSON.stringify(e.transports):null,e.label??null,e.createdAt,e.lastUsedAt??null)}getCredential(e){let n=this.db.prepare("SELECT * FROM webauthn_credentials WHERE credential_id = ?").get(e);return n&&pr(n)}listCredentials(){return this.db.prepare("SELECT * FROM webauthn_credentials ORDER BY created_at").all().map(pr)}countCredentials(){return this.db.prepare("SELECT COUNT(*) AS n FROM webauthn_credentials").get().n}bumpCredentialCounter(e,n,r){this.db.prepare("UPDATE webauthn_credentials SET counter = ?, last_used_at = ? WHERE credential_id = ?").run(n,r,e)}deleteCredential(e){return this.db.prepare("DELETE FROM webauthn_credentials WHERE credential_id = ?").run(e).changes>0}createSession(e,n,r,s){this.db.prepare("INSERT INTO auth_sessions (token, created_at, expires_at, label) VALUES (?, ?, ?, ?)").run(e,n,r,s??null)}getSession(e){let n=this.db.prepare("SELECT token, created_at, expires_at FROM auth_sessions WHERE token = ?").get(e);return n&&{token:n.token,createdAt:n.created_at,expiresAt:n.expires_at}}refreshSession(e,n){this.db.prepare("UPDATE auth_sessions SET expires_at = ? WHERE token = ?").run(n,e)}deleteSession(e){this.db.prepare("DELETE FROM auth_sessions WHERE token = ?").run(e)}pruneExpiredSessions(e){this.db.prepare("DELETE FROM auth_sessions WHERE expires_at <= ?").run(e)}createEnrollToken(e,n){this.db.prepare("INSERT INTO enroll_tokens (token, expires_at, used_at) VALUES (?, ?, NULL)").run(e,n)}isEnrollTokenValid(e,n){return!!this.db.prepare("SELECT 1 FROM enroll_tokens WHERE token = ? AND used_at IS NULL AND expires_at > ?").get(e,n)}consumeEnrollToken(e,n){return this.db.prepare("UPDATE enroll_tokens SET used_at = ? WHERE token = ? AND used_at IS NULL AND expires_at > ?").run(n,e,n).changes>0}close(){this.db.close()}}});import{homedir as br}from"node:os";import{join as Vi}from"node:path";function xt(t){return t==="~"?br():t.startsWith("~/")?Vi(br(),t.slice(2)):t}var nn=R(()=>{});import{homedir as Xi}from"node:os";import{existsSync as kr}from"node:fs";import{dirname as Rr,join as ze,resolve as De}from"node:path";import{fileURLToPath as Ki}from"node:url";function Yi(t){let e={};for(let[n,r]of Object.entries(t))r!==void 0&&r!==""&&(e[n]=r);return e}var Zi,zi,Ji,x,wr,rn,sn,Tr,Er,xr,N,Rt=R(()=>{Gt();W();nn();Zi=Rr(Ki(import.meta.url)),zi=t=>t==="localhost"||t==="::1"||/^127(?:\.\d{1,3}){3}$/.test(t),Ji=g.object({PORT:g.coerce.number().int().positive().default(4e3),HOST:g.string().min(1).refine(zi,"HOST must be loopback; terminate public HTTPS at the reverse proxy").default("localhost"),DISPATCH_CONCURRENCY:g.coerce.number().int().min(1).default(8),SSE_KEEPALIVE_MS:g.coerce.number().int().positive().default(15e3),AUTH_SESSION_TTL_MS:g.coerce.number().int().positive().default(30*24*60*60*1e3),AUTH_COOKIE_NAME:g.string().min(1).default("palmagent_session"),AUTH_RP_ID:g.string().min(1).regex(/^[A-Za-z0-9.-]+$/,"AUTH_RP_ID must be a hostname without a scheme, path, or port").optional(),AUTH_RP_NAME:g.string().min(1).optional(),AUTH_ORIGIN:g.string().url().startsWith("https://","AUTH_ORIGIN must use https://").optional(),AUTH_ENABLED:g.string().optional(),AUTH_DISABLED:g.string().optional(),PUSH_SUBJECT:g.string().regex(/^(mailto:|https:\/\/)/,"PUSH_SUBJECT must be a mailto: or https:// URL").optional(),DISPATCHER_DATA_DIR:g.string().min(1).optional(),XDG_STATE_HOME:g.string().min(1).optional(),DISPATCHER_DB:g.string().min(1).optional(),VAPID_KEY_PATH:g.string().min(1).optional(),STATIC_DIR:g.string().min(1).optional(),REPO_ROOTS:g.string().optional(),GITHUB_TOKEN:g.string().min(1).optional(),RUNNER_SOCKET:g.string().min(1).optional(),CLAUDE_MODEL:g.string().min(1).optional(),CODEX_MODEL:g.string().min(1).optional(),CLAUDE_EFFORT:g.string().min(1).optional(),CODEX_EFFORT:g.string().min(1).optional(),CLAUDE_CONFIG_DIR:g.string().min(1).optional(),NODE_ENV:g.string().optional()}).passthrough();x=Ji.parse(Yi(process.env)),wr=x.AUTH_DISABLED==="1"?!1:x.AUTH_ENABLED==="1"?!0:x.NODE_ENV==="production",rn=x.AUTH_RP_ID??(wr?"":"localhost"),sn=x.DISPATCHER_DATA_DIR?De(x.DISPATCHER_DATA_DIR):x.XDG_STATE_HOME?ze(De(x.XDG_STATE_HOME),_.stateDirName):ze(Xi(),".local","state",_.stateDirName),Tr=ze(sn,"palmagent.db"),Er=ze(sn,"dispatcher.db"),xr=x.DISPATCHER_DB?De(x.DISPATCHER_DB):kr(Tr)||!kr(Er)?Tr:Er,N={port:x.PORT,host:x.HOST,concurrency:x.DISPATCH_CONCURRENCY,dataDir:sn,dbPath:xr,keepAliveMs:x.SSE_KEEPALIVE_MS,claudeModel:x.CLAUDE_MODEL,codexModel:x.CODEX_MODEL,claudeEffort:x.CLAUDE_EFFORT,codexEffort:x.CODEX_EFFORT,claudeConfigDir:x.CLAUDE_CONFIG_DIR?De(xt(x.CLAUDE_CONFIG_DIR)):void 0,vapidKeyPath:x.VAPID_KEY_PATH?De(x.VAPID_KEY_PATH):ze(Rr(xr),"vapid.json"),pushSubject:x.PUSH_SUBJECT,staticDir:x.STATIC_DIR?De(x.STATIC_DIR):ze(Zi,"..","..","web","dist"),repoRoots:(x.REPO_ROOTS??"").split(":").filter(Boolean).map(t=>De(xt(t))),runnerSocket:x.RUNNER_SOCKET,githubToken:x.GITHUB_TOKEN,authEnabled:wr,rpId:rn,rpName:x.AUTH_RP_NAME??_.displayName,authOrigin:x.AUTH_ORIGIN??(rn?`https://${rn}`:""),sessionTtlMs:x.AUTH_SESSION_TTL_MS,cookieName:x.AUTH_COOKIE_NAME,nodeEnv:x.NODE_ENV}});function ta({permission:t,model:e,effort:n,resumeId:r}){let s=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--include-partial-messages","--permission-mode",ea(t),"--permission-prompt-tool","stdio"];return e&&s.push("--model",e),n&&s.push("--effort",n),r&&s.push("--resume",r),s}function na(t,e=[]){let n=e.map(r=>({type:"image",source:{type:"base64",media_type:r.mediaType,data:r.data}}));return n.push({type:"text",text:t}),{type:"user",message:{role:"user",content:n}}}var Qi,Sr,ea,wt,Ar=R(()=>{W();Rt();Qi=1500,Sr={plan:"plan",acceptEdits:"acceptEdits",dontAsk:"dontAsk",bypassPermissions:"bypassPermissions",readonly:"plan","auto-edit":"acceptEdits",full:"bypassPermissions"},ea=t=>Sr[t??""]??Sr[Mt.claude];wt=class{agent="claude";start(e,n,r){let{taskId:s,cwd:i,prompt:a,images:o,resumeId:u,permission:d,model:p,effort:b,reattach:A,resumeFromSeq:D,pendingInput:q}=e,$=ta({permission:d,model:p,effort:b,resumeId:u}),M=u,Pe=N.claudeConfigDir?{CLAUDE_CONFIG_DIR:N.claudeConfigDir}:void 0,H=A?r.attach(s,0):r.start({turnId:s,command:"claude",argv:$,cwd:i,env:Pe});if(!H)return n({taskId:s,kind:"status",sessionId:M,payload:{subtype:"reattach_failed"}}),{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel:()=>{},done:Promise.resolve()};let Je=!1,Dt,$e,Pt=!1,vn=0,ct=new Map;A&&q&&ct.set(q.requestId,{questions:q.questions});let Le=O=>{H.writeStdin(JSON.stringify(O)+`
|
|
120
|
+
`)},bn=(O,Z)=>{Le(na(O,Z))},kn=(O=!1)=>{$e&&clearTimeout($e),Pt=O,$e=setTimeout(()=>{!Je&&H.stdinWritable()&&H.closeStdin()},Qi)},$t=()=>{$e&&clearTimeout($e),$e=void 0,Pt=!1};H.onLine((O,Z)=>{let S;try{S=JSON.parse(Z)}catch{return}S.session_id&&(M=S.session_id);let B=I=>n(I,O),fe=A&&O<=(D??0);switch(Pt&&["stream_event","assistant","user","control_request"].includes(S.type)&&$t(),S.type){case"system":B({taskId:s,kind:"status",sessionId:M,payload:{subtype:S.subtype,model:S.model,cwd:S.cwd,tools:S.tools?.length}});break;case"rate_limit_event":B({taskId:s,kind:"status",sessionId:M,payload:{subtype:"rate_limit",info:S}});break;case"stream_event":{let I=S.event;I?.type==="content_block_delta"&&I.delta?.type==="text_delta"&&B({taskId:s,kind:"assistant_text",sessionId:M,payload:{text:I.delta.text}});break}case"assistant":{for(let I of S.message?.content??[])I.type==="tool_use"&&B({taskId:s,kind:"tool_call",sessionId:M,payload:{id:I.id,name:I.name,input:I.input}});break}case"user":{for(let I of S.message?.content??[])I.type==="tool_result"&&B({taskId:s,kind:"tool_result",sessionId:M,payload:{tool_use_id:I.tool_use_id,content:I.content,is_error:I.is_error}});break}case"result":B({taskId:s,kind:"result",sessionId:M,payload:{subtype:S.subtype,is_error:S.is_error,result:S.result,num_turns:S.num_turns,duration_ms:S.duration_ms,total_cost_usd:S.total_cost_usd}}),Je||kn(!!fe);break;case"control_response":B({taskId:s,kind:"status",sessionId:M,payload:{subtype:"control_response",response:S.response}});break;case"control_request":{if(fe)break;let I=S.request_id,Ye=S.request??{};if(Ye.subtype!=="can_use_tool")break;if(Ye.tool_name==="AskUserQuestion"&&Array.isArray(Ye.input?.questions)){let Ue=Ye.input.questions;ct.set(I,{questions:Ue}),B({taskId:s,kind:"question",sessionId:M,payload:{requestId:I,questions:Ue}})}else Le({type:"control_response",response:{subtype:"success",request_id:I,response:{behavior:"deny",message:"Auto-denied (non-interactive dispatch)."}}});break}default:break}}),H.onStderr(O=>{n({taskId:s,kind:"status",sessionId:M,payload:{subtype:"stderr",text:O}})});let Qr=new Promise(O=>{H.onExit(Z=>{$t(),n({taskId:s,kind:"status",sessionId:M,payload:{subtype:"process_exit",code:Z}}),O()})});return A||bn(a,o),{steer:(O,Z)=>H.stdinWritable()?(Je=!0,$t(),Le({type:"control_request",request_id:`int_${++vn}`,request:{subtype:"interrupt"}}),Dt=setTimeout(()=>{bn(O,Z),Je=!1},250),!0):!1,interrupt:()=>H.stdinWritable()?(Dt&&clearTimeout(Dt),Je=!1,Le({type:"control_request",request_id:`int_${++vn}`,request:{subtype:"interrupt"}}),kn(),!0):!1,approve:()=>!1,answer:O=>{let Z=ct.get(O.requestId);if(!Z||!H.stdinWritable())return!1;ct.delete(O.requestId);let S=new Map(Z.questions.map(z=>[z.question,z])),B={},fe={};for(let z of O.answers??[])z.selected?.length&&(B[z.question]=S.get(z.question)?.multiSelect?z.selected:z.selected[0]),z.notes?.trim()&&(fe[z.question]={notes:z.notes.trim()});let I=O.response?.trim();if(!(Object.keys(B).length>0||Object.keys(fe).length>0||!!I))return Le({type:"control_response",response:{subtype:"success",request_id:O.requestId,response:{behavior:"deny",message:"User declined to answer."}}}),!0;let Ue={questions:Z.questions,answers:B};return Object.keys(fe).length&&(Ue.annotations=fe),I&&(Ue.response=I),Le({type:"control_response",response:{subtype:"success",request_id:O.requestId,response:{behavior:"allow",updatedInput:Ue}}}),!0},cancel:()=>H.kill("SIGINT"),done:Qr}}}});import{mkdtempSync as ra,rmSync as sa,writeFileSync as ia}from"node:fs";import{tmpdir as aa}from"node:os";import{join as Ir}from"node:path";function ua(t){if(!t?.length)return{argv:[],cleanup:()=>{}};let e=ra(Ir(aa(),"palmagent-img-")),n=[];return t.forEach((r,s)=>{let i=Ir(e,`img-${s}${oa[r.mediaType]??".png"}`);ia(i,Buffer.from(r.data,"base64")),n.push("-i",i)}),{argv:n,cleanup:()=>sa(e,{recursive:!0,force:!0})}}function da(t){return Nr[t??""]??Nr["workspace-write"]}function ca({prompt:t,resumeId:e,permission:n,model:r,effort:s},i=[]){let a=[...r?["-c",`model=${r}`]:[],...s?["-c",`model_reasoning_effort=${s}`]:[]],o=da(n),u=e?["-c",`sandbox_mode=${o.mode}`]:["--sandbox",o.mode],d=o.network?["-c","sandbox_workspace_write.network_access=true"]:[],p=["--json","--skip-git-repo-check","-c","approval_policy=never",...u,...d,...a,...i];return e?["exec","resume",e,t,...p]:["exec",t,...p]}var oa,Nr,St,Cr=R(()=>{oa={"image/png":".png","image/jpeg":".jpg","image/webp":".webp","image/gif":".gif"};Nr={"read-only":{mode:"read-only"},"workspace-write":{mode:"workspace-write"},"workspace-write-net":{mode:"workspace-write",network:!0},"danger-full-access":{mode:"danger-full-access"},readonly:{mode:"read-only"},"auto-edit":{mode:"workspace-write"},full:{mode:"danger-full-access"}};St=class{agent="codex";start(e,n,r){let{taskId:s,cwd:i,prompt:a,images:o,resumeId:u,permission:d,model:p,effort:b,reattach:A}=e,D=u;if(A){let Pe=r.attach(s,0);return Pe?this.wire(s,Pe,n,()=>{},()=>D,H=>{D=H}):(n({taskId:s,kind:"status",sessionId:D,payload:{subtype:"reattach_failed"}}),{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel:()=>{},done:Promise.resolve()})}let q=ua(o),$=ca({prompt:a,resumeId:u,permission:d,model:p,effort:b},q.argv),M=r.start({turnId:s,command:"codex",argv:$,cwd:i});return M.closeStdin(),this.wire(s,M,n,q.cleanup,()=>D,Pe=>{D=Pe})}wire(e,n,r,s,i,a){let o=(d,p)=>{let b=i();switch(d?.type){case"agent_message":p({taskId:e,kind:"assistant_text",sessionId:b,payload:{text:d.text}});break;case"reasoning":p({taskId:e,kind:"status",sessionId:b,payload:{subtype:"reasoning",text:d.text}});break;case"command_execution":p({taskId:e,kind:"tool_call",sessionId:b,payload:{name:"bash",command:d.command,status:d.status}}),(d.aggregated_output!=null||d.exit_code!=null)&&p({taskId:e,kind:"tool_result",sessionId:b,payload:{output:d.aggregated_output,exit_code:d.exit_code}});break;case"file_change":p({taskId:e,kind:"tool_call",sessionId:b,payload:{name:"file_change",changes:d.changes}});break;case"mcp_tool_call":case"web_search":p({taskId:e,kind:"tool_call",sessionId:b,payload:{name:d.type,item:d}});break;case"error":p({taskId:e,kind:"error",sessionId:b,payload:{message:d.message}});break;default:p({taskId:e,kind:"status",sessionId:b,payload:{subtype:d?.type??"item",item:d}})}};n.onLine((d,p)=>{let b;try{b=JSON.parse(p)}catch{return}let A=q=>r(q,d),D=i();switch(b.type){case"thread.started":a(b.thread_id),A({taskId:e,kind:"status",sessionId:b.thread_id,payload:{subtype:"thread_started",thread_id:b.thread_id}});break;case"turn.started":A({taskId:e,kind:"status",sessionId:D,payload:{subtype:"turn_started"}});break;case"item.started":b.item?.type==="command_execution"&&o(b.item,A);break;case"item.updated":break;case"item.completed":o(b.item,A);break;case"turn.completed":A({taskId:e,kind:"result",sessionId:D,payload:{usage:b.usage}});break;case"turn.failed":A({taskId:e,kind:"error",sessionId:D,payload:{error:b.error}});break;case"error":A({taskId:e,kind:"error",sessionId:D,payload:{message:b.message}});break;default:break}}),n.onStderr(d=>{r({taskId:e,kind:"status",sessionId:i(),payload:{subtype:"stderr",text:d}})});let u=new Promise(d=>{n.onExit(p=>{s(),r({taskId:e,kind:"status",sessionId:i(),payload:{subtype:"process_exit",code:p}}),d()})});return{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel:()=>n.kill("SIGINT"),done:u}}}});var Tu,Or=R(()=>{Ar();Cr();Tu={claude:new wt,codex:new St}});var Dr=R(()=>{});var ae,Pu,Pr=R(()=>{W();Rt();Or();nn();Dr();ae=class extends Error{constructor(n,r){super(r);this.status=n}},Pu=4.5*1024*1024});var $r={};Lt($r,{AuthService:()=>un,parseCookies:()=>It});import{randomBytes as an}from"node:crypto";import{generateAuthenticationOptions as la,generateRegistrationOptions as pa,verifyAuthenticationResponse as fa,verifyRegistrationResponse as ma}from"@simplewebauthn/server";function It(t){let e=t.headers.cookie;if(!e)return{};let n={};for(let r of e.split(";")){let s=r.indexOf("=");if(s<0)continue;let i=r.slice(0,s).trim(),a=r.slice(s+1).trim();i&&(n[i]=decodeURIComponent(a))}return n}function it(t,e,n){return[`${t}=${encodeURIComponent(e)}`,"Path=/","HttpOnly","Secure","SameSite=Lax",`Max-Age=${n}`].join("; ")}var ha,ga,At,on,_a,un,Lr=R(()=>{W();Rt();Pr();ha=new Uint8Array([161,133,121,187,209,33,68,243,159,173,110,138,162,49,88,53]),ga=_.displayName,At="wa_chal",on=5*60*1e3,_a=2e3;un=class{constructor(e){this.db=e}challenges=new Map;get enabled(){return N.authEnabled}status(e){return{authenticated:this.verifyRequest(e),required:N.authEnabled,credentialCount:this.db.countCredentials()}}verifyRequest(e){let n=It(e)[N.cookieName];if(!n)return!1;let r=Date.now(),s=this.db.getSession(n);return s?s.expiresAt<=r?(this.db.deleteSession(n),!1):(r-s.createdAt>N.sessionTtlMs/3&&this.db.refreshSession(n,r+N.sessionTtlMs),!0):!1}issueSession(e){let n=an(32).toString("base64url"),r=Date.now();return this.db.createSession(n,r,r+N.sessionTtlMs,e),it(N.cookieName,n,Math.floor(N.sessionTtlMs/1e3))}logout(e){let n=It(e)[N.cookieName];return n&&this.db.deleteSession(n),it(N.cookieName,"",0)}putChallenge(e){for(this.pruneChallenges();this.challenges.size>=_a;){let r=this.challenges.keys().next().value;if(r===void 0)break;this.challenges.delete(r)}let n=an(18).toString("base64url");return this.challenges.set(n,e),n}takeChallenge(e,n){let r=It(e)[At],s=r?this.challenges.get(r):void 0;if(!s||s.kind!==n||s.expiresAt<=Date.now())throw r&&this.challenges.delete(r),new ae(400,"challenge expired \u2014 restart the passkey flow");return this.challenges.delete(r),s}pruneChallenges(){let e=Date.now();for(let[n,r]of this.challenges)r.expiresAt<=e&&this.challenges.delete(n)}challengeCookie(e){return it(At,e,Math.floor(on/1e3))}async beginRegistration(e,n){let r=this.verifyRequest(e),s=!!n&&this.db.isEnrollTokenValid(n,Date.now());if(!r&&!s)throw new ae(403,"registration requires a valid enroll token (mint one with the host CLI)");let i=this.db.listCredentials(),a=await pa({rpName:N.rpName,rpID:N.rpId,userName:ga,userID:ha,attestationType:"none",excludeCredentials:i.map(u=>({id:u.credentialId,transports:u.transports})),authenticatorSelection:{residentKey:"required",userVerification:"preferred"}}),o=this.putChallenge({challenge:a.challenge,expiresAt:Date.now()+on,kind:"reg",enrollToken:s?n:void 0});return{options:a,setCookie:this.challengeCookie(o)}}async finishRegistration(e,n,r){let s=this.takeChallenge(e,"reg"),i=await ma({response:n,expectedChallenge:s.challenge,expectedOrigin:N.authOrigin,expectedRPID:N.rpId,requireUserVerification:!1});if(!i.verified||!i.registrationInfo)throw new ae(400,"passkey registration could not be verified");if(s.enrollToken&&!this.db.consumeEnrollToken(s.enrollToken,Date.now()))throw new ae(400,"enroll token already used or expired");let a=i.registrationInfo.credential,o=Date.now();return this.db.insertCredential({credentialId:a.id,publicKey:Buffer.from(a.publicKey).toString("base64url"),counter:a.counter,transports:a.transports,label:r?.slice(0,64)||null,createdAt:o,lastUsedAt:o}),{setCookies:[this.issueSession(r),it(At,"",0)]}}async beginAuthentication(){let e=await la({rpID:N.rpId,userVerification:"preferred",allowCredentials:[]}),n=this.putChallenge({challenge:e.challenge,expiresAt:Date.now()+on,kind:"auth"});return{options:e,setCookie:this.challengeCookie(n)}}async finishAuthentication(e,n){let r=this.takeChallenge(e,"auth"),s=this.db.getCredential(n.id);if(!s)throw new ae(400,"unknown passkey");let i=await fa({response:n,expectedChallenge:r.challenge,expectedOrigin:N.authOrigin,expectedRPID:N.rpId,credential:{id:s.credentialId,publicKey:new Uint8Array(Buffer.from(s.publicKey,"base64url")),counter:s.counter,transports:s.transports},requireUserVerification:!1});if(!i.verified)throw new ae(401,"passkey assertion failed");return this.db.bumpCredentialCounter(s.credentialId,i.authenticationInfo.newCounter,Date.now()),{setCookies:[this.issueSession(s.label??void 0),it(At,"",0)]}}mintEnrollToken(){let e=an(24).toString("base64url"),n=Date.now()+15*60*1e3;return this.db.createEnrollToken(e,n),{token:e,expiresAt:n}}}});W();Qe();import{existsSync as Ia,readFileSync as Na}from"node:fs";import{dirname as Ca,join as Ot}from"node:path";import{fileURLToPath as Oa}from"node:url";Gt();W();Qe();import{execFileSync as Wn}from"node:child_process";import{existsSync as Vt,readFileSync as fi,writeFileSync as mi}from"node:fs";import{homedir as yt,userInfo as hi}from"node:os";import{dirname as Gn,join as Ne,resolve as K}from"node:path";import{fileURLToPath as gi}from"node:url";var Ke={memHigh:"12G",memMax:"16G",tasksMaxRunner:2048,cpuQuota:"300%",nofile:65536,tasksMaxWeb:512},_i=["127","0","0","1"].join("."),Xt={host:_i,port:4100,concurrency:8},Vn=g.string().trim().min(1).max(253).regex(/^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$/,"DOMAIN must be a public hostname without a scheme, path, or port").transform(t=>t.toLowerCase()),yi=t=>t==="localhost"||t==="::1"||/^127(?:\.\d{1,3}){3}$/.test(t),Xn=g.string().min(1).refine(yi,"HOST must be loopback; terminate public HTTPS at nginx"),Kn=g.coerce.number().int().min(1).max(65535),Zn=g.coerce.number().int().min(1),zn=g.string().regex(/^(?:mailto:[^@\s]+@[^@\s]+\.[^@\s]+|https:\/\/\S+)$/,"PUSH_SUBJECT must be a mailto: address or an https:// URL"),vi=g.object({MODE:g.enum(["package","source"]).optional(),RUN_USER:g.string().min(1).optional(),RUN_GROUP:g.string().min(1).optional(),DOMAIN:Vn.optional(),HOST:Xn.default(Xt.host),PORT:Kn.default(Xt.port),DISPATCH_CONCURRENCY:Zn.default(Xt.concurrency),DATA_DIR:g.string().min(1).optional(),RUNNER_SOCKET:g.string().min(1).optional(),DISPATCHER_DB:g.string().min(1).optional(),WORKING_DIR:g.string().min(1).optional(),EXEC_PATH:g.string().min(1).optional(),PKG_DIR:g.string().min(1).optional(),REPO_DIR:g.string().min(1).optional(),REPO_ROOTS:g.string().optional(),CLAUDE_CONFIG_DIR:g.string().min(1).optional(),PUSH_SUBJECT:zn.optional(),CAP_MEM_HIGH:g.string().min(1).default(Ke.memHigh),CAP_MEM_MAX:g.string().min(1).default(Ke.memMax),CAP_TASKS_MAX_RUNNER:g.coerce.number().int().positive().default(Ke.tasksMaxRunner),CAP_CPU_QUOTA:g.string().min(1).default(Ke.cpuQuota),CAP_NOFILE:g.coerce.number().int().positive().default(Ke.nofile),CAP_TASKS_MAX_WEB:g.coerce.number().int().positive().default(Ke.tasksMaxWeb)}).passthrough();function Jn(t){return g.object({domain:Vn,host:Xn,port:Kn,concurrency:Zn,pushSubject:g.union([g.literal(""),zn])}).parse(t)}function bi(){let t=new Set;for(let e of["node","claude","codex"])try{let n=Wn("bash",["-lc",`command -v ${e}`],{encoding:"utf8"}).trim();n&&t.add(Gn(n))}catch{}for(let e of(process.env.PATH??"").split(":"))e&&t.add(e);return[...t].join(":")}function Kt(t){return{rpId:t,rpName:_.productName,authOrigin:t?`https://${t}`:""}}function Yn(t){return Ne(t,"install.env")}function st(t){let e=t??process.env.DISPATCHER_DATA_DIR??Ne(yt(),".local","state",_.stateDirName),n=e==="~"?yt():e.startsWith("~/")?Ne(yt(),e.slice(2)):e;return K(n)}function Zt(t=typeof process.getuid=="function"?process.getuid():void 0){if(t===0)throw new Error(`do not run ${_.cliName} install/setup with sudo or as root; run it as the account that should own the agent processes (the CLI invokes sudo only for system files)`)}function Qn(t,e=yt()){let n=K(t);if(new Set([K("/"),K("/home"),K("/opt"),K("/srv"),K("/tmp"),K("/var"),K("/var/lib"),K(e),K(e,".local"),K(e,".local","state")]).has(n))throw new Error(`refusing to purge broad data directory ${n}; choose the dedicated Palmagent state directory explicitly`)}function ki(t){let e={};for(let n of t.split(`
|
|
121
|
+
`)){let r=n.trim();if(!r||r.startsWith("#"))continue;let s=r.indexOf("=");if(s<0)continue;let i=r.slice(s+1).trim();i!==""&&(e[r.slice(0,s).trim()]=i)}return e}function zt(t={}){let e=st(t.dataDir),n=Yn(e),r=Vt(n);if(t.requireInstalled&&!r)throw new Error(`no install config at ${n} \u2014 run \`${_.cliName} install\` first.`);let s=vi.parse(r?ki(fi(n,"utf8")):{}),i=s.DOMAIN??"";if(t.requireInstalled&&!i)throw new Error(`install config at ${n} is missing DOMAIN \u2014 re-run \`${_.cliName} setup\`.`);let a=s.MODE??(t.pkgDir?"package":"source"),o=s.RUN_USER??Ti()??"",u=s.REPO_DIR,d=t.pkgDir??s.PKG_DIR,p=s.WORKING_DIR??(a==="source"?u?Ne(u,"apps","server"):e:d??e),b=Ne(e,"palmagent.db"),A=Ne(e,"dispatcher.db"),D=s.DISPATCHER_DB??(Vt(b)||!Vt(A)?b:A);return{mode:a,user:o,group:s.RUN_GROUP??Ei(o)??o,dataDir:e,runnerSocket:s.RUNNER_SOCKET??Ne(e,"runner.sock"),dbPath:D,pkgDir:d,repoDir:u,workingDir:p,execPath:s.EXEC_PATH??bi(),domain:i,host:s.HOST,port:s.PORT,concurrency:s.DISPATCH_CONCURRENCY,pushSubject:s.PUSH_SUBJECT??"",repoRoots:s.REPO_ROOTS??"",claudeConfigDir:s.CLAUDE_CONFIG_DIR??"",...Kt(i),caps:{memHigh:s.CAP_MEM_HIGH,memMax:s.CAP_MEM_MAX,tasksMaxRunner:s.CAP_TASKS_MAX_RUNNER,cpuQuota:s.CAP_CPU_QUOTA,nofile:s.CAP_NOFILE,tasksMaxWeb:s.CAP_TASKS_MAX_WEB}}}function Jt(t){Me(t.dataDir);let e=[`# ${_.productName} install config \u2014 written by \`${_.cliName} install/setup\`.`,`# Edit then re-run \`${_.cliName} setup\` to re-render the units + nginx vhost.`,`MODE=${t.mode}`,`RUN_USER=${t.user}`,`RUN_GROUP=${t.group}`,`DOMAIN=${t.domain}`,`HOST=${t.host}`,`PORT=${t.port}`,`DISPATCH_CONCURRENCY=${t.concurrency}`,`DATA_DIR=${t.dataDir}`,`RUNNER_SOCKET=${t.runnerSocket}`,`DISPATCHER_DB=${t.dbPath}`,`WORKING_DIR=${t.workingDir}`,`EXEC_PATH=${t.execPath}`,t.pkgDir?`PKG_DIR=${t.pkgDir}`:"",t.repoDir?`REPO_DIR=${t.repoDir}`:"",t.repoRoots?`REPO_ROOTS=${t.repoRoots}`:"",t.claudeConfigDir?`CLAUDE_CONFIG_DIR=${t.claudeConfigDir}`:"",t.pushSubject?`PUSH_SUBJECT=${t.pushSubject}`:"","# DoS blast-radius caps (adjust per host, then re-run setup):",`CAP_MEM_HIGH=${t.caps.memHigh}`,`CAP_MEM_MAX=${t.caps.memMax}`,`CAP_TASKS_MAX_RUNNER=${t.caps.tasksMaxRunner}`,`CAP_CPU_QUOTA=${t.caps.cpuQuota}`,`CAP_NOFILE=${t.caps.nofile}`,`CAP_TASKS_MAX_WEB=${t.caps.tasksMaxWeb}`,""].filter(r=>r!==""),n=Yn(t.dataDir);return mi(n,e.join(`
|
|
122
|
+
`)+`
|
|
123
|
+
`,{mode:384}),je(n),n}function Ti(){try{return hi().username}catch{return}}function Ei(t){if(t)try{return Wn("id",["-gn",t],{encoding:"utf8"}).trim()||void 0}catch{return}}function er(){return Gn(gi(import.meta.url))}W();import{spawnSync as ya}from"node:child_process";import{existsSync as at,mkdirSync as va,readFileSync as Hr,writeFileSync as Ur}from"node:fs";import{basename as Mr,join as C,resolve as ba}from"node:path";W();import{existsSync as Tt,statSync as Oi}from"node:fs";import{join as rr}from"node:path";W();function le(){return`${_.unitBase}.service`}function ie(){return`${_.unitBase}-runner.service`}function xi(t){return`# Generated by ${_.cliName} \u2014 edit ${t.dataDir}/install.env, then re-run \`${_.cliName} setup\`.`}function Ri(t,e){if(t.mode==="source"){let n=`${t.repoDir}/apps/server/node_modules/.bin/tsx`;return{web:`${n} src/server.ts`,runner:`${n} src/runner-daemon.ts`}}return{web:`${e} ${t.pkgDir}/server.js`,runner:`${e} ${t.pkgDir}/runner-daemon.js`}}function vt(t,e={}){let n=e.header??xi(t),r=e.webUnitName??le(),s=e.runnerUnitName??ie(),i=e.nodeBin??process.execPath,a=Ri(t,i),o=t.caps,u=[n,"[Unit]",`Description=${t.rpName} runner (owns the claude/codex child processes)`,"After=network.target","","[Service]",`User=${t.user}`,`Group=${t.group}`,`WorkingDirectory=${t.workingDir}`,"Environment=NODE_ENV=production",`Environment=RUNNER_SOCKET=${t.runnerSocket}`,"Environment=DISABLE_AUTOUPDATER=1",`Environment=PATH=${t.execPath}`,`ExecStart=${a.runner}`,"Restart=always","RestartSec=2","# Resource caps contain the runner and all of its agent child processes.",`MemoryHigh=${o.memHigh}`,`MemoryMax=${o.memMax}`,`TasksMax=${o.tasksMaxRunner}`,`CPUQuota=${o.cpuQuota}`,`LimitNOFILE=${o.nofile}`,"","[Install]","WantedBy=multi-user.target",""],d=[n,"[Unit]",`Description=${t.rpName} (${t.domain}) \u2014 web/SSE server`,`After=network.target ${s}`,`Wants=${s}`,"","[Service]",`User=${t.user}`,`Group=${t.group}`,`WorkingDirectory=${t.workingDir}`,"Environment=NODE_ENV=production",`Environment=HOST=${t.host}`,`Environment=PORT=${t.port}`,`Environment=DISPATCH_CONCURRENCY=${t.concurrency}`,`Environment=DISPATCHER_DB=${t.dbPath}`,`Environment=RUNNER_SOCKET=${t.runnerSocket}`,"Environment=DISABLE_AUTOUPDATER=1",...t.pushSubject?[`Environment=PUSH_SUBJECT=${t.pushSubject}`]:[],...t.mode==="package"?[`Environment=STATIC_DIR=${t.pkgDir}/web`]:[],...t.repoRoots?[`Environment=REPO_ROOTS=${t.repoRoots}`]:[],...t.claudeConfigDir?["# Isolates the dispatcher's headless Claude sessions from an interactively-used ~/.claude.",`Environment=CLAUDE_CONFIG_DIR=${t.claudeConfigDir}`]:[],"# In-app WebAuthn auth (replaces Authelia on this vhost). Enforced because","# NODE_ENV=production; the RP identity must match the public origin.",`Environment=AUTH_RP_ID=${t.rpId}`,`Environment=AUTH_RP_NAME=${t.rpName}`,`Environment=AUTH_ORIGIN=${t.authOrigin}`,`Environment=PATH=${t.execPath}`,`ExecStart=${a.web}`,"Restart=always","RestartSec=2","# A web restart does NOT touch the runner cgroup, so in-flight agent turns","# survive a web update; the web server reattaches to them on boot.",`TasksMax=${o.tasksMaxWeb}`,`LimitNOFILE=${o.nofile}`,"","[Install]","WantedBy=multi-user.target",""];return{web:{name:r,text:d.join(`
|
|
124
|
+
`)},runner:{name:s,text:u.join(`
|
|
125
|
+
`)}}}import{execFileSync as Do,spawnSync as wi}from"node:child_process";import{mkdtempSync as Si,rmSync as Ai,writeFileSync as Ii}from"node:fs";import{tmpdir as Ni}from"node:os";import{createInterface as nr}from"node:readline/promises";import{join as tr}from"node:path";function P(t,e,n={}){let r=wi(t,e,{encoding:"utf8",input:n.input,env:n.env??process.env,timeout:n.timeout});return{ok:r.status===0,code:r.status,stdout:(r.stdout??"").toString(),stderr:(r.stderr??"").toString()}}function Ce(t){let e=P("bash",["-lc",`command -v ${t}`]),n=e.stdout.trim();return e.ok&&n?n:void 0}function Yt(){return P("sudo",["-n","true"]).ok}function Oe(t,e,n="644"){let r=Si(tr(Ni(),"palmagent-install-")),s=tr(r,"candidate"),i=`${t}.palmagent-${process.pid}.tmp`;try{if(Ii(s,e,{mode:384}),!P("sudo",["install","-m",n,s,i]).ok)return!1;let o=P("sudo",["mv","-f",i,t]);return o.ok||P("sudo",["rm","-f",i]),o.ok}finally{Ai(r,{recursive:!0,force:!0})}}function w(t){return P("sudo",t)}var Ci=process.stdout.isTTY&&!process.env.NO_COLOR,bt=(t,e)=>Ci?`\x1B[${t}m${e}\x1B[0m`:e,f={info:t=>console.log(` ${t}`),step:t=>console.log(bt("36;1",`
|
|
126
|
+
\u25B6 ${t}`)),ok:t=>console.log(` ${bt("32","\u2713")} ${t}`),warn:t=>console.log(` ${bt("33","!")} ${t}`),err:t=>console.error(` ${bt("31","\u2717")} ${t}`),plain:t=>console.log(t)};async function kt(t,e=!0){if(!process.stdin.isTTY)return e;let n=nr({input:process.stdin,output:process.stdout});try{let r=(await n.question(`${t} ${e?"[Y/n]":"[y/N]"} `)).trim().toLowerCase();return r?r==="y"||r==="yes":e}finally{n.close()}}async function Ze(t,e){if(!process.stdin.isTTY)return e;let n=nr({input:process.stdin,output:process.stdout});try{return(await n.question(`${t}${e?` [${e}]`:""}: `)).trim()||e}finally{n.close()}}function sr(t){return P("systemctl",["is-active","--quiet",t]).ok}function Di(t,e){let n={...process.env,NO_COLOR:"1"};return t==="claude"&&e&&(n.CLAUDE_CONFIG_DIR=e),P(t,t==="claude"?["auth","status"]:["login","status"],{env:n,timeout:1e4}).ok}function ir(t){let e=[],n=0;for(let r of["claude","codex"]){let s=Ce(r);if(!s){e.push({name:r,level:"warn",detail:"not installed",fix:`install and sign in to the ${r} CLI to enable this provider`});continue}e.push({name:r,level:"ok",detail:s});let i=Di(r,r==="claude"?t:void 0);i&&n++,e.push(i?{name:`${r} auth`,level:"ok",detail:"CLI reports authenticated"}:{name:`${r} auth`,level:"warn",detail:"CLI authentication status failed",fix:`run \`${r}\` interactively and sign in again`})}return n===0&&e.push({name:"agent provider",level:"fail",detail:"no authenticated CLI is available",fix:"sign in to at least one installed provider CLI"}),e}function ar(){let t=[],e=(n,r)=>{let s=Ce(n);t.push(s?{name:n,level:"ok",detail:s}:{name:n,level:"fail",detail:"not found on PATH",fix:r})};return t.push(process.platform==="linux"?{name:"os",level:"ok",detail:"linux"}:{name:"os",level:"fail",detail:`${process.platform} (Linux + systemd required)`}),e("systemctl","this tool requires a systemd Linux host"),e("node","install Node.js \u2265 22"),e("git","install git"),e("nginx","install nginx (sudo apt install nginx)"),e("certbot","install certbot (sudo apt install certbot python3-certbot-nginx)"),t.push(...ir()),t.push(P("sudo",["-n","true"]).ok?{name:"sudo",level:"ok",detail:"passwordless sudo available"}:{name:"sudo",level:"warn",detail:"sudo will prompt for a password",fix:"install needs sudo for systemd/nginx/certbot"}),t}function or(t){let e=[],n=le(),r=ie();if(e.push(sr(n)?{name:`unit ${n}`,level:"ok",detail:"active"}:{name:`unit ${n}`,level:"fail",detail:"not active",fix:`sudo systemctl status ${n}; journalctl -u ${n} -n 50`}),e.push(sr(r)?{name:`unit ${r}`,level:"ok",detail:"active"}:{name:`unit ${r}`,level:"fail",detail:"not active",fix:`sudo systemctl status ${r}; journalctl -u ${r} -n 50`}),e.push(Tt(t.runnerSocket)?{name:"runner socket",level:"ok",detail:t.runnerSocket}:{name:"runner socket",level:"warn",detail:`${t.runnerSocket} missing (web falls back to in-process)`}),e.push(...ir(t.claudeConfigDir)),Ce("nginx")){let $=P("sudo",["nginx","-t"]);e.push($.ok?{name:"nginx -t",level:"ok",detail:"config valid"}:{name:"nginx -t",level:"fail",detail:$.stderr.trim().split(`
|
|
127
|
+
`).slice(-1)[0]||"invalid",fix:"fix the nginx config, then `sudo nginx -t`"})}let s=`/etc/letsencrypt/live/${t.domain}/fullchain.pem`,i=`/etc/letsencrypt/live/${t.domain}/privkey.pem`,a=w(["test","-s",i]),o=w(["openssl","x509","-checkhost",t.domain,"-enddate","-noout","-in",s]),u=o.ok?/notAfter=(.+)/.exec(o.stdout):void 0,d=u?new Date(u[1]).getTime():Number.NaN;if(!a.ok||!u||!Number.isFinite(d))e.push({name:"TLS cert",level:"fail",detail:`missing, unreadable, or invalid for ${t.domain}`,fix:`sudo certbot certonly --nginx -d ${t.domain}`});else{let $=Math.round((d-Date.now())/864e5);e.push($>14?{name:"TLS cert",level:"ok",detail:`expires in ${$}d (${t.domain})`}:$>=0?{name:"TLS cert",level:"warn",detail:`expires in ${$}d`,fix:"sudo certbot renew"}:{name:"TLS cert",level:"fail",detail:`expired ${Math.abs($)}d ago`,fix:"sudo certbot renew --force-renewal"})}Tt(t.dbPath)&&Oi(t.dbPath).size>0?e.push({name:"database",level:"ok",detail:t.dbPath}):e.push({name:"database",level:"warn",detail:`${t.dbPath} missing/empty (created on first boot)`});let p=rr(t.dataDir,"vapid.json");e.push(Tt(p)?{name:"VAPID keys",level:"ok",detail:`${p} (never delete \u2014 orphans push subscribers)`}:{name:"VAPID keys",level:"warn",detail:"not yet generated (created on first boot)"});let b=P("bash",["-lc",`ss -ltn 2>/dev/null | grep -E ':${t.port}\\b' || true`]);if(b.stdout.trim()){let $=/127(?:\.\d{1,3}){3}/.test(b.stdout)||b.stdout.includes("[::1]");e.push($?{name:"port bind",level:"ok",detail:`:${t.port} on loopback`}:{name:"port bind",level:"warn",detail:`:${t.port} not bound to loopback \u2014 nginx should front it`})}else e.push({name:"port bind",level:"warn",detail:`nothing listening on :${t.port}`});let A=t.mode==="package"&&t.pkgDir?rr(t.pkgDir,"web","index.html"):void 0;A&&e.push(Tt(A)?{name:"PWA dist",level:"ok",detail:"present"}:{name:"PWA dist",level:"fail",detail:"bundled web/ missing",fix:"reinstall the package"});let D=P("bash",["-lc",`df -Pk ${t.dataDir} 2>/dev/null | tail -1 | awk '{print $4}'`]),q=Number(D.stdout.trim());if(q){let $=(q/1024/1024).toFixed(1);e.push(q>1024*1024?{name:"disk",level:"ok",detail:`${$}G free`}:{name:"disk",level:"warn",detail:`${$}G free \u2014 low`,fix:"free up disk"})}return e}function Qt(t,e){f.step(t);let n=0,r=0;for(let s of e){let i=`${s.name.padEnd(22)} ${s.detail}`;s.level==="ok"?f.ok(i):s.level==="warn"?(r++,f.warn(`${i}${s.fix?` \u2192 ${s.fix}`:""}`)):(n++,f.err(`${i}${s.fix?` \u2192 ${s.fix}`:""}`))}return f.plain(""),n?f.err(`${n} failed, ${r} warning(s) \u2014 ${_.productName} is not healthy.`):r?f.warn(`${r} warning(s), 0 failures.`):f.ok("all checks passed."),n?1:0}W();function Pi(){return _.unitBase.replace(/[^a-zA-Z0-9]+/g,"_")}var $i=["127","0","0","1"].join(".");function Li(t){return[`${t}proxy_pass http://${$i}:__PORT__;`,`${t}proxy_http_version 1.1;`,`${t}proxy_set_header Host $host;`,`${t}proxy_set_header X-Real-IP $remote_addr;`,`${t}proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`,`${t}proxy_set_header X-Forwarded-Proto $scheme;`].join(`
|
|
128
|
+
`)}function Et(t){let e=Pi(),n=`${e}_api`,r=`${e}_auth`,s=`${e}_conn`,i=p=>Li(p).replaceAll("__PORT__",String(t.port)),a=[`# ${_.productName} \u2014 per-IP rate/conn limits (http{} context).`,`limit_req_zone $binary_remote_addr zone=${n}:10m rate=20r/s;`,`limit_req_zone $binary_remote_addr zone=${r}:10m rate=5r/s;`,`limit_conn_zone $binary_remote_addr zone=${s}:10m;`,""].join(`
|
|
129
|
+
`),o=`/etc/letsencrypt/live/${t.domain}`,u=[`# ${_.productName} vhost \u2014 generated by ${_.cliName}. HTTPS is mandatory.`,"server {"," listen 80;"," listen [::]:80;",` server_name ${t.domain};`," return 308 https://$host$request_uri;","}","","server {"," listen 443 ssl;"," listen [::]:443 ssl;",` server_name ${t.domain};`,""," # Scope response codes to this vhost so multiple managed apps can coexist."," limit_req_status 429;"," limit_conn_status 429;","",` ssl_certificate ${o}/fullchain.pem;`,` ssl_certificate_key ${o}/privkey.pem;`," ssl_protocols TLSv1.2 TLSv1.3;"," ssl_session_cache shared:SSL:10m;"," ssl_session_timeout 1d;"," ssl_session_tickets off;",' add_header Strict-Transport-Security "max-age=31536000" always;',""," # Image uploads are base64 JSON; match the application's 48MB cap."," client_max_body_size 48m;",""," # SSE: never buffer, hold the connection open. Protected by limit_conn,"," # NEVER limit_req (it's one long-lived request)."," location /api/stream {",i(" ")," proxy_buffering off;"," proxy_cache off;"," proxy_read_timeout 3600s;"," proxy_send_timeout 3600s;",` limit_conn ${s} 30;`," }",""," # Crypto endpoints \u2014 tighter rate."," location /api/auth/ {",i(" "),` limit_req zone=${r} burst=10 nodelay;`," }",""," location /api/ {",i(" "),` limit_req zone=${n} burst=40 nodelay;`,` limit_conn ${s} 30;`," }",""," # PWA shell + assets (load-time fan-out gets a bigger burst)."," location / {",i(" "),` limit_req zone=${n} burst=80 nodelay;`," }","}",""].join(`
|
|
130
|
+
`),d=[`# Temporary ${_.productName} ACME bootstrap \u2014 never proxies the application.`,"server {"," listen 80;"," listen [::]:80;",` server_name ${t.domain};`,""," location / {"," return 404;"," }","}",""].join(`
|
|
131
|
+
`);return{zones:{name:`${_.unitBase}-ratelimit.conf`,text:a},vhost:{name:`${_.unitBase}.conf`,text:u},bootstrap:{name:`${_.unitBase}-acme-bootstrap.conf`,text:d}}}Qe();import{createHash as Ui}from"node:crypto";import{existsSync as Mi,readFileSync as ur,writeFileSync as ji}from"node:fs";import{join as pe}from"node:path";var dr="runner-artifact.sha256";function Fi(t){return t.mode==="package"?t.pkgDir?[pe(t.pkgDir,"runner-daemon.js")]:[]:t.repoDir?[pe(t.repoDir,"apps","server","src","runner-daemon.ts"),pe(t.repoDir,"apps","server","src","daemon-protocol.ts"),pe(t.repoDir,"apps","server","src","ndjson.ts"),pe(t.repoDir,"apps","server","src","private-files.ts"),pe(t.repoDir,"packages","shared","src","branding.ts")]:[]}function cr(t){let e=Fi(t);if(!e.length||e.some(r=>!Mi(r)))return;let n=Ui("sha256");for(let r of e)n.update(r),n.update("\0"),n.update(ur(r)),n.update("\0");return n.digest("hex")}function en(t){let e=cr(t);if(!e)return!0;try{return ur(pe(t.dataDir,dr),"utf8").trim()!==e}catch{return!0}}function lr(t){let e=cr(t);if(!e)throw new Error("runner artifact is missing; reinstall or rebuild before starting the service");Me(t.dataDir);let n=pe(t.dataDir,dr);ji(n,e+`
|
|
132
|
+
`,{mode:384}),je(n)}function Ct(t){return zt({dataDir:t.get("data-dir"),requireInstalled:!0})}function ka(t,e){return["update","--data-dir",t.dataDir,...e.nonInteractive?["-y"]:[]]}var dn="/etc/systemd/system",ot="/etc/nginx/conf.d",ut="/etc/nginx/sites-available",cn="/etc/nginx/sites-enabled";function Ta(){let t=er();if(at(C(t,"server.js")))return{mode:"package",pkgDir:t};let e=ba(t,"..","..","..","..");return at(C(e,"apps","server","package.json"))?{mode:"source",repoDir:e}:{mode:"package",pkgDir:t}}async function qr(t,e=!1){let n=Ta(),r=st(t.get("data-dir")),s=zt({dataDir:r,pkgDir:n.pkgDir,requireInstalled:e}),i=t.get("domain")??(t.nonInteractive?s.domain:await Ze("Public domain (e.g. dispatch.example.com)",s.domain));if(!i)throw new Error("a public domain is required \u2014 pass --domain or enter it at the prompt (no default).");let a=Number(t.get("port")??(t.nonInteractive?s.port:await Ze("Internal port",String(s.port)))),o=Number(t.get("concurrency")??(t.nonInteractive?s.concurrency:await Ze("Max concurrent turns",String(s.concurrency)))),u=t.get("repo-roots")??(t.nonInteractive?s.repoRoots:await Ze("Repo scan roots (colon-separated, blank = ~/code)",s.repoRoots)),d=t.get("claude-config-dir")??(t.nonInteractive?s.claudeConfigDir:await Ze("Claude CLI config dir (CLAUDE_CONFIG_DIR, blank = ~/.claude default)",s.claudeConfigDir)),p=Jn({domain:i,host:t.get("host")??s.host,port:a,concurrency:o,pushSubject:t.get("push-subject")??s.pushSubject});return{...s,mode:n.mode,pkgDir:n.pkgDir,repoDir:n.repoDir,workingDir:n.mode==="source"?C(n.repoDir,"apps","server"):n.pkgDir,dataDir:r,runnerSocket:C(r,"runner.sock"),dbPath:s.dbPath,domain:p.domain,host:p.host,port:p.port,concurrency:p.concurrency,pushSubject:p.pushSubject,repoRoots:u,claudeConfigDir:d,...Kt(p.domain)}}function ln(t,e){let n=vt(t),r=C(dn,n.web.name),s=C(dn,n.runner.name),i;try{i=Hr(s,"utf8")}catch{}let a=i!==n.runner.text;if(e.dryRun)return f.info(`[dry-run] would write ${r} and ${s}`),f.info(`[dry-run] runner ${a?"CHANGED \u2192 would restart":"unchanged \u2192 would leave running"}`),f.plain(`
|
|
133
|
+
# ${s}
|
|
134
|
+
${n.runner.text}`),f.plain(`
|
|
135
|
+
# ${r}
|
|
136
|
+
${n.web.text}`),{runnerChanged:a};if(!Oe(s,n.runner.text))throw new Error(`failed to write ${s}`);if(!Oe(r,n.web.text))throw new Error(`failed to write ${r}`);let o=w(["systemctl","daemon-reload"]);if(!o.ok)throw new Error(`systemd daemon-reload failed:
|
|
137
|
+
${o.stderr}`);let u=w(["systemctl","enable",n.runner.name,n.web.name]);if(!u.ok)throw new Error(`failed to enable Palmagent units:
|
|
138
|
+
${u.stderr}`);return{runnerChanged:a}}function Br(t){let e=w(["readlink",t]);if(e.ok)return{kind:"symlink",target:e.stdout.trim()};let n=w(["cat",t]);return n.ok?{kind:"file",content:n.stdout}:{kind:"missing"}}function Wr(t,e){if(w(["rm","-f",t]),e.kind==="file"&&!Oe(t,e.content))throw new Error(`failed to restore ${t}`);if(e.kind==="symlink"&&!w(["ln","-s",e.target,t]).ok)throw new Error(`failed to restore symlink ${t}`)}function Ea(t,e){let n=C(t.dataDir,"nginx-last-good");va(n,{recursive:!0,mode:448});for(let[r,s]of e)s.kind==="file"&&Ur(C(n,Mr(r)),s.content,{mode:384}),s.kind==="symlink"&&Ur(C(n,`${Mr(r)}.symlink`),`${s.target}
|
|
139
|
+
`,{mode:384})}function dt(){let t=w(["nginx","-t"]);if(!t.ok)throw new Error(`nginx config invalid:
|
|
140
|
+
${t.stderr}`)}function Nt(){let t=w(["systemctl","reload","nginx"]);if(!t.ok)throw new Error(`nginx reload failed:
|
|
141
|
+
${t.stderr}`)}function xa(t){for(let[e,n]of[...t].reverse())Wr(e,n);dt(),Nt()}function pn(t,e){let n=Et(t),r=at(ut),s=r?C(ut,n.vhost.name):C(ot,n.vhost.name),i=C(ot,n.zones.name),a=r?C(cn,n.vhost.name):void 0;if(e.dryRun){f.info(`[dry-run] would write ${i} and ${s}`),f.info("[dry-run] would require a valid TLS certificate before activating the HTTPS vhost"),f.info("[dry-run] if absent, would use the ACME-only bootstrap without proxying the application over HTTP"),f.plain(`
|
|
142
|
+
# ${i}
|
|
143
|
+
${n.zones.text}`),f.plain(`
|
|
144
|
+
# ${s}
|
|
145
|
+
${n.vhost.text}`),f.plain(`
|
|
146
|
+
# temporary ACME bootstrap
|
|
147
|
+
${n.bootstrap.text}`);return}dt();let o=[i,s,...a?[a]:[]],u=new Map(o.map(d=>[d,Br(d)]));Ea(t,u);try{if(!Oe(i,n.zones.text))throw new Error(`failed to write ${i}`);if(!Oe(s,n.vhost.text))throw new Error(`failed to write ${s}`);if(a&&!w(["ln","-sfn",s,a]).ok)throw new Error(`failed to enable ${s}`);dt(),Nt()}catch(d){throw xa(u),d}f.ok("HTTPS-only nginx vhost applied")}function jr(t){let e=`/etc/letsencrypt/live/${t.domain}/fullchain.pem`,n=`/etc/letsencrypt/live/${t.domain}/privkey.pem`;return w(["test","-s",n]).ok&&w(["openssl","x509","-checkend","0","-checkhost",t.domain,"-noout","-in",e]).ok}function fn(t,e){if(e.dryRun){f.info(`[dry-run] would verify or obtain a valid TLS certificate for ${t.domain}`);return}if(jr(t)){f.ok(`TLS cert already present for ${t.domain}`);return}let n=Et(t),r=at(ut),s=r?C(ut,n.bootstrap.name):C(ot,n.bootstrap.name),i=r?C(cn,n.bootstrap.name):void 0,a=[s,...i?[i]:[]],o=new Map(a.map(u=>[u,Br(u)]));f.info(`obtaining TLS cert for ${t.domain} \u2026`);try{if(!Oe(s,n.bootstrap.text))throw new Error(`failed to write ${s}`);if(i&&!w(["ln","-sfn",s,i]).ok)throw new Error(`failed to enable ${s}`);dt(),Nt();let u=w(["certbot","certonly","--nginx","-d",t.domain,"--non-interactive","--agree-tos","--register-unsafely-without-email","--force-renewal"]);if(!u.ok)throw new Error(`certbot did not complete:
|
|
148
|
+
${u.stderr}`)}finally{for(let[u,d]of[...o].reverse())Wr(u,d);dt(),Nt()}if(!jr(t))throw new Error(`certbot did not produce a valid TLS certificate for ${t.domain}`);f.ok("TLS cert obtained")}async function Gr(t,e){if(e.dryRun){f.info("[dry-run] would mint a first-passkey enroll link");return}try{let{Db:n}=await Promise.resolve().then(()=>(vr(),yr)),{AuthService:r}=await Promise.resolve().then(()=>(Lr(),$r)),s=new n(t.dbPath),i=new r(s),{token:a,expiresAt:o}=i.mintEnrollToken();s.close(),f.ok("First-passkey enroll link (single-use, 15 min):"),f.plain(`
|
|
149
|
+
${t.authOrigin}/#/enroll/${a}
|
|
150
|
+
`),f.info(`expires ${new Date(o).toISOString()} \u2014 open it on the device you want to register`)}catch(n){f.warn(`could not mint enroll token: ${n.message}. Run \`${_.cliName} passkey\` later.`)}}function Ra(t){for(let e=0;e<15;e++){if(P("systemctl",["is-active","--quiet",ie()]).ok&&at(t.runnerSocket))return;P("sleep",["1"])}throw new Error(`runner did not become active at ${t.runnerSocket}; see journalctl -u ${ie()} -n 50`)}function mn(t){let e=w(["systemctl","restart",ie()]);if(!e.ok)throw new Error(`failed to restart ${ie()}:
|
|
151
|
+
${e.stderr}`);Ra(t),lr(t)}function hn(){let t=w(["systemctl","restart",le()]);if(!t.ok)throw new Error(`failed to restart ${le()}:
|
|
152
|
+
${t.stderr}`)}function wa(t){let e=vt(t);if(e.runner.name!==ie()||e.web.name!==le())throw new Error("rendered unit names do not match the installed Palmagent units");mn(t),hn()}async function gn(t){let e=`http://${t.host}:${t.port}/api/health`;for(let n=0;n<30;n++){if(P("curl",["-fsS",e]).ok)return!0;P("sleep",["1"])}return!1}async function Vr(t){f.step(`${_.productName} install`),t.dryRun||Zt();let e=ar();if(Qt("Preflight",e)!==0&&!t.force)return f.err("preflight failed \u2014 fix the above or re-run with --force. Aborting."),1;!t.dryRun&&!Yt()&&f.warn("sudo will prompt for a password during install.");let r=await qr(t);if(f.step("Configuration"),f.info(`mode=${r.mode} domain=${r.domain} port=${r.port} user=${r.user} data=${r.dataDir}`),!t.dryRun&&!t.nonInteractive&&!await kt("Proceed with this configuration?"))return 1;if(t.dryRun)f.info("[dry-run] would write install.env");else{let s=Jt(r);f.ok(`wrote ${s}`)}if(f.step("TLS (certbot)"),fn(r,t),f.step("systemd units"),ln(r,t),f.step("HTTPS-only nginx vhost + rate limits"),pn(r,t),!t.dryRun){if(f.step("starting services"),wa(r),!await gn(r))return f.err(`service did not become healthy \u2014 see: journalctl -u ${le()} -n 50`),1;f.ok(`host-local health check passed; public origin is https://${r.domain}`),f.step("first passkey"),await Gr(r,t)}return f.step("done"),f.ok(`${_.productName} installed. Open https://${r.domain} and register your passkey.`),0}async function Xr(t){f.step(`${_.productName} setup (reconfigure)`),t.dryRun||Zt();let e=await qr(t,!0),n=en(e);f.step("TLS"),fn(e,t),t.dryRun||(Jt(e),f.ok("updated install.env"));let{runnerChanged:r}=ln(e,t);if(pn(e,t),!t.dryRun){r||n?(f.warn(`runner ${r?"unit":"artifact"} changed \u2014 restarting it (ends in-flight turns)`),mn(e)):f.ok("runner unchanged \u2014 leaving it up so in-flight turns survive"),hn();let s=await gn(e);return f[s?"ok":"err"](s?"healthy":"not healthy after restart"),s?0:1}return 0}var Fr="PALMAGENT_UPDATE_POST_UPGRADE";function Sa(t){if(!t)return"latest";try{return String(JSON.parse(Hr(C(t,"package.json"),"utf8")).version??"").includes("-")?"next":"latest"}catch{return"latest"}}function Aa(t,e){let n=`${t}@${e}`,r=P("npm",["install","-g",n]);return r.ok?!0:/EACCES|permission denied|EROFS/i.test(r.stderr)&&Yt()?(f.info("retrying the global install with sudo \u2026"),w(["npm","install","-g",n]).ok):(r.stderr.trim()&&f.err(r.stderr.trim()),!1)}async function Kr(t){f.step(`${_.productName} update`);let e=Ct(t);if(t.pull&&e.mode==="source")return f.err("source checkouts are maintainer-managed and cannot self-update; use the repository pnpm verification/build workflow, then run palmagent setup"),1;if(t.pull&&e.mode==="package"&&process.env[Fr]!=="1"){let i=Sa(e.pkgDir);if(t.dryRun)f.info(`[dry-run] would run: npm install -g ${_.packageName}@${i}, then re-render units + restart`);else{if(f.info(`upgrading ${_.packageName} via npm (i -g ${_.packageName}@${i}) \u2026`),!Aa(_.packageName,i))return f.err(`npm upgrade failed \u2014 install it yourself (\`npm i -g ${_.packageName}@${i}\`, add sudo if your npm prefix needs it) then re-run \`${_.cliName} update\`.`),1;f.ok(`upgraded ${_.packageName}`);let a=Ce(_.cliName);if(a)return f.info("applying units + restarting with the upgraded CLI \u2026"),ya(a,ka(e,t),{stdio:"inherit",env:{...process.env,[Fr]:"1"}}).status??1;f.warn(`could not locate the upgraded ${_.cliName} on PATH \u2014 applying units with the current CLI; re-run \`${_.cliName} setup --data-dir ${e.dataDir}\` if this release changed the unit templates.`)}}fn(e,t);let n=en(e),{runnerChanged:r}=ln(e,t);if(pn(e,t),t.dryRun)return 0;r||n?(f.warn(`runner ${r?"unit":"artifact"} changed \u2014 restarting it (ends in-flight turns)`),mn(e)):f.ok("runner unchanged \u2014 leaving it up so in-flight turns survive"),hn();let s=await gn(e);return f[s?"ok":"err"](s?"updated + healthy":"not healthy after update"),s?0:1}async function Zr(t){f.step(`${_.productName} uninstall`);let e=Ct(t);t.purge&&Qn(e.dataDir);let n=vt(e);if(t.dryRun)return f.info(`[dry-run] would stop+disable ${n.web.name} and ${n.runner.name}, remove their unit files and the nginx vhost`),t.purge&&f.info(`[dry-run] --purge would DELETE the data dir ${e.dataDir}`),0;if(!t.nonInteractive&&!await kt(`Remove ${_.productName} services on this host?`,!1))return 1;for(let s of[n.web.name,n.runner.name])w(["systemctl","disable","--now",s]),w(["rm","-f",C(dn,s)]);w(["systemctl","daemon-reload"]);let r=Et(e);if(w(["rm","-f",C(cn,r.vhost.name),C(ut,r.vhost.name),C(ot,r.vhost.name),C(ot,r.zones.name)]),Ce("nginx")&&w(["systemctl","reload","nginx"]),f.ok("services + nginx vhost removed"),t.purge)if(t.nonInteractive||await kt(`DELETE all data at ${e.dataDir} (DB, push subscribers, VAPID keys \u2014 irreversible)?`,!1)){let i=w(["rm","-rf",e.dataDir]);if(!i.ok)throw new Error(`failed to purge ${e.dataDir}:
|
|
153
|
+
${i.stderr}`);f.ok(`purged ${e.dataDir}`)}else f.info(`data preserved at ${e.dataDir}`);else f.info(`data preserved at ${e.dataDir} (use --purge to delete)`);return 0}async function zr(t){let e=Ct(t);return await Gr(e,{dryRun:!1}),0}function Jr(t){let e=Ct(t);return Qt(`${_.productName} doctor \u2014 ${e.domain}`,or(e))}var yn=Ca(Oa(import.meta.url));function Yr(){try{return String(JSON.parse(Na(Ot(yn,"package.json"),"utf8")).version??"0.0.0")}catch{return"0.0.0"}}async function Da(t){let e=st(t.get("data-dir"));if(Me(e),process.env.DISPATCHER_DATA_DIR=e,!process.env.STATIC_DIR){let n=Ot(yn,"web");Ia(Ot(n,"index.html"))&&(process.env.STATIC_DIR=n)}await import(Ot(yn,"server.js"))}function Pa(t){let e=new Set(["dry-run","non-interactive","force","purge","pull"]),n={},r=new Set;for(let s=0;s<t.length;s++){let i=t[s];if(i==="-y"){r.add("non-interactive");continue}if(!i.startsWith("--"))continue;let a=i.indexOf("=");if(a>=0){n[i.slice(2,a)]=i.slice(a+1);continue}let o=i.slice(2);e.has(o)?r.add(o):s+1<t.length&&!t[s+1].startsWith("--")?n[o]=t[++s]:r.add(o)}return{dryRun:r.has("dry-run"),nonInteractive:r.has("non-interactive"),force:r.has("force"),purge:r.has("purge"),pull:r.has("pull"),get:s=>n[s]}}function _n(){console.log(`${_.productName} \u2014 ${_.cliName} v${Yr()}
|
|
154
|
+
|
|
155
|
+
Usage: ${_.cliName} <command> [options]
|
|
156
|
+
|
|
157
|
+
Commands:
|
|
158
|
+
install First-run setup: systemd units, nginx, TLS (certbot), first passkey
|
|
159
|
+
setup Reconfigure an existing install + re-render units/nginx
|
|
160
|
+
doctor Diagnose a running instance + suggest fixes
|
|
161
|
+
update Apply config, or fetch the installed npm channel with --pull (package installs only)
|
|
162
|
+
uninstall Remove the units + nginx vhost (data preserved unless --purge)
|
|
163
|
+
passkey Mint a fresh device-enroll link for an existing install
|
|
164
|
+
start Run the web server directly (dev/manual; reads env)
|
|
165
|
+
|
|
166
|
+
Common options:
|
|
167
|
+
--dry-run Render + print everything, change nothing (install/setup/update/uninstall)
|
|
168
|
+
--non-interactive,-y Never prompt; use flags/defaults
|
|
169
|
+
--domain <d> Public domain (required for a fresh install)
|
|
170
|
+
--port <n> Internal loopback port (default 4100)
|
|
171
|
+
--concurrency <n> Max concurrent turns (default 8)
|
|
172
|
+
--data-dir <path> Locate install state for every command (default ~/.local/state/${_.stateDirName})
|
|
173
|
+
--repo-roots <list> Colon-separated repo scan roots
|
|
174
|
+
--claude-config-dir <path> Claude CLI config/creds dir (CLAUDE_CONFIG_DIR); blank = ~/.claude
|
|
175
|
+
--force Proceed past failed preflight (install)
|
|
176
|
+
--pull update: fetch the installed npm release channel (source checkouts are maintainer-managed)
|
|
177
|
+
--purge uninstall: also delete the data dir (irreversible)
|
|
178
|
+
|
|
179
|
+
--version Print the version
|
|
180
|
+
--help Print this help
|
|
181
|
+
`)}async function $a(){let[t,...e]=process.argv.slice(2);if(e.includes("--help")||e.includes("-h")){_n();return}let n=Pa(e);switch(t){case"start":return Da(n);case"install":process.exit(await Vr(n));case"setup":process.exit(await Xr(n));case"doctor":process.exit(Jr(n));case"update":process.exit(await Kr(n));case"uninstall":process.exit(await Zr(n));case"passkey":process.exit(await zr(n));case"--version":case"-v":console.log(Yr());return;case void 0:case"--help":case"-h":_n();return;default:console.error(`unknown command: ${t}
|
|
182
|
+
`),_n(),process.exit(2)}}$a().catch(t=>{console.error(`
|
|
183
|
+
${t instanceof Error?t.message:String(t)}`),process.exit(1)});
|