palmagent 0.1.0-alpha.97 → 0.1.0-alpha.99

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/build-info.json +2 -2
  2. package/execution-host.js +7 -7
  3. package/package.json +1 -1
  4. package/server.js +46 -44
  5. package/web/assets/{CodeHighlight-DLrtIfEF.js → CodeHighlight-BWAuRBpy.js} +1 -1
  6. package/web/assets/{MermaidViewport-CJYAgQrL.js → MermaidViewport-U40wFtcG.js} +1 -1
  7. package/web/assets/{abnfDiagram-O67JEVCF-BhUnZwjO.js → abnfDiagram-O67JEVCF-DGhfhoBx.js} +1 -1
  8. package/web/assets/{arc-CD7GEUo5.js → arc-C5cEh0eD.js} +1 -1
  9. package/web/assets/{architectureDiagram-NJMV4G6O-B1Q3lDsJ.js → architectureDiagram-NJMV4G6O-BVBfekyc.js} +1 -1
  10. package/web/assets/{blockDiagram-BEXU5L5S-BlYbdM5B.js → blockDiagram-BEXU5L5S-J1Wroiz9.js} +1 -1
  11. package/web/assets/{c4Diagram-YGBWAQC7-CqSnqzJ3.js → c4Diagram-YGBWAQC7-MN7y0edo.js} +1 -1
  12. package/web/assets/channel-OOf3RC4P.js +1 -0
  13. package/web/assets/{chunk-2Q5K7J3B-vjlLgdMB.js → chunk-2Q5K7J3B-BD0yNTMU.js} +1 -1
  14. package/web/assets/{chunk-3FUC2YCW-CoKEJP-x.js → chunk-3FUC2YCW-BvURxAUO.js} +2 -2
  15. package/web/assets/{chunk-5VM5RSS4-C1J_MAld.js → chunk-5VM5RSS4-CbfIa1-K.js} +1 -1
  16. package/web/assets/{chunk-GTNCS2PH-DESIVZ5f.js → chunk-GTNCS2PH--ahhm1Y4.js} +1 -1
  17. package/web/assets/{chunk-GWA4HPMP-Kudj_s1H.js → chunk-GWA4HPMP-C94fNZ1y.js} +1 -1
  18. package/web/assets/{chunk-JWPE2WC7-DjvOWrPV.js → chunk-JWPE2WC7-B1HceEB8.js} +1 -1
  19. package/web/assets/{chunk-NETBCI7D-Dn0LgODj.js → chunk-NETBCI7D-CY1cCRb0.js} +1 -1
  20. package/web/assets/{chunk-WEXAMYUT-3G7SRLBO.js → chunk-WEXAMYUT-C6RJjiG6.js} +1 -1
  21. package/web/assets/{chunk-XXDRQBXY-CIXJUBal.js → chunk-XXDRQBXY-BB3rEl3T.js} +1 -1
  22. package/web/assets/{classDiagram-v2-NBCMYWYE-CjSMC-4w.js → classDiagram-v2-NBCMYWYE-BGtGWJgv.js} +1 -1
  23. package/web/assets/{cose-bilkent-JH36ORCC-CctXHYNj.js → cose-bilkent-JH36ORCC-BmpQcWTG.js} +1 -1
  24. package/web/assets/{cynefin-OW5HDTMX-BS7mFy8X.js → cynefin-OW5HDTMX-DTMLqokC.js} +1 -1
  25. package/web/assets/{cynefinDiagram-VND7K2PF-B_PtGT2T.js → cynefinDiagram-VND7K2PF-DbTMW9qS.js} +1 -1
  26. package/web/assets/{dagre-6A5THRUB-szOZdsS8.js → dagre-6A5THRUB-nZzonNGi.js} +1 -1
  27. package/web/assets/{diagram-22UHCM2B-CBLw0rxJ.js → diagram-22UHCM2B-BRgjAlv4.js} +1 -1
  28. package/web/assets/{diagram-3UASUU5V-C8lgdbTg.js → diagram-3UASUU5V-Dpd_48ET.js} +1 -1
  29. package/web/assets/{diagram-ATOU4E4O-fMIpamed.js → diagram-ATOU4E4O-Bb-FS9ML.js} +1 -1
  30. package/web/assets/{diagram-CDSNMT55-Ctv_mZjI.js → diagram-CDSNMT55-BhmWJr3L.js} +1 -1
  31. package/web/assets/{diagram-MLGK6HIB-DWUKEFnS.js → diagram-MLGK6HIB-WnGV8OOO.js} +1 -1
  32. package/web/assets/{diagram-MPIPVDR6-BBdTOpxn.js → diagram-MPIPVDR6-DAUBxuYY.js} +1 -1
  33. package/web/assets/{ebnfDiagram-ZINNZB2B-jm3amGo1.js → ebnfDiagram-ZINNZB2B-DrUdKyAG.js} +1 -1
  34. package/web/assets/{elk-276RUBZZ-BsLMEgkz.js → elk-276RUBZZ-CvsRJLSA.js} +1 -1
  35. package/web/assets/{erDiagram-OPXOYQCR-lhkO7PoK.js → erDiagram-OPXOYQCR-DZPnBHNQ.js} +1 -1
  36. package/web/assets/{flowDiagram-KWPJA3E3-BVhVYVqB.js → flowDiagram-KWPJA3E3-BX-zOWxa.js} +1 -1
  37. package/web/assets/{ganttDiagram-FUAMR5RP-9jJoPnU_.js → ganttDiagram-FUAMR5RP-mCQPjZEp.js} +1 -1
  38. package/web/assets/{gitGraphDiagram-X574FWY7-HiKQV-fh.js → gitGraphDiagram-X574FWY7-2XxJVTxw.js} +1 -1
  39. package/web/assets/{index-C07nyT_3.js → index-BI8iehxC.js} +92 -92
  40. package/web/assets/{infoDiagram-VRGFBTTK-ZODNnSXb.js → infoDiagram-VRGFBTTK-GFiPxpSs.js} +1 -1
  41. package/web/assets/{ishikawaDiagram-OU5B5YK6-DRDdfReK.js → ishikawaDiagram-OU5B5YK6-Ck0LXJJJ.js} +1 -1
  42. package/web/assets/{journeyDiagram-ZHPQQLJL-CbQm1c-f.js → journeyDiagram-ZHPQQLJL-BFPTdxW-.js} +1 -1
  43. package/web/assets/{kanban-definition-PNTS6WVX-zFJA0aZJ.js → kanban-definition-PNTS6WVX-9U7aoidM.js} +1 -1
  44. package/web/assets/{linear-DCq8Op4m.js → linear-VAaRhFk7.js} +1 -1
  45. package/web/assets/{mermaid.core-CCqpf1l7.js → mermaid.core-B-WF684S.js} +4 -4
  46. package/web/assets/{mindmap-definition-NLK3R4M7-CJT_WBkO.js → mindmap-definition-NLK3R4M7-BMjnrPkT.js} +1 -1
  47. package/web/assets/{pegDiagram-GJSIUBJH-C7QTGmAR.js → pegDiagram-GJSIUBJH-BKveL162.js} +1 -1
  48. package/web/assets/{pieDiagram-5QR66LMP-DN7a5kxC.js → pieDiagram-5QR66LMP-DLCrQm3-.js} +1 -1
  49. package/web/assets/{quadrantDiagram-O4NWA36T-BouM2yas.js → quadrantDiagram-O4NWA36T-CkeEer_v.js} +1 -1
  50. package/web/assets/{railroadDiagram-XR7U4H2S-Ch1WvcP6.js → railroadDiagram-XR7U4H2S-BwHgsuW_.js} +1 -1
  51. package/web/assets/{requirementDiagram-PLB6GJNP-Cm4QgaC9.js → requirementDiagram-PLB6GJNP-qCqYRyhz.js} +1 -1
  52. package/web/assets/{sankeyDiagram-IPEJSGJF-CotBHoNG.js → sankeyDiagram-IPEJSGJF-CJkQp-T4.js} +1 -1
  53. package/web/assets/{sequenceDiagram-PO4LG4MO-Bc9aNMlf.js → sequenceDiagram-PO4LG4MO-dcox7hEK.js} +1 -1
  54. package/web/assets/{sizeCapture-INFHLROL-Bw-xUm-Z.js → sizeCapture-INFHLROL-CqUhZJ_m.js} +1 -1
  55. package/web/assets/{stateDiagram-v2-GCMORJYK-BuM7PKFJ.js → stateDiagram-v2-GCMORJYK-DMPCzqHq.js} +1 -1
  56. package/web/assets/{swimlanes-2SLR337P-CcOESApt.js → swimlanes-2SLR337P-CmOg2RGp.js} +1 -1
  57. package/web/assets/swimlanesDiagram-TC7HE7FX-BNars3W-.js +8 -0
  58. package/web/assets/{timeline-definition-EJHVYXUP-0IH3aBhj.js → timeline-definition-EJHVYXUP-B22tsiRm.js} +1 -1
  59. package/web/assets/{usecaseDiagram-POWQR4AR-hYX1NYcX.js → usecaseDiagram-POWQR4AR-CRlSqwnU.js} +1 -1
  60. package/web/assets/{vennDiagram-UO4OBE2U-DBLCzgn5.js → vennDiagram-UO4OBE2U-CyFyBhNy.js} +1 -1
  61. package/web/assets/{wardleyDiagram-VNRHLVJA-C0vLDofA.js → wardleyDiagram-VNRHLVJA-Dxf2zVHi.js} +1 -1
  62. package/web/assets/{xychartDiagram-PMCCYNJV-DPbMayya.js → xychartDiagram-PMCCYNJV-DOaC5IKt.js} +1 -1
  63. package/web/index.html +1 -1
  64. package/web/sw.js +1 -1
  65. package/web/assets/channel-OCD596gs.js +0 -1
  66. package/web/assets/swimlanesDiagram-TC7HE7FX-uZS8mTGP.js +0 -8
package/build-info.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.1.0-alpha.97",
2
+ "version": "0.1.0-alpha.99",
3
3
  "agentCliCompatibility": {
4
4
  "claude": {
5
5
  "range": ">=2.1.268 <2.2.0",
@@ -12,6 +12,6 @@
12
12
  "exclusiveMaximum": "0.156.0"
13
13
  }
14
14
  },
15
- "sourceCommit": "ab842da146c308dd05b6342b616d5fbc3b0b835b",
15
+ "sourceCommit": "09c5ef89a9bcd263c35aa4e5c40b524457a3cb3e",
16
16
  "dirty": false
17
17
  }
package/execution-host.js CHANGED
@@ -1,4 +1,4 @@
1
- var Mr=Object.defineProperty;var Lr=(r,e)=>{for(var t in e)Mr(r,t,{get:e[t],enumerable:!0})};import{readFileSync as Zs}from"node:fs";import{join as Ws,resolve as Xs}from"node:path";var a={};Lr(a,{BRAND:()=>ln,DIRTY:()=>ke,EMPTY_PATH:()=>Fr,INVALID:()=>y,NEVER:()=>Jn,OK:()=>F,ParseStatus:()=>H,Schema:()=>E,ZodAny:()=>ye,ZodArray:()=>fe,ZodBigInt:()=>Ee,ZodBoolean:()=>Te,ZodBranded:()=>Ke,ZodCatch:()=>De,ZodDate:()=>we,ZodDefault:()=>Ue,ZodDiscriminatedUnion:()=>ot,ZodEffects:()=>Q,ZodEnum:()=>je,ZodError:()=>z,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>dt,ZodIntersection:()=>Ne,ZodIssueCode:()=>u,ZodLazy:()=>Ce,ZodLiteral:()=>Oe,ZodMap:()=>Ve,ZodNaN:()=>Ze,ZodNativeEnum:()=>Pe,ZodNever:()=>ie,ZodNull:()=>Re,ZodNullable:()=>ce,ZodNumber:()=>Se,ZodObject:()=>Z,ZodOptional:()=>K,ZodParsedType:()=>m,ZodPipeline:()=>Ye,ZodPromise:()=>_e,ZodReadonly:()=>Me,ZodRecord:()=>ct,ZodSchema:()=>E,ZodSet:()=>ze,ZodString:()=>ge,ZodSymbol:()=>Fe,ZodTransformer:()=>Q,ZodTuple:()=>oe,ZodType:()=>E,ZodUndefined:()=>Ie,ZodUnion:()=>Ae,ZodUnknown:()=>me,ZodVoid:()=>Be,addIssueToContext:()=>p,any:()=>bn,array:()=>En,bigint:()=>hn,boolean:()=>Kt,coerce:()=>Xn,custom:()=>Xt,date:()=>gn,datetimeRegex:()=>Zt,defaultErrorMap:()=>le,discriminatedUnion:()=>Rn,effect:()=>Hn,enum:()=>Mn,function:()=>Pn,getErrorMap:()=>qe,getParsedType:()=>ae,instanceof:()=>mn,intersection:()=>An,isAborted:()=>it,isAsync:()=>He,isDirty:()=>at,isValid:()=>he,late:()=>pn,lazy:()=>Un,literal:()=>Dn,makeIssue:()=>Ge,map:()=>On,nan:()=>fn,nativeEnum:()=>Ln,never:()=>kn,null:()=>xn,nullable:()=>Fn,number:()=>Gt,object:()=>Tn,objectUtil:()=>bt,oboolean:()=>Wn,onumber:()=>Zn,optional:()=>$n,ostring:()=>zn,pipeline:()=>Vn,preprocess:()=>Bn,promise:()=>qn,quotelessJson:()=>qr,record:()=>Cn,set:()=>jn,setErrorMap:()=>$r,strictObject:()=>wn,string:()=>Jt,symbol:()=>yn,transformer:()=>Hn,tuple:()=>Nn,undefined:()=>_n,union:()=>In,unknown:()=>vn,util:()=>I,void:()=>Sn});var I;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),o={};for(let c of i)o[c]=s[c];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(I||(I={}));var bt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(bt||(bt={}));var m=I.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ae=r=>{switch(typeof r){case"undefined":return m.undefined;case"string":return m.string;case"number":return Number.isNaN(r)?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(r)?m.array:r===null?m.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?m.promise:typeof Map<"u"&&r instanceof Map?m.map:typeof Set<"u"&&r instanceof Set?m.set:typeof Date<"u"&&r instanceof Date?m.date:m.object;default:return m.unknown}};var u=I.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"]),qr=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),z=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let c=n,l=0;for(;l<o.path.length;){let d=o.path[l];l===o.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(t(o))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,I.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};z.create=r=>new z(r);var Hr=(r,e)=>{let t;switch(r.code){case u.invalid_type:r.received===m.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case u.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,I.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${I.joinValues(r.keys,", ")}`;break;case u.invalid_union:t="Invalid input";break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${I.joinValues(r.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${I.joinValues(r.options)}, received '${r.received}'`;break;case u.invalid_arguments:t="Invalid function arguments";break;case u.invalid_return_type:t="Invalid function return type";break;case u.invalid_date:t="Invalid date";break;case u.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:I.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case u.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case u.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case u.custom:t="Invalid input";break;case u.invalid_intersection_types:t="Intersection results could not be merged";break;case u.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case u.not_finite:t="Number must be finite";break;default:t=e.defaultError,I.assertNever(r)}return{message:t}},le=Hr;var $t=le;function $r(r){$t=r}function qe(){return $t}var Ge=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="",l=n.filter(d=>!!d).slice().reverse();for(let d of l)c=d(o,{data:e,defaultError:c}).message;return{...s,path:i,message:c}},Fr=[];function p(r,e){let t=qe(),n=Ge({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===le?void 0:le].filter(s=>!!s)});r.common.issues.push(n)}var H=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return y;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return y;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},y=Object.freeze({status:"aborted"}),ke=r=>({status:"dirty",value:r}),F=r=>({status:"valid",value:r}),it=r=>r.status==="aborted",at=r=>r.status==="dirty",he=r=>r.status==="valid",He=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var Y=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,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}},Ft=(r,e)=>{if(he(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new z(r.common.issues);return this._error=t,this._error}}};function k(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))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:(o,c)=>{let{message:l}=r;return o.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??n??c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:l??t??c.defaultError}},description:s}}var E=class{get description(){return this._def.description}_getType(e){return ae(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new H,ctx:{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(He(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Ft(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return he(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>he(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(He(s)?s:Promise.resolve(s));return Ft(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),c=()=>i.addIssue({code:u.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Q({schema:this,typeName:_.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:t=>this["~validate"](t)}}optional(){return K.create(this,this._def)}nullable(){return ce.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fe.create(this)}promise(){return _e.create(this,this._def)}or(e){return Ae.create([this,e],this._def)}and(e){return Ne.create(this,e,this._def)}transform(e){return new Q({...k(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ue({...k(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new Ke({typeName:_.ZodBranded,type:this,...k(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new De({...k(this._def),innerType:this,catchValue:t,typeName:_.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ye.create(this,e)}readonly(){return Me.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Br=/^c[^\s-]{8,}$/i,Vr=/^[0-9a-z]+$/,zr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zr=/^[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,Wr=/^[a-z0-9_-]{21}$/i,Xr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Jr=/^[-+]?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)?)??$/,Gr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Kr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vt,Yr=/^(?:(?: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])$/,Qr=/^(?:(?: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])$/,en=/^(([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]))$/,tn=/^(([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])$/,rn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vt="((\\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])))",sn=new RegExp(`^${Vt}$`);function zt(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function an(r){return new RegExp(`^${zt(r)}$`)}function Zt(r){let e=`${Vt}T${zt(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function on(r,e){return!!((e==="v4"||!e)&&Yr.test(r)||(e==="v6"||!e)&&en.test(r))}function cn(r,e){if(!Xr.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function dn(r,e){return!!((e==="v4"||!e)&&Qr.test(r)||(e==="v6"||!e)&&tn.test(r))}var ge=class r extends E{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){let i=this._getOrReturnCtx(e);return p(i,{code:u.invalid_type,expected:m.string,received:i.parsedType}),y}let n=new H,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,c=e.data.length<i.value;(o||c)&&(s=this._getOrReturnCtx(e,s),o?p(s,{code:u.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&p(s,{code:u.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Gr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"email",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")vt||(vt=new RegExp(Kr,"u")),vt.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"emoji",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Zr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"uuid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Wr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"nanoid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Br.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Vr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid2",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")zr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ulid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),p(s,{validation:"url",code:u.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"regex",code:u.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.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),p(s,{code:u.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Zt(i).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?sn.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?an(i).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Jr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?on(e.data,i.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ip",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?cn(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"jwt",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?dn(e.data,i.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cidr",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?rn.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?nn.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:u.invalid_string,message:i.message}),n.dirty()):I.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:u.invalid_string,...h.errToObj(n)})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};ge.create=r=>new ge({checks:[],typeName:_.ZodString,coerce:r?.coerce??!1,...k(r)});function un(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Se=class r extends E{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 p(i,{code:u.invalid_type,expected:m.number,received:i.parsedType}),y}let n,s=new H;for(let i of this._def.checks)i.kind==="int"?I.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:u.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.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)&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?un(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:u.not_finite,message:i.message}),s.dirty()):I.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&I.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Se.create=r=>new Se({checks:[],typeName:_.ZodNumber,coerce:r?.coerce||!1,...k(r)});var Ee=class r extends E{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 n,s=new H;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.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)&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):I.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:u.invalid_type,expected:m.bigint,received:t.parsedType}),y}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ee.create=r=>new Ee({checks:[],typeName:_.ZodBigInt,coerce:r?.coerce??!1,...k(r)});var Te=class extends E{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.boolean,received:n.parsedType}),y}return F(e.data)}};Te.create=r=>new Te({typeName:_.ZodBoolean,coerce:r?.coerce||!1,...k(r)});var we=class r extends E{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){let i=this._getOrReturnCtx(e);return p(i,{code:u.invalid_type,expected:m.date,received:i.parsedType}),y}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:u.invalid_date}),y}let n=new H,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):I.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};we.create=r=>new we({checks:[],coerce:r?.coerce||!1,typeName:_.ZodDate,...k(r)});var Fe=class extends E{_parse(e){if(this._getType(e)!==m.symbol){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.symbol,received:n.parsedType}),y}return F(e.data)}};Fe.create=r=>new Fe({typeName:_.ZodSymbol,...k(r)});var Ie=class extends E{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.undefined,received:n.parsedType}),y}return F(e.data)}};Ie.create=r=>new Ie({typeName:_.ZodUndefined,...k(r)});var Re=class extends E{_parse(e){if(this._getType(e)!==m.null){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.null,received:n.parsedType}),y}return F(e.data)}};Re.create=r=>new Re({typeName:_.ZodNull,...k(r)});var ye=class extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return F(e.data)}};ye.create=r=>new ye({typeName:_.ZodAny,...k(r)});var me=class extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return F(e.data)}};me.create=r=>new me({typeName:_.ZodUnknown,...k(r)});var ie=class extends E{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:u.invalid_type,expected:m.never,received:t.parsedType}),y}};ie.create=r=>new ie({typeName:_.ZodNever,...k(r)});var Be=class extends E{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.void,received:n.parsedType}),y}return F(e.data)}};Be.create=r=>new Be({typeName:_.ZodVoid,...k(r)});var fe=class r extends E{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==m.array)return p(t,{code:u.invalid_type,expected:m.array,received:t.parsedType}),y;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,c=t.data.length<s.exactLength.value;(o||c)&&(p(t,{code:o?u.too_big:u.too_small,minimum:c?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(p(t,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(p(t,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,c)=>s.type._parseAsync(new Y(t,o,t.path,c)))).then(o=>H.mergeArray(n,o));let i=[...t.data].map((o,c)=>s.type._parseSync(new Y(t,o,t.path,c)));return H.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};fe.create=(r,e)=>new fe({type:r,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...k(e)});function $e(r){if(r instanceof Z){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=K.create($e(n))}return new Z({...r._def,shape:()=>e})}else return r instanceof fe?new fe({...r._def,type:$e(r.element)}):r instanceof K?K.create($e(r.unwrap())):r instanceof ce?ce.create($e(r.unwrap())):r instanceof oe?oe.create(r.items.map(e=>$e(e))):r}var Z=class r extends E{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(),t=I.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==m.object){let d=this._getOrReturnCtx(e);return p(d,{code:u.invalid_type,expected:m.object,received:d.parsedType}),y}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof ie&&this._def.unknownKeys==="strip"))for(let d in s.data)o.includes(d)||c.push(d);let l=[];for(let d of o){let f=i[d],v=s.data[d];l.push({key:{status:"valid",value:d},value:f._parse(new Y(s,v,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ie){let d=this._def.unknownKeys;if(d==="passthrough")for(let f of c)l.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(d==="strict")c.length>0&&(p(s,{code:u.unrecognized_keys,keys:c}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let f of c){let v=s.data[f];l.push({key:{status:"valid",value:f},value:d._parse(new Y(s,v,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let f of l){let v=await f.key,U=await f.value;d.push({key:v,value:U,alwaysSet:f.alwaysSet})}return d}).then(d=>H.mergeObjectSync(n,d)):H.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of I.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of I.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return $e(this)}partial(e){let t={};for(let n of I.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of I.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof K;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Wt(I.objectKeys(this.shape))}};Z.create=(r,e)=>new Z({shape:()=>r,unknownKeys:"strip",catchall:ie.create(),typeName:_.ZodObject,...k(e)});Z.strictCreate=(r,e)=>new Z({shape:()=>r,unknownKeys:"strict",catchall:ie.create(),typeName:_.ZodObject,...k(e)});Z.lazycreate=(r,e)=>new Z({shape:r,unknownKeys:"strip",catchall:ie.create(),typeName:_.ZodObject,...k(e)});var Ae=class extends E{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let o=i.map(c=>new z(c.ctx.common.issues));return p(t,{code:u.invalid_union,unionErrors:o}),y}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let l of n){let d={...t,common:{...t.common,issues:[]},parent:null},f=l._parseSync({data:t.data,path:t.path,parent:d});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let c=o.map(l=>new z(l));return p(t,{code:u.invalid_union,unionErrors:c}),y}}get options(){return this._def.options}};Ae.create=(r,e)=>new Ae({options:r,typeName:_.ZodUnion,...k(e)});var pe=r=>r instanceof Ce?pe(r.schema):r instanceof Q?pe(r.innerType()):r instanceof Oe?[r.value]:r instanceof je?r.options:r instanceof Pe?I.objectValues(r.enum):r instanceof Ue?pe(r._def.innerType):r instanceof Ie?[void 0]:r instanceof Re?[null]:r instanceof K?[void 0,...pe(r.unwrap())]:r instanceof ce?[null,...pe(r.unwrap())]:r instanceof Ke||r instanceof Me?pe(r.unwrap()):r instanceof De?pe(r._def.innerType):[],ot=class r extends E{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.object)return p(t,{code:u.invalid_type,expected:m.object,received:t.parsedType}),y;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=pe(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of o){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,i)}}return new r({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...k(n)})}};function kt(r,e){let t=ae(r),n=ae(e);if(r===e)return{valid:!0,data:r};if(t===m.object&&n===m.object){let s=I.objectKeys(e),i=I.objectKeys(r).filter(c=>s.indexOf(c)!==-1),o={...r,...e};for(let c of i){let l=kt(r[c],e[c]);if(!l.valid)return{valid:!1};o[c]=l.data}return{valid:!0,data:o}}else if(t===m.array&&n===m.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],c=e[i],l=kt(o,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===m.date&&n===m.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Ne=class extends E{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(it(i)||it(o))return y;let c=kt(i.value,o.value);return c.valid?((at(i)||at(o))&&t.dirty(),{status:t.value,value:c.data}):(p(n,{code:u.invalid_intersection_types}),y)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ne.create=(r,e,t)=>new Ne({left:r,right:e,typeName:_.ZodIntersection,...k(t)});var oe=class r extends E{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.array)return p(n,{code:u.invalid_type,expected:m.array,received:n.parsedType}),y;if(n.data.length<this._def.items.length)return p(n,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),y;!this._def.rest&&n.data.length>this._def.items.length&&(p(n,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new Y(n,o,n.path,c)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>H.mergeArray(t,o)):H.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};oe.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new oe({items:r,typeName:_.ZodTuple,rest:null,...k(e)})};var ct=class r extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.object)return p(n,{code:u.invalid_type,expected:m.object,received:n.parsedType}),y;let s=[],i=this._def.keyType,o=this._def.valueType;for(let c in n.data)s.push({key:i._parse(new Y(n,c,n.path,c)),value:o._parse(new Y(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?H.mergeObjectAsync(t,s):H.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof E?new r({keyType:e,valueType:t,typeName:_.ZodRecord,...k(n)}):new r({keyType:ge.create(),valueType:e,typeName:_.ZodRecord,...k(t)})}},Ve=class extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.map)return p(n,{code:u.invalid_type,expected:m.map,received:n.parsedType}),y;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([c,l],d)=>({key:s._parse(new Y(n,c,n.path,[d,"key"])),value:i._parse(new Y(n,l,n.path,[d,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of o){let d=await l.key,f=await l.value;if(d.status==="aborted"||f.status==="aborted")return y;(d.status==="dirty"||f.status==="dirty")&&t.dirty(),c.set(d.value,f.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let l of o){let d=l.key,f=l.value;if(d.status==="aborted"||f.status==="aborted")return y;(d.status==="dirty"||f.status==="dirty")&&t.dirty(),c.set(d.value,f.value)}return{status:t.value,value:c}}}};Ve.create=(r,e,t)=>new Ve({valueType:e,keyType:r,typeName:_.ZodMap,...k(t)});var ze=class r extends E{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.set)return p(n,{code:u.invalid_type,expected:m.set,received:n.parsedType}),y;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(p(n,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(p(n,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(l){let d=new Set;for(let f of l){if(f.status==="aborted")return y;f.status==="dirty"&&t.dirty(),d.add(f.value)}return{status:t.value,value:d}}let c=[...n.data.values()].map((l,d)=>i._parse(new Y(n,l,n.path,d)));return n.common.async?Promise.all(c).then(l=>o(l)):o(c)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ze.create=(r,e)=>new ze({valueType:r,minSize:null,maxSize:null,typeName:_.ZodSet,...k(e)});var dt=class r extends E{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.function)return p(t,{code:u.invalid_type,expected:m.function,received:t.parsedType}),y;function n(c,l){return Ge({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,qe(),le].filter(d=>!!d),issueData:{code:u.invalid_arguments,argumentsError:l}})}function s(c,l){return Ge({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,qe(),le].filter(d=>!!d),issueData:{code:u.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof _e){let c=this;return F(async function(...l){let d=new z([]),f=await c._def.args.parseAsync(l,i).catch(C=>{throw d.addIssue(n(l,C)),d}),v=await Reflect.apply(o,this,f);return await c._def.returns._def.type.parseAsync(v,i).catch(C=>{throw d.addIssue(s(v,C)),d})})}else{let c=this;return F(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new z([n(l,d.error)]);let f=Reflect.apply(o,this,d.data),v=c._def.returns.safeParse(f,i);if(!v.success)throw new z([s(f,v.error)]);return v.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:oe.create(e).rest(me.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||oe.create([]).rest(me.create()),returns:t||me.create(),typeName:_.ZodFunction,...k(n)})}},Ce=class extends E{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ce.create=(r,e)=>new Ce({getter:r,typeName:_.ZodLazy,...k(e)});var Oe=class extends E{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}};Oe.create=(r,e)=>new Oe({value:r,typeName:_.ZodLiteral,...k(e)});function Wt(r,e){return new je({values:r,typeName:_.ZodEnum,...k(e)})}var je=class r extends E{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:I.joinValues(n),received:t.parsedType,code:u.invalid_type}),y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{received:t.data,code:u.invalid_enum_value,options:n}),y}return F(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};je.create=Wt;var Pe=class extends E{_parse(e){let t=I.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==m.string&&n.parsedType!==m.number){let s=I.objectValues(t);return p(n,{expected:I.joinValues(s),received:n.parsedType,code:u.invalid_type}),y}if(this._cache||(this._cache=new Set(I.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=I.objectValues(t);return p(n,{received:n.data,code:u.invalid_enum_value,options:s}),y}return F(e.data)}get enum(){return this._def.values}};Pe.create=(r,e)=>new Pe({values:r,typeName:_.ZodNativeEnum,...k(e)});var _e=class extends E{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.promise&&t.common.async===!1)return p(t,{code:u.invalid_type,expected:m.promise,received:t.parsedType}),y;let n=t.parsedType===m.promise?t.data:Promise.resolve(t.data);return F(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};_e.create=(r,e)=>new _e({type:r,typeName:_.ZodPromise,...k(e)});var Q=class extends E{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{p(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async c=>{if(t.value==="aborted")return y;let l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?y:l.status==="dirty"?ke(l.value):t.value==="dirty"?ke(l.value):l});{if(t.value==="aborted")return y;let c=this._def.schema._parseSync({data:o,path:n.path,parent:n});return c.status==="aborted"?y:c.status==="dirty"?ke(c.value):t.value==="dirty"?ke(c.value):c}}if(s.type==="refinement"){let o=c=>{let l=s.refinement(c,i);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?y:(c.status==="dirty"&&t.dirty(),o(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?y:(c.status==="dirty"&&t.dirty(),o(c.value).then(()=>({status:t.value,value:c.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!he(o))return y;let c=s.transform(o.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>he(o)?Promise.resolve(s.transform(o.value,i)).then(c=>({status:t.value,value:c})):y);I.assertNever(s)}};Q.create=(r,e,t)=>new Q({schema:r,typeName:_.ZodEffects,effect:e,...k(t)});Q.createWithPreprocess=(r,e,t)=>new Q({schema:e,effect:{type:"preprocess",transform:r},typeName:_.ZodEffects,...k(t)});var K=class extends E{_parse(e){return this._getType(e)===m.undefined?F(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};K.create=(r,e)=>new K({innerType:r,typeName:_.ZodOptional,...k(e)});var ce=class extends E{_parse(e){return this._getType(e)===m.null?F(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ce.create=(r,e)=>new ce({innerType:r,typeName:_.ZodNullable,...k(e)});var Ue=class extends E{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===m.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ue.create=(r,e)=>new Ue({innerType:r,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...k(e)});var De=class extends E{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return He(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};De.create=(r,e)=>new De({innerType:r,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...k(e)});var Ze=class extends E{_parse(e){if(this._getType(e)!==m.nan){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.nan,received:n.parsedType}),y}return{status:"valid",value:e.data}}};Ze.create=r=>new Ze({typeName:_.ZodNaN,...k(r)});var ln=Symbol("zod_brand"),Ke=class extends E{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Ye=class r extends E{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?y:i.status==="dirty"?(t.dirty(),ke(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?y:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:_.ZodPipeline})}},Me=class extends E{_parse(e){let t=this._def.innerType._parse(e),n=s=>(he(s)&&(s.value=Object.freeze(s.value)),s);return He(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Me.create=(r,e)=>new Me({innerType:r,typeName:_.ZodReadonly,...k(e)});function Bt(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xt(r,e={},t){return r?ye.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let c=Bt(e,n),l=c.fatal??t??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let o=Bt(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}}):ye.create()}var pn={object:Z.lazycreate},_;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(_||(_={}));var mn=(r,e={message:`Input not instance of ${r.name}`})=>Xt(t=>t instanceof r,e),Jt=ge.create,Gt=Se.create,fn=Ze.create,hn=Ee.create,Kt=Te.create,gn=we.create,yn=Fe.create,_n=Ie.create,xn=Re.create,bn=ye.create,vn=me.create,kn=ie.create,Sn=Be.create,En=fe.create,Tn=Z.create,wn=Z.strictCreate,In=Ae.create,Rn=ot.create,An=Ne.create,Nn=oe.create,Cn=ct.create,On=Ve.create,jn=ze.create,Pn=dt.create,Un=Ce.create,Dn=Oe.create,Mn=je.create,Ln=Pe.create,qn=_e.create,Hn=Q.create,$n=K.create,Fn=ce.create,Bn=Q.createWithPreprocess,Vn=Ye.create,zn=()=>Jt().optional(),Zn=()=>Gt().optional(),Wn=()=>Kt().optional(),Xn={string:r=>ge.create({...r,coerce:!0}),number:r=>Se.create({...r,coerce:!0}),boolean:r=>Te.create({...r,coerce:!0}),bigint:r=>Ee.create({...r,coerce:!0}),date:r=>we.create({...r,coerce:!0})};var Jn=y;var Gn=a.object({id:a.string().min(1).max(128),name:a.string().min(1).max(200),source:a.string().max(200),pluginId:a.string().max(200).optional(),path:a.string().max(4096).optional()}),de=a.array(Gn).max(1).optional(),Yt=a.object({taskId:a.string().min(1).optional(),repoId:a.string().min(1).optional(),agent:a.enum(["claude","codex"]).optional()}).refine(r=>r.taskId?!r.repoId&&!r.agent:!!r.repoId&&!!r.agent,"Select a task or a repository and agent");var ut=a.enum(["stable","preview"]),Kn=a.object({schemaVersion:a.literal(1),status:a.enum(["applying","succeeded","failed","deferred"]),previousVersion:a.string(),targetVersion:a.string(),reason:a.string(),pluginsUpdated:a.number().int().nonnegative().optional(),pluginActivationPending:a.boolean().optional(),checkedAt:a.string()}),Yn=a.union([a.object({channel:ut}).strict(),a.object({autoUpdate:a.boolean()}).strict()]),Ti=a.union([a.object({action:a.enum(["visit","check"])}).strict(),a.object({action:a.literal("install"),version:a.string().min(1).max(100)}).strict()]),Qn=a.object({channel:ut,currentVersion:a.string(),targetVersion:a.string().nullable(),checkedAt:a.string().datetime(),eligible:a.boolean(),pluginsPending:a.number().int().nonnegative().optional(),error:a.boolean()}),es=a.object({id:a.string().uuid(),channel:ut,currentVersion:a.string(),targetVersion:a.string(),automatic:a.boolean()}),ts=a.object({availability:a.enum(["available","not-installed","source-install","installation-mismatch","permission-required","authentication-required","unavailable"]),settings:a.object({channel:ut,autoUpdate:a.boolean(),independentExecutions:a.boolean().optional(),discovery:Qn.nullable(),pending:es.nullable(),lastUpdate:Kn.nullable()}).nullable()}),wi=a.union([a.object({ok:a.literal(!0),state:ts}),a.object({ok:a.literal(!1),error:a.enum(["busy","unavailable","save-failed","stale-update","update-failed"])})]);var rs=a.string().trim().min(1).max(4096).refine(r=>!/[\x00-\x1f\x7f]/.test(r),"Path contains control characters"),lt=a.array(rs).max(64),ns=a.discriminatedUnion("action",[a.object({action:a.literal("set"),paths:lt}).strict(),a.object({action:a.literal("add"),paths:lt.min(1)}).strict(),a.object({action:a.literal("remove"),paths:lt.min(1)}).strict(),a.object({action:a.literal("reset")}).strict()]);var Et=a.enum(["claude","codex"]),N=a.string(),D=N.min(1),Qe={permission:N.optional(),model:N.optional(),effort:N.optional()},Qt=a.number().int().min(1).max(1e5),xe=a.object({mediaType:N,data:N,width:Qt.optional(),height:Qt.optional()}).refine(({width:r,height:e})=>r===void 0==(e===void 0)),Tt=a.array(xe).optional(),Oi=a.object({path:D,name:N.optional(),defaultBaseRef:N.optional()}),ji=a.object({repoId:D,agent:Et,prompt:N,skills:de,...Qe,title:N.optional(),images:Tt,isolate:a.boolean().optional()}),Pi=a.object({prompt:N,images:Tt,...Qe}),Ui=a.object({title:N.trim().min(1,"Enter a session name.").max(200,"Use 200 characters or fewer.").regex(/^[^\r\n]*$/,"Use a single line for the session name.")}),Di=a.object({text:N,images:Tt,...Qe}),Mi=a.object({decision:a.enum(["approve","deny"]),scope:N.optional()}),ss=a.object({questionId:D.optional(),question:N,selected:a.array(N),notes:N.optional()}),tr=a.object({requestId:D,answers:a.array(ss),response:N.optional()}),rr={preset:a.enum(["hourly","daily","weekly","weekdays","manual","custom"]).optional(),schedule:N.optional(),hour:a.number().int().min(0).max(23).optional(),dayOfWeek:a.number().int().min(0).max(6).optional()},nr=a.object({command:N.trim().min(1).max(16e3),timeoutSeconds:a.number().int().min(1).max(3600).optional()}),Li=a.object({repoId:D,agent:Et.optional(),prompt:D.optional(),kind:a.enum(["agent","script"]).optional(),script:nr.optional(),...rr,...Qe,title:N.optional(),enabled:a.boolean().optional()}).superRefine((r,e)=>{r.kind==="script"?(r.script||e.addIssue({code:"custom",path:["script"],message:"script is required"}),[r.agent,r.prompt,r.permission,r.model,r.effort].some(t=>t!==void 0)&&e.addIssue({code:"custom",message:"script routines do not accept agent settings"})):((!r.agent||!r.prompt?.trim())&&e.addIssue({code:"custom",message:"agent and prompt are required"}),r.script&&e.addIssue({code:"custom",path:["script"],message:"script requires kind script"}))}),qi=a.object({script:nr.optional(),prompt:D.optional(),...rr,...Qe,title:N.optional(),enabled:a.boolean().optional()}),is=a.object({endpoint:D,expirationTime:a.number().nullable().optional(),keys:a.record(N).optional()}),Hi=a.object({subscription:is}),$i=a.object({endpoint:D}),Fi=a.object({agent:Et,sessionId:D,cwd:D,home:D,waitPid:a.number().int().positive()}),as=a.enum(["queued","running","awaiting_approval","awaiting_input","idle","archived","failed","cancelled"]),Bi=a.object({status:as.optional()}),St=a.string().regex(/^\d+$/).refine(r=>{let e=Number(r);return Number.isSafeInteger(e)&&e>=1}),er=a.string().regex(/^\d+$/).refine(r=>{let e=Number(r);return Number.isSafeInteger(e)&&e>=0}),Vi=a.object({before:St.optional(),details:a.enum(["summary","full"]).optional()}),zi=a.object({after:er,through:er.optional(),details:a.enum(["summary","full"]).optional()}),Zi=a.object({from:St,through:St}),Wi=a.object({path:N.min(1).max(4096).regex(/^[^\u0000-\u001f\u007f]*$/)}),Xi=a.object({task:N.optional(),snapshots:a.literal("1").optional(),details:a.enum(["summary","full"]).optional()}),Ji=a.object({path:N.optional()}),Gi=a.object({refresh:a.enum(["0","1"]).optional()}),os=a.object({id:D}),Ki=os.extend({messageId:D}),Yi=a.object({}),Qi=a.object({token:N.optional()}),sr={id:D,rawId:D,type:a.literal("public-key"),authenticatorAttachment:a.enum(["platform","cross-platform"]).optional(),clientExtensionResults:a.object({}).passthrough()},ea=a.object({...sr,response:a.object({clientDataJSON:D,authenticatorData:D,signature:D,userHandle:N.optional()})}),ta=a.object({response:a.object({...sr,response:a.object({clientDataJSON:D,attestationObject:D,transports:a.array(a.enum(["ble","cable","hybrid","internal","nfc","smart-card","usb"])).optional(),publicKeyAlgorithm:a.number().optional(),publicKey:N.optional(),authenticatorData:N.optional()})}),label:N.optional()});var et=1,ir=a.string().uuid(),wt=a.object({taskId:a.string().min(1),agent:a.enum(["claude","codex"]),cwd:a.string().min(1),prompt:a.string(),resumeId:a.string().optional(),providerHome:a.string().optional(),permission:a.string().optional(),model:a.string().optional(),effort:a.string().optional(),images:a.array(xe).optional(),messageId:a.string().optional(),interactive:a.boolean().optional()}).strict(),It=a.discriminatedUnion("kind",[a.object({kind:a.literal("send"),skills:de,text:a.string(),images:a.array(xe).optional(),messageId:a.string()}),a.object({kind:a.literal("steer"),text:a.string(),images:a.array(xe).optional()}),a.object({kind:a.literal("answer"),answer:tr}),a.object({kind:a.literal("approve"),decision:a.string(),scope:a.string().optional()}),a.object({kind:a.literal("interrupt")}),a.object({kind:a.literal("cancel")})]);var ar={claude:"acceptEdits",codex:"workspace-write"};var pt={productName:"Palmagent",displayName:"PalmAgent",packageName:"palmagent",cliName:"palmagent",unitBase:"palmagent",stateDirName:"palmagent"};var cs=a.object({model:a.string().optional(),effort:a.string().optional(),permission:a.string().optional()}),_a=a.object({clientMessageId:a.string().uuid(),mode:a.enum(["send","queue"]),text:a.string().trim().min(1).max(1e5),skills:de,images:a.array(xe).optional(),expectedRunId:a.string().nullable(),settings:cs.optional()}),xa=a.discriminatedUnion("action",[a.object({action:a.literal("edit"),version:a.number().int(),token:a.string().uuid()}),a.object({action:a.literal("renew"),token:a.string().uuid()}),a.object({action:a.literal("save"),token:a.string().uuid(),version:a.number().int(),text:a.string().trim().min(1).max(1e5),skills:de,images:a.array(xe).optional()}),a.object({action:a.literal("release"),token:a.string().uuid()}),a.object({action:a.literal("delete"),version:a.number().int()}),a.object({action:a.literal("send"),version:a.number().int(),expectedRunId:a.string().nullable()})]);var Sa=a.object({id:a.string().uuid(),mediaType:a.enum(["image/png","image/jpeg","image/gif","image/webp"]),size:a.number().int().positive(),width:a.number().int().min(1).max(1e5).optional(),height:a.number().int().min(1).max(1e5).optional()}).refine(({width:r,height:e})=>r===void 0==(e===void 0)),Ea=a.object({id:a.string().min(1),attachmentId:a.string().uuid()});var Ra=a.object({context:Yt,sdp:a.string().min(1).max(65536).startsWith("v=0")}),be=a.number().finite().min(0).max(10*6e4),ds=a.object({outcome:a.enum(["completed","cancelled","failed"]),audioContextResumeMs:be.optional(),microphoneRequestMs:be.optional(),localOfferMs:be.optional(),serverRequestMs:be.optional(),remoteDescriptionMs:be.optional(),tapToReadyMs:be.optional(),tapToFirstTranscriptMs:be.optional(),voiceToFirstTranscriptMs:be.optional()}).strict(),Aa=a.object({timings:ds.optional()}).strict();import bs from"better-sqlite3";import{randomUUID as vs,createHash as xr}from"node:crypto";import{join as ks}from"node:path";import{chmodSync as or,mkdirSync as us,openSync as Za,closeSync as Wa,fsyncSync as Xa,writeFileSync as Ja,renameSync as Ga,unlinkSync as Ka}from"node:fs";function cr(r){us(r,{recursive:!0,mode:448}),or(r,448)}function dr(r){or(r,384)}import{createHash as _s}from"node:crypto";import{readFileSync as yr,readdirSync as _o,realpathSync as xo,statSync as bo}from"node:fs";import{homedir as ps}from"node:os";import{existsSync as lr}from"node:fs";import{dirname as hr,join as We,resolve as Le}from"node:path";import{fileURLToPath as ms}from"node:url";var Rt={maxBytes:1073741824,minFreeBytes:268435456,unusedGraceMs:864e5,retentionMs:0},Qa=60*60*1e3;import{homedir as ur}from"node:os";import{join as ls}from"node:path";function At(r){return r==="~"?ur():r.startsWith("~/")?ls(ur(),r.slice(2)):r}var fs=hr(ms(import.meta.url)),hs=r=>r==="localhost"||r==="::1"||/^127(?:\.\d{1,3}){3}$/.test(r),gs=a.object({PORT:a.coerce.number().int().positive().default(4e3),HOST:a.string().min(1).refine(hs,"HOST must be loopback; terminate public HTTPS at the reverse proxy").default("localhost"),ATTACHMENT_MAX_BYTES:a.coerce.number().int().positive().safe().default(Rt.maxBytes),ATTACHMENT_MIN_FREE_BYTES:a.coerce.number().int().nonnegative().safe().default(Rt.minFreeBytes),ATTACHMENT_UNUSED_GRACE_HOURS:a.coerce.number().int().min(1).max(8760).default(24),ATTACHMENT_RETENTION_DAYS:a.coerce.number().int().min(0).max(36500).default(0),DISPATCH_CONCURRENCY:a.coerce.number().int().min(1).default(8),SSE_KEEPALIVE_MS:a.coerce.number().int().positive().default(15e3),AUTH_SESSION_TTL_MS:a.coerce.number().int().positive().default(30*24*60*60*1e3),AUTH_COOKIE_NAME:a.string().min(1).default("palmagent_session"),AUTH_RP_ID:a.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:a.string().min(1).optional(),AUTH_ORIGIN:a.string().url().startsWith("https://","AUTH_ORIGIN must use https://").optional(),AUTH_ENABLED:a.string().optional(),AUTH_DISABLED:a.string().optional(),PUSH_SUBJECT:a.string().regex(/^(mailto:|https:\/\/)/,"PUSH_SUBJECT must be a mailto: or https:// URL").optional(),DISPATCHER_DATA_DIR:a.string().min(1).optional(),XDG_STATE_HOME:a.string().min(1).optional(),DISPATCHER_DB:a.string().min(1).optional(),VAPID_KEY_PATH:a.string().min(1).optional(),STATIC_DIR:a.string().min(1).optional(),REPO_ROOTS:a.string().optional(),GITHUB_TOKEN:a.string().min(1).optional(),RUNNER_SOCKET:a.string().min(1).optional(),EXECUTION_RELEASE:a.string().min(1).optional(),EXECUTION_NODE:a.string().min(1).optional(),CLAUDE_MODEL:a.string().min(1).optional(),CODEX_MODEL:a.string().min(1).optional(),CLAUDE_EFFORT:a.string().min(1).optional(),CODEX_EFFORT:a.string().min(1).optional(),CLAUDE_CONFIG_DIR:a.string().min(1).optional(),NODE_ENV:a.string().optional()}).passthrough();function ys(r){let e={};for(let[t,n]of Object.entries(r))n!==void 0&&n!==""&&(e[t]=n);return e}var w=gs.parse(ys(process.env)),gr=w.AUTH_DISABLED==="1"?!1:w.AUTH_ENABLED==="1"?!0:w.NODE_ENV==="production",Nt=w.AUTH_RP_ID??(gr?"":"localhost"),Ct=w.DISPATCHER_DATA_DIR?Le(w.DISPATCHER_DATA_DIR):w.XDG_STATE_HOME?We(Le(w.XDG_STATE_HOME),pt.stateDirName):We(ps(),".local","state",pt.stateDirName),pr=We(Ct,"palmagent.db"),mr=We(Ct,"dispatcher.db"),fr=w.DISPATCHER_DB?Le(w.DISPATCHER_DB):lr(pr)||!lr(mr)?pr:mr,Ot={port:w.PORT,host:w.HOST,concurrency:w.DISPATCH_CONCURRENCY,attachmentStorage:{maxBytes:w.ATTACHMENT_MAX_BYTES,minFreeBytes:w.ATTACHMENT_MIN_FREE_BYTES,unusedGraceMs:w.ATTACHMENT_UNUSED_GRACE_HOURS*60*60*1e3,retentionMs:w.ATTACHMENT_RETENTION_DAYS*24*60*60*1e3},dataDir:Ct,dbPath:fr,keepAliveMs:w.SSE_KEEPALIVE_MS,claudeModel:w.CLAUDE_MODEL,codexModel:w.CODEX_MODEL,claudeEffort:w.CLAUDE_EFFORT,codexEffort:w.CODEX_EFFORT,claudeConfigDir:w.CLAUDE_CONFIG_DIR?Le(At(w.CLAUDE_CONFIG_DIR)):void 0,vapidKeyPath:w.VAPID_KEY_PATH?Le(w.VAPID_KEY_PATH):We(hr(fr),"vapid.json"),pushSubject:w.PUSH_SUBJECT,staticDir:w.STATIC_DIR?Le(w.STATIC_DIR):We(fs,"..","..","web","dist"),repoRoots:(w.REPO_ROOTS??"").split(":").filter(Boolean).map(r=>Le(At(r))),runnerSocket:w.RUNNER_SOCKET,executionRelease:w.EXECUTION_RELEASE,executionNode:w.EXECUTION_NODE,githubToken:w.GITHUB_TOKEN,authEnabled:gr,rpId:Nt,rpName:w.AUTH_RP_NAME??pt.displayName,authOrigin:w.AUTH_ORIGIN??(Nt?`https://${Nt}`:""),sessionTtlMs:w.AUTH_SESSION_TTL_MS,cookieName:w.AUTH_COOKIE_NAME,nodeEnv:w.NODE_ENV};var xs=r=>_s("sha256").update(r).digest("hex");function _r(r){if(!Number.isSafeInteger(r)||r<=1)throw new Error("A valid local CLI process id is required");try{let e=yr(`/proc/${r}/stat`,"utf8"),t=e.slice(e.lastIndexOf(")")+2).split(" ");return t[0]==="Z"?void 0:`${yr("/proc/sys/kernel/random/boot_id","utf8").trim()}:${t[19]}`}catch(e){if(e.code==="ENOENT")return;throw new Error("Cannot verify the local CLI process; ownership is retained")}}var So=xs(Buffer.alloc(0));var mt=class{constructor(e){this.directory=e;cr(e);let t=ks(e,"executions.sqlite");this.db=new bs(t),dr(t),this.db.pragma("busy_timeout = 5000"),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = FULL");let n=this.db.pragma("user_version",{simple:!0});if(n!==0&&n!==et)throw this.db.close(),new Error("Unsupported execution store version");this.db.exec(`
1
+ var Mr=Object.defineProperty;var Lr=(r,e)=>{for(var t in e)Mr(r,t,{get:e[t],enumerable:!0})};import{readFileSync as Zs}from"node:fs";import{join as Ws,resolve as Xs}from"node:path";var a={};Lr(a,{BRAND:()=>ln,DIRTY:()=>ke,EMPTY_PATH:()=>Fr,INVALID:()=>y,NEVER:()=>Jn,OK:()=>F,ParseStatus:()=>H,Schema:()=>E,ZodAny:()=>ye,ZodArray:()=>fe,ZodBigInt:()=>Ee,ZodBoolean:()=>Te,ZodBranded:()=>Ke,ZodCatch:()=>De,ZodDate:()=>we,ZodDefault:()=>Ue,ZodDiscriminatedUnion:()=>ot,ZodEffects:()=>Q,ZodEnum:()=>je,ZodError:()=>z,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>dt,ZodIntersection:()=>Ce,ZodIssueCode:()=>u,ZodLazy:()=>Ne,ZodLiteral:()=>Oe,ZodMap:()=>Ve,ZodNaN:()=>Ze,ZodNativeEnum:()=>Pe,ZodNever:()=>ie,ZodNull:()=>Re,ZodNullable:()=>ce,ZodNumber:()=>Se,ZodObject:()=>Z,ZodOptional:()=>K,ZodParsedType:()=>m,ZodPipeline:()=>Ye,ZodPromise:()=>_e,ZodReadonly:()=>Me,ZodRecord:()=>ct,ZodSchema:()=>E,ZodSet:()=>ze,ZodString:()=>ge,ZodSymbol:()=>Fe,ZodTransformer:()=>Q,ZodTuple:()=>oe,ZodType:()=>E,ZodUndefined:()=>Ie,ZodUnion:()=>Ae,ZodUnknown:()=>me,ZodVoid:()=>Be,addIssueToContext:()=>p,any:()=>bn,array:()=>En,bigint:()=>hn,boolean:()=>Kt,coerce:()=>Xn,custom:()=>Xt,date:()=>gn,datetimeRegex:()=>Zt,defaultErrorMap:()=>le,discriminatedUnion:()=>Rn,effect:()=>Hn,enum:()=>Mn,function:()=>Pn,getErrorMap:()=>qe,getParsedType:()=>ae,instanceof:()=>mn,intersection:()=>An,isAborted:()=>it,isAsync:()=>He,isDirty:()=>at,isValid:()=>he,late:()=>pn,lazy:()=>Un,literal:()=>Dn,makeIssue:()=>Ge,map:()=>On,nan:()=>fn,nativeEnum:()=>Ln,never:()=>kn,null:()=>xn,nullable:()=>Fn,number:()=>Gt,object:()=>Tn,objectUtil:()=>bt,oboolean:()=>Wn,onumber:()=>Zn,optional:()=>$n,ostring:()=>zn,pipeline:()=>Vn,preprocess:()=>Bn,promise:()=>qn,quotelessJson:()=>qr,record:()=>Nn,set:()=>jn,setErrorMap:()=>$r,strictObject:()=>wn,string:()=>Jt,symbol:()=>yn,transformer:()=>Hn,tuple:()=>Cn,undefined:()=>_n,union:()=>In,unknown:()=>vn,util:()=>I,void:()=>Sn});var I;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let i={};for(let o of s)i[o]=o;return i},r.getValidEnumValues=s=>{let i=r.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),o={};for(let c of i)o[c]=s[c];return r.objectValues(o)},r.objectValues=s=>r.objectKeys(s).map(function(i){return s[i]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let i=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},r.find=(s,i)=>{for(let o of s)if(i(o))return o},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}r.joinValues=n,r.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(I||(I={}));var bt;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(bt||(bt={}));var m=I.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ae=r=>{switch(typeof r){case"undefined":return m.undefined;case"string":return m.string;case"number":return Number.isNaN(r)?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(r)?m.array:r===null?m.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?m.promise:typeof Map<"u"&&r instanceof Map?m.map:typeof Set<"u"&&r instanceof Set?m.set:typeof Date<"u"&&r instanceof Date?m.date:m.object;default:return m.unknown}};var u=I.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"]),qr=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),z=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},n={_errors:[]},s=i=>{for(let o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(t(o));else{let c=n,l=0;for(;l<o.path.length;){let d=o.path[l];l===o.path.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(t(o))):c[d]=c[d]||{_errors:[]},c=c[d],l++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,I.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let i=s.path[0];t[i]=t[i]||[],t[i].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};z.create=r=>new z(r);var Hr=(r,e)=>{let t;switch(r.code){case u.invalid_type:r.received===m.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case u.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,I.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${I.joinValues(r.keys,", ")}`;break;case u.invalid_union:t="Invalid input";break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${I.joinValues(r.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${I.joinValues(r.options)}, received '${r.received}'`;break;case u.invalid_arguments:t="Invalid function arguments";break;case u.invalid_return_type:t="Invalid function return type";break;case u.invalid_date:t="Invalid date";break;case u.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:I.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case u.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case u.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case u.custom:t="Invalid input";break;case u.invalid_intersection_types:t="Intersection results could not be merged";break;case u.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case u.not_finite:t="Number must be finite";break;default:t=e.defaultError,I.assertNever(r)}return{message:t}},le=Hr;var $t=le;function $r(r){$t=r}function qe(){return $t}var Ge=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,i=[...t,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let c="",l=n.filter(d=>!!d).slice().reverse();for(let d of l)c=d(o,{data:e,defaultError:c}).message;return{...s,path:i,message:c}},Fr=[];function p(r,e){let t=qe(),n=Ge({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===le?void 0:le].filter(s=>!!s)});r.common.issues.push(n)}var H=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return y;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let i=await s.key,o=await s.value;n.push({key:i,value:o})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return y;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[i.value]=o.value)}return{status:e.value,value:n}}},y=Object.freeze({status:"aborted"}),ke=r=>({status:"dirty",value:r}),F=r=>({status:"valid",value:r}),it=r=>r.status==="aborted",at=r=>r.status==="dirty",he=r=>r.status==="valid",He=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var Y=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,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}},Ft=(r,e)=>{if(he(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new z(r.common.issues);return this._error=t,this._error}}};function k(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))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:(o,c)=>{let{message:l}=r;return o.code==="invalid_enum_value"?{message:l??c.defaultError}:typeof c.data>"u"?{message:l??n??c.defaultError}:o.code!=="invalid_type"?{message:c.defaultError}:{message:l??t??c.defaultError}},description:s}}var E=class{get description(){return this._def.description}_getType(e){return ae(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new H,ctx:{common:e.parent.common,data:e.data,parsedType:ae(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(He(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Ft(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return he(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>he(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ae(e)},s=this._parse({data:e,path:n.path,parent:n}),i=await(He(s)?s:Promise.resolve(s));return Ft(n,i)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,i)=>{let o=e(s),c=()=>i.addIssue({code:u.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new Q({schema:this,typeName:_.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:t=>this["~validate"](t)}}optional(){return K.create(this,this._def)}nullable(){return ce.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fe.create(this)}promise(){return _e.create(this,this._def)}or(e){return Ae.create([this,e],this._def)}and(e){return Ce.create(this,e,this._def)}transform(e){return new Q({...k(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ue({...k(this._def),innerType:this,defaultValue:t,typeName:_.ZodDefault})}brand(){return new Ke({typeName:_.ZodBranded,type:this,...k(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new De({...k(this._def),innerType:this,catchValue:t,typeName:_.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ye.create(this,e)}readonly(){return Me.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Br=/^c[^\s-]{8,}$/i,Vr=/^[0-9a-z]+$/,zr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zr=/^[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,Wr=/^[a-z0-9_-]{21}$/i,Xr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Jr=/^[-+]?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)?)??$/,Gr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Kr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",vt,Yr=/^(?:(?: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])$/,Qr=/^(?:(?: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])$/,en=/^(([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]))$/,tn=/^(([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])$/,rn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nn=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vt="((\\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])))",sn=new RegExp(`^${Vt}$`);function zt(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function an(r){return new RegExp(`^${zt(r)}$`)}function Zt(r){let e=`${Vt}T${zt(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function on(r,e){return!!((e==="v4"||!e)&&Yr.test(r)||(e==="v6"||!e)&&en.test(r))}function cn(r,e){if(!Xr.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function dn(r,e){return!!((e==="v4"||!e)&&Qr.test(r)||(e==="v6"||!e)&&tn.test(r))}var ge=class r extends E{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){let i=this._getOrReturnCtx(e);return p(i,{code:u.invalid_type,expected:m.string,received:i.parsedType}),y}let n=new H,s;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){let o=e.data.length>i.value,c=e.data.length<i.value;(o||c)&&(s=this._getOrReturnCtx(e,s),o?p(s,{code:u.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&p(s,{code:u.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Gr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"email",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")vt||(vt=new RegExp(Kr,"u")),vt.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"emoji",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")Zr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"uuid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Wr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"nanoid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Br.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Vr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid2",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")zr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ulid",code:u.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),p(s,{validation:"url",code:u.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"regex",code:u.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.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),p(s,{code:u.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?Zt(i).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?sn.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?an(i).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:u.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Jr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?on(e.data,i.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ip",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?cn(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"jwt",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?dn(e.data,i.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cidr",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?rn.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:u.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?nn.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:u.invalid_string,message:i.message}),n.dirty()):I.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:u.invalid_string,...h.errToObj(n)})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};ge.create=r=>new ge({checks:[],typeName:_.ZodString,coerce:r?.coerce??!1,...k(r)});function un(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,i=Number.parseInt(r.toFixed(s).replace(".","")),o=Number.parseInt(e.toFixed(s).replace(".",""));return i%o/10**s}var Se=class r extends E{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 p(i,{code:u.invalid_type,expected:m.number,received:i.parsedType}),y}let n,s=new H;for(let i of this._def.checks)i.kind==="int"?I.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:u.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.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)&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?un(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:u.not_finite,message:i.message}),s.dirty()):I.assertNever(i);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&I.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Se.create=r=>new Se({checks:[],typeName:_.ZodNumber,coerce:r?.coerce||!1,...k(r)});var Ee=class r extends E{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 n,s=new H;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.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)&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),p(n,{code:u.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):I.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:u.invalid_type,expected:m.bigint,received:t.parsedType}),y}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ee.create=r=>new Ee({checks:[],typeName:_.ZodBigInt,coerce:r?.coerce??!1,...k(r)});var Te=class extends E{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.boolean,received:n.parsedType}),y}return F(e.data)}};Te.create=r=>new Te({typeName:_.ZodBoolean,coerce:r?.coerce||!1,...k(r)});var we=class r extends E{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){let i=this._getOrReturnCtx(e);return p(i,{code:u.invalid_type,expected:m.date,received:i.parsedType}),y}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return p(i,{code:u.invalid_date}),y}let n=new H,s;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:u.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):I.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};we.create=r=>new we({checks:[],coerce:r?.coerce||!1,typeName:_.ZodDate,...k(r)});var Fe=class extends E{_parse(e){if(this._getType(e)!==m.symbol){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.symbol,received:n.parsedType}),y}return F(e.data)}};Fe.create=r=>new Fe({typeName:_.ZodSymbol,...k(r)});var Ie=class extends E{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.undefined,received:n.parsedType}),y}return F(e.data)}};Ie.create=r=>new Ie({typeName:_.ZodUndefined,...k(r)});var Re=class extends E{_parse(e){if(this._getType(e)!==m.null){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.null,received:n.parsedType}),y}return F(e.data)}};Re.create=r=>new Re({typeName:_.ZodNull,...k(r)});var ye=class extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return F(e.data)}};ye.create=r=>new ye({typeName:_.ZodAny,...k(r)});var me=class extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return F(e.data)}};me.create=r=>new me({typeName:_.ZodUnknown,...k(r)});var ie=class extends E{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:u.invalid_type,expected:m.never,received:t.parsedType}),y}};ie.create=r=>new ie({typeName:_.ZodNever,...k(r)});var Be=class extends E{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.void,received:n.parsedType}),y}return F(e.data)}};Be.create=r=>new Be({typeName:_.ZodVoid,...k(r)});var fe=class r extends E{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==m.array)return p(t,{code:u.invalid_type,expected:m.array,received:t.parsedType}),y;if(s.exactLength!==null){let o=t.data.length>s.exactLength.value,c=t.data.length<s.exactLength.value;(o||c)&&(p(t,{code:o?u.too_big:u.too_small,minimum:c?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(p(t,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(p(t,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((o,c)=>s.type._parseAsync(new Y(t,o,t.path,c)))).then(o=>H.mergeArray(n,o));let i=[...t.data].map((o,c)=>s.type._parseSync(new Y(t,o,t.path,c)));return H.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};fe.create=(r,e)=>new fe({type:r,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...k(e)});function $e(r){if(r instanceof Z){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=K.create($e(n))}return new Z({...r._def,shape:()=>e})}else return r instanceof fe?new fe({...r._def,type:$e(r.element)}):r instanceof K?K.create($e(r.unwrap())):r instanceof ce?ce.create($e(r.unwrap())):r instanceof oe?oe.create(r.items.map(e=>$e(e))):r}var Z=class r extends E{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(),t=I.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==m.object){let d=this._getOrReturnCtx(e);return p(d,{code:u.invalid_type,expected:m.object,received:d.parsedType}),y}let{status:n,ctx:s}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof ie&&this._def.unknownKeys==="strip"))for(let d in s.data)o.includes(d)||c.push(d);let l=[];for(let d of o){let f=i[d],v=s.data[d];l.push({key:{status:"valid",value:d},value:f._parse(new Y(s,v,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ie){let d=this._def.unknownKeys;if(d==="passthrough")for(let f of c)l.push({key:{status:"valid",value:f},value:{status:"valid",value:s.data[f]}});else if(d==="strict")c.length>0&&(p(s,{code:u.unrecognized_keys,keys:c}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let f of c){let v=s.data[f];l.push({key:{status:"valid",value:f},value:d._parse(new Y(s,v,s.path,f)),alwaysSet:f in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let f of l){let v=await f.key,U=await f.value;d.push({key:v,value:U,alwaysSet:f.alwaysSet})}return d}).then(d=>H.mergeObjectSync(n,d)):H.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of I.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of I.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return $e(this)}partial(e){let t={};for(let n of I.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of I.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof K;)i=i._def.innerType;t[n]=i}return new r({...this._def,shape:()=>t})}keyof(){return Wt(I.objectKeys(this.shape))}};Z.create=(r,e)=>new Z({shape:()=>r,unknownKeys:"strip",catchall:ie.create(),typeName:_.ZodObject,...k(e)});Z.strictCreate=(r,e)=>new Z({shape:()=>r,unknownKeys:"strict",catchall:ie.create(),typeName:_.ZodObject,...k(e)});Z.lazycreate=(r,e)=>new Z({shape:r,unknownKeys:"strip",catchall:ie.create(),typeName:_.ZodObject,...k(e)});var Ae=class extends E{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let o=i.map(c=>new z(c.ctx.common.issues));return p(t,{code:u.invalid_union,unionErrors:o}),y}if(t.common.async)return Promise.all(n.map(async i=>{let o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(s);{let i,o=[];for(let l of n){let d={...t,common:{...t.common,issues:[]},parent:null},f=l._parseSync({data:t.data,path:t.path,parent:d});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:d}),d.common.issues.length&&o.push(d.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let c=o.map(l=>new z(l));return p(t,{code:u.invalid_union,unionErrors:c}),y}}get options(){return this._def.options}};Ae.create=(r,e)=>new Ae({options:r,typeName:_.ZodUnion,...k(e)});var pe=r=>r instanceof Ne?pe(r.schema):r instanceof Q?pe(r.innerType()):r instanceof Oe?[r.value]:r instanceof je?r.options:r instanceof Pe?I.objectValues(r.enum):r instanceof Ue?pe(r._def.innerType):r instanceof Ie?[void 0]:r instanceof Re?[null]:r instanceof K?[void 0,...pe(r.unwrap())]:r instanceof ce?[null,...pe(r.unwrap())]:r instanceof Ke||r instanceof Me?pe(r.unwrap()):r instanceof De?pe(r._def.innerType):[],ot=class r extends E{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.object)return p(t,{code:u.invalid_type,expected:m.object,received:t.parsedType}),y;let n=this.discriminator,s=t.data[n],i=this.optionsMap.get(s);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),y)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let i of t){let o=pe(i.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of o){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,i)}}return new r({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...k(n)})}};function kt(r,e){let t=ae(r),n=ae(e);if(r===e)return{valid:!0,data:r};if(t===m.object&&n===m.object){let s=I.objectKeys(e),i=I.objectKeys(r).filter(c=>s.indexOf(c)!==-1),o={...r,...e};for(let c of i){let l=kt(r[c],e[c]);if(!l.valid)return{valid:!1};o[c]=l.data}return{valid:!0,data:o}}else if(t===m.array&&n===m.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let i=0;i<r.length;i++){let o=r[i],c=e[i],l=kt(o,c);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===m.date&&n===m.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Ce=class extends E{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(i,o)=>{if(it(i)||it(o))return y;let c=kt(i.value,o.value);return c.valid?((at(i)||at(o))&&t.dirty(),{status:t.value,value:c.data}):(p(n,{code:u.invalid_intersection_types}),y)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ce.create=(r,e,t)=>new Ce({left:r,right:e,typeName:_.ZodIntersection,...k(t)});var oe=class r extends E{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.array)return p(n,{code:u.invalid_type,expected:m.array,received:n.parsedType}),y;if(n.data.length<this._def.items.length)return p(n,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),y;!this._def.rest&&n.data.length>this._def.items.length&&(p(n,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...n.data].map((o,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new Y(n,o,n.path,c)):null}).filter(o=>!!o);return n.common.async?Promise.all(i).then(o=>H.mergeArray(t,o)):H.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};oe.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new oe({items:r,typeName:_.ZodTuple,rest:null,...k(e)})};var ct=class r extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.object)return p(n,{code:u.invalid_type,expected:m.object,received:n.parsedType}),y;let s=[],i=this._def.keyType,o=this._def.valueType;for(let c in n.data)s.push({key:i._parse(new Y(n,c,n.path,c)),value:o._parse(new Y(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?H.mergeObjectAsync(t,s):H.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof E?new r({keyType:e,valueType:t,typeName:_.ZodRecord,...k(n)}):new r({keyType:ge.create(),valueType:e,typeName:_.ZodRecord,...k(t)})}},Ve=class extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.map)return p(n,{code:u.invalid_type,expected:m.map,received:n.parsedType}),y;let s=this._def.keyType,i=this._def.valueType,o=[...n.data.entries()].map(([c,l],d)=>({key:s._parse(new Y(n,c,n.path,[d,"key"])),value:i._parse(new Y(n,l,n.path,[d,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of o){let d=await l.key,f=await l.value;if(d.status==="aborted"||f.status==="aborted")return y;(d.status==="dirty"||f.status==="dirty")&&t.dirty(),c.set(d.value,f.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let l of o){let d=l.key,f=l.value;if(d.status==="aborted"||f.status==="aborted")return y;(d.status==="dirty"||f.status==="dirty")&&t.dirty(),c.set(d.value,f.value)}return{status:t.value,value:c}}}};Ve.create=(r,e,t)=>new Ve({valueType:e,keyType:r,typeName:_.ZodMap,...k(t)});var ze=class r extends E{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.set)return p(n,{code:u.invalid_type,expected:m.set,received:n.parsedType}),y;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(p(n,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(p(n,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let i=this._def.valueType;function o(l){let d=new Set;for(let f of l){if(f.status==="aborted")return y;f.status==="dirty"&&t.dirty(),d.add(f.value)}return{status:t.value,value:d}}let c=[...n.data.values()].map((l,d)=>i._parse(new Y(n,l,n.path,d)));return n.common.async?Promise.all(c).then(l=>o(l)):o(c)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ze.create=(r,e)=>new ze({valueType:r,minSize:null,maxSize:null,typeName:_.ZodSet,...k(e)});var dt=class r extends E{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.function)return p(t,{code:u.invalid_type,expected:m.function,received:t.parsedType}),y;function n(c,l){return Ge({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,qe(),le].filter(d=>!!d),issueData:{code:u.invalid_arguments,argumentsError:l}})}function s(c,l){return Ge({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,qe(),le].filter(d=>!!d),issueData:{code:u.invalid_return_type,returnTypeError:l}})}let i={errorMap:t.common.contextualErrorMap},o=t.data;if(this._def.returns instanceof _e){let c=this;return F(async function(...l){let d=new z([]),f=await c._def.args.parseAsync(l,i).catch(N=>{throw d.addIssue(n(l,N)),d}),v=await Reflect.apply(o,this,f);return await c._def.returns._def.type.parseAsync(v,i).catch(N=>{throw d.addIssue(s(v,N)),d})})}else{let c=this;return F(function(...l){let d=c._def.args.safeParse(l,i);if(!d.success)throw new z([n(l,d.error)]);let f=Reflect.apply(o,this,d.data),v=c._def.returns.safeParse(f,i);if(!v.success)throw new z([s(f,v.error)]);return v.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:oe.create(e).rest(me.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||oe.create([]).rest(me.create()),returns:t||me.create(),typeName:_.ZodFunction,...k(n)})}},Ne=class extends E{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ne.create=(r,e)=>new Ne({getter:r,typeName:_.ZodLazy,...k(e)});var Oe=class extends E{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),y}return{status:"valid",value:e.data}}get value(){return this._def.value}};Oe.create=(r,e)=>new Oe({value:r,typeName:_.ZodLiteral,...k(e)});function Wt(r,e){return new je({values:r,typeName:_.ZodEnum,...k(e)})}var je=class r extends E{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:I.joinValues(n),received:t.parsedType,code:u.invalid_type}),y}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{received:t.data,code:u.invalid_enum_value,options:n}),y}return F(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};je.create=Wt;var Pe=class extends E{_parse(e){let t=I.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==m.string&&n.parsedType!==m.number){let s=I.objectValues(t);return p(n,{expected:I.joinValues(s),received:n.parsedType,code:u.invalid_type}),y}if(this._cache||(this._cache=new Set(I.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=I.objectValues(t);return p(n,{received:n.data,code:u.invalid_enum_value,options:s}),y}return F(e.data)}get enum(){return this._def.values}};Pe.create=(r,e)=>new Pe({values:r,typeName:_.ZodNativeEnum,...k(e)});var _e=class extends E{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.promise&&t.common.async===!1)return p(t,{code:u.invalid_type,expected:m.promise,received:t.parsedType}),y;let n=t.parsedType===m.promise?t.data:Promise.resolve(t.data);return F(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};_e.create=(r,e)=>new _e({type:r,typeName:_.ZodPromise,...k(e)});var Q=class extends E{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:o=>{p(n,o),o.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){let o=s.transform(n.data,i);if(n.common.async)return Promise.resolve(o).then(async c=>{if(t.value==="aborted")return y;let l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?y:l.status==="dirty"?ke(l.value):t.value==="dirty"?ke(l.value):l});{if(t.value==="aborted")return y;let c=this._def.schema._parseSync({data:o,path:n.path,parent:n});return c.status==="aborted"?y:c.status==="dirty"?ke(c.value):t.value==="dirty"?ke(c.value):c}}if(s.type==="refinement"){let o=c=>{let l=s.refinement(c,i);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?y:(c.status==="dirty"&&t.dirty(),o(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?y:(c.status==="dirty"&&t.dirty(),o(c.value).then(()=>({status:t.value,value:c.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!he(o))return y;let c=s.transform(o.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>he(o)?Promise.resolve(s.transform(o.value,i)).then(c=>({status:t.value,value:c})):y);I.assertNever(s)}};Q.create=(r,e,t)=>new Q({schema:r,typeName:_.ZodEffects,effect:e,...k(t)});Q.createWithPreprocess=(r,e,t)=>new Q({schema:e,effect:{type:"preprocess",transform:r},typeName:_.ZodEffects,...k(t)});var K=class extends E{_parse(e){return this._getType(e)===m.undefined?F(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};K.create=(r,e)=>new K({innerType:r,typeName:_.ZodOptional,...k(e)});var ce=class extends E{_parse(e){return this._getType(e)===m.null?F(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ce.create=(r,e)=>new ce({innerType:r,typeName:_.ZodNullable,...k(e)});var Ue=class extends E{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===m.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ue.create=(r,e)=>new Ue({innerType:r,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...k(e)});var De=class extends E{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return He(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};De.create=(r,e)=>new De({innerType:r,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...k(e)});var Ze=class extends E{_parse(e){if(this._getType(e)!==m.nan){let n=this._getOrReturnCtx(e);return p(n,{code:u.invalid_type,expected:m.nan,received:n.parsedType}),y}return{status:"valid",value:e.data}}};Ze.create=r=>new Ze({typeName:_.ZodNaN,...k(r)});var ln=Symbol("zod_brand"),Ke=class extends E{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},Ye=class r extends E{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?y:i.status==="dirty"?(t.dirty(),ke(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?y:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:_.ZodPipeline})}},Me=class extends E{_parse(e){let t=this._def.innerType._parse(e),n=s=>(he(s)&&(s.value=Object.freeze(s.value)),s);return He(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Me.create=(r,e)=>new Me({innerType:r,typeName:_.ZodReadonly,...k(e)});function Bt(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xt(r,e={},t){return r?ye.create().superRefine((n,s)=>{let i=r(n);if(i instanceof Promise)return i.then(o=>{if(!o){let c=Bt(e,n),l=c.fatal??t??!0;s.addIssue({code:"custom",...c,fatal:l})}});if(!i){let o=Bt(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}}):ye.create()}var pn={object:Z.lazycreate},_;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(_||(_={}));var mn=(r,e={message:`Input not instance of ${r.name}`})=>Xt(t=>t instanceof r,e),Jt=ge.create,Gt=Se.create,fn=Ze.create,hn=Ee.create,Kt=Te.create,gn=we.create,yn=Fe.create,_n=Ie.create,xn=Re.create,bn=ye.create,vn=me.create,kn=ie.create,Sn=Be.create,En=fe.create,Tn=Z.create,wn=Z.strictCreate,In=Ae.create,Rn=ot.create,An=Ce.create,Cn=oe.create,Nn=ct.create,On=Ve.create,jn=ze.create,Pn=dt.create,Un=Ne.create,Dn=Oe.create,Mn=je.create,Ln=Pe.create,qn=_e.create,Hn=Q.create,$n=K.create,Fn=ce.create,Bn=Q.createWithPreprocess,Vn=Ye.create,zn=()=>Jt().optional(),Zn=()=>Gt().optional(),Wn=()=>Kt().optional(),Xn={string:r=>ge.create({...r,coerce:!0}),number:r=>Se.create({...r,coerce:!0}),boolean:r=>Te.create({...r,coerce:!0}),bigint:r=>Ee.create({...r,coerce:!0}),date:r=>we.create({...r,coerce:!0})};var Jn=y;var Gn=a.object({id:a.string().min(1).max(128),name:a.string().min(1).max(200),source:a.string().max(200),pluginId:a.string().max(200).optional(),path:a.string().max(4096).optional()}),de=a.array(Gn).max(1).optional(),Yt=a.object({taskId:a.string().min(1).optional(),repoId:a.string().min(1).optional(),agent:a.enum(["claude","codex"]).optional()}).refine(r=>r.taskId?!r.repoId&&!r.agent:!!r.repoId&&!!r.agent,"Select a task or a repository and agent");var ut=a.enum(["stable","preview"]),Kn=a.object({schemaVersion:a.literal(1),status:a.enum(["applying","succeeded","failed","deferred"]),previousVersion:a.string(),targetVersion:a.string(),reason:a.string(),pluginsUpdated:a.number().int().nonnegative().optional(),pluginActivationPending:a.boolean().optional(),checkedAt:a.string()}),Yn=a.union([a.object({channel:ut}).strict(),a.object({autoUpdate:a.boolean()}).strict()]),Ti=a.union([a.object({action:a.enum(["visit","check"])}).strict(),a.object({action:a.literal("install"),version:a.string().min(1).max(100)}).strict()]),Qn=a.object({channel:ut,currentVersion:a.string(),targetVersion:a.string().nullable(),checkedAt:a.string().datetime(),eligible:a.boolean(),pluginsPending:a.number().int().nonnegative().optional(),error:a.boolean()}),es=a.object({id:a.string().uuid(),channel:ut,currentVersion:a.string(),targetVersion:a.string(),automatic:a.boolean()}),ts=a.object({availability:a.enum(["available","not-installed","source-install","installation-mismatch","permission-required","authentication-required","unavailable"]),settings:a.object({channel:ut,autoUpdate:a.boolean(),independentExecutions:a.boolean().optional(),discovery:Qn.nullable(),pending:es.nullable(),lastUpdate:Kn.nullable()}).nullable()}),wi=a.union([a.object({ok:a.literal(!0),state:ts}),a.object({ok:a.literal(!1),error:a.enum(["busy","unavailable","save-failed","stale-update","update-failed"])})]);var rs=a.string().trim().min(1).max(4096).refine(r=>!/[\x00-\x1f\x7f]/.test(r),"Path contains control characters"),lt=a.array(rs).max(64),ns=a.discriminatedUnion("action",[a.object({action:a.literal("set"),paths:lt}).strict(),a.object({action:a.literal("add"),paths:lt.min(1)}).strict(),a.object({action:a.literal("remove"),paths:lt.min(1)}).strict(),a.object({action:a.literal("reset")}).strict()]);var Et=a.enum(["claude","codex"]),C=a.string(),D=C.min(1),Qe={permission:C.optional(),model:C.optional(),effort:C.optional()},Qt=a.number().int().min(1).max(1e5),xe=a.object({mediaType:C,data:C,width:Qt.optional(),height:Qt.optional()}).refine(({width:r,height:e})=>r===void 0==(e===void 0)),Tt=a.array(xe).optional(),Oi=a.object({path:D,name:C.optional(),defaultBaseRef:C.optional()}),ji=a.object({repoId:D,agent:Et,prompt:C,skills:de,...Qe,title:C.optional(),images:Tt,isolate:a.boolean().optional()}),Pi=a.object({prompt:C,images:Tt,...Qe}),Ui=a.object({title:C.trim().min(1,"Enter a session name.").max(200,"Use 200 characters or fewer.").regex(/^[^\r\n]*$/,"Use a single line for the session name.")}),Di=a.object({text:C,images:Tt,...Qe}),Mi=a.object({decision:a.enum(["approve","deny"]),scope:C.optional()}),ss=a.object({questionId:D.optional(),question:C,selected:a.array(C),notes:C.optional()}),tr=a.object({requestId:D,answers:a.array(ss),response:C.optional()}),rr={preset:a.enum(["hourly","daily","weekly","weekdays","manual","custom"]).optional(),schedule:C.optional(),hour:a.number().int().min(0).max(23).optional(),dayOfWeek:a.number().int().min(0).max(6).optional()},nr=a.object({command:C.trim().min(1).max(16e3),timeoutSeconds:a.number().int().min(1).max(3600).optional()}),Li=a.object({repoId:D,agent:Et.optional(),prompt:D.optional(),kind:a.enum(["agent","script"]).optional(),script:nr.optional(),...rr,...Qe,title:C.optional(),enabled:a.boolean().optional()}).superRefine((r,e)=>{r.kind==="script"?(r.script||e.addIssue({code:"custom",path:["script"],message:"script is required"}),[r.agent,r.prompt,r.permission,r.model,r.effort].some(t=>t!==void 0)&&e.addIssue({code:"custom",message:"script routines do not accept agent settings"})):((!r.agent||!r.prompt?.trim())&&e.addIssue({code:"custom",message:"agent and prompt are required"}),r.script&&e.addIssue({code:"custom",path:["script"],message:"script requires kind script"}))}),qi=a.object({script:nr.optional(),prompt:D.optional(),...rr,...Qe,title:C.optional(),enabled:a.boolean().optional()}),is=a.object({endpoint:D,expirationTime:a.number().nullable().optional(),keys:a.record(C).optional()}),Hi=a.object({subscription:is}),$i=a.object({endpoint:D}),Fi=a.object({agent:Et,sessionId:D,cwd:D,home:D,waitPid:a.number().int().positive()}),as=a.enum(["queued","running","awaiting_approval","awaiting_input","idle","archived","failed","cancelled"]),Bi=a.object({status:as.optional()}),St=a.string().regex(/^\d+$/).refine(r=>{let e=Number(r);return Number.isSafeInteger(e)&&e>=1}),er=a.string().regex(/^\d+$/).refine(r=>{let e=Number(r);return Number.isSafeInteger(e)&&e>=0}),Vi=a.object({before:St.optional(),details:a.enum(["summary","full"]).optional()}),zi=a.object({after:er,through:er.optional(),details:a.enum(["summary","full"]).optional()}),Zi=a.object({from:St,through:St}),Wi=a.object({path:C.min(1).max(4096).regex(/^[^\u0000-\u001f\u007f]*$/)}),Xi=a.object({task:C.optional(),snapshots:a.literal("1").optional(),details:a.enum(["summary","full"]).optional()}),Ji=a.object({path:C.optional()}),Gi=a.object({refresh:a.enum(["0","1"]).optional()}),os=a.object({id:D}),Ki=os.extend({messageId:D}),Yi=a.object({}),Qi=a.object({token:C.optional()}),sr={id:D,rawId:D,type:a.literal("public-key"),authenticatorAttachment:a.enum(["platform","cross-platform"]).optional(),clientExtensionResults:a.object({}).passthrough()},ea=a.object({...sr,response:a.object({clientDataJSON:D,authenticatorData:D,signature:D,userHandle:C.optional()})}),ta=a.object({response:a.object({...sr,response:a.object({clientDataJSON:D,attestationObject:D,transports:a.array(a.enum(["ble","cable","hybrid","internal","nfc","smart-card","usb"])).optional(),publicKeyAlgorithm:a.number().optional(),publicKey:C.optional(),authenticatorData:C.optional()})}),label:C.optional()});var et=1,ir=a.string().uuid(),wt=a.object({taskId:a.string().min(1),agent:a.enum(["claude","codex"]),cwd:a.string().min(1),prompt:a.string(),resumeId:a.string().optional(),providerHome:a.string().optional(),permission:a.string().optional(),model:a.string().optional(),effort:a.string().optional(),images:a.array(xe).optional(),messageId:a.string().optional(),interactive:a.boolean().optional()}).strict(),It=a.discriminatedUnion("kind",[a.object({kind:a.literal("send"),skills:de,text:a.string(),images:a.array(xe).optional(),messageId:a.string()}),a.object({kind:a.literal("steer"),text:a.string(),images:a.array(xe).optional()}),a.object({kind:a.literal("answer"),answer:tr}),a.object({kind:a.literal("approve"),decision:a.string(),scope:a.string().optional()}),a.object({kind:a.literal("interrupt")}),a.object({kind:a.literal("cancel")})]);var ar={claude:"acceptEdits",codex:"workspace-write"};var pt={productName:"Palmagent",displayName:"PalmAgent",packageName:"palmagent",cliName:"palmagent",unitBase:"palmagent",stateDirName:"palmagent"};var cs=a.object({model:a.string().optional(),effort:a.string().optional(),permission:a.string().optional()}),_a=a.object({clientMessageId:a.string().uuid(),mode:a.enum(["send","queue"]),text:a.string().trim().min(1).max(1e5),skills:de,images:a.array(xe).optional(),expectedRunId:a.string().nullable(),settings:cs.optional()}),xa=a.discriminatedUnion("action",[a.object({action:a.literal("edit"),version:a.number().int(),token:a.string().uuid()}),a.object({action:a.literal("renew"),token:a.string().uuid()}),a.object({action:a.literal("save"),token:a.string().uuid(),version:a.number().int(),text:a.string().trim().min(1).max(1e5),skills:de,images:a.array(xe).optional()}),a.object({action:a.literal("release"),token:a.string().uuid()}),a.object({action:a.literal("delete"),version:a.number().int()}),a.object({action:a.literal("send"),version:a.number().int(),expectedRunId:a.string().nullable()})]);var Sa=a.object({id:a.string().uuid(),mediaType:a.enum(["image/png","image/jpeg","image/gif","image/webp"]),size:a.number().int().positive(),width:a.number().int().min(1).max(1e5).optional(),height:a.number().int().min(1).max(1e5).optional()}).refine(({width:r,height:e})=>r===void 0==(e===void 0)),Ea=a.object({id:a.string().min(1),attachmentId:a.string().uuid()});var Ra=a.object({context:Yt,sdp:a.string().min(1).max(65536).startsWith("v=0")}),be=a.number().finite().min(0).max(10*6e4),ds=a.object({outcome:a.enum(["completed","cancelled","failed"]),audioContextResumeMs:be.optional(),microphoneRequestMs:be.optional(),localOfferMs:be.optional(),serverRequestMs:be.optional(),remoteDescriptionMs:be.optional(),tapToReadyMs:be.optional(),tapToFirstTranscriptMs:be.optional(),voiceToFirstTranscriptMs:be.optional()}).strict(),Aa=a.object({timings:ds.optional()}).strict();import bs from"better-sqlite3";import{randomUUID as vs,createHash as xr}from"node:crypto";import{join as ks}from"node:path";import{chmodSync as or,mkdirSync as us,openSync as Za,closeSync as Wa,fsyncSync as Xa,writeFileSync as Ja,renameSync as Ga,unlinkSync as Ka}from"node:fs";function cr(r){us(r,{recursive:!0,mode:448}),or(r,448)}function dr(r){or(r,384)}import{createHash as _s}from"node:crypto";import{readFileSync as yr,readdirSync as _o,realpathSync as xo,statSync as bo}from"node:fs";import{homedir as ps}from"node:os";import{existsSync as lr}from"node:fs";import{dirname as hr,join as We,resolve as Le}from"node:path";import{fileURLToPath as ms}from"node:url";var Rt={maxBytes:1073741824,minFreeBytes:268435456,unusedGraceMs:864e5,retentionMs:0},Qa=60*60*1e3;import{homedir as ur}from"node:os";import{join as ls}from"node:path";function At(r){return r==="~"?ur():r.startsWith("~/")?ls(ur(),r.slice(2)):r}var fs=hr(ms(import.meta.url)),hs=r=>r==="localhost"||r==="::1"||/^127(?:\.\d{1,3}){3}$/.test(r),gs=a.object({PORT:a.coerce.number().int().positive().default(4e3),HOST:a.string().min(1).refine(hs,"HOST must be loopback; terminate public HTTPS at the reverse proxy").default("localhost"),ATTACHMENT_MAX_BYTES:a.coerce.number().int().positive().safe().default(Rt.maxBytes),ATTACHMENT_MIN_FREE_BYTES:a.coerce.number().int().nonnegative().safe().default(Rt.minFreeBytes),ATTACHMENT_UNUSED_GRACE_HOURS:a.coerce.number().int().min(1).max(8760).default(24),ATTACHMENT_RETENTION_DAYS:a.coerce.number().int().min(0).max(36500).default(0),DISPATCH_CONCURRENCY:a.coerce.number().int().min(1).default(8),SSE_KEEPALIVE_MS:a.coerce.number().int().positive().default(15e3),AUTH_SESSION_TTL_MS:a.coerce.number().int().positive().default(30*24*60*60*1e3),AUTH_COOKIE_NAME:a.string().min(1).default("palmagent_session"),AUTH_RP_ID:a.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:a.string().min(1).optional(),AUTH_ORIGIN:a.string().url().startsWith("https://","AUTH_ORIGIN must use https://").optional(),AUTH_ENABLED:a.string().optional(),AUTH_DISABLED:a.string().optional(),PUSH_SUBJECT:a.string().regex(/^(mailto:|https:\/\/)/,"PUSH_SUBJECT must be a mailto: or https:// URL").optional(),DISPATCHER_DATA_DIR:a.string().min(1).optional(),XDG_STATE_HOME:a.string().min(1).optional(),DISPATCHER_DB:a.string().min(1).optional(),VAPID_KEY_PATH:a.string().min(1).optional(),STATIC_DIR:a.string().min(1).optional(),REPO_ROOTS:a.string().optional(),GITHUB_TOKEN:a.string().min(1).optional(),RUNNER_SOCKET:a.string().min(1).optional(),EXECUTION_RELEASE:a.string().min(1).optional(),EXECUTION_NODE:a.string().min(1).optional(),CLAUDE_MODEL:a.string().min(1).optional(),CODEX_MODEL:a.string().min(1).optional(),CLAUDE_EFFORT:a.string().min(1).optional(),CODEX_EFFORT:a.string().min(1).optional(),CLAUDE_CONFIG_DIR:a.string().min(1).optional(),NODE_ENV:a.string().optional()}).passthrough();function ys(r){let e={};for(let[t,n]of Object.entries(r))n!==void 0&&n!==""&&(e[t]=n);return e}var w=gs.parse(ys(process.env)),gr=w.AUTH_DISABLED==="1"?!1:w.AUTH_ENABLED==="1"?!0:w.NODE_ENV==="production",Ct=w.AUTH_RP_ID??(gr?"":"localhost"),Nt=w.DISPATCHER_DATA_DIR?Le(w.DISPATCHER_DATA_DIR):w.XDG_STATE_HOME?We(Le(w.XDG_STATE_HOME),pt.stateDirName):We(ps(),".local","state",pt.stateDirName),pr=We(Nt,"palmagent.db"),mr=We(Nt,"dispatcher.db"),fr=w.DISPATCHER_DB?Le(w.DISPATCHER_DB):lr(pr)||!lr(mr)?pr:mr,Ot={port:w.PORT,host:w.HOST,concurrency:w.DISPATCH_CONCURRENCY,attachmentStorage:{maxBytes:w.ATTACHMENT_MAX_BYTES,minFreeBytes:w.ATTACHMENT_MIN_FREE_BYTES,unusedGraceMs:w.ATTACHMENT_UNUSED_GRACE_HOURS*60*60*1e3,retentionMs:w.ATTACHMENT_RETENTION_DAYS*24*60*60*1e3},dataDir:Nt,dbPath:fr,keepAliveMs:w.SSE_KEEPALIVE_MS,claudeModel:w.CLAUDE_MODEL,codexModel:w.CODEX_MODEL,claudeEffort:w.CLAUDE_EFFORT,codexEffort:w.CODEX_EFFORT,claudeConfigDir:w.CLAUDE_CONFIG_DIR?Le(At(w.CLAUDE_CONFIG_DIR)):void 0,vapidKeyPath:w.VAPID_KEY_PATH?Le(w.VAPID_KEY_PATH):We(hr(fr),"vapid.json"),pushSubject:w.PUSH_SUBJECT,staticDir:w.STATIC_DIR?Le(w.STATIC_DIR):We(fs,"..","..","web","dist"),repoRoots:(w.REPO_ROOTS??"").split(":").filter(Boolean).map(r=>Le(At(r))),runnerSocket:w.RUNNER_SOCKET,executionRelease:w.EXECUTION_RELEASE,executionNode:w.EXECUTION_NODE,githubToken:w.GITHUB_TOKEN,authEnabled:gr,rpId:Ct,rpName:w.AUTH_RP_NAME??pt.displayName,authOrigin:w.AUTH_ORIGIN??(Ct?`https://${Ct}`:""),sessionTtlMs:w.AUTH_SESSION_TTL_MS,cookieName:w.AUTH_COOKIE_NAME,nodeEnv:w.NODE_ENV};var xs=r=>_s("sha256").update(r).digest("hex");function _r(r){if(!Number.isSafeInteger(r)||r<=1)throw new Error("A valid local CLI process id is required");try{let e=yr(`/proc/${r}/stat`,"utf8"),t=e.slice(e.lastIndexOf(")")+2).split(" ");return t[0]==="Z"?void 0:`${yr("/proc/sys/kernel/random/boot_id","utf8").trim()}:${t[19]}`}catch(e){if(e.code==="ENOENT")return;throw new Error("Cannot verify the local CLI process; ownership is retained")}}var So=xs(Buffer.alloc(0));var mt=class{constructor(e){this.directory=e;cr(e);let t=ks(e,"executions.sqlite");this.db=new bs(t),dr(t),this.db.pragma("busy_timeout = 5000"),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = FULL");let n=this.db.pragma("user_version",{simple:!0});if(n!==0&&n!==et)throw this.db.close(),new Error("Unsupported execution store version");this.db.exec(`
2
2
  CREATE TABLE IF NOT EXISTS executions (
3
3
  id TEXT PRIMARY KEY, taskId TEXT NOT NULL, protocol INTEGER NOT NULL,
4
4
  release TEXT NOT NULL, node TEXT NOT NULL, args TEXT NOT NULL,
@@ -15,10 +15,10 @@ var Mr=Object.defineProperty;var Lr=(r,e)=>{for(var t in e)Mr(r,t,{get:e[t],enum
15
15
  `)}db;close(){this.db.close()}saveControl(e,t){this.db.prepare("INSERT INTO control_state VALUES (?,?) ON CONFLICT(taskId) DO UPDATE SET body=excluded.body").run(e,JSON.stringify(t))}loadControl(e){let t=this.db.prepare("SELECT body FROM control_state WHERE taskId=?").get(e);return t?JSON.parse(t.body):void 0}get(e){let t=this.db.prepare("SELECT * FROM executions WHERE id=?").get(e);if(!t)throw new Error("Execution not found");let n=this.db.prepare("SELECT body FROM skill_inputs WHERE execution=?").get(e);return{...t,args:wt.parse(JSON.parse(t.args)),...n?{skills:de.parse(JSON.parse(n.body))}:{}}}latest(e){let t=this.db.prepare("SELECT id FROM executions WHERE taskId=? ORDER BY rowid DESC LIMIT 1").get(e);return t&&this.get(t.id)}list(){return this.db.prepare("SELECT id FROM executions ORDER BY rowid").all().map(({id:e})=>this.get(e))}reserve(e,t,n,s){let i=wt.parse(e),o=de.parse(s);return this.db.transaction(()=>{let c=this.latest(i.taskId);if(c&&["queued","starting","running"].includes(c.state)){if(i.messageId&&c.args.messageId===i.messageId&&JSON.stringify(c.args)===JSON.stringify(i)&&JSON.stringify(c.skills)===JSON.stringify(o))return c;throw new Error("An execution already owns this task")}let l=vs(),d=xr("sha256").update(JSON.stringify([i.agent,i.providerHome??"",i.resumeId??l])).digest("hex");return this.db.prepare("INSERT INTO executions(id,taskId,protocol,release,node,args,state,ownerKey,createdAt) VALUES (?,?,?,?,?,?,'queued',?,?)").run(l,i.taskId,et,t,n,JSON.stringify(i),d,Date.now()),o!==void 0&&this.db.prepare("INSERT INTO skill_inputs VALUES (?,?)").run(l,JSON.stringify(o)),this.append(l,{taskId:i.taskId,kind:"status",payload:{subtype:"execution_queued"}}),this.get(l)}).immediate()}setCapacity(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Invalid execution capacity");this.db.prepare("INSERT INTO admission_settings VALUES (1,?) ON CONFLICT(id) DO UPDATE SET capacity=excluded.capacity").run(e)}admit(e){return this.db.transaction(()=>{e=this.db.prepare("SELECT capacity FROM admission_settings WHERE id=1").get()?.capacity??e;let{count:n}=this.db.prepare("SELECT count(*) AS count FROM executions WHERE state IN ('starting','running')").get(),s=this.db.prepare("SELECT id FROM executions WHERE state='queued' ORDER BY rowid LIMIT ?").all(Math.max(0,e-n));for(let{id:i}of s)this.db.prepare("UPDATE executions SET state='starting' WHERE id=?").run(i);return s.map(({id:i})=>this.get(i))}).immediate()}bindSession(e,t){let n=this.get(e),s=xr("sha256").update(JSON.stringify([n.args.agent,n.args.providerHome??"",t])).digest("hex");this.db.prepare("UPDATE executions SET ownerKey=? WHERE id=? AND state='running'").run(s,e)}claim(e){let t=_r(process.pid);if(!t)throw new Error("Cannot establish execution host identity");return this.db.prepare("UPDATE executions SET state='running',pid=?,identity=? WHERE id=? AND state='starting' AND pid IS NULL").run(process.pid,t,e).changes===1}append(e,t){return this.db.transaction(()=>{let n=this.get(e).lastSeq+1;return this.db.prepare("INSERT INTO events VALUES (?,?,?)").run(e,n,JSON.stringify(t)),this.db.prepare("UPDATE executions SET lastSeq=? WHERE id=?").run(n,e),t.kind==="question"&&this.db.prepare("UPDATE executions SET question=? WHERE id=?").run(JSON.stringify(t.payload),e),t.kind==="status"&&t.payload.subtype==="input_resolved"&&this.clearQuestion(e,t.payload.requestId),n}).immediate()}events(e,t){return this.db.prepare("SELECT seq,body FROM events WHERE execution=? AND seq>? ORDER BY seq LIMIT 256").all(e,t).map(({seq:n,body:s})=>({seq:n,event:JSON.parse(s)}))}cancelBeforeStart(e){return this.db.transaction(()=>{let t=this.get(e);return!["queued","starting"].includes(t.state)||t.pid!==null?!1:(this.append(e,{taskId:t.taskId,kind:"status",payload:{subtype:"process_exit",code:-1}}),this.finish(e),!0)}).immediate()}finish(e,t=!1){this.db.transaction(()=>{this.db.prepare("UPDATE executions SET state=?,question=NULL WHERE id=?").run(t?"lost":"finished",e),this.db.prepare("UPDATE commands SET result='unknown' WHERE execution=? AND result='accepted'").run(e)}).immediate()}enqueue(e,t,n){let s=JSON.stringify(It.parse(n));return this.db.transaction(()=>{let i=this.command(e,t);if(i){if(JSON.stringify(i.body)!==s)throw new Error("Command identity was reused with different content");return i.result}let o=this.get(e);return o.state!=="running"||n.kind==="answer"&&((o.question?JSON.parse(o.question):void 0)?.requestId!==n.answer.requestId||this.db.prepare(`SELECT 1 FROM commands WHERE execution=?
16
16
  AND json_extract(body,'$.kind')='answer' AND json_extract(body,'$.answer.requestId')=?
17
17
  AND result!='rejected' LIMIT 1`).get(e,n.answer.requestId))?"rejected":(this.db.prepare("INSERT INTO commands(execution,id,body,result) VALUES (?,?,?,'accepted')").run(e,t,s),"accepted")}).immediate()}command(e,t){let n=this.db.prepare("SELECT * FROM commands WHERE execution=? AND id=?").get(e,t);return n&&{...n,body:It.parse(JSON.parse(n.body))}}pending(e){return this.db.transaction(()=>{let t=this.db.prepare("SELECT id FROM commands WHERE execution=? AND result='accepted' AND claimed=0 ORDER BY rowid").all(e);for(let n of t)this.db.prepare("UPDATE commands SET claimed=1 WHERE execution=? AND id=?").run(e,n.id);return t.map(n=>this.command(e,n.id))}).immediate()}settle(e,t,n){this.db.transaction(()=>{let s=this.command(e,t);if(!(!s||s.result!=="accepted")&&(this.db.prepare("UPDATE commands SET result=? WHERE execution=? AND id=?").run(n,e,t),s.body.kind==="answer"&&n==="delivered")){let{answer:i}=s.body;this.clearQuestion(e,i.requestId),this.append(e,{taskId:this.get(e).taskId,kind:"status",payload:{subtype:"answer",...i}})}}).immediate()}clearQuestion(e,t){this.db.prepare("UPDATE executions SET question=NULL WHERE id=? AND json_extract(question,'$.requestId')=?").run(e,t)}};import{randomUUID as Ss}from"node:crypto";import{spawnSync as Es}from"node:child_process";import{writeFileSync as Ts,renameSync as ws,openSync as br,closeSync as vr,fsyncSync as kr}from"node:fs";import{join as Is}from"node:path";function Rs(r){if(Es("sudo",["-n","/usr/local/libexec/palmagent-execution-start",r.id],{encoding:"utf8",timeout:1e4}).status!==0)throw new Error("Execution launch could not be confirmed; the invocation remains reserved")}function As(r,e){let t=Is(r.directory,`${e.id}.json`),n=`${t}.${Ss()}.tmp`;Ts(n,JSON.stringify({protocol:e.protocol,id:e.id,directory:r.directory,node:e.node,release:e.release})+`
18
- `,{mode:384});let s=br(n,"r");try{kr(s)}finally{vr(s)}ws(n,t);let i=br(r.directory,"r");try{kr(i)}finally{vr(i)}}var jt=new Map;function Sr(r,e,t=Rs){r.admit(e);for(let n of r.list()){if(n.state!=="starting"||n.pid!==null){jt.delete(n.id);continue}if(!(Date.now()-(jt.get(n.id)??0)<5e3)){jt.set(n.id,Date.now());try{As(r,n),t(n)}catch{}}}}import{watch as Ns}from"node:fs";function Er(r,e){let t,n=()=>{t??=setImmediate(()=>{t=void 0,e()})},s=Ns(r,n);s.on("error",n);let i=setInterval(n,1e3);return i.unref(),()=>{s.close(),clearInterval(i),t&&clearImmediate(t)}}var Cs=1500,Tr={plan:"plan",auto:"auto",acceptEdits:"acceptEdits",manual:"manual",dontAsk:"dontAsk",bypassPermissions:"bypassPermissions",default:"auto",readonly:"plan","auto-edit":"acceptEdits",full:"bypassPermissions"},Os=r=>Tr[r??""]??Tr[ar.claude];function js({permission:r,model:e,effort:t,resumeId:n}){let s=Os(r),i=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--include-partial-messages",...s==="bypassPermissions"?["--allow-dangerously-skip-permissions"]:[],"--permission-mode",s,"--permission-prompt-tool","stdio"];return e&&i.push("--model",e),t&&i.push("--effort",t),n&&i.push("--resume",n),i}function Ps(r,e=[]){let t=e.map(n=>({type:"image",source:{type:"base64",media_type:n.mediaType,data:n.data}}));return t.push({type:"text",text:r}),{type:"user",message:{role:"user",content:t}}}var ft=class{agent="claude";start(e,t,n){let{taskId:s,cwd:i,prompt:o,images:c,resumeId:l,permission:d,model:f,effort:v,reattach:U,resumeFromSeq:C,pendingInput:W,pendingApproval:re}=e,j=js({permission:d,model:f,effort:v,resumeId:l});e.interactive&&j.push("--replay-user-messages");let P=l,$=e.providerHome??Ot.claudeConfigDir,Xe=$?{CLAUDE_CONFIG_DIR:$}:void 0,g=U?n.attach(s,0):n.start({turnId:s,command:"claude",argv:j,cwd:i,env:Xe});if(!g)return t({taskId:s,kind:"status",sessionId:P,payload:{subtype:"reattach_failed"}}),{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel:()=>{},done:Promise.resolve()};let A,b=O=>{A&&(clearTimeout(A.timer),A.resolve(O),A=void 0,x=!1)},S,x=!1,L,B,ne=!1,Ht=0,Je=new Map,nt=new Map;U&&W&&Je.set(W.requestId,{questions:W.questions}),U&&re&&nt.set(re.requestId,re);let ve=O=>g.writeStdin(JSON.stringify(O)+`
19
- `),_t=(O,q,T)=>{ve({...Ps(O,q),...T?{uuid:T}:{}})},xt=(O=!1)=>{B&&clearTimeout(B),ne=O,B=setTimeout(()=>{!x&&g.stdinWritable()&&g.closeStdin()},Cs)},st=()=>{B&&clearTimeout(B),B=void 0,ne=!1};g.onLine((O,q)=>{let T;try{T=JSON.parse(q)}catch{return}T.session_id&&(P=T.session_id);let M=R=>t(R,O),ue=U&&O<=(C??0);switch(ne&&["stream_event","assistant","user","control_request"].includes(T.type)&&st(),T.type){case"system":M({taskId:s,kind:"status",sessionId:P,payload:{subtype:T.subtype,model:T.model,cwd:T.cwd,tools:T.tools?.length}});break;case"rate_limit_event":M({taskId:s,kind:"status",sessionId:P,payload:{subtype:"rate_limit",info:T}});break;case"stream_event":{let R=T.event;if(R?.type==="message_start"&&(S=R.message?.id),R?.type==="message_delta"&&S){let X=R.delta?.stop_reason,G=X==="tool_use"?"progress":X==="end_turn"?"final":void 0;G&&M({taskId:s,kind:"status",sessionId:P,payload:{subtype:"assistant_message",messageId:S,phase:G}})}R?.type==="message_stop"&&(S=void 0),R?.type==="content_block_delta"&&R.delta?.type==="text_delta"&&M({taskId:s,kind:"assistant_text",sessionId:P,payload:{text:R.delta.text,...S?{messageId:S}:{}}});break}case"assistant":{for(let R of T.message?.content??[])R.type==="tool_use"&&M({taskId:s,kind:"tool_call",sessionId:P,payload:{id:R.id,name:R.name,input:R.input}});break}case"user":{typeof T.uuid=="string"&&(T.uuid===e.messageId||T.uuid===A?.id||e.interactive&&T.message?.role==="user"&&T.message?.content?.some(R=>R.type==="text"))&&(M({taskId:s,kind:"status",sessionId:P,payload:{subtype:"message_delivered",messageId:T.uuid}}),A?.id===T.uuid&&b("delivered"));for(let R of T.message?.content??[])R.type==="tool_result"&&M({taskId:s,kind:"tool_result",sessionId:P,payload:{tool_use_id:R.tool_use_id,content:R.content,is_error:R.is_error}});break}case"result":M({taskId:s,kind:"result",sessionId:P,payload:{subtype:T.subtype,is_error:T.is_error,result:T.result,num_turns:T.num_turns,duration_ms:T.duration_ms,total_cost_usd:T.total_cost_usd}}),A&&!A.sent&&(A.sent=!0,_t(A.text,A.images,A.id)),x||xt(!!ue);break;case"control_response":M({taskId:s,kind:"status",sessionId:P,payload:{subtype:"control_response",response:T.response}});break;case"control_request":{if(ue)break;let R=T.request_id,X=T.request??{};if(X.subtype!=="can_use_tool")break;if(X.tool_name==="AskUserQuestion"&&Array.isArray(X.input?.questions)){let G=X.input.questions;Je.set(R,{questions:G}),M({taskId:s,kind:"question",sessionId:P,payload:{requestId:R,questions:G}})}else{let G={requestId:R,tool:typeof X.tool_name=="string"?X.tool_name:"Requested action",input:X.input,...typeof X.reason=="string"?{reason:X.reason}:{}};nt.set(R,G),M({taskId:s,kind:"approval_request",sessionId:P,payload:G})}break}default:break}}),g.onStderr(O=>{t({taskId:s,kind:"status",sessionId:P,payload:{subtype:"stderr",text:O}})});let Dr=new Promise(O=>{g.onExit(q=>{st(),b("unknown"),t({taskId:s,kind:"status",sessionId:P,payload:{subtype:"process_exit",code:q}}),O()})});return U||_t(wr(o,e.skills),c,e.messageId),{send:(O,q,T,M)=>!g.stdinWritable()||A||B||!e.interactive?Promise.resolve("rejected"):(x=!0,st(),new Promise(ue=>{let R=setTimeout(()=>{b("unknown"),xt()},15e3);R.unref(),A={id:T,text:wr(O,M),images:q,sent:!1,resolve:ue,timer:R},ve({type:"control_request",request_id:`send_${T}`,request:{subtype:"interrupt"}})})),steer:(O,q)=>g.stdinWritable()?(x=!0,st(),ve({type:"control_request",request_id:`int_${++Ht}`,request:{subtype:"interrupt"}}),L=setTimeout(()=>{_t(O,q),x=!1},250),!0):!1,interrupt:()=>g.stdinWritable()?(L&&clearTimeout(L),b(A?.sent?"unknown":"rejected"),x=!1,ve({type:"control_request",request_id:`int_${++Ht}`,request:{subtype:"interrupt"}}),xt(),!0):!1,approve:O=>{let q=nt.values().next().value;if(!q||!g.stdinWritable())return!1;let T=O==="approve",M=ve({type:"control_response",response:{subtype:"success",request_id:q.requestId,response:T?{behavior:"allow",updatedInput:q.input}:{behavior:"deny",message:"Denied by the user."}}});return M&&nt.delete(q.requestId),M},answer:O=>{let q=Je.get(O.requestId);if(!q||!g.stdinWritable())return!1;let T=new Map(q.questions.map(se=>[se.question,se])),M={},ue={};for(let se of O.answers??[])se.selected?.length&&(M[se.question]=T.get(se.question)?.multiSelect?se.selected:se.selected[0]),se.notes?.trim()&&(ue[se.question]={notes:se.notes.trim()});let R=O.response?.trim();if(!(Object.keys(M).length>0||Object.keys(ue).length>0||!!R))return ve({type:"control_response",response:{subtype:"success",request_id:O.requestId,response:{behavior:"deny",message:"User declined to answer."}}})?(Je.delete(O.requestId),!0):!1;let G={questions:q.questions,answers:M};return Object.keys(ue).length&&(G.annotations=ue),R&&(G.response=R),ve({type:"control_response",response:{subtype:"success",request_id:O.requestId,response:{behavior:"allow",updatedInput:G}}})?(Je.delete(O.requestId),!0):!1},cancel:()=>g.kill("SIGINT"),done:Dr}}};function wr(r,e){return e?.length?`/${e[0].name} ${r}`:r}var Ir=(r,e,t)=>[{type:"text",text:[...(t??[]).map(n=>`$${n.name}`),r].join(`
20
- `),text_elements:[]},...(t??[]).map(n=>({type:"skill",name:n.name,path:n.path})),...(e??[]).map(n=>({type:"image",url:`data:${n.mediaType};base64,${n.data}`}))];function Rr(r,e,t){let{taskId:n,reattach:s}=r,i=r.resumeId,o,c=!1,l,d=new Map,f=new Map;s&&r.pendingInput&&f.set(r.pendingInput.requestId,r.pendingInput);let v=r.permission,U=v==="read-only"||v==="readonly"?"read-only":v==="danger-full-access"||v==="full"?"danger-full-access":"workspace-write",C=s?t.attach(n,0):t.start({turnId:n,command:"codex",cwd:r.cwd,argv:["app-server","--listen","stdio://","-c",'approval_policy="never"',"-c",`sandbox_mode=${JSON.stringify(U)}`,...v==="workspace-write-net"?["-c","sandbox_workspace_write.network_access=true"]:[]],...r.providerHome?{env:{CODEX_HOME:r.providerHome}}:{}});if(!C)return e({taskId:n,kind:"status",sessionId:i,payload:{subtype:"reattach_failed"}}),{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel(){},done:Promise.resolve()};let W=g=>C.writeStdin(JSON.stringify(g)+`
21
- `),re=(g,A,b)=>W({jsonrpc:"2.0",id:g,method:A,params:b}),j=(g,A,b)=>e({taskId:n,sessionId:i,kind:g,payload:A},b),P=(g,A)=>{j("status",{subtype:"message_delivered",messageId:g},A);let b=d.get(g);b&&(clearTimeout(b.timer),d.delete(g),b.resolve("delivered"))},$=setTimeout(()=>{!o&&!c&&(j("error",{message:"Codex did not start a turn; the request will not be replayed automatically."}),C.kill("SIGINT"))},3e4);$.unref(),C.onLine((g,A)=>{let b;try{b=JSON.parse(A)}catch{return}let S=b.params??{};if(typeof b.id=="string"&&("result"in b||"error"in b)){if(b.id.startsWith("message:")){let x=b.id.slice(8),L=d.get(x);b.error?L&&(clearTimeout(L.timer),d.delete(x),L.resolve("rejected")):P(x,g)}else b.error?(j("error",{message:b.error.message??"Codex request failed"},g),c=!0,C.closeStdin()):b.id==="initialize"&&!s?(W({jsonrpc:"2.0",method:"initialized",params:{}}),re("session",r.resumeId?"thread/resume":"thread/start",{...r.resumeId?{threadId:r.resumeId}:{},cwd:r.cwd,approvalPolicy:"never",sandbox:U,...r.model?{model:r.model}:{},...r.effort?{config:{model_reasoning_effort:r.effort}}:{}})):b.id==="session"?(i=b.result.thread.id,j("status",{subtype:"thread_started"},g),s||re("start","turn/start",{threadId:i,input:Ir(r.prompt,r.images,r.skills),...r.messageId?{clientUserMessageId:r.messageId}:{},...r.effort?{effort:r.effort}:{}})):b.id==="start"&&(o=b.result.turn.id,clearTimeout($),r.messageId&&P(r.messageId,g));return}if(!(S.threadId&&i&&S.threadId!==i))switch(b.method){case"thread/started":i=S.thread.id,j("status",{subtype:"thread_started"},g);break;case"turn/started":o=S.turn.id,clearTimeout($),j("status",{subtype:"turn_started",turnId:o},g);break;case"item/agentMessage/delta":j("assistant_text",{text:S.delta,messageId:S.itemId},g);break;case"item/started":S.item?.type==="commandExecution"&&j("tool_call",{id:S.item.id,name:"bash",command:S.item.command},g);break;case"item/completed":{let x=S.item;x?.type==="userMessage"&&x.clientId?P(x.clientId,g):x?.type==="agentMessage"?j("status",{subtype:"assistant_message",messageId:x.id,phase:x.phase==="commentary"?"progress":x.phase==="final_answer"?"final":void 0},g):x?.type==="commandExecution"?j("tool_result",{tool_use_id:x.id,output:x.aggregatedOutput,exit_code:x.exitCode},g):x?.type==="fileChange"?j("tool_call",{id:x.id,name:"file_change",changes:x.changes},g):(x?.type==="mcpToolCall"||x?.type==="webSearch")&&j("tool_result",{tool_use_id:x.id,content:x.result??x.action,name:x.tool??x.type},g);break}case"turn/completed":c=!0,o=void 0,f.clear(),clearTimeout($),S.turn.status==="failed"&&j("error",{message:S.turn.error?.message??"Codex turn failed."},g),j("result",{is_error:S.turn.status!=="completed",subtype:S.turn.status,error:S.turn.error,usage:l},g),C.closeStdin();break;case"thread/tokenUsage/updated":S.tokenUsage?.last&&(l={input_tokens:S.tokenUsage.last.inputTokens,cached_input_tokens:S.tokenUsage.last.cachedInputTokens,output_tokens:S.tokenUsage.last.outputTokens}),j("status",{subtype:"usage",usage:S.tokenUsage},g);break;case"error":j("error",{message:S.error?.message??S.message},g);break;case"item/commandExecution/requestApproval":case"item/fileChange/requestApproval":W({jsonrpc:"2.0",id:b.id,result:{decision:"decline"}});break;case"item/tool/requestUserInput":{if(typeof b.id!="string"&&typeof b.id!="number")break;let x=JSON.stringify(b.id);if(s&&g<=(r.resumeFromSeq??0)||!Array.isArray(S.questions))break;let L={requestId:x,questions:S.questions.map(B=>({id:B.id,question:B.question,header:B.header,options:B.options??[]}))};f.set(x,L),j("question",L,g);break}case"serverRequest/resolved":{let x=JSON.stringify(S.requestId);f.delete(x),j("status",{subtype:"input_resolved",requestId:x},g);break}}}),C.onStderr(g=>j("status",{subtype:"stderr",text:g}));let Xe=new Promise(g=>C.onExit(A=>{clearTimeout($);for(let b of d.values())clearTimeout(b.timer),b.resolve("unknown");d.clear(),f.clear(),c||j("error",{message:"Codex exited before a terminal turn result."}),j("status",{subtype:"process_exit",code:A}),g()}));return s||re("initialize","initialize",{clientInfo:{name:"palmagent",version:"1.0.0"},capabilities:{}}),{send:(g,A,b,S)=>!o||c||!C.stdinWritable()?Promise.resolve("rejected"):new Promise(x=>{let L=setTimeout(()=>{d.delete(b),x("unknown")},15e3);L.unref(),d.set(b,{resolve:x,timer:L}),re(`message:${b}`,"turn/steer",{threadId:i,expectedTurnId:o,clientUserMessageId:b,input:Ir(g,A,S)})||(clearTimeout(L),d.delete(b),x("unknown"))}),steer:()=>!1,interrupt:()=>!!o&&!c&&re(`stop:${o}`,"turn/interrupt",{threadId:i,turnId:o}),approve:()=>!1,answer:g=>{let A=f.get(g.requestId);if(!A||c||!C.stdinWritable())return!1;let b={};for(let S of A.questions){if(!S.id)return!1;let x=g.answers.filter(ne=>ne.questionId?ne.questionId===S.id:ne.question===S.question),L=x[0];if(x.length>1||L&&!L.questionId&&A.questions.filter(ne=>ne.question===S.question).length>1)return!1;let B=[...L?.selected??[],...[L?.notes?.trim(),g.response?.trim()].filter(ne=>!!ne)];B.length&&(b[S.id]={answers:B})}return W({jsonrpc:"2.0",id:JSON.parse(g.requestId),result:{answers:b}})?(f.delete(g.requestId),!0):!1},cancel:()=>C.kill("SIGINT"),done:Xe}}import{mkdtempSync as Us,rmSync as Ds,writeFileSync as Ms}from"node:fs";import{tmpdir as Ls}from"node:os";import{join as Ar}from"node:path";var qs={"image/png":".png","image/jpeg":".jpg","image/webp":".webp","image/gif":".gif"};function Hs(r){if(!r?.length)return{argv:[],cleanup:()=>{}};let e=Us(Ar(Ls(),"palmagent-img-")),t=[];return r.forEach((n,s)=>{let i=Ar(e,`img-${s}${qs[n.mediaType]??".png"}`);Ms(i,Buffer.from(n.data,"base64")),t.push("-i",i)}),{argv:t,cleanup:()=>Ds(e,{recursive:!0,force:!0})}}var 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"}};function $s(r){return Nr[r??""]??Nr["workspace-write"]}function Fs({prompt:r,resumeId:e,permission:t,model:n,effort:s},i=[]){let o=[...n?["-c",`model=${n}`]:[],...s?["-c",`model_reasoning_effort=${s}`]:[]],c=$s(t),l=e?["-c",`sandbox_mode=${c.mode}`]:["--sandbox",c.mode],d=c.network?["-c","sandbox_workspace_write.network_access=true"]:[],f=["--json","--skip-git-repo-check","-c","approval_policy=never",...l,...d,...o,...i];return e?["exec","resume",e,r,...f]:["exec",r,...f]}var ht=class{agent="codex";start(e,t,n){if(e.interactive)return Rr(e,t,n);let{taskId:s,cwd:i,prompt:o,images:c,resumeId:l,permission:d,model:f,effort:v,reattach:U}=e,C=l;if(U){let $=n.attach(s,0);return $?this.wire(s,$,t,()=>{},()=>C,Xe=>{C=Xe}):(t({taskId:s,kind:"status",sessionId:C,payload:{subtype:"reattach_failed"}}),{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel:()=>{},done:Promise.resolve()})}let W=Hs(c),re=e.skills?.length?e.skills.map($=>`$${$.name} (${$.path})`).join(`
18
+ `,{mode:384});let s=br(n,"r");try{kr(s)}finally{vr(s)}ws(n,t);let i=br(r.directory,"r");try{kr(i)}finally{vr(i)}}var jt=new Map;function Sr(r,e,t=Rs){r.admit(e);for(let n of r.list()){if(n.state!=="starting"||n.pid!==null){jt.delete(n.id);continue}if(!(Date.now()-(jt.get(n.id)??0)<5e3)){jt.set(n.id,Date.now());try{As(r,n),t(n)}catch{}}}}import{watch as Cs}from"node:fs";function Er(r,e){let t,n=()=>{t??=setImmediate(()=>{t=void 0,e()})},s=Cs(r,n);s.on("error",n);let i=setInterval(n,1e3);return i.unref(),()=>{s.close(),clearInterval(i),t&&clearImmediate(t)}}var Ns=1500,Tr={plan:"plan",auto:"auto",acceptEdits:"acceptEdits",manual:"manual",dontAsk:"dontAsk",bypassPermissions:"bypassPermissions",default:"auto",readonly:"plan","auto-edit":"acceptEdits",full:"bypassPermissions"},Os=r=>Tr[r??""]??Tr[ar.claude];function js({permission:r,model:e,effort:t,resumeId:n}){let s=Os(r),i=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--include-partial-messages",...s==="bypassPermissions"?["--allow-dangerously-skip-permissions"]:[],"--permission-mode",s,"--permission-prompt-tool","stdio"];return e&&i.push("--model",e),t&&i.push("--effort",t),n&&i.push("--resume",n),i}function Ps(r,e=[]){let t=e.map(n=>({type:"image",source:{type:"base64",media_type:n.mediaType,data:n.data}}));return t.push({type:"text",text:r}),{type:"user",message:{role:"user",content:t}}}var ft=class{agent="claude";start(e,t,n){let{taskId:s,cwd:i,prompt:o,images:c,resumeId:l,permission:d,model:f,effort:v,reattach:U,resumeFromSeq:N,pendingInput:W,pendingApproval:re}=e,j=js({permission:d,model:f,effort:v,resumeId:l});e.interactive&&j.push("--replay-user-messages");let P=l,$=e.providerHome??Ot.claudeConfigDir,Xe=$?{CLAUDE_CONFIG_DIR:$}:void 0,g=U?n.attach(s,0):n.start({turnId:s,command:"claude",argv:j,cwd:i,env:Xe});if(!g)return t({taskId:s,kind:"status",sessionId:P,payload:{subtype:"reattach_failed"}}),{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel:()=>{},done:Promise.resolve()};let A,b=O=>{A&&(clearTimeout(A.timer),A.resolve(O),A=void 0,x=!1)},S,x=!1,L,B,ne=!1,Ht=0,Je=new Map,nt=new Map;U&&W&&Je.set(W.requestId,{questions:W.questions}),U&&re&&nt.set(re.requestId,re);let ve=O=>g.writeStdin(JSON.stringify(O)+`
19
+ `),_t=(O,q,T)=>{ve({...Ps(O,q),...T?{uuid:T}:{}})},xt=(O=!1)=>{B&&clearTimeout(B),ne=O,B=setTimeout(()=>{!x&&g.stdinWritable()&&g.closeStdin()},Ns)},st=()=>{B&&clearTimeout(B),B=void 0,ne=!1};g.onLine((O,q)=>{let T;try{T=JSON.parse(q)}catch{return}T.session_id&&(P=T.session_id);let M=R=>t(R,O),ue=U&&O<=(N??0);switch(ne&&["stream_event","assistant","user","control_request"].includes(T.type)&&st(),T.type){case"system":M({taskId:s,kind:"status",sessionId:P,payload:{subtype:T.subtype,model:T.model,cwd:T.cwd,tools:T.tools?.length}});break;case"rate_limit_event":M({taskId:s,kind:"status",sessionId:P,payload:{subtype:"rate_limit",info:T}});break;case"stream_event":{let R=T.event;if(R?.type==="message_start"&&(S=R.message?.id),R?.type==="message_delta"&&S){let X=R.delta?.stop_reason,G=X==="tool_use"?"progress":X==="end_turn"?"final":void 0;G&&M({taskId:s,kind:"status",sessionId:P,payload:{subtype:"assistant_message",messageId:S,phase:G}})}R?.type==="message_stop"&&(S=void 0),R?.type==="content_block_delta"&&R.delta?.type==="text_delta"&&M({taskId:s,kind:"assistant_text",sessionId:P,payload:{text:R.delta.text,...S?{messageId:S}:{}}});break}case"assistant":{for(let R of T.message?.content??[])R.type==="tool_use"&&M({taskId:s,kind:"tool_call",sessionId:P,payload:{id:R.id,name:R.name,input:R.input}});break}case"user":{typeof T.uuid=="string"&&(T.uuid===e.messageId||T.uuid===A?.id||e.interactive&&T.message?.role==="user"&&T.message?.content?.some(R=>R.type==="text"))&&(M({taskId:s,kind:"status",sessionId:P,payload:{subtype:"message_delivered",messageId:T.uuid}}),A?.id===T.uuid&&b("delivered"));for(let R of T.message?.content??[])R.type==="tool_result"&&M({taskId:s,kind:"tool_result",sessionId:P,payload:{tool_use_id:R.tool_use_id,content:R.content,is_error:R.is_error}});break}case"result":M({taskId:s,kind:"result",sessionId:P,payload:{subtype:T.subtype,is_error:T.is_error,result:T.result,num_turns:T.num_turns,duration_ms:T.duration_ms,total_cost_usd:T.total_cost_usd}}),A&&!A.sent&&(A.sent=!0,_t(A.text,A.images,A.id)),x||xt(!!ue);break;case"control_response":M({taskId:s,kind:"status",sessionId:P,payload:{subtype:"control_response",response:T.response}});break;case"control_request":{if(ue)break;let R=T.request_id,X=T.request??{};if(X.subtype!=="can_use_tool")break;if(X.tool_name==="AskUserQuestion"&&Array.isArray(X.input?.questions)){let G=X.input.questions;Je.set(R,{questions:G}),M({taskId:s,kind:"question",sessionId:P,payload:{requestId:R,questions:G}})}else{let G={requestId:R,tool:typeof X.tool_name=="string"?X.tool_name:"Requested action",input:X.input,...typeof X.reason=="string"?{reason:X.reason}:{}};nt.set(R,G),M({taskId:s,kind:"approval_request",sessionId:P,payload:G})}break}default:break}}),g.onStderr(O=>{t({taskId:s,kind:"status",sessionId:P,payload:{subtype:"stderr",text:O}})});let Dr=new Promise(O=>{g.onExit(q=>{st(),b("unknown"),t({taskId:s,kind:"status",sessionId:P,payload:{subtype:"process_exit",code:q}}),O()})});return U||_t(wr(o,e.skills),c,e.messageId),{send:(O,q,T,M)=>!g.stdinWritable()||A||B||!e.interactive?Promise.resolve("rejected"):(x=!0,st(),new Promise(ue=>{let R=setTimeout(()=>{b("unknown"),xt()},15e3);R.unref(),A={id:T,text:wr(O,M),images:q,sent:!1,resolve:ue,timer:R},ve({type:"control_request",request_id:`send_${T}`,request:{subtype:"interrupt"}})})),steer:(O,q)=>g.stdinWritable()?(x=!0,st(),ve({type:"control_request",request_id:`int_${++Ht}`,request:{subtype:"interrupt"}}),L=setTimeout(()=>{_t(O,q),x=!1},250),!0):!1,interrupt:()=>g.stdinWritable()?(L&&clearTimeout(L),b(A?.sent?"unknown":"rejected"),x=!1,ve({type:"control_request",request_id:`int_${++Ht}`,request:{subtype:"interrupt"}}),xt(),!0):!1,approve:O=>{let q=nt.values().next().value;if(!q||!g.stdinWritable())return!1;let T=O==="approve",M=ve({type:"control_response",response:{subtype:"success",request_id:q.requestId,response:T?{behavior:"allow",updatedInput:q.input}:{behavior:"deny",message:"Denied by the user."}}});return M&&nt.delete(q.requestId),M},answer:O=>{let q=Je.get(O.requestId);if(!q||!g.stdinWritable())return!1;let T=new Map(q.questions.map(se=>[se.question,se])),M={},ue={};for(let se of O.answers??[])se.selected?.length&&(M[se.question]=T.get(se.question)?.multiSelect?se.selected:se.selected[0]),se.notes?.trim()&&(ue[se.question]={notes:se.notes.trim()});let R=O.response?.trim();if(!(Object.keys(M).length>0||Object.keys(ue).length>0||!!R))return ve({type:"control_response",response:{subtype:"success",request_id:O.requestId,response:{behavior:"deny",message:"User declined to answer."}}})?(Je.delete(O.requestId),!0):!1;let G={questions:q.questions,answers:M};return Object.keys(ue).length&&(G.annotations=ue),R&&(G.response=R),ve({type:"control_response",response:{subtype:"success",request_id:O.requestId,response:{behavior:"allow",updatedInput:G}}})?(Je.delete(O.requestId),!0):!1},cancel:()=>g.kill("SIGINT"),done:Dr}}};function wr(r,e){return e?.length?`/${e[0].name} ${r}`:r}var Ir=(r,e,t)=>[{type:"text",text:[...(t??[]).map(n=>`$${n.name}`),r].join(`
20
+ `),text_elements:[]},...(t??[]).map(n=>({type:"skill",name:n.name,path:n.path})),...(e??[]).map(n=>({type:"image",url:`data:${n.mediaType};base64,${n.data}`}))];function Rr(r,e,t){let{taskId:n,reattach:s}=r,i=r.resumeId,o,c=!1,l,d=new Map,f=new Map;s&&r.pendingInput&&f.set(r.pendingInput.requestId,r.pendingInput);let v=r.permission,U=v==="read-only"||v==="readonly"?"read-only":v==="danger-full-access"||v==="full"?"danger-full-access":"workspace-write",N=s?t.attach(n,0):t.start({turnId:n,command:"codex",cwd:r.cwd,argv:["app-server","--listen","stdio://","-c",'approval_policy="never"',"-c",`sandbox_mode=${JSON.stringify(U)}`,...v==="workspace-write-net"?["-c","sandbox_workspace_write.network_access=true"]:[]],...r.providerHome?{env:{CODEX_HOME:r.providerHome}}:{}});if(!N)return e({taskId:n,kind:"status",sessionId:i,payload:{subtype:"reattach_failed"}}),{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel(){},done:Promise.resolve()};let W=g=>N.writeStdin(JSON.stringify(g)+`
21
+ `),re=(g,A,b)=>W({jsonrpc:"2.0",id:g,method:A,params:b}),j=(g,A,b)=>e({taskId:n,sessionId:i,kind:g,payload:A},b),P=(g,A)=>{j("status",{subtype:"message_delivered",messageId:g},A);let b=d.get(g);b&&(clearTimeout(b.timer),d.delete(g),b.resolve("delivered"))},$=setTimeout(()=>{!o&&!c&&(j("error",{message:"Codex did not start a turn; the request will not be replayed automatically."}),N.kill("SIGINT"))},3e4);$.unref(),N.onLine((g,A)=>{let b;try{b=JSON.parse(A)}catch{return}let S=b.params??{};if(typeof b.id=="string"&&("result"in b||"error"in b)){if(b.id.startsWith("message:")){let x=b.id.slice(8),L=d.get(x);b.error?L&&(clearTimeout(L.timer),d.delete(x),L.resolve("rejected")):P(x,g)}else b.error?(j("error",{message:b.error.message??"Codex request failed"},g),c=!0,N.closeStdin()):b.id==="initialize"&&!s?(W({jsonrpc:"2.0",method:"initialized",params:{}}),re("session",r.resumeId?"thread/resume":"thread/start",{...r.resumeId?{threadId:r.resumeId}:{},cwd:r.cwd,approvalPolicy:"never",sandbox:U,...r.model?{model:r.model}:{},...r.effort?{config:{model_reasoning_effort:r.effort}}:{}})):b.id==="session"?(i=b.result.thread.id,j("status",{subtype:"thread_started"},g),s||re("start","turn/start",{threadId:i,input:Ir(r.prompt,r.images,r.skills),...r.messageId?{clientUserMessageId:r.messageId}:{},...r.effort?{effort:r.effort}:{}})):b.id==="start"&&(o=b.result.turn.id,clearTimeout($),r.messageId&&P(r.messageId,g));return}if(!(S.threadId&&i&&S.threadId!==i))switch(b.method){case"thread/started":i=S.thread.id,j("status",{subtype:"thread_started"},g);break;case"turn/started":o=S.turn.id,clearTimeout($),j("status",{subtype:"turn_started",turnId:o},g);break;case"item/agentMessage/delta":j("assistant_text",{text:S.delta,messageId:S.itemId},g);break;case"item/started":S.item?.type==="commandExecution"&&j("tool_call",{id:S.item.id,name:"bash",command:S.item.command},g);break;case"item/completed":{let x=S.item;x?.type==="userMessage"&&x.clientId?P(x.clientId,g):x?.type==="agentMessage"?j("status",{subtype:"assistant_message",messageId:x.id,phase:x.phase==="commentary"?"progress":x.phase==="final_answer"?"final":void 0},g):x?.type==="commandExecution"?j("tool_result",{tool_use_id:x.id,output:x.aggregatedOutput,exit_code:x.exitCode},g):x?.type==="fileChange"?j("tool_call",{id:x.id,name:"file_change",changes:x.changes},g):(x?.type==="mcpToolCall"||x?.type==="webSearch")&&j("tool_result",{tool_use_id:x.id,content:x.result??x.action,name:x.tool??x.type},g);break}case"turn/completed":c=!0,o=void 0,f.clear(),clearTimeout($),S.turn.status==="failed"&&j("error",{message:S.turn.error?.message??"Codex turn failed."},g),j("result",{is_error:S.turn.status!=="completed",subtype:S.turn.status,error:S.turn.error,usage:l},g),N.closeStdin();break;case"thread/tokenUsage/updated":S.tokenUsage?.last&&(l={input_tokens:S.tokenUsage.last.inputTokens,cached_input_tokens:S.tokenUsage.last.cachedInputTokens,output_tokens:S.tokenUsage.last.outputTokens}),j("status",{subtype:"usage",usage:S.tokenUsage},g);break;case"error":j("error",{message:S.error?.message??S.message},g);break;case"item/commandExecution/requestApproval":case"item/fileChange/requestApproval":W({jsonrpc:"2.0",id:b.id,result:{decision:"decline"}});break;case"item/tool/requestUserInput":{if(typeof b.id!="string"&&typeof b.id!="number")break;let x=JSON.stringify(b.id);if(s&&g<=(r.resumeFromSeq??0)||!Array.isArray(S.questions))break;let L={requestId:x,questions:S.questions.map(B=>({id:B.id,question:B.question,header:B.header,options:B.options??[]}))};f.set(x,L),j("question",L,g);break}case"serverRequest/resolved":{let x=JSON.stringify(S.requestId);f.delete(x),j("status",{subtype:"input_resolved",requestId:x},g);break}}}),N.onStderr(g=>j("status",{subtype:"stderr",text:g}));let Xe=new Promise(g=>N.onExit(A=>{clearTimeout($);for(let b of d.values())clearTimeout(b.timer),b.resolve("unknown");d.clear(),f.clear(),c||j("error",{message:"Codex exited before a terminal turn result."}),j("status",{subtype:"process_exit",code:A}),g()}));return s||re("initialize","initialize",{clientInfo:{name:"palmagent",version:"1.0.0"},capabilities:{}}),{send:(g,A,b,S)=>!o||c||!N.stdinWritable()?Promise.resolve("rejected"):new Promise(x=>{let L=setTimeout(()=>{d.delete(b),x("unknown")},15e3);L.unref(),d.set(b,{resolve:x,timer:L}),re(`message:${b}`,"turn/steer",{threadId:i,expectedTurnId:o,clientUserMessageId:b,input:Ir(g,A,S)})||(clearTimeout(L),d.delete(b),x("unknown"))}),steer:()=>!1,interrupt:()=>!!o&&!c&&re(`stop:${o}`,"turn/interrupt",{threadId:i,turnId:o}),approve:()=>!1,answer:g=>{let A=f.get(g.requestId);if(!A||c||!N.stdinWritable())return!1;let b={};for(let S of A.questions){if(!S.id)return!1;let x=g.answers.filter(ne=>ne.questionId?ne.questionId===S.id:ne.question===S.question),L=x[0];if(x.length>1||L&&!L.questionId&&A.questions.filter(ne=>ne.question===S.question).length>1)return!1;let B=[...L?.selected??[],...[L?.notes?.trim(),g.response?.trim()].filter(ne=>!!ne)];B.length&&(b[S.id]={answers:B})}return W({jsonrpc:"2.0",id:JSON.parse(g.requestId),result:{answers:b}})?(f.delete(g.requestId),!0):!1},cancel:()=>N.kill("SIGINT"),done:Xe}}import{mkdtempSync as Us,rmSync as Ds,writeFileSync as Ms}from"node:fs";import{tmpdir as Ls}from"node:os";import{join as Ar}from"node:path";var qs={"image/png":".png","image/jpeg":".jpg","image/webp":".webp","image/gif":".gif"};function Hs(r){if(!r?.length)return{argv:[],cleanup:()=>{}};let e=Us(Ar(Ls(),"palmagent-img-")),t=[];return r.forEach((n,s)=>{let i=Ar(e,`img-${s}${qs[n.mediaType]??".png"}`);Ms(i,Buffer.from(n.data,"base64")),t.push("-i",i)}),{argv:t,cleanup:()=>Ds(e,{recursive:!0,force:!0})}}var Cr={"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"}};function $s(r){return Cr[r??""]??Cr["workspace-write"]}function Fs({prompt:r,resumeId:e,permission:t,model:n,effort:s},i=[]){let o=[...n?["-c",`model=${n}`]:[],...s?["-c",`model_reasoning_effort=${s}`]:[]],c=$s(t),l=e?["-c",`sandbox_mode=${c.mode}`]:["--sandbox",c.mode],d=c.network?["-c","sandbox_workspace_write.network_access=true"]:[],f=["--json","--skip-git-repo-check","-c","approval_policy=never",...l,...d,...o,...i];return e?["exec","resume",e,r,...f]:["exec",r,...f]}var ht=class{agent="codex";start(e,t,n){if(e.interactive)return Rr(e,t,n);let{taskId:s,cwd:i,prompt:o,images:c,resumeId:l,permission:d,model:f,effort:v,reattach:U}=e,N=l;if(U){let $=n.attach(s,0);return $?this.wire(s,$,t,()=>{},()=>N,Xe=>{N=Xe}):(t({taskId:s,kind:"status",sessionId:N,payload:{subtype:"reattach_failed"}}),{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel:()=>{},done:Promise.resolve()})}let W=Hs(c),re=e.skills?.length?e.skills.map($=>`$${$.name} (${$.path})`).join(`
22
22
  `)+`
23
- `+o:o,j=Fs({prompt:re,resumeId:l,permission:d,model:f,effort:v},W.argv),P=n.start({turnId:s,command:"codex",argv:j,cwd:i,...e.providerHome?{env:{CODEX_HOME:e.providerHome}}:{}});return P.closeStdin(),this.wire(s,P,t,W.cleanup,()=>C,$=>{C=$})}wire(e,t,n,s,i,o){let c=(d,f)=>{let v=i();switch(d?.type){case"agent_message":f({taskId:e,kind:"assistant_text",sessionId:v,payload:{text:d.text,messageId:d.id,...d.phase==="commentary"?{phase:"progress"}:d.phase==="final_answer"?{phase:"final"}:{}}});break;case"reasoning":f({taskId:e,kind:"status",sessionId:v,payload:{subtype:"reasoning",text:d.text}});break;case"command_execution":f({taskId:e,kind:"tool_call",sessionId:v,payload:{id:d.id,name:"bash",command:d.command,status:d.status}}),(d.aggregated_output!=null||d.exit_code!=null)&&f({taskId:e,kind:"tool_result",sessionId:v,payload:{tool_use_id:d.id,output:d.aggregated_output,exit_code:d.exit_code,status:d.status}});break;case"file_change":f({taskId:e,kind:"tool_call",sessionId:v,payload:{id:d.id,name:"file_change",changes:d.changes,status:d.status}});break;case"mcp_tool_call":case"web_search":f({taskId:e,kind:"tool_call",sessionId:v,payload:{id:d.id,name:d.type,status:d.status,item:d}});break;case"error":f({taskId:e,kind:"error",sessionId:v,payload:{message:d.message}});break;default:f({taskId:e,kind:"status",sessionId:v,payload:{subtype:d?.type??"item",item:d}})}};t.onLine((d,f)=>{let v;try{v=JSON.parse(f)}catch{return}let U=W=>n(W,d),C=i();switch(v.type){case"thread.started":o(v.thread_id),U({taskId:e,kind:"status",sessionId:v.thread_id,payload:{subtype:"thread_started",thread_id:v.thread_id}});break;case"turn.started":U({taskId:e,kind:"status",sessionId:C,payload:{subtype:"turn_started"}});break;case"item.started":v.item?.type==="command_execution"&&c(v.item,U);break;case"item.updated":break;case"item.completed":c(v.item,U);break;case"turn.completed":U({taskId:e,kind:"result",sessionId:C,payload:{usage:v.usage}});break;case"turn.failed":U({taskId:e,kind:"error",sessionId:C,payload:{error:v.error}});break;case"error":U({taskId:e,kind:"error",sessionId:C,payload:{message:v.message}});break;default:break}}),t.onStderr(d=>{n({taskId:e,kind:"status",sessionId:i(),payload:{subtype:"stderr",text:d}})});let l=new Promise(d=>{t.onExit(f=>{s(),n({taskId:e,kind:"status",sessionId:i(),payload:{subtype:"process_exit",code:f}}),d()})});return{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel:()=>t.kill("SIGINT"),done:l}}};var Bs={claude:new ft,codex:new ht};function gt(r){let e=Bs[r];if(!e)throw new Error(`unknown agent: ${r}`);return e}import{once as Vs}from"node:events";import{spawn as zs}from"node:child_process";function Cr(r){let e="";return{push(t){e+=t.toString();let n;for(;(n=e.indexOf(`
24
- `))!==-1;){let s=e.slice(0,n);e=e.slice(n+1);let i=s.replace(/\r$/,"").trim();i&&r(i)}},flush(){let t=e.replace(/\r$/,"").trim();e="",t&&r(t)}}}var yt=class{children=new Set;agentRunner(e){return gt(e)}async close(){await Promise.all([...this.children].map(async e=>{if(e.exitCode!==null||e.signalCode!==null)return;let t=Vs(e,"exit");e.kill("SIGINT");let n=setTimeout(()=>e.kill("SIGKILL"),2e3);try{await t}finally{clearTimeout(n),e.stdin.destroy(),e.stdout.destroy(),e.stderr.destroy()}}))}start(e){let t=zs(e.command,e.argv,{cwd:e.cwd,env:e.env?{...process.env,...e.env}:process.env,stdio:["pipe","pipe","pipe"]});return this.children.add(t),t.once("close",()=>this.children.delete(t)),new Pt(e.turnId,t)}attach(){}async listLive(){return[]}},Pt=class{constructor(e,t){this.turnId=e;this.child=t;t.stdout.on("data",i=>this.splitter.push(i)),t.stderr.on("data",i=>{let o=i.toString().trim();if(o)for(let c of this.stderrCbs)c(o)});let n,s=!1;t.on("exit",()=>{n=setTimeout(()=>{t.stdout.destroy(),t.stderr.destroy(),t.stdin.destroy()},2e3),n.unref()}),t.on("close",i=>{n&&clearTimeout(n),this.splitter.flush();for(let o of this.exitCbs)o(s?-1:i)}),t.on("error",()=>{s=!0})}seq=0;lineCbs=[];stderrCbs=[];exitCbs=[];splitter=Cr(e=>{let t=++this.seq;for(let n of this.lineCbs)n(t,e)});onLine(e){this.lineCbs.push(e)}onStderr(e){this.stderrCbs.push(e)}onExit(e){this.exitCbs.push(e)}stdinWritable(){return this.child.stdin.writable}writeStdin(e){return this.child.stdin.writable?(this.child.stdin.write(e),!0):!1}closeStdin(){this.child.stdin.writable&&this.child.stdin.end()}kill(e){this.child.kill(e)}};var qt=process.argv[2],te=ir.parse(process.argv[3]);if(!qt)throw new Error("Execution state directory is required");var V=new mt(Xs(qt)),J=V.get(te),Or=JSON.parse(Zs(Ws(qt,`${te}.json`),"utf8"));if(J.protocol!==et||Or.release!==J.release||Or.node!==J.node)throw new Error("Execution launch identity mismatch");V.claim(te)||(V.close(),process.exit(0));var Pr=new yt,ee,rt=!1,Ut=!1,Ur=()=>{},tt=J.args.resumeId,Dt=!1,Mt=r=>{if(!(rt||Dt)){if(r.sessionId&&tt&&r.sessionId!==tt){Dt=!0,V.append(te,{taskId:J.taskId,sessionId:tt,kind:"error",payload:{message:"Provider session identity changed; the invocation was stopped"}}),V.append(te,{taskId:J.taskId,kind:"status",payload:{subtype:"process_exit",code:-1}}),queueMicrotask(()=>ee?.cancel());return}if(!tt&&r.sessionId)try{V.bindSession(te,r.sessionId)}catch{Dt=!0,V.append(te,{taskId:J.taskId,kind:"error",payload:{message:"Provider session is already owned; the invocation was stopped"}}),V.append(te,{taskId:J.taskId,kind:"status",payload:{subtype:"process_exit",code:-1}}),queueMicrotask(()=>ee?.cancel());return}tt??=r.sessionId,V.append(te,r)}};async function jr(){if(!(Ut||rt||!ee)){Ut=!0;try{for(let r of V.pending(te)){let e="unknown";try{let t=r.body,n=!1;switch(t.kind){case"send":e=await ee.send?.(t.text,t.images,t.messageId,t.skills)??"rejected";break;case"steer":n=ee.steer(t.text,t.images);break;case"answer":n=await ee.answer(t.answer);break;case"approve":n=ee.approve(t.decision,t.scope);break;case"interrupt":n=ee.interrupt(),n||(ee.cancel(),n=!0);break;case"cancel":ee.cancel(),n=!0;break}t.kind!=="send"&&(e=n?"delivered":"rejected")}catch{}if(rt)return;V.settle(te,r.id,e)}}finally{Ut=!1}}}async function Lt(r=!1){if(rt)return;rt=!0,Ur(),V.finish(te,r),await Pr.close();let e=Number(process.env.PALMAGENT_EXECUTION_CONCURRENCY||8);Number.isSafeInteger(e)&&e>0&&Sr(V,e),V.close(),setImmediate(()=>process.exit(r?1:0))}try{Mt({taskId:J.taskId,kind:"status",payload:{subtype:"execution_started"}}),ee=gt(J.args.agent).start({...J.args,skills:J.skills},Mt,Pr),Ur=Er(V.directory,()=>{jr()}),jr(),ee.done.then(()=>Lt(),()=>Lt(!0))}catch{Mt({taskId:J.taskId,kind:"error",payload:{message:"Execution host could not start the provider"}}),Lt(!0)}
23
+ `+o:o,j=Fs({prompt:re,resumeId:l,permission:d,model:f,effort:v},W.argv),P=n.start({turnId:s,command:"codex",argv:j,cwd:i,...e.providerHome?{env:{CODEX_HOME:e.providerHome}}:{}});return P.closeStdin(),this.wire(s,P,t,W.cleanup,()=>N,$=>{N=$})}wire(e,t,n,s,i,o){let c=(d,f)=>{let v=i();switch(d?.type){case"agent_message":f({taskId:e,kind:"assistant_text",sessionId:v,payload:{text:d.text,messageId:d.id,...d.phase==="commentary"?{phase:"progress"}:d.phase==="final_answer"?{phase:"final"}:{}}});break;case"reasoning":f({taskId:e,kind:"status",sessionId:v,payload:{subtype:"reasoning",text:d.text}});break;case"command_execution":f({taskId:e,kind:"tool_call",sessionId:v,payload:{id:d.id,name:"bash",command:d.command,status:d.status}}),(d.aggregated_output!=null||d.exit_code!=null)&&f({taskId:e,kind:"tool_result",sessionId:v,payload:{tool_use_id:d.id,output:d.aggregated_output,exit_code:d.exit_code,status:d.status}});break;case"file_change":f({taskId:e,kind:"tool_call",sessionId:v,payload:{id:d.id,name:"file_change",changes:d.changes,status:d.status}});break;case"mcp_tool_call":case"web_search":f({taskId:e,kind:"tool_call",sessionId:v,payload:{id:d.id,name:d.type,status:d.status,item:d}});break;case"error":f({taskId:e,kind:"error",sessionId:v,payload:{message:d.message}});break;default:f({taskId:e,kind:"status",sessionId:v,payload:{subtype:d?.type??"item",item:d}})}};t.onLine((d,f)=>{let v;try{v=JSON.parse(f)}catch{return}let U=W=>n(W,d),N=i();switch(v.type){case"thread.started":o(v.thread_id),U({taskId:e,kind:"status",sessionId:v.thread_id,payload:{subtype:"thread_started",thread_id:v.thread_id}});break;case"turn.started":U({taskId:e,kind:"status",sessionId:N,payload:{subtype:"turn_started"}});break;case"item.started":v.item?.type==="command_execution"&&c(v.item,U);break;case"item.updated":break;case"item.completed":c(v.item,U);break;case"turn.completed":U({taskId:e,kind:"result",sessionId:N,payload:{usage:v.usage}});break;case"turn.failed":U({taskId:e,kind:"error",sessionId:N,payload:{error:v.error}});break;case"error":U({taskId:e,kind:"error",sessionId:N,payload:{message:v.message}});break;default:break}}),t.onStderr(d=>{n({taskId:e,kind:"status",sessionId:i(),payload:{subtype:"stderr",text:d}})});let l=new Promise(d=>{t.onExit(f=>{s(),n({taskId:e,kind:"status",sessionId:i(),payload:{subtype:"process_exit",code:f}}),d()})});return{steer:()=>!1,interrupt:()=>!1,approve:()=>!1,answer:()=>!1,cancel:()=>t.kill("SIGINT"),done:l}}};var Bs={claude:new ft,codex:new ht};function gt(r){let e=Bs[r];if(!e)throw new Error(`unknown agent: ${r}`);return e}import{once as Vs}from"node:events";import{spawn as zs}from"node:child_process";function Nr(r){let e="";return{push(t){e+=t.toString();let n;for(;(n=e.indexOf(`
24
+ `))!==-1;){let s=e.slice(0,n);e=e.slice(n+1);let i=s.replace(/\r$/,"").trim();i&&r(i)}},flush(){let t=e.replace(/\r$/,"").trim();e="",t&&r(t)}}}var yt=class{children=new Set;agentRunner(e){return gt(e)}async close(){await Promise.all([...this.children].map(async e=>{if(e.exitCode!==null||e.signalCode!==null)return;let t=Vs(e,"exit");e.kill("SIGINT");let n=setTimeout(()=>e.kill("SIGKILL"),2e3);try{await t}finally{clearTimeout(n),e.stdin.destroy(),e.stdout.destroy(),e.stderr.destroy()}}))}start(e){let t=zs(e.command,e.argv,{cwd:e.cwd,env:e.env?{...process.env,...e.env}:process.env,stdio:["pipe","pipe","pipe"]});return this.children.add(t),t.once("close",()=>this.children.delete(t)),new Pt(e.turnId,t)}attach(){}async listLive(){return[]}},Pt=class{constructor(e,t){this.turnId=e;this.child=t;t.stdout.on("data",i=>this.splitter.push(i)),t.stderr.on("data",i=>{let o=i.toString().trim();if(o)for(let c of this.stderrCbs)c(o)});let n,s=!1;t.on("exit",()=>{n=setTimeout(()=>{t.stdout.destroy(),t.stderr.destroy(),t.stdin.destroy()},2e3),n.unref()}),t.on("close",i=>{n&&clearTimeout(n),this.splitter.flush();for(let o of this.exitCbs)o(s?-1:i)}),t.on("error",()=>{s=!0})}seq=0;lineCbs=[];stderrCbs=[];exitCbs=[];splitter=Nr(e=>{let t=++this.seq;for(let n of this.lineCbs)n(t,e)});onLine(e){this.lineCbs.push(e)}onStderr(e){this.stderrCbs.push(e)}onExit(e){this.exitCbs.push(e)}stdinWritable(){return this.child.stdin.writable}writeStdin(e){return this.child.stdin.writable?(this.child.stdin.write(e),!0):!1}closeStdin(){this.child.stdin.writable&&this.child.stdin.end()}kill(e){this.child.kill(e)}};var qt=process.argv[2],te=ir.parse(process.argv[3]);if(!qt)throw new Error("Execution state directory is required");var V=new mt(Xs(qt)),J=V.get(te),Or=JSON.parse(Zs(Ws(qt,`${te}.json`),"utf8"));if(J.protocol!==et||Or.release!==J.release||Or.node!==J.node)throw new Error("Execution launch identity mismatch");V.claim(te)||(V.close(),process.exit(0));var Pr=new yt,ee,rt=!1,Ut=!1,Ur=()=>{},tt=J.args.resumeId,Dt=!1,Mt=r=>{if(!(rt||Dt)){if(r.sessionId&&tt&&r.sessionId!==tt){Dt=!0,V.append(te,{taskId:J.taskId,sessionId:tt,kind:"error",payload:{message:"Provider session identity changed; the invocation was stopped"}}),V.append(te,{taskId:J.taskId,kind:"status",payload:{subtype:"process_exit",code:-1}}),queueMicrotask(()=>ee?.cancel());return}if(!tt&&r.sessionId)try{V.bindSession(te,r.sessionId)}catch{Dt=!0,V.append(te,{taskId:J.taskId,kind:"error",payload:{message:"Provider session is already owned; the invocation was stopped"}}),V.append(te,{taskId:J.taskId,kind:"status",payload:{subtype:"process_exit",code:-1}}),queueMicrotask(()=>ee?.cancel());return}tt??=r.sessionId,V.append(te,r)}};async function jr(){if(!(Ut||rt||!ee)){Ut=!0;try{for(let r of V.pending(te)){let e="unknown";try{let t=r.body,n=!1;switch(t.kind){case"send":e=await ee.send?.(t.text,t.images,t.messageId,t.skills)??"rejected";break;case"steer":n=ee.steer(t.text,t.images);break;case"answer":n=await ee.answer(t.answer);break;case"approve":n=ee.approve(t.decision,t.scope);break;case"interrupt":n=ee.interrupt(),n||(ee.cancel(),n=!0);break;case"cancel":ee.cancel(),n=!0;break}t.kind!=="send"&&(e=n?"delivered":"rejected")}catch{}if(rt)return;V.settle(te,r.id,e)}}finally{Ut=!1}}}async function Lt(r=!1){if(rt)return;rt=!0,Ur(),V.finish(te,r),await Pr.close();let e=Number(process.env.PALMAGENT_EXECUTION_CONCURRENCY||8);Number.isSafeInteger(e)&&e>0&&Sr(V,e),V.close(),setImmediate(()=>process.exit(r?1:0))}try{Mt({taskId:J.taskId,kind:"status",payload:{subtype:"execution_started"}}),ee=gt(J.args.agent).start({...J.args,skills:J.skills},Mt,Pr),Ur=Er(V.directory,()=>{jr()}),jr(),ee.done.then(()=>Lt(),()=>Lt(!0))}catch{Mt({taskId:J.taskId,kind:"error",payload:{message:"Execution host could not start the provider"}}),Lt(!0)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "palmagent",
3
- "version": "0.1.0-alpha.97",
3
+ "version": "0.1.0-alpha.99",
4
4
  "palmagent": {
5
5
  "agentCliCompatibility": {
6
6
  "claude": {