@tonyclaw/agent-inspector 4.0.13 → 4.0.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.output/backend/nitro.json +1 -1
- package/.output/cli.js +2 -2
- package/.output/server/_ssr/index.mjs +1 -1
- package/.output/server/_ssr/{router-C1qBqYEd.mjs → router-CylQ5CaO.mjs} +1 -1
- package/.output/server/index.mjs +1 -1
- package/.output/ui/assets/{CompareDrawer-B6l7sK_o.js → CompareDrawer-fZn0FGib.js} +1 -1
- package/.output/ui/assets/{InspectorPet-Dv-hDdxU.js → InspectorPet-BFOtvhfh.js} +1 -1
- package/.output/ui/assets/ProxyViewerContainer-ANS_miHE.js +60 -0
- package/.output/ui/assets/{ReplayDialog-BACtWGKs.js → ReplayDialog-D_uYZ_3h.js} +1 -1
- package/.output/ui/assets/{RequestAnatomy-DqG3yRes.js → RequestAnatomy-BFD31ztr.js} +1 -1
- package/.output/ui/assets/{ResponseView-CwqmhaXg.js → ResponseView-BFhTRvjN.js} +1 -1
- package/.output/ui/assets/{StreamingChunkSequence-DMdSkso8.js → StreamingChunkSequence-B6T6xhfP.js} +1 -1
- package/.output/ui/assets/{_sessionId-C_2LW0jh.js → _sessionId-B1Gn0T4f.js} +1 -1
- package/.output/ui/assets/{_sessionId-Ca0TjDw_.js → _sessionId-BBWltkCM.js} +1 -1
- package/.output/ui/assets/{index-Dt0cOy7U.js → index-BX8D0Res.js} +1 -1
- package/.output/ui/assets/{index-DZdFLvt4.js → index-BZfQZzne.js} +1 -1
- package/.output/ui/assets/index-CIvE7pNX.css +1 -0
- package/.output/ui/assets/{index-C85xqQrL.js → index-Uq8AFPJC.js} +1 -1
- package/.output/ui/assets/{index-OquTzqLZ.js → index-vSnusLnr.js} +3 -3
- package/.output/ui/assets/{json-viewer-DIr-vdVp.js → json-viewer-BIhQpPF5.js} +1 -1
- package/.output/ui/assets/{jszip.min-D5ch91g-.js → jszip.min-BBgtyBfh.js} +1 -1
- package/.output/ui/index.html +5 -4
- package/package.json +4 -4
- package/.output/ui/assets/ProxyViewerContainer-B5SUiugd.js +0 -60
- package/.output/ui/assets/index-B-Qod-aA.css +0 -1
package/.output/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Wk=Object.defineProperty;var y=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(o){throw r=[o],o}};var Te=(e,t)=>{for(var r in t)Wk(e,r,{get:t[r],enumerable:!0})};var lt,os=y(()=>{lt={name:"@tonyclaw/agent-inspector",version:"4.0.13",type:"module",description:"Agent observability and knowledge capture layer for AI coding tools.",license:"MIT",engines:{node:">=22.0.0"},author:"TonyClaw",repository:{type:"git",url:"git+https://gitcode.com/TonyClaw/OpenInspector.git"},homepage:"https://gitcode.com/TonyClaw/OpenInspector#readme",workspaces:["packages/*"],bugs:{url:"https://gitcode.com/TonyClaw/OpenInspector/issues"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["claude","anthropic","openai","proxy","api-inspector","agent-observability","agent-memory","debugging","llm","ai-coding-tools"],bin:{"agent-inspector":"bin/agent-inspector.js"},files:["bin","src/assets/agent-inspector.ico","scripts/setup-windows-runtime.mjs","scripts/setup-agent-skills.mjs","scripts/generate-theme-scales.mjs","docs/instance-control.openapi.yaml","styles",".output","!.output/*.exe"],scripts:{dev:"node scripts/dev-decoupled.mjs","dev:ui":"vite dev --config vite.ui.config.ts","dev:backend":"node scripts/dev-backend.mjs","test:smoke":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs smoke","test:fast":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs smoke","test:unit":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs unit","test:integration":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs integration","test:changed":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs changed","test:all":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs all","test:hostile-inputs":"bun test src/proxy/identityProxy.test.ts src/proxy/handler.cancellationCompatibility.test.ts src/proxy/logImporter.test.ts src/backend/routes/api/-logs.stream.test.ts src/proxy/handler.admission.test.ts src/proxy/runtimeHealth.test.ts src/proxy/storageLifecycle.test.ts","test:compatibility-tooling":"node scripts/run-compatibility-tests.mjs ultra","test:compatibility-tooling:extended":"node scripts/run-compatibility-tests.mjs extended","test:compatibility-conformance":"node scripts/run-compatibility-tests.mjs conformance",start:"node .output/cli.js","start:backend":"node .output/cli.js --backend-only --no-open","preview:ui":"vite preview --config vite.ui.config.ts","clean:output":"node scripts/clean-output.mjs",build:"bun clean:output && bun build:backend && bun build:ui && bun smoke:ui-preview && bun build:workers && bun build:cli && bun build:mcp && bun check:bundle && bun check:boundaries","build:backend":"vite build --config vite.backend.config.ts","build:ui":"vite build --config vite.ui.config.ts","build:workers":"npx esbuild src/proxy/logFinalizer.worker.ts src/proxy/sessionWorkerEntry.ts --bundle --minify --legal-comments=none --platform=node --target=node22 --format=esm --outdir=.output/workers --external:better-sqlite3","smoke:workers":"node scripts/smoke-production-workers.mjs","smoke:packed-workers":"node scripts/smoke-packed-workers.mjs","smoke:instances":"node scripts/smoke-windows-instances.mjs","smoke:coding-agent-instances":"node scripts/smoke-coding-agent-instances.mjs","smoke:ui-preview":"node scripts/smoke-decoupled-ui-preview.mjs","check:bundle":"node scripts/check-client-bundle.mjs","check:boundaries":"node scripts/check-runtime-boundaries.mjs","check:commercial-performance":"node scripts/check-commercial-performance-budgets.mjs","check:hostile-inputs":"node scripts/check-hostile-input-coverage.mjs","check:supply-chain":"node scripts/check-commercial-supply-chain.mjs","compatibility:bdd":"node scripts/lint-bdd-catalog.mjs","compatibility:compare":"node scripts/compatibility/cli.mjs compare","compatibility:drift":"node scripts/check-backend-compatibility.mjs","compatibility:fixtures":"bun scripts/validate-compatibility-fixtures.ts","compatibility:freeze":"node scripts/freeze-backend-baseline.mjs","compatibility:run":"node scripts/compatibility/cli.mjs run","compatibility:performance":"node scripts/compatibility/performance-cli.mjs","compatibility:performance:verify":"node scripts/compatibility/performance-cli.mjs verify","build:cli":"npx esbuild src/cli.ts --bundle --minify --legal-comments=none --platform=node --target=node22 --format=esm --outfile=.output/cli.js","build:mcp":"npx esbuild packages/agent-inspector-mcp/src/cli.ts --bundle --minify --legal-comments=none --platform=node --target=node22 --format=esm --outfile=packages/agent-inspector-mcp/dist/cli.js","rust:build-package":"node scripts/rust/build-platform.mjs","rust:stage-package":"node scripts/rust/stage-platform.mjs","rust:verify-package":"node scripts/rust/verify-platform.mjs","rust:pack-package":"node scripts/rust/pack-platform.mjs","rust:native-artifact":"node scripts/rust/create-native-artifact.mjs","rust:native:aggregate":"node scripts/rust/aggregate-native-artifacts.mjs","rust:release-gate:preflight":"node scripts/rust/release-gate-preflight.mjs","rust:release-evidence:plan":"node scripts/rust/release-evidence-plan.mjs","commercial:release-gate:preflight":"node scripts/commercial-release-preflight.mjs","test:commercial-release-gate":"bun test scripts/commercialReleasePreflight.test.ts","test:rust-packaging":"bun test scripts/rust/npmPackaging.test.ts scripts/rust/nativeReleaseContract.test.ts scripts/rust/nativeStartupSmoke.test.ts scripts/rust/releaseGatePreflight.test.ts scripts/releaseCore.test.ts","rust:packages:check":"node scripts/rust/sync-package-versions.mjs","rust:packages:sync":"node scripts/rust/sync-package-versions.mjs --write","themes:generate":"node scripts/generate-theme-scales.mjs",postinstall:"node scripts/setup-windows-runtime.mjs && node scripts/setup-agent-skills.mjs",prepublishOnly:"node scripts/rust/require-release-orchestrator.mjs",typecheck:"tsc --noEmit --incremental --tsBuildInfoFile .cache/tsconfig.tsbuildinfo",lint:"eslint . --cache --cache-location .cache/eslintcache",format:"biome format --write .","format:check":"biome format .","verify:ultra":"node scripts/compatibility/ultra-gate.mjs","verify:ultra:fresh":"node scripts/compatibility/ultra-gate.mjs --no-cache","verify:ultra:smoke":"npm run verify:ultra && npm run test:smoke","verify:fast":"bun scripts/run-static-checks.mjs --format && bun test:changed","extension:zip":"node scripts/pack-chrome-extension.mjs","extension:release":"node scripts/release-chrome-extension.mjs",release:"node scripts/release.mjs",knip:"knip",check:"bun scripts/run-static-checks.mjs --format && bun check:boundaries && bun check:commercial-performance && bun check:hostile-inputs && bun compatibility:bdd && bun rust:packages:check",prepare:"husky",ladle:"ladle serve","ladle:build":"ladle build"},dependencies:{"@mariozechner/pi-agent-core":"^0.73.1","@mariozechner/pi-ai":"^0.73.1","@modelcontextprotocol/server":"^2.0.0-beta.4","@tailwindcss/typography":"^0.5.20","@tanstack/react-router":"^1.170.18","@tanstack/react-start":"^1.168.28","@tanstack/react-virtual":"^3.14.6","class-variance-authority":"^0.7.1",clsx:"^2.1.1",conf:"^15.1.0",diff:"^9.0.0",jszip:"^3.10.1","lucide-react":"^0.563.0","radix-ui":"1.6.2",react:"^19.2.7","react-dom":"^19.2.7","react-markdown":"^10.1.0",swr:"^2.4.2","tailwind-merge":"^3.6.0",three:"0.185.1","tw-animate-css":"^1.4.0",zod:"^4.4.3"},optionalDependencies:{"@tonyclaw/agent-inspector-backend-darwin-arm64":"4.0.13","@tonyclaw/agent-inspector-backend-linux-x64-gnu":"4.0.13","@tonyclaw/agent-inspector-backend-win32-x64-msvc":"4.0.13","better-sqlite3":"^12.11.1",rcedit:"4.0.1"},devDependencies:{"@biomejs/biome":"^2.5.3","@eslint/js":"^10.0.1","@ladle/react":"^5.1.1","@radix-ui/colors":"^3.0.0","@tailwindcss/vite":"^4.3.2","@tanstack/router-plugin":"^1.168.20","@types/bun":"^1.3.14","@types/react":"^19.2.17","@types/react-dom":"^19.2.3","@types/three":"0.185.1","@typescript-eslint/eslint-plugin":"^8.64.0","@typescript-eslint/parser":"^8.64.0","@vitejs/plugin-react":"^5.2.0",ajv:"8.20.0","ajv-formats":"3.0.1","colorjs.io":"^0.7.0",esbuild:"^0.28.1",eslint:"^9.39.5","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-functional":"^9.0.5","eslint-plugin-unicorn":"^63.0.0",husky:"^9.1.7",knip:"^5.88.1",nitro:"^3.0.260610-beta",playwright:"^1.61.1",tailwindcss:"^4.3.2",typescript:"^5.9.3",vite:"^7.3.6","vite-tsconfig-paths":"^6.1.1"},overrides:{undici:">=7.24.0 <8.0.0",rollup:">=4.59.0 <5.0.0",postcss:">=8.5.10 <9.0.0","js-yaml":">=4.1.2 <5.0.0",flatted:">=3.4.0 <4.0.0","smol-toml":">=1.6.1 <2.0.0",koa:">=2.16.4 <3.0.0","@babel/core":">=7.29.1 <8.0.0","@typescript-eslint/typescript-estree":"^8.63.0",vite:"^7.3.6"}}});function m(e,t,r){function o(s,u){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,u);let l=a.prototype,d=Object.keys(l);for(let p=0;p<d.length;p++){let f=d[p];f in s||(s[f]=l[f].bind(s))}}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function a(s){var u;let l=r?.Parent?new i:this;o(l,s),(u=l._zod).deferred??(u.deferred=[]);for(let d of l._zod.deferred)d();return l}return Object.defineProperty(a,"init",{value:o}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>r?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}function W(e){return e&&Object.assign(Nt,e),Nt}var Ef,is,as,Fe,dt,Nt,Ct=y(()=>{is=Object.freeze({status:"aborted"});as=Symbol("zod_brand"),Fe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},dt=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(Ef=globalThis).__zod_globalConfig??(Ef.__zod_globalConfig={});Nt=globalThis.__zod_globalConfig});var $={};Te($,{BIGINT_FORMAT_RANGES:()=>hs,Class:()=>cs,NUMBER_FORMAT_RANGES:()=>gs,aborted:()=>gt,allowsEval:()=>ds,assert:()=>ex,assertEqual:()=>Kk,assertIs:()=>Yk,assertNever:()=>Qk,assertNotEqual:()=>Xk,assignProp:()=>mt,base64ToUint8Array:()=>Nf,base64urlToUint8Array:()=>vx,cached:()=>sn,captureStackTrace:()=>_o,cleanEnum:()=>hx,cleanRegex:()=>rr,clone:()=>he,cloneDef:()=>nx,createTransparentProxy:()=>cx,defineLazy:()=>N,esc:()=>bo,escapeRegex:()=>Le,explicitlyAborted:()=>vs,extend:()=>dx,finalizeIssue:()=>ve,floatSafeRemainder:()=>us,getElementAtPath:()=>rx,getEnumValues:()=>nr,getLengthableOrigin:()=>ar,getParsedType:()=>sx,getSizableOrigin:()=>ir,hexToUint8Array:()=>bx,isObject:()=>zt,isPlainObject:()=>ft,issue:()=>cn,joinValues:()=>h,jsonStringifyReplacer:()=>an,merge:()=>mx,mergeDefs:()=>rt,normalizeParams:()=>k,nullish:()=>pt,numKeys:()=>ax,objectClone:()=>tx,omit:()=>lx,optionalKeys:()=>fs,parsedType:()=>_,partial:()=>fx,pick:()=>ux,prefixIssues:()=>_e,primitiveTypes:()=>ms,promiseAllObject:()=>ox,propertyKeyTypes:()=>or,randomString:()=>ix,required:()=>gx,safeExtend:()=>px,shallowClone:()=>ps,slugify:()=>ls,stringifyPrimitive:()=>b,uint8ArrayToBase64:()=>Cf,uint8ArrayToBase64url:()=>yx,uint8ArrayToHex:()=>_x,unwrapMessage:()=>tr});function Kk(e){return e}function Xk(e){return e}function Yk(e){}function Qk(e){throw new Error("Unexpected value in exhaustive check")}function ex(e){}function nr(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function h(e,t="|"){return e.map(r=>b(r)).join(t)}function an(e,t){return typeof t=="bigint"?t.toString():t}function sn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function pt(e){return e==null}function rr(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function us(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}function N(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==Af)return o===void 0&&(o=Af,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function tx(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function mt(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function rt(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function nx(e){return rt(e._zod.def)}function rx(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function ox(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function ix(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function bo(e){return JSON.stringify(e)}function ls(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function zt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ft(e){if(zt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(zt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ps(e){return ft(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function ax(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function Le(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function he(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function k(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function cx(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function b(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function fs(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function ux(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=rt(e._zod.def,{get shape(){let a={};for(let s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(a[s]=r.shape[s])}return mt(this,"shape",a),a},checks:[]});return he(e,i)}function lx(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=rt(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete a[s]}return mt(this,"shape",a),a},checks:[]});return he(e,i)}function dx(e,t){if(!ft(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(i,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=rt(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return mt(this,"shape",i),i}});return he(e,n)}function px(e,t){if(!ft(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=rt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return mt(this,"shape",o),o}});return he(e,r)}function mx(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=rt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return mt(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return he(e,r)}function fx(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let a=rt(t._zod.def,{get shape(){let s=t._zod.def.shape,u={...s};if(r)for(let l in r){if(!(l in s))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(u[l]=e?new e({type:"optional",innerType:s[l]}):s[l])}else for(let l in s)u[l]=e?new e({type:"optional",innerType:s[l]}):s[l];return mt(this,"shape",u),u},checks:[]});return he(t,a)}function gx(e,t,r){let o=rt(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let a in r){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=new e({type:"nonoptional",innerType:n[a]}))}else for(let a in n)i[a]=new e({type:"nonoptional",innerType:n[a]});return mt(this,"shape",i),i}});return he(t,o)}function gt(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function vs(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function _e(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function tr(e){return typeof e=="string"?e:e?.message}function ve(e,t,r){let o=e.message?e.message:tr(e.inst?._zod.def?.error?.(e))??tr(t?.error?.(e))??tr(r.customError?.(e))??tr(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:a,...s}=e;return s.path??(s.path=[]),s.message=o,t?.reportInput&&(s.input=a),s}function ir(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ar(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function _(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function cn(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function hx(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Nf(e){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function Cf(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function vx(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return Nf(t+r)}function yx(e){return Cf(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function bx(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function _x(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Af,_o,ds,sx,or,ms,gs,hs,cs,S=y(()=>{Ct();Af=Symbol("evaluating");_o="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};ds=sn(()=>{if(Nt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});sx=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},or=new Set(["string","number","symbol"]),ms=new Set(["string","number","bigint","boolean","symbol","undefined"]);gs={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},hs={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};cs=class{constructor(...t){}}});function cr(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}function ur(e,t=r=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let a of n.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(s=>o({issues:s},[...i,...a.path]));else if(a.code==="invalid_key")o({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")o({issues:a.issues},[...i,...a.path]);else{let s=[...i,...a.path];if(s.length===0)r._errors.push(t(a));else{let u=r,l=0;for(;l<s.length;){let d=s[l];l===s.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(a))):u[d]=u[d]||{_errors:[]},u=u[d],l++}}}};return o(e),r}function ys(e,t=r=>r.message){let r={errors:[]},o=(n,i=[])=>{var a,s;for(let u of n.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(l=>o({issues:l},[...i,...u.path]));else if(u.code==="invalid_key")o({issues:u.issues},[...i,...u.path]);else if(u.code==="invalid_element")o({issues:u.issues},[...i,...u.path]);else{let l=[...i,...u.path];if(l.length===0){r.errors.push(t(u));continue}let d=r,p=0;for(;p<l.length;){let f=l[p],v=p===l.length-1;typeof f=="string"?(d.properties??(d.properties={}),(a=d.properties)[f]??(a[f]={errors:[]}),d=d.properties[f]):(d.items??(d.items=[]),(s=d.items)[f]??(s[f]={errors:[]}),d=d.items[f]),v&&d.errors.push(t(u)),p++}}};return o(e),r}function Df(e){let t=[],r=e.map(o=>typeof o=="object"?o.key:o);for(let o of r)typeof o=="number"?t.push(`[${o}]`):typeof o=="symbol"?t.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?t.push(`[${JSON.stringify(o)}]`):(t.length&&t.push("."),t.push(o));return t.join("")}function bs(e){let t=[],r=[...e.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)t.push(`\u2716 ${o.message}`),o.path?.length&&t.push(` \u2192 at ${Df(o.path)}`);return t.join(`
|
|
2
|
+
var Wk=Object.defineProperty;var y=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(o){throw r=[o],o}};var Te=(e,t)=>{for(var r in t)Wk(e,r,{get:t[r],enumerable:!0})};var lt,os=y(()=>{lt={name:"@tonyclaw/agent-inspector",version:"4.0.14",type:"module",description:"Agent observability and knowledge capture layer for AI coding tools.",license:"MIT",engines:{node:">=22.0.0"},author:"TonyClaw",repository:{type:"git",url:"git+https://gitcode.com/TonyClaw/OpenInspector.git"},homepage:"https://gitcode.com/TonyClaw/OpenInspector#readme",workspaces:["packages/*"],bugs:{url:"https://gitcode.com/TonyClaw/OpenInspector/issues"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["claude","anthropic","openai","proxy","api-inspector","agent-observability","agent-memory","debugging","llm","ai-coding-tools"],bin:{"agent-inspector":"bin/agent-inspector.js"},files:["bin","src/assets/agent-inspector.ico","scripts/setup-windows-runtime.mjs","scripts/setup-agent-skills.mjs","scripts/generate-theme-scales.mjs","docs/instance-control.openapi.yaml","styles",".output","!.output/*.exe"],scripts:{dev:"node scripts/dev-decoupled.mjs","dev:ui":"vite dev --config vite.ui.config.ts","dev:backend":"node scripts/dev-backend.mjs","test:smoke":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs smoke","test:fast":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs smoke","test:unit":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs unit","test:integration":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs integration","test:changed":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs changed","test:all":"node scripts/run-local-bun.mjs scripts/run-test-suite.mjs all","test:hostile-inputs":"bun test src/proxy/identityProxy.test.ts src/proxy/handler.cancellationCompatibility.test.ts src/proxy/logImporter.test.ts src/backend/routes/api/-logs.stream.test.ts src/proxy/handler.admission.test.ts src/proxy/runtimeHealth.test.ts src/proxy/storageLifecycle.test.ts","test:compatibility-tooling":"node scripts/run-compatibility-tests.mjs ultra","test:compatibility-tooling:extended":"node scripts/run-compatibility-tests.mjs extended","test:compatibility-conformance":"node scripts/run-compatibility-tests.mjs conformance",start:"node .output/cli.js","start:backend":"node .output/cli.js --backend-only --no-open","preview:ui":"vite preview --config vite.ui.config.ts","clean:output":"node scripts/clean-output.mjs",build:"bun clean:output && bun build:backend && bun build:ui && bun smoke:ui-preview && bun build:workers && bun build:cli && bun build:mcp && bun check:bundle && bun check:boundaries","build:backend":"vite build --config vite.backend.config.ts","build:ui":"vite build --config vite.ui.config.ts","build:workers":"npx esbuild src/proxy/logFinalizer.worker.ts src/proxy/sessionWorkerEntry.ts --bundle --minify --legal-comments=none --platform=node --target=node22 --format=esm --outdir=.output/workers --external:better-sqlite3","smoke:workers":"node scripts/smoke-production-workers.mjs","smoke:packed-workers":"node scripts/smoke-packed-workers.mjs","smoke:instances":"node scripts/smoke-windows-instances.mjs","smoke:coding-agent-instances":"node scripts/smoke-coding-agent-instances.mjs","smoke:ui-preview":"node scripts/smoke-decoupled-ui-preview.mjs","check:bundle":"node scripts/check-client-bundle.mjs","check:boundaries":"node scripts/check-runtime-boundaries.mjs","check:commercial-performance":"node scripts/check-commercial-performance-budgets.mjs","check:hostile-inputs":"node scripts/check-hostile-input-coverage.mjs","check:supply-chain":"node scripts/check-commercial-supply-chain.mjs","compatibility:bdd":"node scripts/lint-bdd-catalog.mjs","compatibility:compare":"node scripts/compatibility/cli.mjs compare","compatibility:drift":"node scripts/check-backend-compatibility.mjs","compatibility:fixtures":"bun scripts/validate-compatibility-fixtures.ts","compatibility:freeze":"node scripts/freeze-backend-baseline.mjs","compatibility:run":"node scripts/compatibility/cli.mjs run","compatibility:performance":"node scripts/compatibility/performance-cli.mjs","compatibility:performance:verify":"node scripts/compatibility/performance-cli.mjs verify","build:cli":"npx esbuild src/cli.ts --bundle --minify --legal-comments=none --platform=node --target=node22 --format=esm --outfile=.output/cli.js","build:mcp":"npx esbuild packages/agent-inspector-mcp/src/cli.ts --bundle --minify --legal-comments=none --platform=node --target=node22 --format=esm --outfile=packages/agent-inspector-mcp/dist/cli.js","rust:build-package":"node scripts/rust/build-platform.mjs","rust:stage-package":"node scripts/rust/stage-platform.mjs","rust:verify-package":"node scripts/rust/verify-platform.mjs","rust:pack-package":"node scripts/rust/pack-platform.mjs","rust:native-artifact":"node scripts/rust/create-native-artifact.mjs","rust:native:aggregate":"node scripts/rust/aggregate-native-artifacts.mjs","rust:release-gate:preflight":"node scripts/rust/release-gate-preflight.mjs","rust:release-evidence:plan":"node scripts/rust/release-evidence-plan.mjs","commercial:release-gate:preflight":"node scripts/commercial-release-preflight.mjs","test:commercial-release-gate":"bun test scripts/commercialReleasePreflight.test.ts","test:rust-packaging":"bun test scripts/rust/npmPackaging.test.ts scripts/rust/nativeReleaseContract.test.ts scripts/rust/nativeStartupSmoke.test.ts scripts/rust/releaseGatePreflight.test.ts scripts/releaseCore.test.ts","rust:packages:check":"node scripts/rust/sync-package-versions.mjs","rust:packages:sync":"node scripts/rust/sync-package-versions.mjs --write","themes:generate":"node scripts/generate-theme-scales.mjs",postinstall:"node scripts/setup-windows-runtime.mjs && node scripts/setup-agent-skills.mjs",prepublishOnly:"node scripts/rust/require-release-orchestrator.mjs",typecheck:"tsc --noEmit --incremental --tsBuildInfoFile .cache/tsconfig.tsbuildinfo",lint:"eslint . --cache --cache-location .cache/eslintcache",format:"biome format --write .","format:check":"biome format .","verify:ultra":"node scripts/compatibility/ultra-gate.mjs","verify:ultra:fresh":"node scripts/compatibility/ultra-gate.mjs --no-cache","verify:ultra:smoke":"npm run verify:ultra && npm run test:smoke","verify:fast":"bun scripts/run-static-checks.mjs --format && bun test:changed","extension:zip":"node scripts/pack-chrome-extension.mjs","extension:release":"node scripts/release-chrome-extension.mjs",release:"node scripts/release.mjs",knip:"knip",check:"bun scripts/run-static-checks.mjs --format && bun check:boundaries && bun check:commercial-performance && bun check:hostile-inputs && bun compatibility:bdd && bun rust:packages:check",prepare:"husky",ladle:"ladle serve","ladle:build":"ladle build"},dependencies:{"@mariozechner/pi-agent-core":"^0.73.1","@mariozechner/pi-ai":"^0.73.1","@modelcontextprotocol/server":"^2.0.0-beta.4","@tailwindcss/typography":"^0.5.20","@tanstack/react-router":"^1.170.18","@tanstack/react-start":"^1.168.28","@tanstack/react-virtual":"^3.14.6","class-variance-authority":"^0.7.1",clsx:"^2.1.1",conf:"^15.1.0",diff:"^9.0.0",jszip:"^3.10.1","lucide-react":"^0.563.0","radix-ui":"1.6.2",react:"^19.2.7","react-dom":"^19.2.7","react-markdown":"^10.1.0",swr:"^2.4.2","tailwind-merge":"^3.6.0",three:"0.185.1","tw-animate-css":"^1.4.0",zod:"^4.4.3"},optionalDependencies:{"@tonyclaw/agent-inspector-backend-darwin-arm64":"4.0.14","@tonyclaw/agent-inspector-backend-linux-x64-gnu":"4.0.14","@tonyclaw/agent-inspector-backend-win32-x64-msvc":"4.0.14","better-sqlite3":"^12.11.1",rcedit:"4.0.1"},devDependencies:{"@biomejs/biome":"^2.5.3","@eslint/js":"^10.0.1","@ladle/react":"^5.1.1","@radix-ui/colors":"^3.0.0","@tailwindcss/vite":"^4.3.2","@tanstack/router-plugin":"^1.168.20","@types/bun":"^1.3.14","@types/react":"^19.2.17","@types/react-dom":"^19.2.3","@types/three":"0.185.1","@typescript-eslint/eslint-plugin":"^8.64.0","@typescript-eslint/parser":"^8.64.0","@vitejs/plugin-react":"^5.2.0",ajv:"8.20.0","ajv-formats":"3.0.1","colorjs.io":"^0.7.0",esbuild:"^0.28.1",eslint:"^9.39.5","eslint-plugin-eslint-comments":"^3.2.0","eslint-plugin-functional":"^9.0.5","eslint-plugin-unicorn":"^63.0.0",husky:"^9.1.7",knip:"^5.88.1",nitro:"^3.0.260610-beta",playwright:"^1.61.1",tailwindcss:"^4.3.2",typescript:"^5.9.3",vite:"^7.3.6","vite-tsconfig-paths":"^6.1.1"},overrides:{undici:">=7.24.0 <8.0.0",rollup:">=4.59.0 <5.0.0",postcss:">=8.5.10 <9.0.0","js-yaml":">=4.1.2 <5.0.0",flatted:">=3.4.0 <4.0.0","smol-toml":">=1.6.1 <2.0.0",koa:">=2.16.4 <3.0.0","@babel/core":">=7.29.1 <8.0.0","@typescript-eslint/typescript-estree":"^8.63.0",vite:"^7.3.6"}}});function m(e,t,r){function o(s,u){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,u);let l=a.prototype,d=Object.keys(l);for(let p=0;p<d.length;p++){let f=d[p];f in s||(s[f]=l[f].bind(s))}}let n=r?.Parent??Object;class i extends n{}Object.defineProperty(i,"name",{value:e});function a(s){var u;let l=r?.Parent?new i:this;o(l,s),(u=l._zod).deferred??(u.deferred=[]);for(let d of l._zod.deferred)d();return l}return Object.defineProperty(a,"init",{value:o}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>r?.Parent&&s instanceof r.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}function W(e){return e&&Object.assign(Nt,e),Nt}var Ef,is,as,Fe,dt,Nt,Ct=y(()=>{is=Object.freeze({status:"aborted"});as=Symbol("zod_brand"),Fe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},dt=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(Ef=globalThis).__zod_globalConfig??(Ef.__zod_globalConfig={});Nt=globalThis.__zod_globalConfig});var $={};Te($,{BIGINT_FORMAT_RANGES:()=>hs,Class:()=>cs,NUMBER_FORMAT_RANGES:()=>gs,aborted:()=>gt,allowsEval:()=>ds,assert:()=>ex,assertEqual:()=>Kk,assertIs:()=>Yk,assertNever:()=>Qk,assertNotEqual:()=>Xk,assignProp:()=>mt,base64ToUint8Array:()=>Nf,base64urlToUint8Array:()=>vx,cached:()=>sn,captureStackTrace:()=>_o,cleanEnum:()=>hx,cleanRegex:()=>rr,clone:()=>he,cloneDef:()=>nx,createTransparentProxy:()=>cx,defineLazy:()=>N,esc:()=>bo,escapeRegex:()=>Le,explicitlyAborted:()=>vs,extend:()=>dx,finalizeIssue:()=>ve,floatSafeRemainder:()=>us,getElementAtPath:()=>rx,getEnumValues:()=>nr,getLengthableOrigin:()=>ar,getParsedType:()=>sx,getSizableOrigin:()=>ir,hexToUint8Array:()=>bx,isObject:()=>zt,isPlainObject:()=>ft,issue:()=>cn,joinValues:()=>h,jsonStringifyReplacer:()=>an,merge:()=>mx,mergeDefs:()=>rt,normalizeParams:()=>k,nullish:()=>pt,numKeys:()=>ax,objectClone:()=>tx,omit:()=>lx,optionalKeys:()=>fs,parsedType:()=>_,partial:()=>fx,pick:()=>ux,prefixIssues:()=>_e,primitiveTypes:()=>ms,promiseAllObject:()=>ox,propertyKeyTypes:()=>or,randomString:()=>ix,required:()=>gx,safeExtend:()=>px,shallowClone:()=>ps,slugify:()=>ls,stringifyPrimitive:()=>b,uint8ArrayToBase64:()=>Cf,uint8ArrayToBase64url:()=>yx,uint8ArrayToHex:()=>_x,unwrapMessage:()=>tr});function Kk(e){return e}function Xk(e){return e}function Yk(e){}function Qk(e){throw new Error("Unexpected value in exhaustive check")}function ex(e){}function nr(e){let t=Object.values(e).filter(o=>typeof o=="number");return Object.entries(e).filter(([o,n])=>t.indexOf(+o)===-1).map(([o,n])=>n)}function h(e,t="|"){return e.map(r=>b(r)).join(t)}function an(e,t){return typeof t=="bigint"?t.toString():t}function sn(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function pt(e){return e==null}function rr(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function us(e,t){let r=e/t,o=Math.round(r),n=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-o)<n?0:r-o}function N(e,t,r){let o;Object.defineProperty(e,t,{get(){if(o!==Af)return o===void 0&&(o=Af,o=r()),o},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function tx(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function mt(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function rt(...e){let t={};for(let r of e){let o=Object.getOwnPropertyDescriptors(r);Object.assign(t,o)}return Object.defineProperties({},t)}function nx(e){return rt(e._zod.def)}function rx(e,t){return t?t.reduce((r,o)=>r?.[o],e):e}function ox(e){let t=Object.keys(e),r=t.map(o=>e[o]);return Promise.all(r).then(o=>{let n={};for(let i=0;i<t.length;i++)n[t[i]]=o[i];return n})}function ix(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let o=0;o<e;o++)r+=t[Math.floor(Math.random()*t.length)];return r}function bo(e){return JSON.stringify(e)}function ls(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function zt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ft(e){if(zt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(zt(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ps(e){return ft(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function ax(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function Le(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function he(e,t,r){let o=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(o._zod.parent=e),o}function k(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function cx(e){let t;return new Proxy({},{get(r,o,n){return t??(t=e()),Reflect.get(t,o,n)},set(r,o,n,i){return t??(t=e()),Reflect.set(t,o,n,i)},has(r,o){return t??(t=e()),Reflect.has(t,o)},deleteProperty(r,o){return t??(t=e()),Reflect.deleteProperty(t,o)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,o){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,o)},defineProperty(r,o,n){return t??(t=e()),Reflect.defineProperty(t,o,n)}})}function b(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function fs(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function ux(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=rt(e._zod.def,{get shape(){let a={};for(let s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(a[s]=r.shape[s])}return mt(this,"shape",a),a},checks:[]});return he(e,i)}function lx(e,t){let r=e._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=rt(e._zod.def,{get shape(){let a={...e._zod.def.shape};for(let s in t){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete a[s]}return mt(this,"shape",a),a},checks:[]});return he(e,i)}function dx(e,t){if(!ft(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(i,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let n=rt(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return mt(this,"shape",i),i}});return he(e,n)}function px(e,t){if(!ft(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=rt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t};return mt(this,"shape",o),o}});return he(e,r)}function mx(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=rt(e._zod.def,{get shape(){let o={...e._zod.def.shape,...t._zod.def.shape};return mt(this,"shape",o),o},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return he(e,r)}function fx(e,t,r){let n=t._zod.def.checks;if(n&&n.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let a=rt(t._zod.def,{get shape(){let s=t._zod.def.shape,u={...s};if(r)for(let l in r){if(!(l in s))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(u[l]=e?new e({type:"optional",innerType:s[l]}):s[l])}else for(let l in s)u[l]=e?new e({type:"optional",innerType:s[l]}):s[l];return mt(this,"shape",u),u},checks:[]});return he(t,a)}function gx(e,t,r){let o=rt(t._zod.def,{get shape(){let n=t._zod.def.shape,i={...n};if(r)for(let a in r){if(!(a in i))throw new Error(`Unrecognized key: "${a}"`);r[a]&&(i[a]=new e({type:"nonoptional",innerType:n[a]}))}else for(let a in n)i[a]=new e({type:"nonoptional",innerType:n[a]});return mt(this,"shape",i),i}});return he(t,o)}function gt(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function vs(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function _e(e,t){return t.map(r=>{var o;return(o=r).path??(o.path=[]),r.path.unshift(e),r})}function tr(e){return typeof e=="string"?e:e?.message}function ve(e,t,r){let o=e.message?e.message:tr(e.inst?._zod.def?.error?.(e))??tr(t?.error?.(e))??tr(r.customError?.(e))??tr(r.localeError?.(e))??"Invalid input",{inst:n,continue:i,input:a,...s}=e;return s.path??(s.path=[]),s.message=o,t?.reportInput&&(s.input=a),s}function ir(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function ar(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function _(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function cn(...e){let[t,r,o]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:o}:{...t}}function hx(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Nf(e){let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function Cf(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function vx(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return Nf(t+r)}function yx(e){return Cf(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function bx(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let o=0;o<t.length;o+=2)r[o/2]=Number.parseInt(t.slice(o,o+2),16);return r}function _x(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var Af,_o,ds,sx,or,ms,gs,hs,cs,S=y(()=>{Ct();Af=Symbol("evaluating");_o="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};ds=sn(()=>{if(Nt.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});sx=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},or=new Set(["string","number","symbol"]),ms=new Set(["string","number","bigint","boolean","symbol","undefined"]);gs={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},hs={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};cs=class{constructor(...t){}}});function cr(e,t=r=>r.message){let r={},o=[];for(let n of e.issues)n.path.length>0?(r[n.path[0]]=r[n.path[0]]||[],r[n.path[0]].push(t(n))):o.push(t(n));return{formErrors:o,fieldErrors:r}}function ur(e,t=r=>r.message){let r={_errors:[]},o=(n,i=[])=>{for(let a of n.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(s=>o({issues:s},[...i,...a.path]));else if(a.code==="invalid_key")o({issues:a.issues},[...i,...a.path]);else if(a.code==="invalid_element")o({issues:a.issues},[...i,...a.path]);else{let s=[...i,...a.path];if(s.length===0)r._errors.push(t(a));else{let u=r,l=0;for(;l<s.length;){let d=s[l];l===s.length-1?(u[d]=u[d]||{_errors:[]},u[d]._errors.push(t(a))):u[d]=u[d]||{_errors:[]},u=u[d],l++}}}};return o(e),r}function ys(e,t=r=>r.message){let r={errors:[]},o=(n,i=[])=>{var a,s;for(let u of n.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(l=>o({issues:l},[...i,...u.path]));else if(u.code==="invalid_key")o({issues:u.issues},[...i,...u.path]);else if(u.code==="invalid_element")o({issues:u.issues},[...i,...u.path]);else{let l=[...i,...u.path];if(l.length===0){r.errors.push(t(u));continue}let d=r,p=0;for(;p<l.length;){let f=l[p],v=p===l.length-1;typeof f=="string"?(d.properties??(d.properties={}),(a=d.properties)[f]??(a[f]={errors:[]}),d=d.properties[f]):(d.items??(d.items=[]),(s=d.items)[f]??(s[f]={errors:[]}),d=d.items[f]),v&&d.errors.push(t(u)),p++}}};return o(e),r}function Df(e){let t=[],r=e.map(o=>typeof o=="object"?o.key:o);for(let o of r)typeof o=="number"?t.push(`[${o}]`):typeof o=="symbol"?t.push(`[${JSON.stringify(String(o))}]`):/[^\w$]/.test(o)?t.push(`[${JSON.stringify(o)}]`):(t.length&&t.push("."),t.push(o));return t.join("")}function bs(e){let t=[],r=[...e.issues].sort((o,n)=>(o.path??[]).length-(n.path??[]).length);for(let o of r)t.push(`\u2716 ${o.message}`),o.path?.length&&t.push(` \u2192 at ${Df(o.path)}`);return t.join(`
|
|
3
3
|
`)}var zf,sr,$e,_s=y(()=>{Ct();S();zf=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,an,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},sr=m("$ZodError",zf),$e=m("$ZodError",zf,{Parent:Error})});var un,$o,ln,ko,dn,$s,pn,ks,xo,kx,Io,xx,So,Ix,Po,Sx,wo,Px,Ro,wx,To,Rx,Oo,Tx,xs=y(()=>{Ct();_s();S();un=e=>(t,r,o,n)=>{let i=o?{...o,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise)throw new Fe;if(a.issues.length){let s=new(n?.Err??e)(a.issues.map(u=>ve(u,i,W())));throw _o(s,n?.callee),s}return a.value},$o=un($e),ln=e=>async(t,r,o,n)=>{let i=o?{...o,async:!0}:{async:!0},a=t._zod.run({value:r,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(n?.Err??e)(a.issues.map(u=>ve(u,i,W())));throw _o(s,n?.callee),s}return a.value},ko=ln($e),dn=e=>(t,r,o)=>{let n=o?{...o,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},n);if(i instanceof Promise)throw new Fe;return i.issues.length?{success:!1,error:new(e??sr)(i.issues.map(a=>ve(a,n,W())))}:{success:!0,data:i.value}},$s=dn($e),pn=e=>async(t,r,o)=>{let n=o?{...o,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(a=>ve(a,n,W())))}:{success:!0,data:i.value}},ks=pn($e),xo=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return un(e)(t,r,n)},kx=xo($e),Io=e=>(t,r,o)=>un(e)(t,r,o),xx=Io($e),So=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return ln(e)(t,r,n)},Ix=So($e),Po=e=>async(t,r,o)=>ln(e)(t,r,o),Sx=Po($e),wo=e=>(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return dn(e)(t,r,n)},Px=wo($e),Ro=e=>(t,r,o)=>dn(e)(t,r,o),wx=Ro($e),To=e=>async(t,r,o)=>{let n=o?{...o,direction:"backward"}:{direction:"backward"};return pn(e)(t,r,n)},Rx=To($e),Oo=e=>async(t,r,o)=>pn(e)(t,r,o),Tx=Oo($e)});var Oe={};Te(Oe,{base64:()=>Ls,base64url:()=>Eo,bigint:()=>Hs,boolean:()=>Ws,browserEmail:()=>Ux,cidrv4:()=>Us,cidrv6:()=>js,cuid:()=>Is,cuid2:()=>Ss,date:()=>Fs,datetime:()=>Gs,domain:()=>Mx,duration:()=>Os,e164:()=>Bs,email:()=>As,emoji:()=>Ns,extendedDuration:()=>Ox,guid:()=>Es,hex:()=>Bx,hostname:()=>Lx,html5Email:()=>Cx,httpProtocol:()=>Ms,idnEmail:()=>Dx,integer:()=>Vs,ipv4:()=>Cs,ipv6:()=>zs,ksuid:()=>Rs,lowercase:()=>Xs,mac:()=>Ds,md5_base64:()=>Zx,md5_base64url:()=>Gx,md5_hex:()=>Fx,nanoid:()=>Ts,null:()=>qs,number:()=>Ao,rfc5322Email:()=>zx,sha1_base64:()=>Hx,sha1_base64url:()=>Vx,sha1_hex:()=>Jx,sha256_base64:()=>qx,sha256_base64url:()=>Kx,sha256_hex:()=>Wx,sha384_base64:()=>Yx,sha384_base64url:()=>Qx,sha384_hex:()=>Xx,sha512_base64:()=>tI,sha512_base64url:()=>nI,sha512_hex:()=>eI,string:()=>Js,time:()=>Zs,ulid:()=>Ps,undefined:()=>Ks,unicodeEmail:()=>Uf,uppercase:()=>Ys,uuid:()=>Dt,uuid4:()=>Ex,uuid6:()=>Ax,uuid7:()=>Nx,xid:()=>ws});function Ns(){return new RegExp(jx,"u")}function Lf(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Zs(e){return new RegExp(`^${Lf(e)}$`)}function Gs(e){let t=Lf({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let o=`${t}(?:${r.join("|")})`;return new RegExp(`^${jf}T(?:${o})$`)}function lr(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function dr(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var Is,Ss,Ps,ws,Rs,Ts,Os,Ox,Es,Dt,Ex,Ax,Nx,As,Cx,zx,Uf,Dx,Ux,jx,Cs,zs,Ds,Us,js,Ls,Eo,Lx,Mx,Ms,Bs,jf,Fs,Js,Hs,Vs,Ao,Ws,qs,Ks,Xs,Ys,Bx,Fx,Zx,Gx,Jx,Hx,Vx,Wx,qx,Kx,Xx,Yx,Qx,eI,tI,nI,No=y(()=>{S();Is=/^[cC][0-9a-z]{6,}$/,Ss=/^[0-9a-z]+$/,Ps=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ws=/^[0-9a-vA-V]{20}$/,Rs=/^[A-Za-z0-9]{27}$/,Ts=/^[a-zA-Z0-9_-]{21}$/,Os=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ox=/^[-+]?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)?)??$/,Es=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Dt=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ex=Dt(4),Ax=Dt(6),Nx=Dt(7),As=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Cx=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,zx=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Uf=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Dx=Uf,Ux=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,jx="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Cs=/^(?:(?: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])$/,zs=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,Ds=e=>{let t=Le(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},Us=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,js=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ls=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Eo=/^[A-Za-z0-9_-]*$/,Lx=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Mx=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Ms=/^https?$/,Bs=/^\+[1-9]\d{6,14}$/,jf="(?:(?:\\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])))",Fs=new RegExp(`^${jf}$`);Js=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Hs=/^-?\d+n?$/,Vs=/^-?\d+$/,Ao=/^-?\d+(?:\.\d+)?$/,Ws=/^(?:true|false)$/i,qs=/^null$/i,Ks=/^undefined$/i,Xs=/^[^A-Z]*$/,Ys=/^[^a-z]*$/,Bx=/^[0-9a-fA-F]*$/;Fx=/^[0-9a-fA-F]{32}$/,Zx=lr(22,"=="),Gx=dr(22),Jx=/^[0-9a-fA-F]{40}$/,Hx=lr(27,"="),Vx=dr(27),Wx=/^[0-9a-fA-F]{64}$/,qx=lr(43,"="),Kx=dr(43),Xx=/^[0-9a-fA-F]{96}$/,Yx=lr(64,""),Qx=dr(64),eI=/^[0-9a-fA-F]{128}$/,tI=lr(86,"=="),nI=dr(86)});function Mf(e,t,r){e.issues.length&&t.issues.push(..._e(r,e.issues))}var J,Bf,Co,zo,Qs,ec,tc,nc,rc,oc,ic,ac,sc,mn,cc,uc,lc,dc,pc,mc,fc,gc,hc,Do=y(()=>{Ct();No();S();J=m("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Bf={number:"number",bigint:"bigint",object:"date"},Co=m("$ZodCheckLessThan",(e,t)=>{J.init(e,t);let r=Bf[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value<=t.value:o.value<t.value)||o.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),zo=m("$ZodCheckGreaterThan",(e,t)=>{J.init(e,t);let r=Bf[typeof t.value];e._zod.onattach.push(o=>{let n=o._zod.bag,i=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=o=>{(t.inclusive?o.value>=t.value:o.value>t.value)||o.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:o.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Qs=m("$ZodCheckMultipleOf",(e,t)=>{J.init(e,t),e._zod.onattach.push(r=>{var o;(o=r._zod.bag).multipleOf??(o.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):us(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ec=m("$ZodCheckNumberFormat",(e,t)=>{J.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),o=r?"int":"number",[n,i]=gs[t.format];e._zod.onattach.push(a=>{let s=a._zod.bag;s.format=t.format,s.minimum=n,s.maximum=i,r&&(s.pattern=Vs)}),e._zod.check=a=>{let s=a.value;if(r){if(!Number.isInteger(s)){a.issues.push({expected:o,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:o,inclusive:!0,continue:!t.abort});return}}s<n&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),tc=m("$ZodCheckBigIntFormat",(e,t)=>{J.init(e,t);let[r,o]=hs[t.format];e._zod.onattach.push(n=>{let i=n._zod.bag;i.format=t.format,i.minimum=r,i.maximum=o}),e._zod.check=n=>{let i=n.value;i<r&&n.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>o&&n.issues.push({origin:"bigint",input:i,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),nc=m("$ZodCheckMaxSize",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!pt(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;n.size<=t.maximum||o.issues.push({origin:ir(n),code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),rc=m("$ZodCheckMinSize",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!pt(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;n.size>=t.minimum||o.issues.push({origin:ir(n),code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),oc=m("$ZodCheckSizeEquals",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!pt(n)&&n.size!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.size,n.maximum=t.size,n.size=t.size}),e._zod.check=o=>{let n=o.value,i=n.size;if(i===t.size)return;let a=i>t.size;o.issues.push({origin:ir(n),...a?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),ic=m("$ZodCheckMaxLength",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!pt(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(o._zod.bag.maximum=t.maximum)}),e._zod.check=o=>{let n=o.value;if(n.length<=t.maximum)return;let a=ar(n);o.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),ac=m("$ZodCheckMinLength",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!pt(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(o._zod.bag.minimum=t.minimum)}),e._zod.check=o=>{let n=o.value;if(n.length>=t.minimum)return;let a=ar(n);o.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:n,inst:e,continue:!t.abort})}}),sc=m("$ZodCheckLengthEquals",(e,t)=>{var r;J.init(e,t),(r=e._zod.def).when??(r.when=o=>{let n=o.value;return!pt(n)&&n.length!==void 0}),e._zod.onattach.push(o=>{let n=o._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=o=>{let n=o.value,i=n.length;if(i===t.length)return;let a=ar(n),s=i>t.length;o.issues.push({origin:a,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:o.value,inst:e,continue:!t.abort})}}),mn=m("$ZodCheckStringFormat",(e,t)=>{var r,o;J.init(e,t),e._zod.onattach.push(n=>{let i=n._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(o=e._zod).check??(o.check=()=>{})}),cc=m("$ZodCheckRegex",(e,t)=>{mn.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),uc=m("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Xs),mn.init(e,t)}),lc=m("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Ys),mn.init(e,t)}),dc=m("$ZodCheckIncludes",(e,t)=>{J.init(e,t);let r=Le(t.includes),o=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=o,e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(o)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),pc=m("$ZodCheckStartsWith",(e,t)=>{J.init(e,t);let r=new RegExp(`^${Le(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.startsWith(t.prefix)||o.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:o.value,inst:e,continue:!t.abort})}}),mc=m("$ZodCheckEndsWith",(e,t)=>{J.init(e,t);let r=new RegExp(`.*${Le(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(o=>{let n=o._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(r)}),e._zod.check=o=>{o.value.endsWith(t.suffix)||o.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:o.value,inst:e,continue:!t.abort})}});fc=m("$ZodCheckProperty",(e,t)=>{J.init(e,t),e._zod.check=r=>{let o=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(o instanceof Promise)return o.then(n=>Mf(n,r,t.property));Mf(o,r,t.property)}}),gc=m("$ZodCheckMimeType",(e,t)=>{J.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(o=>{o._zod.bag.mime=t.mime}),e._zod.check=o=>{r.has(o.value.type)||o.issues.push({code:"invalid_value",values:t.mime,input:o.value.type,inst:e,continue:!t.abort})}}),hc=m("$ZodCheckOverwrite",(e,t)=>{J.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}})});var pr,vc=y(()=>{pr=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let o=t.split(`
|
|
4
4
|
`).filter(a=>a),n=Math.min(...o.map(a=>a.length-a.trimStart().length)),i=o.map(a=>a.slice(n)).map(a=>" ".repeat(this.indent*2)+a);for(let a of i)this.content.push(a)}compile(){let t=Function,r=this?.args,n=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,n.join(`
|
|
5
5
|
`))}}});var yc,bc=y(()=>{yc={major:4,minor:4,patch:3}});function Bc(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function rg(e){if(!Eo.test(e))return!1;let t=e.replace(/[-_]/g,o=>o==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Bc(r)}function og(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[o]=r;if(!o)return!1;let n=JSON.parse(atob(o));return!("typ"in n&&n?.typ!=="JWT"||!n.alg||t&&(!("alg"in n)||n.alg!==t))}catch{return!1}}function Zf(e,t,r){e.issues.length&&t.issues.push(..._e(r,e.issues)),t.value[r]=e.value}function Mo(e,t,r,o,n,i){let a=r in o;if(e.issues.length){if(n&&i&&!a)return;t.issues.push(..._e(r,e.issues))}if(!a&&!n){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?a&&(t.value[r]=void 0):t.value[r]=e.value}function ig(e){let t=Object.keys(e.shape);for(let o of t)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);let r=fs(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function ag(e,t,r,o,n,i){let a=[],s=n.keySet,u=n.catchall._zod,l=u.def.type,d=u.optin==="optional",p=u.optout==="optional";for(let f in t){if(f==="__proto__"||s.has(f))continue;if(l==="never"){a.push(f);continue}let v=u.run({value:t[f],issues:[]},o);v instanceof Promise?e.push(v.then(g=>Mo(g,r,f,t,d,p))):Mo(v,r,f,t,d,p)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}function Gf(e,t,r,o){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let n=e.filter(i=>!gt(i));return n.length===1?(t.value=n[0].value,n[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(a=>ve(a,o,W())))}),t)}function Jf(e,t,r,o){let n=e.filter(i=>i.issues.length===0);return n.length===1?(t.value=n[0].value,t):(n.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(a=>ve(a,o,W())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}function _c(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ft(e)&&ft(t)){let r=Object.keys(t),o=Object.keys(e).filter(i=>r.indexOf(i)!==-1),n={...e,...t};for(let i of o){let a=_c(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n[i]=a.data}return{valid:!0,data:n}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<e.length;o++){let n=e[o],i=t[o],a=_c(n,i);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Hf(e,t,r){let o=new Map,n;for(let s of t.issues)if(s.code==="unrecognized_keys"){n??(n=s);for(let u of s.keys)o.has(u)||o.set(u,{}),o.get(u).l=!0}else e.issues.push(s);for(let s of r.issues)if(s.code==="unrecognized_keys")for(let u of s.keys)o.has(u)||o.set(u,{}),o.get(u).r=!0;else e.issues.push(s);let i=[...o].filter(([,s])=>s.l&&s.r).map(([s])=>s);if(i.length&&n&&e.issues.push({...n,keys:i}),gt(e))return e;let a=_c(t.value,r.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}function Vf(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]._zod[t]!=="optional")return r+1;return 0}function Wf(e,t,r){e.issues.length&&t.issues.push(..._e(r,e.issues)),t.value[r]=e.value}function qf(e,t,r,o,n){for(let i=0;i<r.length;i++){let a=e[i],s=i<o.length;if(a.issues.length){if(!s&&i>=n){t.value.length=i;break}t.issues.push(..._e(i,a.issues))}t.value[i]=a.value}for(let i=t.value.length-1;i>=o.length&&(r[i]._zod.optout==="optional"&&t.value[i]===void 0);i--)t.value.length=i;return t}function Kf(e,t,r,o,n,i,a){e.issues.length&&(or.has(typeof o)?r.issues.push(..._e(o,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:n,inst:i,issues:e.issues.map(s=>ve(s,a,W()))})),t.issues.length&&(or.has(typeof o)?r.issues.push(..._e(o,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:n,inst:i,key:o,issues:t.issues.map(s=>ve(s,a,W()))})),r.value.set(e.value,t.value)}function Xf(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function Yf(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}function Qf(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function eg(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function Uo(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}function jo(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let n=t.transform(e.value,e);return n instanceof Promise?n.then(i=>Lo(e,i,t.out,r)):Lo(e,n,t.out,r)}else{let n=t.reverseTransform(e.value,e);return n instanceof Promise?n.then(i=>Lo(e,i,t.in,r)):Lo(e,n,t.in,r)}}function Lo(e,t,r,o){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},o)}function tg(e){return e.value=Object.freeze(e.value),e}function ng(e,t,r,o){if(!e){let n={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(n.params=o._zod.def.params),t.issues.push(cn(n))}}var T,Ut,F,$c,kc,xc,Ic,Sc,Pc,wc,Rc,Tc,Oc,Ec,Ac,Nc,Cc,zc,Dc,Uc,jc,Lc,Mc,Fc,Zc,Gc,Jc,Hc,Bo,Vc,mr,Fo,Wc,qc,Kc,Xc,Yc,Qc,eu,tu,nu,ru,sg,ou,fr,iu,au,su,Zo,cu,uu,lu,du,pu,mu,fu,Go,gu,hu,vu,yu,bu,_u,$u,ku,Jo,gr,xu,Iu,Su,Pu,wu,Ru,Tu,Ou=y(()=>{Do();Ct();vc();xs();No();S();bc();S();T=m("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=yc;let o=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&o.unshift(e);for(let n of o)for(let i of n._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let n=(a,s,u)=>{let l=gt(a),d;for(let p of s){if(p._zod.def.when){if(vs(a)||!p._zod.def.when(a))continue}else if(l)continue;let f=a.issues.length,v=p._zod.check(a);if(v instanceof Promise&&u?.async===!1)throw new Fe;if(d||v instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await v,a.issues.length!==f&&(l||(l=gt(a,f)))});else{if(a.issues.length===f)continue;l||(l=gt(a,f))}}return d?d.then(()=>a):a},i=(a,s,u)=>{if(gt(a))return a.aborted=!0,a;let l=n(s,o,u);if(l instanceof Promise){if(u.async===!1)throw new Fe;return l.then(d=>e._zod.parse(d,u))}return e._zod.parse(l,u)};e._zod.run=(a,s)=>{if(s.skipChecks)return e._zod.parse(a,s);if(s.direction==="backward"){let l=e._zod.parse({value:a.value,issues:[]},{...s,skipChecks:!0});return l instanceof Promise?l.then(d=>i(d,a,s)):i(l,a,s)}let u=e._zod.parse(a,s);if(u instanceof Promise){if(s.async===!1)throw new Fe;return u.then(l=>n(l,o,s))}return n(u,o,s)}}N(e,"~standard",()=>({validate:n=>{try{let i=$s(e,n);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return ks(e,n).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),Ut=m("$ZodString",(e,t)=>{T.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Js(e._zod.bag),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),F=m("$ZodStringFormat",(e,t)=>{mn.init(e,t),Ut.init(e,t)}),$c=m("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Es),F.init(e,t)}),kc=m("$ZodUUID",(e,t)=>{if(t.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(o===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Dt(o))}else t.pattern??(t.pattern=Dt());F.init(e,t)}),xc=m("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=As),F.init(e,t)}),Ic=m("$ZodURL",(e,t)=>{F.init(e,t),e._zod.check=r=>{try{let o=r.value.trim();if(!t.normalize&&t.protocol?.source===Ms.source&&!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let n=new URL(o);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=n.href:r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),Sc=m("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Ns()),F.init(e,t)}),Pc=m("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Ts),F.init(e,t)}),wc=m("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Is),F.init(e,t)}),Rc=m("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Ss),F.init(e,t)}),Tc=m("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ps),F.init(e,t)}),Oc=m("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ws),F.init(e,t)}),Ec=m("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Rs),F.init(e,t)}),Ac=m("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Gs(t)),F.init(e,t)}),Nc=m("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Fs),F.init(e,t)}),Cc=m("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Zs(t)),F.init(e,t)}),zc=m("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Os),F.init(e,t)}),Dc=m("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Cs),F.init(e,t),e._zod.bag.format="ipv4"}),Uc=m("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=zs),F.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),jc=m("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=Ds(t.delimiter)),F.init(e,t),e._zod.bag.format="mac"}),Lc=m("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Us),F.init(e,t)}),Mc=m("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=js),F.init(e,t),e._zod.check=r=>{let o=r.value.split("/");try{if(o.length!==2)throw new Error;let[n,i]=o;if(!i)throw new Error;let a=Number(i);if(`${a}`!==i)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});Fc=m("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Ls),F.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{Bc(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});Zc=m("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Eo),F.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{rg(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),Gc=m("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Bs),F.init(e,t)});Jc=m("$ZodJWT",(e,t)=>{F.init(e,t),e._zod.check=r=>{og(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Hc=m("$ZodCustomStringFormat",(e,t)=>{F.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),Bo=m("$ZodNumber",(e,t)=>{T.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ao,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let n=r.value;if(typeof n=="number"&&!Number.isNaN(n)&&Number.isFinite(n))return r;let i=typeof n=="number"?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:e,...i?{received:i}:{}}),r}}),Vc=m("$ZodNumberFormat",(e,t)=>{ec.init(e,t),Bo.init(e,t)}),mr=m("$ZodBoolean",(e,t)=>{T.init(e,t),e._zod.pattern=Ws,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=!!r.value}catch{}let n=r.value;return typeof n=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:n,inst:e}),r}}),Fo=m("$ZodBigInt",(e,t)=>{T.init(e,t),e._zod.pattern=Hs,e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),Wc=m("$ZodBigIntFormat",(e,t)=>{tc.init(e,t),Fo.init(e,t)}),qc=m("$ZodSymbol",(e,t)=>{T.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;return typeof n=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:n,inst:e}),r}}),Kc=m("$ZodUndefined",(e,t)=>{T.init(e,t),e._zod.pattern=Ks,e._zod.values=new Set([void 0]),e._zod.parse=(r,o)=>{let n=r.value;return typeof n>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:n,inst:e}),r}}),Xc=m("$ZodNull",(e,t)=>{T.init(e,t),e._zod.pattern=qs,e._zod.values=new Set([null]),e._zod.parse=(r,o)=>{let n=r.value;return n===null||r.issues.push({expected:"null",code:"invalid_type",input:n,inst:e}),r}}),Yc=m("$ZodAny",(e,t)=>{T.init(e,t),e._zod.parse=r=>r}),Qc=m("$ZodUnknown",(e,t)=>{T.init(e,t),e._zod.parse=r=>r}),eu=m("$ZodNever",(e,t)=>{T.init(e,t),e._zod.parse=(r,o)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),tu=m("$ZodVoid",(e,t)=>{T.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;return typeof n>"u"||r.issues.push({expected:"void",code:"invalid_type",input:n,inst:e}),r}}),nu=m("$ZodDate",(e,t)=>{T.init(e,t),e._zod.parse=(r,o)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let n=r.value,i=n instanceof Date;return i&&!Number.isNaN(n.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:n,...i?{received:"Invalid Date"}:{},inst:e}),r}});ru=m("$ZodArray",(e,t)=>{T.init(e,t),e._zod.parse=(r,o)=>{let n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:e}),r;r.value=Array(n.length);let i=[];for(let a=0;a<n.length;a++){let s=n[a],u=t.element._zod.run({value:s,issues:[]},o);u instanceof Promise?i.push(u.then(l=>Zf(l,r,a))):Zf(u,r,a)}return i.length?Promise.all(i).then(()=>r):r}});sg=m("$ZodObject",(e,t)=>{if(T.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let s=t.shape;Object.defineProperty(t,"shape",{get:()=>{let u={...s};return Object.defineProperty(t,"shape",{value:u}),u}})}let o=sn(()=>ig(t));N(e._zod,"propValues",()=>{let s=t.shape,u={};for(let l in s){let d=s[l]._zod;if(d.values){u[l]??(u[l]=new Set);for(let p of d.values)u[l].add(p)}}return u});let n=zt,i=t.catchall,a;e._zod.parse=(s,u)=>{a??(a=o.value);let l=s.value;if(!n(l))return s.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),s;s.value={};let d=[],p=a.shape;for(let f of a.keys){let v=p[f],g=v._zod.optin==="optional",P=v._zod.optout==="optional",R=v._zod.run({value:l[f],issues:[]},u);R instanceof Promise?d.push(R.then(j=>Mo(j,s,f,l,g,P))):Mo(R,s,f,l,g,P)}return i?ag(d,l,s,u,o.value,e):d.length?Promise.all(d).then(()=>s):s}}),ou=m("$ZodObjectJIT",(e,t)=>{sg.init(e,t);let r=e._zod.parse,o=sn(()=>ig(t)),n=f=>{let v=new pr(["shape","payload","ctx"]),g=o.value,P=E=>{let z=bo(E);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};v.write("const input = payload.value;");let R=Object.create(null),j=0;for(let E of g.keys)R[E]=`key_${j++}`;v.write("const newResult = {};");for(let E of g.keys){let z=R[E],w=bo(E),M=f[E],Se=M?._zod?.optin==="optional",Pe=M?._zod?.optout==="optional";v.write(`const ${z} = ${P(E)};`),Se&&Pe?v.write(`
|
|
@@ -1057,7 +1057,7 @@ ${Sk()}`),2;let{options:n}=o,i=`http://${tA(n.host)}:${n.port}`,a=`${i}${qE}`,s=
|
|
|
1057
1057
|
`)}function Um(){let e=process.env.LOG_DIR;return e!==void 0&&e!==""?Be.isAbsolute(e)?e:Be.join(ba(),e):Be.join(ba(),"logs")}function gT(){let e=new Date,t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),o=String(e.getUTCDate()).padStart(2,"0");return Be.join(Um(),`${t}-${r}-${o}.jsonl`)}function q_(){let e=process.env.AGENT_INSPECTOR_LOG_FILE;return e!==void 0&&e!==""?e:Be.join(ba(),"logs","inspector.log")}function Am(e,t,r,o){let n=process.env[e];if(n===void 0||n==="")return t;let i=Number(n);return!Number.isInteger(i)||i<r||i>o?t:i}function K_(){let e=Am("LOG_RETENTION_DAYS",pT,1,3650);return{maxBytes:Am("AGENT_INSPECTOR_APP_LOG_MAX_BYTES",mT,1,1024*1024*1024),maxFiles:Am("AGENT_INSPECTOR_APP_LOG_MAX_FILES",fT,1,100),retentionMs:e*dT}}function hT(e,t){let r=`${t}.`;if(!e.startsWith(r))return null;let o=e.slice(r.length);if(!/^\d+$/.test(o))return null;let n=Number(o);return!Number.isSafeInteger(n)||n<1?null:n}async function vT(e){let t=Be.dirname(e),r=Be.basename(e),o=await V_(t),n=[];for(let i of o){let a=i===r?0:hT(i,r);if(a===null)continue;let s=Be.join(t,i);try{let u=await io(s);if(!u.isFile())continue;n.push({generation:a,modifiedAt:u.mtimeMs,path:s})}catch{}}return n}async function Ma(e){try{await io(e)}catch{return!0}try{return await W_(e),!0}catch{return!1}}async function yT(e,t){let r=Be.dirname(e);if(!fe(r))return!1;let o;try{o=await vT(e)}catch{return!1}for(let l of o)if(!ze(l.path))return!1;let n=Date.now()-t.retentionMs,i=o.filter(l=>l.modifiedAt>=n),a=!0;for(let l of o)l.modifiedAt<n&&!await Ma(l.path)&&(a=!1);let s=i.filter(l=>l.generation>0).sort((l,d)=>d.modifiedAt-l.modifiedAt),u=Math.max(0,t.maxFiles-1);for(let l of s.slice(u))await Ma(l.path)||(a=!1);return a}async function J_(e,t){try{await io(e)}catch{return!0}try{return await lT(e,t),ze(t)?!0:(st("[logger] Failed to secure rotated application log:",t),!1)}catch(r){return st("[logger] Failed to rotate application log:",r),!1}}async function bT(e,t){if(t===1)return await Ma(e);if(!await Ma(`${e}.${String(t-1)}`))return!1;for(let r=t-2;r>=1;r-=1)if(!await J_(`${e}.${String(r)}`,`${e}.${String(r+1)}`))return!1;return await J_(e,`${e}.1`)}async function _T(e,t,r){try{let o=await io(e);return o.size>0&&o.size+t>r.maxBytes?await bT(e,r.maxFiles):!0}catch{return!0}}async function $T(){let e=Um(),t=K_(),r=Date.now()-t.retentionMs;try{if(!fe(e))st("[logger] Failed to secure log directory:",e);else if(!ya(e))st("[logger] Failed to secure existing log files:",e);else{let n=await Z_(e);if(n.level==="unavailable")st("[logger] Captured-log recovery blocked readiness:",n.diagnostic??"unknown recovery failure");else{let i=await V_(e);for(let a of i){if(!a.endsWith(".jsonl"))continue;let s=Be.join(e,a);try{(await io(s)).mtimeMs<r&&await W_(s)}catch{}}}}}catch(n){st("[logger] Failed to initialize log directory:",n)}let o=q_();await yT(o,t)||st("[logger] Failed to initialize application log lifecycle:",o)}var Nm=null,Cm=Promise.resolve(),ja=null,zm=0,kT=5e3;function xT(){return Nm===null&&(Nm=$T()),Nm}async function IT(e,t,r){let o=Be.dirname(e);if(!fe(o))return{ok:!1,reason:"application log directory is not private"};try{return await _T(e,H_.byteLength(t,"utf-8"),r)?(await uT(e,t,{encoding:"utf-8",mode:He}),ze(e)?{ok:!0}:{ok:!1,reason:"application log permissions could not be secured"}):{ok:!1,reason:"application log rotation failed"}}catch(n){return{ok:!1,reason:n}}}async function La(e){let t=q_(),r=`[${new Date().toISOString()}] ${e}
|
|
1058
1058
|
`,o=xT(),n=async()=>{await o;let i=await IT(t,r,K_());if(!i.ok){let a=`${t}:${String(i.reason)}`,s=Date.now();(a!==ja||s-zm>=kT)&&(ja=a,zm=s,st(`[logger] Failed to write to ${t}:`,i.reason));return}ja!==null&&(st(`[logger] Application log writes recovered for ${t}:`,"ok"),ja=null,zm=0)};Cm=Cm.then(n,n),await Cm}var jm={debug(e,...t){let r=t.length>0?`${e} ${t.map(String).join(" ")}`:e;La(`[DEBUG] ${r}`)},info(e,...t){let r=t.length>0?`${e} ${t.map(String).join(" ")}`:e;La(`[INFO] ${r}`)},warn(e,...t){let r=t.length>0?`${e} ${t.map(String).join(" ")}`:e;La(`[WARN] ${r}`)},error(e,...t){let r=t.length>0?`${e} ${t.map(String).join(" ")}`:e;La(`[ERROR] ${r}`)}};var Dm=[],nj=Promise.resolve(),rj=Promise.resolve();function ST(){let e=Dm.join("");return Dm=[],e}process.on("exit",()=>{if(Dm.length>0){let e=ST();try{let t=gT();if(!fe(Be.dirname(t))||!G_(Um(),t))return;let r=sT(t,Em.O_WRONLY|Em.O_APPEND|Em.O_NOFOLLOW,He);try{let o=H_.from(e,"utf-8"),n=0;for(;n<o.length;){let i=cT(r,o,n,o.length-n);if(i===0)return;n+=i}aT(r)}finally{iT(r)}ze(t)}catch{}}});var ao=RT(PT);var lj=300*1e3;var TT=c.number().int().min(1).max(65535),dj=c.object({remotePort:TT.nullish()}).passthrough();function Lm(e,t){if(!e)return{cwd:null,projectFolder:null};let r=e.match(/^"([^"]+)"/)||e.match(/^([^\s]+)/);if(r?.[1]!==void 0){let o=r[1],n=o.lastIndexOf(t);if(n>0){let i=o.substring(0,n);return{cwd:i,projectFolder:i.split(t).pop()??null}}}return{cwd:null,projectFolder:null}}async function OT(e){let t=process.platform;try{if(t==="win32"){let r=[`$proc = Get-CimInstance Win32_Process -Filter "ProcessId=${e}" -ErrorAction SilentlyContinue`,"if ($proc) { Write-Output $proc.CommandLine }"].join("; "),{stdout:o}=await ao("powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command",r],{windowsHide:!0,timeout:3e3,maxBuffer:64*1024}),n=o.trim();if(n.length>0)return Lm(n,"\\")}else{try{let o=(await wT(`/proc/${String(e)}/cmdline`,"utf8")).replace(/\0/g," ").trim();if(o)return Lm(o,"/")}catch{}if(t==="darwin"){let{stdout:r}=await ao("ps",["-p",String(e),"-o","comm="],{timeout:3e3,maxBuffer:65536}),o=r.trim();if(o)return Lm(o,"/")}}return{cwd:null,projectFolder:null}}catch{return{cwd:null,projectFolder:null}}}var X_=300*1e3,Mm=new Map;async function Bm(e){if(!Number.isInteger(e)||e<=0||e>65535)return{port:null,pid:null,cwd:null,projectFolder:null};let t=Mm.get(e);if(t!==void 0&&Date.now()<t.expiresAt)return t.info;try{let r=await ET(e);if(r===null){let a={port:e,pid:null,cwd:null,projectFolder:null};return Mm.set(e,{info:a,expiresAt:Date.now()+X_}),a}let{cwd:o,projectFolder:n}=await OT(r),i={port:e,pid:r,cwd:o,projectFolder:n};return Mm.set(e,{info:i,expiresAt:Date.now()+X_}),i}catch(r){return jm.debug(`[socketTracker] lookupClientByPort(${e}) failed:`,String(r)),{port:e,pid:null,cwd:null,projectFolder:null}}}async function ET(e){let t=process.platform;try{if(t==="win32"){let{stdout:r}=await ao("netstat.exe",["-ano","-p","TCP"],{windowsHide:!0,timeout:2e3,maxBuffer:2097152}),o=`:${e}`;for(let n of r.split(`
|
|
1059
1059
|
`)){let i=n.trim();if(i==="")continue;let a=i.split(/\s+/);if(a.length<5)continue;let s=a[1]??"";if((a[3]??"")!=="ESTABLISHED"||!s.endsWith(o))continue;let l=a[a.length-1]??"",d=parseInt(l,10);if(Number.isInteger(d)&&d>0)return d}return null}try{let{stdout:r}=await ao("ss",["-tanp","state","established","sport",`= :${e}`],{timeout:2e3,maxBuffer:2097152}),o=r.match(/pid=(\d+)/);if(o!==null){let n=parseInt(o[1]??"",10);if(Number.isInteger(n)&&n>0)return n}}catch{}try{let{stdout:r}=await ao("lsof",["-ti",`tcp:${e}`,"-sTCP:ESTABLISHED"],{timeout:2e3,maxBuffer:65536}),o=r.trim().split(`
|
|
1060
|
-
`)[0]??"",n=parseInt(o,10);if(Number.isInteger(n)&&n>0)return n}catch{}return null}catch(r){return jm.debug(`[socketTracker] lookupPidByLocalPort(${e}) failed:`,String(r)),null}}import{readFile as AT}from"node:fs/promises";import{extname as Q_,relative as NT,resolve as Fm,sep as CT}from"node:path";var e$={".css":"text/css; charset=utf-8",".html":"text/html; charset=utf-8",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2"};function zT(e){let t;try{t=decodeURIComponent(e)}catch{return null}return t.includes("\\")||t.includes("\0")||t.split("/").some(r=>r==="."||r==="..")?null:t}function DT(e,t){let r=NT(t,e);return r===""||!r.startsWith("..")&&!r.startsWith(CT)}function UT(e,t){let r=zT(t);if(r===null)return null;let o=Fm(e,`.${r}`);return DT(o,Fm(e))?o:null}async function Y_(e){try{return await AT(e)}catch{return null}}function jT(e){return e$[Q_(e).toLowerCase()]??"application/octet-stream"}function LT(e){return e==="/api"||e.startsWith("/api/")||e==="/proxy"||e.startsWith("/proxy/")||e==="/livez"||e==="/readyz"}function MT(e){return e==="/"||e.length===0?!0:!(e.split("/").at(-1)??"").includes(".")}async function t$(e,t){if(LT(t))return null;let r=UT(e,t);if(r===null)return null;let o=await Y_(r);if(o!==null)return{body:o,cacheControl:t.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-cache",contentType:jT(r),document:Q_(r).toLowerCase()===".html"};if(!MT(t))return null;let n=Fm(e,"index.html"),i=await Y_(n);return i===null?null:{body:i,cacheControl:"no-store",contentType:e$[".html"]??"text/html; charset=utf-8",document:!0}}var Ba={pid:"x-agent-inspector-client-pid",port:"x-agent-inspector-client-port",cwd:"x-agent-inspector-client-cwd",projectFolder:"x-agent-inspector-client-project-folder"},BT="x-agent-inspector-",FT="x-agent-inspector-proxy-token",Ja="x-agent-inspector-csrf",ZT=new Set([Ja]),GT=64*1024*1024,JT=12e4,Fa=8*1024,HT=64*1024,VT=1024*1024,so="/.agent-inspector",m$=`${so}/base-path-aliases`;function r$(e){let t=H(e);if(t===null)return{ok:!1,code:"invalid",error:"Base Path aliases may contain only URL-safe path segments."};if(t.length===0)return{ok:!1,code:"invalid",error:"Base Path aliases must be non-root paths such as /inspector."};if(t===so||t.startsWith(`${so}/`))return{ok:!1,code:"reserved",error:`${t} collides with the reserved Agent Inspector control path.`};let r=["/api","/assets","/proxy","/session","/livez","/readyz"].find(o=>t===o||t.startsWith(`${o}/`));return r!==void 0?{ok:!1,code:"reserved",error:`${t} collides with the reserved ${r} public namespace.`}:{ok:!0,basePath:t}}function co(e,t){return e===t||e.startsWith(`${t}/`)}function o$(e,t){return co(e,t)||co(t,e)}function WT(e,t=[]){let r=H(e)??"",o=[],n=u=>{let l=r$(u);if(!l.ok)return l;if(l.basePath===r)return{ok:!1,code:"canonical",error:`${l.basePath} is already the canonical Base Path.`};if(r.length>0&&o$(l.basePath,r))return{ok:!1,code:"overlap",error:`${l.basePath} overlaps the canonical Base Path ${r}.`};if(o.includes(l.basePath))return{ok:!1,code:"duplicate",error:`${l.basePath} is already an active runtime alias.`};let d=o.find(p=>o$(l.basePath,p));return d!==void 0?{ok:!1,code:"overlap",error:`${l.basePath} overlaps the active runtime alias ${d}.`}:(o.push(l.basePath),o.sort((p,f)=>f.length-p.length||p.localeCompare(f)),{ok:!0,basePath:l.basePath})},s={canonicalBasePath:r,add:n,list:()=>[...o],remove:u=>{let l=r$(u);if(!l.ok)return l;if(l.basePath===r)return{ok:!1,code:"canonical",error:`${l.basePath} is the canonical Base Path and cannot be removed.`};let d=o.indexOf(l.basePath);return d===-1?{ok:!1,code:"not-found",error:`${l.basePath} is not an active runtime alias.`}:(o.splice(d,1),{ok:!0,basePath:l.basePath})},resolve:u=>{let l=new URL(u,"http://localhost"),d=o.find(f=>co(l.pathname,f)),p=d??r;return{effectiveBasePath:p,isAlias:d!==void 0,upstreamPath:Cy(u,p)}}};for(let u of t)n(u);return s}function qT(e,t){return e.resolve(t)}var Xm=new WeakMap,f$=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailers","transfer-encoding","upgrade","content-length"]),KT=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailers","transfer-encoding","upgrade"]),g$={"permissions-policy":"camera=(), microphone=(), geolocation=()","referrer-policy":"no-referrer","x-content-type-options":"nosniff","x-frame-options":"DENY"},h$=["default-src 'self'","base-uri 'self'","connect-src 'self'","font-src 'self' data:","frame-ancestors 'none'","img-src 'self' data: blob:","object-src 'none'","script-src 'self' 'unsafe-inline'","style-src 'self' 'unsafe-inline'","worker-src 'self' blob:"].join("; ");function Zm(e){return e.replace(/&/gu,"&").replace(/"/gu,""").replace(/</gu,"<").replace(/>/gu,">")}function Ha(e,t,r){if(!e.startsWith("/")||e.startsWith("//"))return e;let o=H(t),n=H(r);if(o===null||n===null)return e;let i=e.search(/[?#]/u),a=i===-1?e:e.slice(0,i),s=i===-1?"":e.slice(i);if(o.length>0&&co(a,o))return e;let u=n.length>0&&co(a,n)?a.slice(n.length)||"/":a,l=_p(u,o),d=a.endsWith("/")&&!l.endsWith("/")?"/":"";return`${l}${d}${s}`}function v$(e,t,r,o){return e.replace(/(["'])(\/(?:[^"'/]+\/)*assets\/)/gu,(n,i,a)=>`${i}${o(Ha(a,t,r),i)}`)}function y$(e,t,r=""){let o=H(t),n=H(r);if(o===null||n===null)return e;let i=Zm(o),a=`<meta name="${ca}" content="${i}">`,s=new RegExp(`<meta\\b[^>]*\\bname\\s*=\\s*("|')${ca}\\1[^>]*>`,"giu"),u=!1,l=e.replace(s,()=>u?"":(u=!0,a)),p=(u?l:l.replace(/<head(\s[^>]*)?>/iu,f=>`${f}${a}`)).replace(/\b(href|src|action)=(["'])(\/(?!\/)[^"']*)\2/giu,(f,v,g,P)=>`${v}=${g}${Zm(Ha(P,o,n))}${g}`);return v$(p,o,n,f=>Zm(f))}function Gm(e,t){let r=e.replace(/\\/gu,"\\\\").replace(/\r/gu,"\\r").replace(/\n/gu,"\\n").replace(/\u2028/gu,"\\u2028").replace(/\u2029/gu,"\\u2029").replace(/&/gu,"\\u0026").replace(/</gu,"\\u003c").replace(/>/gu,"\\u003e");return t==="'"?r.replace(/'/gu,"\\'"):r.replace(/"/gu,'\\"')}function b$(e,t,r=""){let o=H(t),n=H(r);if(o===null||n===null)return e;let i=Gm(o,'"'),s=e.replace(/\bbasepath:\s*(["'])[^"']*\1/gu,`basepath:"${i}"`).replace(/return(["'])(\/(?!\/)[^"']*)\1\+([A-Za-z_$][\w$]*)/gu,(u,l,d,p)=>{let f=Ha(d,o,n);return`return${l}${Gm(f,l)}${l}+${p}`});return v$(s,o,n,Gm)}function _$(e,t){if(t.publicOrigin!==void 0)try{return new URL(t.publicOrigin).origin}catch{}return`http://${e.headers.host??"localhost"}`}function XT(e,t,r){let o=_$(e,t),n=H(r)??"",i=n.length===0?o:`${o}${n}`;return{schemaVersion:fm,deploymentMode:"composed",ui:{basePath:n.length===0?"/":n},control:{baseUrl:i},agent:{baseUrl:i},capabilities:{rest:!0,sse:!0,proxy:!0,mcp:!0}}}function YT(e){return JSON.stringify(e).replace(/&/gu,"\\u0026").replace(/</gu,"\\u003c").replace(/>/gu,"\\u003e").replace(/\u2028/gu,"\\u2028").replace(/\u2029/gu,"\\u2029")}function QT(e,t){let r=YT(t);if(e.includes(gm))return e.replaceAll(gm,r);let o=`<script>window.__AGENT_INSPECTOR_RUNTIME__=${r};</script>`;return e.replace(/<head(\s[^>]*)?>/iu,n=>`${n}${o}`)}async function eO(e,t,r,o,n,i){let a=(e.method??"GET").toUpperCase();if(a!=="GET"&&a!=="HEAD"||r.uiDirectory===void 0)return!1;let s=await t$(r.uiDirectory,o);if(s===null)return!1;let u=s.body;if(s.document){let d=y$(u.toString("utf8"),n,i);u=Ue.from(QT(d,XT(e,r,n)),"utf8")}else n.length>0&&s.contentType.includes("javascript")&&(u=Ue.from(b$(u.toString("utf8"),n,i),"utf8"));let l={...g$,"cache-control":s.cacheControl,"content-length":u.byteLength,"content-type":s.contentType};return s.document&&(l["content-security-policy"]=h$),t.writeHead(200,l),a==="HEAD"?t.end():t.end(u),e.resume(),!0}function qm(e){if(e===void 0)return!1;let t=e.toLowerCase();return t==="::1"||t.startsWith("127.")||t.startsWith("::ffff:127.")}function Jm(e){return e===void 0?null:/^Bearer\s+(.+)$/i.exec(e.trim())?.[1]??null}function Hm(e,t){if(e===null||t===void 0||t==="")return!1;let r=Ue.from(e),o=Ue.from(t);return r.byteLength===o.byteLength&&d$(r,o)}function tO(e,t){if(e===void 0||e.length===0||t.length===0)return!1;let r=n$("sha256").update(e).digest(),o=n$("sha256").update(t).digest();return d$(r,o)}function tt(e){return typeof e=="string"?e:e?.[0]}function Vm(e){let t=e.trim();if(t.length===0)return null;try{return new URL(`http://${t}`).hostname.toLowerCase().replace(/^\[|]$/g,"")}catch{return null}}function Za(e){let t=e.toLowerCase().replace(/^\[|]$/g,"");return t==="localhost"||t==="::1"?!0:p$(t)!==4?!1:t.split(".",1)[0]==="127"}function nO(e){try{return new URL(e)}catch{return null}}function Ym(e){let t=[],r=[];for(let o of(e??"").split(",")){let n=o.trim();if(n.length===0)continue;let i=nO(n);if(!(i!==null&&(i.protocol==="http:"||i.protocol==="https:")&&i.username.length===0&&i.password.length===0&&i.pathname==="/"&&i.search.length===0&&i.hash.length===0&&Za(i.hostname.toLowerCase().replace(/^\[|\]$/gu,"")))||i===null){r.push(n);continue}t.includes(i.origin)||t.push(i.origin)}return{origins:t,rejected:r}}function rO(e){if(e!==void 0)return $$(e.trim())}function oO(e,t){if(e===void 0)return!1;let r=Vm(e);if(r===null)return!1;if(Za(r)||p$(r)!==0)return!0;let o=Vm(t.listenHost);return o!==null&&r===o?!0:(t.trustedHosts??[]).some(n=>Vm(n)===r)}function iO(e){let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"||t==="OPTIONS"}var i$=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],a$=["authorization","content-type","last-event-id",Ja];function $$(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"||t.username.length>0||t.password.length>0||t.pathname!=="/"||t.search.length>0||t.hash.length>0?null:t.origin}catch{return null}}function s$(e){let t=$$(e);return t===null?null:new URL(t)}function aO(e,t){return e.origin===t.origin?!0:e.protocol===t.protocol&&e.port===t.port&&Za(e.hostname)&&Za(t.hostname)}function k$(e,t,r){let o=s$(e);if(o===null)return!1;let n=s$(r??`http://${t??"localhost"}`);return n!==null&&aO(o,n)}function x$(e,t){return e===void 0?null:(t??[]).find(r=>r===e)??null}function c$(e){return e==="/livez"||e==="/readyz"?!0:e==="/api/mcp"?!1:e==="/api"||e.startsWith("/api/")}function Km(e){return e==="/proxy"||e.startsWith("/proxy/")}function en(e){return e===null?{}:{"access-control-allow-origin":e,"access-control-expose-headers":"Content-Disposition",vary:"Origin"}}function sO(e,t){let r=(Array.isArray(e)?e.join(","):e??"").split(",").map(o=>o.trim()).filter(o=>o.length>0);return r.some(o=>o.toLowerCase()===t.toLowerCase())||r.push(t),r.join(", ")}function cO(e){return(e??"").split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function uO(e,t,r){let o=tt(e.headers["access-control-request-method"])?.toUpperCase(),n=cO(tt(e.headers["access-control-request-headers"])),i=o!==void 0&&i$.some(s=>s===o),a=n.every(s=>a$.some(u=>u===s));if(!i||!a){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(r)}),t.end(JSON.stringify({error:"CORS preflight is not allowed for this request."})),e.resume();return}t.writeHead(204,{"cache-control":"no-store","access-control-allow-origin":r,"access-control-allow-methods":i$.join(", "),"access-control-allow-headers":a$.join(", "),"access-control-max-age":"600",vary:"Origin, Access-Control-Request-Method, Access-Control-Request-Headers"}),t.end(),e.resume()}function lO(e){return e==="/livez"||e==="/readyz"||e==="/api/health"}function I$(e){return e==="/api/instances"||e.startsWith("/api/instances/")}function u$(e,t){return e!==void 0&&Number.isSafeInteger(e)&&e>0?e:t}function S$(e){if(e===void 0)return null;if(!/^\d+$/.test(e))return Number.NaN;let t=Number(e);return Number.isSafeInteger(t)?t:Number.NaN}function P$(e){if(iO(e.method))return!0;let t=ua(new URL(e.path,"http://localhost").pathname,e.basePath??oe(process.env)),r=e.secFetchSite?.toLowerCase();if(!(e.origin!==void 0||r!==void 0))return!0;let n=e.origin!==void 0?k$(e.origin,e.host,e.publicOrigin):!1;if(Km(t))return r!==void 0&&r!=="same-origin"&&!n||e.origin!==void 0&&!n?!1:e.csrfToken==="1";let i=x$(e.origin,e.allowedUiOrigins);return r!==void 0&&r!=="same-origin"&&!n&&i===null||e.origin!==void 0&&!n&&i===null?!1:e.csrfToken==="1"}function dO(e){let t=ua(new URL(e.path,"http://localhost").pathname,e.basePath??oe(process.env));if(!qm(e.remoteAddress)&&I$(t))return Hm(Jm(e.authorization),e.options.controlToken);if(e.options.restrictRemoteControl!==!0||e.options.allowRemoteControl===!0||qm(e.remoteAddress))return!0;if(t==="/proxy"||t.startsWith("/proxy/")){if(e.options.allowUnauthenticatedRemoteProxy===!0)return!0;let r=Jm(e.proxyAuthorization)??e.proxyTokenHeader??null;return Hm(r,e.options.proxyToken)}return lO(t)?!0:Hm(Jm(e.authorization),e.options.controlToken)}function pO(e){let t=S$(e.headers["content-length"]);return t!==null&&(!Number.isFinite(t)||t<0)?(e.resume(),Promise.resolve({ok:!1,status:400,error:"Invalid Content-Length header"})):t!==null&&t>Fa?(e.resume(),Promise.resolve({ok:!1,status:413,error:`Alias control body exceeds ${String(Fa)} bytes`})):new Promise(r=>{let o=[],n=0,i=!1,a=s=>{i||(i=!0,r(s))};e.on("data",s=>{if(i)return;let u=Ga(s);if(n+=u.byteLength,n>Fa){a({ok:!1,status:413,error:`Alias control body exceeds ${String(Fa)} bytes`});return}o.push(u)}),e.on("end",()=>{a({ok:!0,body:Ue.concat(o).toString("utf8")})}),e.on("aborted",()=>{a({ok:!1,status:400,error:"Client aborted alias control request"})}),e.on("error",()=>{a({ok:!1,status:400,error:"Alias control request body failed"})})})}function mO(e,t,r){return new Promise(o=>{let n=[],i=0,a=!1,s=setTimeout(()=>{u({ok:!1,status:408,error:"Instance request body timed out"}),e.resume()},r),u=l=>{a||(a=!0,clearTimeout(s),o(l))};e.on("data",l=>{if(a)return;let d=Ga(l);if(i+=d.byteLength,i>t){u({ok:!1,status:413,error:`Instance request body exceeds ${String(t)} bytes`}),e.resume();return}n.push(d)}),e.on("end",()=>u({ok:!0,body:Ue.concat(n)})),e.on("aborted",()=>u({ok:!1,status:400,error:"Client aborted instance request body"})),e.on("error",()=>u({ok:!1,status:400,error:"Instance request body failed"}))})}function Wm(e,t,r,o){e.writeHead(t,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(o)}),e.end(JSON.stringify({error:r}))}async function fO(e,t,r,o,n,i,a,s){let u=await mO(e,Math.min(a,HT),s);if(!u.ok){Wm(t,u.status,u.error,i);return}let l=(e.method??"GET").toUpperCase(),d=new Headers,p=tt(e.headers["content-type"]);p!==void 0&&d.set("content-type",p);let f=new Request(new URL(o,n),{method:l,headers:d,body:l==="GET"||l==="HEAD"?void 0:u.body.toString("utf8")}),v;try{v=await r(f)}catch{Wm(t,503,"Instance supervisor request failed",i);return}let g=Ue.from(await v.arrayBuffer());if(g.byteLength>VT){Wm(t,502,"Instance supervisor response exceeded its resource limit",i);return}let P={...en(i),"content-length":String(g.byteLength)};v.headers.forEach((R,j)=>{let Y=j.toLowerCase();!f$.has(Y)&&Y!=="content-length"&&(P[Y]=R)}),P["cache-control"]="no-store",t.writeHead(v.status,P),t.end(g)}function gO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hO(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:"Alias control body must be valid JSON."}}return!gO(t)||typeof t.basePath!="string"?{ok:!1,error:'Alias control body must contain a string "basePath" field.'}:{ok:!0,basePath:t.basePath}}function wt(e,t,r,o=void 0,n={}){e.writeHead(r,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...n}),e.end(JSON.stringify({canonicalBasePath:t.canonicalBasePath,aliases:t.list(),runtimeScoped:!0,...o}))}async function vO(e,t,r){if(!qm(e.socket.remoteAddress)){e.resume(),wt(t,r,403,{error:"Base Path aliases can only be managed from the local machine."});return}if(!P$({path:e.url??m$,basePath:"",method:e.method,host:e.headers.host,origin:e.headers.origin,secFetchSite:tt(e.headers["sec-fetch-site"]),csrfToken:tt(e.headers[Ja])})){e.resume(),wt(t,r,403,{error:"Browser mutation requires same-origin CSRF proof."});return}let o=(e.method??"GET").toUpperCase();if(o==="GET"){e.resume(),wt(t,r,200);return}if(o!=="POST"&&o!=="DELETE"){e.resume(),wt(t,r,405,{error:"Alias control supports GET, POST, and DELETE."},{allow:"GET, POST, DELETE"});return}let n=await pO(e);if(!n.ok){wt(t,r,n.status,{error:n.error});return}let i=hO(n.body);if(!i.ok){wt(t,r,400,{error:i.error});return}let a=o==="POST"?r.add(i.basePath):r.remove(i.basePath);if(a.ok){wt(t,r,o==="POST"?201:200,{basePath:a.basePath});return}let s=a.code==="duplicate"||a.code==="overlap"?409:a.code==="not-found"?404:400;wt(t,r,s,{code:a.code,error:a.error})}function Qt(e,t,r,o={},n=void 0){e.writeHead(t,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...o}),e.end(JSON.stringify(r),n)}function yO(e,t,r,o){if(e.resume(),o===void 0){Qt(t,404,{error:"Control endpoint not found"});return}if(!tO(tt(e.headers[da]),o.controlToken)){Qt(t,403,{error:"Instance control access denied"});return}let i=(e.method??"GET").toUpperCase();if(r===kt){if(i!=="GET"){Qt(t,405,{error:"Instance identity supports GET only"},{allow:"GET"});return}Qt(t,200,{schemaVersion:1,backend:o.backend??"typescript",name:o.name,instanceId:o.instanceId,launchId:o.launchId,supervisorPid:o.supervisorPid,startedAt:o.startedAt,publicPort:o.publicPort,upstreamPort:o.upstreamPort});return}if(i!=="POST"){Qt(t,405,{error:"Instance shutdown supports POST only"},{allow:"POST"});return}Qt(t,202,{accepted:!0,launchId:o.launchId},{},()=>{process.nextTick(o.requestShutdown)})}function bO(e){return e===so||e.startsWith(`${so}/`)}function w$(e){let t=Ym(e.allowedUiOrigins?.join(","));if(t.rejected.length>0)return Promise.reject(new Error(`Unsafe UI origins are not accepted: ${t.rejected.join(", ")}. Only exact loopback HTTP(S) origins are supported.`));let r=rO(e.publicOrigin);if(r===null)return Promise.reject(new Error("publicOrigin must be an exact HTTP(S) origin without credentials, path, or query."));let o={...e,allowedUiOrigins:t.origins,publicOrigin:r};return new Promise((n,i)=>{let a=l$.createServer(),s=e.aliasRegistry??WT(oe(process.env)),u={acceptingRequests:!0,activeRequests:0,drainWaiters:new Set};Xm.set(a,u),a.on("connection",l=>{let d=l.remotePort;d!==void 0&&d>0&&Bm(d).catch(()=>null)}),a.on("request",(l,d)=>{if(!u.acceptingRequests){d.writeHead(503,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",connection:"close","retry-after":"5"}),d.end(JSON.stringify({error:"Agent Inspector is shutting down"})),l.resume();return}u.activeRequests+=1;let p=!1,f=()=>{if(!p&&(p=!0,u.activeRequests=Math.max(0,u.activeRequests-1),u.activeRequests===0)){for(let v of u.drainWaiters)v();u.drainWaiters.clear()}};d.once("finish",f),d.once("close",f),$O(l,d,o,s).catch(v=>{let g=v instanceof Error?v.message:String(v);d.headersSent||d.writeHead(502,{"content-type":"text/plain"}),d.end(`Identity proxy error: ${g}`)})}),a.once("error",i),a.listen(e.listenPort,e.listenHost,()=>{a.removeListener("error",i),n(a)})})}function Va(e){let t=Xm.get(e);t!==void 0&&(t.acceptingRequests=!1)}async function _O(e){let t=Xm.get(e);t===void 0||t.activeRequests===0||await new Promise(r=>{t.drainWaiters.add(r)})}async function Qm(e){Va(e);let t=new Promise(r=>{if(!e.listening){r();return}e.close(()=>r())});await Promise.all([t,_O(e)])}function R$(e){Va(e),e.closeAllConnections(),e.close()}async function $O(e,t,r,o){let n=new URL(e.url??"/","http://localhost");if(!oO(e.headers.host,r)){t.writeHead(400,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),t.end(JSON.stringify({error:"Untrusted Host header"})),e.resume();return}if(n.pathname===m$){await vO(e,t,o);return}if(n.pathname===kt||n.pathname===la){yO(e,t,n.pathname,r.managedInstance);return}if(bO(n.pathname)){e.resume(),Qt(t,404,{error:"Control endpoint not found"});return}let i=qT(o,e.url??"/"),a=i.effectiveBasePath,s=i.upstreamPath,u=new URL(s,"http://localhost").pathname,l=e.headers.origin,d=_$(e,r),p=l!==void 0&&!k$(l,e.headers.host,d),f=p?x$(l,r.allowedUiOrigins):null;if(p&&Km(u)){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),t.end(JSON.stringify({error:"Cross-origin browser access to the model proxy is forbidden."})),e.resume();return}if(p&&u==="/api/mcp"){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),t.end(JSON.stringify({error:"Browser CORS is not enabled for the MCP endpoint."})),e.resume();return}if(p&&c$(u)){if(f===null){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),t.end(JSON.stringify({error:"UI origin is not allowed by this Agent Inspector runtime."})),e.resume();return}if((e.method??"GET").toUpperCase()==="OPTIONS"){uO(e,t,f);return}}if(a.length>0&&n.pathname.startsWith("/assets/")){t.writeHead(307,{location:`${a}${n.pathname}${n.search}`,"cache-control":"no-store"}),t.end(),e.resume();return}if(!P$({path:e.url??"/",basePath:a,method:e.method,host:e.headers.host,origin:e.headers.origin,secFetchSite:tt(e.headers["sec-fetch-site"]),csrfToken:tt(e.headers[Ja]),allowedUiOrigins:r.allowedUiOrigins,publicOrigin:d})){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(f)}),t.end(JSON.stringify({error:"Browser mutation requires same-origin CSRF proof"})),e.resume();return}if(!dO({path:e.url??"/",basePath:a,remoteAddress:e.socket.remoteAddress,authorization:e.headers.authorization,proxyAuthorization:e.headers["proxy-authorization"],proxyTokenHeader:tt(e.headers[FT]),options:r})){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(f)}),t.end(JSON.stringify({error:"Remote access requires a credential scoped to this endpoint."})),e.resume();return}if(await eO(e,t,r,u,a,o.canonicalBasePath))return;let v=e.socket.remotePort,g=null;if(v!==void 0&&v>0)try{g=await Bm(v)}catch{g=null}let P=u$(r.maxRequestBytes,GT),R=S$(e.headers["content-length"]);if(R!==null&&(!Number.isFinite(R)||R<0)){t.writeHead(400,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(f)}),t.end(JSON.stringify({error:"Invalid Content-Length header"})),e.resume();return}if(R!==null&&R>P){t.writeHead(413,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(f)}),t.end(JSON.stringify({error:`Request body exceeds ${String(P)} bytes`})),e.resume();return}let j={};for(let[G,Q]of Object.entries(e.headers)){let ae=G.toLowerCase();f$.has(ae)||a.length>0&&(ae==="accept-encoding"||ae==="range"||ae==="if-range")||ae.startsWith(BT)&&!ZT.has(ae)||ae==="authorization"&&!Km(u)||Q!==void 0&&(j[G]=Q)}j[Ey]=a.length===0?"/":a,j[Ny]=d;let Y=e.socket.localPort;Y!==void 0&&Y>0&&Y<=65535&&(j[Ay]=String(Y)),g!==null&&g.pid!==null&&(j[Ba.pid]=String(g.pid),g.port!==null&&(j[Ba.port]=String(g.port)),g.cwd!==null&&(j[Ba.cwd]=g.cwd),g.projectFolder!==null&&(j[Ba.projectFolder]=g.projectFolder));let E=!1,z=u$(r.requestTimeoutMs,JT);if(r.instanceApiHandler!==void 0&&I$(u)){await fO(e,t,r.instanceApiHandler,s,d,f,P,z);return}let w=l$.request({hostname:r.upstreamHost,port:r.upstreamPort,path:s,method:e.method,headers:j},G=>{if(E||t.destroyed){G.destroy();return}let Q=()=>{G.destroy(),G.socket.destroy(),w.destroy()},ae=()=>{t.removeListener("close",Q),t.removeListener("error",Q),e.socket.removeListener("close",Q)};t.once("close",Q),t.once("error",Q),e.socket.once("close",Q),G.once("end",ae),G.once("close",ae);let ge={},Ot=tt(G.headers["content-type"]),nn=a.length>0&&Ot?.toLowerCase().includes("text/html")===!0,go=a.length>0&&(Ot?.toLowerCase().includes("javascript")===!0||s.split("?",1)[0]?.endsWith(".js")===!0),Yn=nn||go;for(let[V,ne]of Object.entries(G.headers)){let je=V.toLowerCase();KT.has(je)||Yn&&(je==="content-length"||je==="content-range"||je==="accept-ranges"||je==="etag"||je==="last-modified"||je==="content-md5"||je==="digest")||ne!==void 0&&(je==="location"&&a.length>0&&typeof ne=="string"&&ne.startsWith("/")&&!ne.startsWith("//")?ge[V]=Ha(ne,a,o.canonicalBasePath):ge[V]=ne)}for(let[V,ne]of Object.entries(g$))ge[V]=ne;ge[aa]=r.backendImplementation??"typescript",f!==null&&c$(u)&&(ge["access-control-allow-origin"]=f,ge["access-control-expose-headers"]="Content-Disposition",ge.vary=sO(ge.vary,"Origin")),Ot?.toLowerCase().includes("text/html")===!0&&(ge["content-security-policy"]=h$);let se=Yn&&G.statusCode===206?200:G.statusCode??502;if(t.writeHead(se,ge),Yn){let V=[];G.on("data",ne=>{V.push(Ga(ne))}),G.on("end",()=>{let ne=Ue.concat(V).toString("utf8");t.write(nn?y$(ne,a,o.canonicalBasePath):b$(ne,a,o.canonicalBasePath)),t.end()}),G.on("error",()=>{t.writableEnded||t.destroy()});return}G.pipe(t)}),M=setTimeout(()=>{Pe(408,"Request body deadline exceeded")},z);M.unref();function Se(){clearTimeout(M)}function Pe(G,Q){E||(E=!0,Se(),w.destroy(),t.headersSent?t.destroy():(t.writeHead(G,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),t.end(JSON.stringify({error:Q}))),e.resume())}w.on("error",G=>{E||(E=!0,Se(),t.headersSent||t.writeHead(502,{"content-type":"text/plain"}),t.end(`Upstream error: ${G.message}`))}),w.on("drain",()=>e.resume()),t.once("close",()=>{Se(),w.destroy()});let we=0;e.on("data",G=>{if(E)return;let Q=Ga(G);if(we+=Q.byteLength,we>P){Pe(413,`Request body exceeds ${String(P)} bytes`);return}Q.byteLength>0&&!w.write(Q)&&e.pause()}),e.on("end",()=>{E||(Se(),w.end())}),e.on("aborted",()=>{Pe(400,"Client aborted request body")}),e.on("error",()=>{Pe(400,"Request body stream failed")})}function Ga(e){return Ue.isBuffer(e)?e:typeof e=="string"?Ue.from(e):e instanceof ArrayBuffer?Ue.from(e):e instanceof Uint8Array?Ue.from(e.buffer,e.byteOffset,e.byteLength):Ue.alloc(0)}ka();Wr();var fA=lA(import.meta.url),pf=dA(fA),$f=9527,kf=9527,mf=9529,Nk="127.0.0.1",Xa=5e3,gA="agent-inspector.exe",hA="simple",vA=15e3,yA=2e3,Mk=1e4,bA=100,_A=1e4,$A=6e4,Ck="AGENT_INSPECTOR_BACKGROUND_SUPERVISOR";process.title="Agent Inspector";var ff=process.argv[2];function Bk(){console.log(`agent-inspector ${lt.version} - Agent observability and knowledge capture
|
|
1060
|
+
`)[0]??"",n=parseInt(o,10);if(Number.isInteger(n)&&n>0)return n}catch{}return null}catch(r){return jm.debug(`[socketTracker] lookupPidByLocalPort(${e}) failed:`,String(r)),null}}import{readFile as AT}from"node:fs/promises";import{extname as Q_,relative as NT,resolve as Fm,sep as CT}from"node:path";var e$={".css":"text/css; charset=utf-8",".html":"text/html; charset=utf-8",".ico":"image/x-icon",".jpeg":"image/jpeg",".jpg":"image/jpeg",".js":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp",".woff":"font/woff",".woff2":"font/woff2"};function zT(e){let t;try{t=decodeURIComponent(e)}catch{return null}return t.includes("\\")||t.includes("\0")||t.split("/").some(r=>r==="."||r==="..")?null:t}function DT(e,t){let r=NT(t,e);return r===""||!r.startsWith("..")&&!r.startsWith(CT)}function UT(e,t){let r=zT(t);if(r===null)return null;let o=Fm(e,`.${r}`);return DT(o,Fm(e))?o:null}async function Y_(e){try{return await AT(e)}catch{return null}}function jT(e){return e$[Q_(e).toLowerCase()]??"application/octet-stream"}function LT(e){return e==="/api"||e.startsWith("/api/")||e==="/proxy"||e.startsWith("/proxy/")||e==="/livez"||e==="/readyz"}function MT(e){return e==="/"||e.length===0?!0:!(e.split("/").at(-1)??"").includes(".")}async function t$(e,t){if(LT(t))return null;let r=UT(e,t);if(r===null)return null;let o=await Y_(r);if(o!==null)return{body:o,cacheControl:t.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-cache",contentType:jT(r),document:Q_(r).toLowerCase()===".html"};if(!MT(t))return null;let n=Fm(e,"index.html"),i=await Y_(n);return i===null?null:{body:i,cacheControl:"no-store",contentType:e$[".html"]??"text/html; charset=utf-8",document:!0}}var Ba={pid:"x-agent-inspector-client-pid",port:"x-agent-inspector-client-port",cwd:"x-agent-inspector-client-cwd",projectFolder:"x-agent-inspector-client-project-folder"},BT="x-agent-inspector-",FT="x-agent-inspector-proxy-token",Ja="x-agent-inspector-csrf",ZT=new Set([Ja]),GT=64*1024*1024,JT=12e4,Fa=8*1024,HT=64*1024,VT=1024*1024,so="/.agent-inspector",m$=`${so}/base-path-aliases`;function r$(e){let t=H(e);if(t===null)return{ok:!1,code:"invalid",error:"Base Path aliases may contain only URL-safe path segments."};if(t.length===0)return{ok:!1,code:"invalid",error:"Base Path aliases must be non-root paths such as /inspector."};if(t===so||t.startsWith(`${so}/`))return{ok:!1,code:"reserved",error:`${t} collides with the reserved Agent Inspector control path.`};let r=["/api","/assets","/proxy","/session","/livez","/readyz"].find(o=>t===o||t.startsWith(`${o}/`));return r!==void 0?{ok:!1,code:"reserved",error:`${t} collides with the reserved ${r} public namespace.`}:{ok:!0,basePath:t}}function co(e,t){return e===t||e.startsWith(`${t}/`)}function o$(e,t){return co(e,t)||co(t,e)}function WT(e,t=[]){let r=H(e)??"",o=[],n=u=>{let l=r$(u);if(!l.ok)return l;if(l.basePath===r)return{ok:!1,code:"canonical",error:`${l.basePath} is already the canonical Base Path.`};if(r.length>0&&o$(l.basePath,r))return{ok:!1,code:"overlap",error:`${l.basePath} overlaps the canonical Base Path ${r}.`};if(o.includes(l.basePath))return{ok:!1,code:"duplicate",error:`${l.basePath} is already an active runtime alias.`};let d=o.find(p=>o$(l.basePath,p));return d!==void 0?{ok:!1,code:"overlap",error:`${l.basePath} overlaps the active runtime alias ${d}.`}:(o.push(l.basePath),o.sort((p,f)=>f.length-p.length||p.localeCompare(f)),{ok:!0,basePath:l.basePath})},s={canonicalBasePath:r,add:n,list:()=>[...o],remove:u=>{let l=r$(u);if(!l.ok)return l;if(l.basePath===r)return{ok:!1,code:"canonical",error:`${l.basePath} is the canonical Base Path and cannot be removed.`};let d=o.indexOf(l.basePath);return d===-1?{ok:!1,code:"not-found",error:`${l.basePath} is not an active runtime alias.`}:(o.splice(d,1),{ok:!0,basePath:l.basePath})},resolve:u=>{let l=new URL(u,"http://localhost"),d=o.find(f=>co(l.pathname,f)),p=d??r;return{effectiveBasePath:p,isAlias:d!==void 0,upstreamPath:Cy(u,p)}}};for(let u of t)n(u);return s}function qT(e,t){return e.resolve(t)}var Xm=new WeakMap,f$=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailers","transfer-encoding","upgrade","content-length"]),KT=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailers","transfer-encoding","upgrade"]),g$={"permissions-policy":"camera=(), microphone=(), geolocation=()","referrer-policy":"no-referrer","x-content-type-options":"nosniff","x-frame-options":"DENY"},h$=["default-src 'self'","base-uri 'self'","connect-src 'self' https://registry.npmjs.org","font-src 'self' data:","frame-ancestors 'none'","img-src 'self' data: blob:","object-src 'none'","script-src 'self' 'unsafe-inline'","style-src 'self' 'unsafe-inline'","worker-src 'self' blob:"].join("; ");function Zm(e){return e.replace(/&/gu,"&").replace(/"/gu,""").replace(/</gu,"<").replace(/>/gu,">")}function Ha(e,t,r){if(!e.startsWith("/")||e.startsWith("//"))return e;let o=H(t),n=H(r);if(o===null||n===null)return e;let i=e.search(/[?#]/u),a=i===-1?e:e.slice(0,i),s=i===-1?"":e.slice(i);if(o.length>0&&co(a,o))return e;let u=n.length>0&&co(a,n)?a.slice(n.length)||"/":a,l=_p(u,o),d=a.endsWith("/")&&!l.endsWith("/")?"/":"";return`${l}${d}${s}`}function v$(e,t,r,o){return e.replace(/(["'])(\/(?:[^"'/]+\/)*assets\/)/gu,(n,i,a)=>`${i}${o(Ha(a,t,r),i)}`)}function y$(e,t,r=""){let o=H(t),n=H(r);if(o===null||n===null)return e;let i=Zm(o),a=`<meta name="${ca}" content="${i}">`,s=new RegExp(`<meta\\b[^>]*\\bname\\s*=\\s*("|')${ca}\\1[^>]*>`,"giu"),u=!1,l=e.replace(s,()=>u?"":(u=!0,a)),p=(u?l:l.replace(/<head(\s[^>]*)?>/iu,f=>`${f}${a}`)).replace(/\b(href|src|action)=(["'])(\/(?!\/)[^"']*)\2/giu,(f,v,g,P)=>`${v}=${g}${Zm(Ha(P,o,n))}${g}`);return v$(p,o,n,f=>Zm(f))}function Gm(e,t){let r=e.replace(/\\/gu,"\\\\").replace(/\r/gu,"\\r").replace(/\n/gu,"\\n").replace(/\u2028/gu,"\\u2028").replace(/\u2029/gu,"\\u2029").replace(/&/gu,"\\u0026").replace(/</gu,"\\u003c").replace(/>/gu,"\\u003e");return t==="'"?r.replace(/'/gu,"\\'"):r.replace(/"/gu,'\\"')}function b$(e,t,r=""){let o=H(t),n=H(r);if(o===null||n===null)return e;let i=Gm(o,'"'),s=e.replace(/\bbasepath:\s*(["'])[^"']*\1/gu,`basepath:"${i}"`).replace(/return(["'])(\/(?!\/)[^"']*)\1\+([A-Za-z_$][\w$]*)/gu,(u,l,d,p)=>{let f=Ha(d,o,n);return`return${l}${Gm(f,l)}${l}+${p}`});return v$(s,o,n,Gm)}function _$(e,t){if(t.publicOrigin!==void 0)try{return new URL(t.publicOrigin).origin}catch{}return`http://${e.headers.host??"localhost"}`}function XT(e,t,r){let o=_$(e,t),n=H(r)??"",i=n.length===0?o:`${o}${n}`;return{schemaVersion:fm,deploymentMode:"composed",ui:{basePath:n.length===0?"/":n},control:{baseUrl:i},agent:{baseUrl:i},capabilities:{rest:!0,sse:!0,proxy:!0,mcp:!0}}}function YT(e){return JSON.stringify(e).replace(/&/gu,"\\u0026").replace(/</gu,"\\u003c").replace(/>/gu,"\\u003e").replace(/\u2028/gu,"\\u2028").replace(/\u2029/gu,"\\u2029")}function QT(e,t){let r=YT(t);if(e.includes(gm))return e.replaceAll(gm,r);let o=`<script>window.__AGENT_INSPECTOR_RUNTIME__=${r};</script>`;return e.replace(/<head(\s[^>]*)?>/iu,n=>`${n}${o}`)}async function eO(e,t,r,o,n,i){let a=(e.method??"GET").toUpperCase();if(a!=="GET"&&a!=="HEAD"||r.uiDirectory===void 0)return!1;let s=await t$(r.uiDirectory,o);if(s===null)return!1;let u=s.body;if(s.document){let d=y$(u.toString("utf8"),n,i);u=Ue.from(QT(d,XT(e,r,n)),"utf8")}else n.length>0&&s.contentType.includes("javascript")&&(u=Ue.from(b$(u.toString("utf8"),n,i),"utf8"));let l={...g$,"cache-control":s.cacheControl,"content-length":u.byteLength,"content-type":s.contentType};return s.document&&(l["content-security-policy"]=h$),t.writeHead(200,l),a==="HEAD"?t.end():t.end(u),e.resume(),!0}function qm(e){if(e===void 0)return!1;let t=e.toLowerCase();return t==="::1"||t.startsWith("127.")||t.startsWith("::ffff:127.")}function Jm(e){return e===void 0?null:/^Bearer\s+(.+)$/i.exec(e.trim())?.[1]??null}function Hm(e,t){if(e===null||t===void 0||t==="")return!1;let r=Ue.from(e),o=Ue.from(t);return r.byteLength===o.byteLength&&d$(r,o)}function tO(e,t){if(e===void 0||e.length===0||t.length===0)return!1;let r=n$("sha256").update(e).digest(),o=n$("sha256").update(t).digest();return d$(r,o)}function tt(e){return typeof e=="string"?e:e?.[0]}function Vm(e){let t=e.trim();if(t.length===0)return null;try{return new URL(`http://${t}`).hostname.toLowerCase().replace(/^\[|]$/g,"")}catch{return null}}function Za(e){let t=e.toLowerCase().replace(/^\[|]$/g,"");return t==="localhost"||t==="::1"?!0:p$(t)!==4?!1:t.split(".",1)[0]==="127"}function nO(e){try{return new URL(e)}catch{return null}}function Ym(e){let t=[],r=[];for(let o of(e??"").split(",")){let n=o.trim();if(n.length===0)continue;let i=nO(n);if(!(i!==null&&(i.protocol==="http:"||i.protocol==="https:")&&i.username.length===0&&i.password.length===0&&i.pathname==="/"&&i.search.length===0&&i.hash.length===0&&Za(i.hostname.toLowerCase().replace(/^\[|\]$/gu,"")))||i===null){r.push(n);continue}t.includes(i.origin)||t.push(i.origin)}return{origins:t,rejected:r}}function rO(e){if(e!==void 0)return $$(e.trim())}function oO(e,t){if(e===void 0)return!1;let r=Vm(e);if(r===null)return!1;if(Za(r)||p$(r)!==0)return!0;let o=Vm(t.listenHost);return o!==null&&r===o?!0:(t.trustedHosts??[]).some(n=>Vm(n)===r)}function iO(e){let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"||t==="OPTIONS"}var i$=["GET","POST","PUT","PATCH","DELETE","OPTIONS"],a$=["authorization","content-type","last-event-id",Ja];function $$(e){try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"||t.username.length>0||t.password.length>0||t.pathname!=="/"||t.search.length>0||t.hash.length>0?null:t.origin}catch{return null}}function s$(e){let t=$$(e);return t===null?null:new URL(t)}function aO(e,t){return e.origin===t.origin?!0:e.protocol===t.protocol&&e.port===t.port&&Za(e.hostname)&&Za(t.hostname)}function k$(e,t,r){let o=s$(e);if(o===null)return!1;let n=s$(r??`http://${t??"localhost"}`);return n!==null&&aO(o,n)}function x$(e,t){return e===void 0?null:(t??[]).find(r=>r===e)??null}function c$(e){return e==="/livez"||e==="/readyz"?!0:e==="/api/mcp"?!1:e==="/api"||e.startsWith("/api/")}function Km(e){return e==="/proxy"||e.startsWith("/proxy/")}function en(e){return e===null?{}:{"access-control-allow-origin":e,"access-control-expose-headers":"Content-Disposition",vary:"Origin"}}function sO(e,t){let r=(Array.isArray(e)?e.join(","):e??"").split(",").map(o=>o.trim()).filter(o=>o.length>0);return r.some(o=>o.toLowerCase()===t.toLowerCase())||r.push(t),r.join(", ")}function cO(e){return(e??"").split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function uO(e,t,r){let o=tt(e.headers["access-control-request-method"])?.toUpperCase(),n=cO(tt(e.headers["access-control-request-headers"])),i=o!==void 0&&i$.some(s=>s===o),a=n.every(s=>a$.some(u=>u===s));if(!i||!a){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(r)}),t.end(JSON.stringify({error:"CORS preflight is not allowed for this request."})),e.resume();return}t.writeHead(204,{"cache-control":"no-store","access-control-allow-origin":r,"access-control-allow-methods":i$.join(", "),"access-control-allow-headers":a$.join(", "),"access-control-max-age":"600",vary:"Origin, Access-Control-Request-Method, Access-Control-Request-Headers"}),t.end(),e.resume()}function lO(e){return e==="/livez"||e==="/readyz"||e==="/api/health"}function I$(e){return e==="/api/instances"||e.startsWith("/api/instances/")}function u$(e,t){return e!==void 0&&Number.isSafeInteger(e)&&e>0?e:t}function S$(e){if(e===void 0)return null;if(!/^\d+$/.test(e))return Number.NaN;let t=Number(e);return Number.isSafeInteger(t)?t:Number.NaN}function P$(e){if(iO(e.method))return!0;let t=ua(new URL(e.path,"http://localhost").pathname,e.basePath??oe(process.env)),r=e.secFetchSite?.toLowerCase();if(!(e.origin!==void 0||r!==void 0))return!0;let n=e.origin!==void 0?k$(e.origin,e.host,e.publicOrigin):!1;if(Km(t))return r!==void 0&&r!=="same-origin"&&!n||e.origin!==void 0&&!n?!1:e.csrfToken==="1";let i=x$(e.origin,e.allowedUiOrigins);return r!==void 0&&r!=="same-origin"&&!n&&i===null||e.origin!==void 0&&!n&&i===null?!1:e.csrfToken==="1"}function dO(e){let t=ua(new URL(e.path,"http://localhost").pathname,e.basePath??oe(process.env));if(!qm(e.remoteAddress)&&I$(t))return Hm(Jm(e.authorization),e.options.controlToken);if(e.options.restrictRemoteControl!==!0||e.options.allowRemoteControl===!0||qm(e.remoteAddress))return!0;if(t==="/proxy"||t.startsWith("/proxy/")){if(e.options.allowUnauthenticatedRemoteProxy===!0)return!0;let r=Jm(e.proxyAuthorization)??e.proxyTokenHeader??null;return Hm(r,e.options.proxyToken)}return lO(t)?!0:Hm(Jm(e.authorization),e.options.controlToken)}function pO(e){let t=S$(e.headers["content-length"]);return t!==null&&(!Number.isFinite(t)||t<0)?(e.resume(),Promise.resolve({ok:!1,status:400,error:"Invalid Content-Length header"})):t!==null&&t>Fa?(e.resume(),Promise.resolve({ok:!1,status:413,error:`Alias control body exceeds ${String(Fa)} bytes`})):new Promise(r=>{let o=[],n=0,i=!1,a=s=>{i||(i=!0,r(s))};e.on("data",s=>{if(i)return;let u=Ga(s);if(n+=u.byteLength,n>Fa){a({ok:!1,status:413,error:`Alias control body exceeds ${String(Fa)} bytes`});return}o.push(u)}),e.on("end",()=>{a({ok:!0,body:Ue.concat(o).toString("utf8")})}),e.on("aborted",()=>{a({ok:!1,status:400,error:"Client aborted alias control request"})}),e.on("error",()=>{a({ok:!1,status:400,error:"Alias control request body failed"})})})}function mO(e,t,r){return new Promise(o=>{let n=[],i=0,a=!1,s=setTimeout(()=>{u({ok:!1,status:408,error:"Instance request body timed out"}),e.resume()},r),u=l=>{a||(a=!0,clearTimeout(s),o(l))};e.on("data",l=>{if(a)return;let d=Ga(l);if(i+=d.byteLength,i>t){u({ok:!1,status:413,error:`Instance request body exceeds ${String(t)} bytes`}),e.resume();return}n.push(d)}),e.on("end",()=>u({ok:!0,body:Ue.concat(n)})),e.on("aborted",()=>u({ok:!1,status:400,error:"Client aborted instance request body"})),e.on("error",()=>u({ok:!1,status:400,error:"Instance request body failed"}))})}function Wm(e,t,r,o){e.writeHead(t,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(o)}),e.end(JSON.stringify({error:r}))}async function fO(e,t,r,o,n,i,a,s){let u=await mO(e,Math.min(a,HT),s);if(!u.ok){Wm(t,u.status,u.error,i);return}let l=(e.method??"GET").toUpperCase(),d=new Headers,p=tt(e.headers["content-type"]);p!==void 0&&d.set("content-type",p);let f=new Request(new URL(o,n),{method:l,headers:d,body:l==="GET"||l==="HEAD"?void 0:u.body.toString("utf8")}),v;try{v=await r(f)}catch{Wm(t,503,"Instance supervisor request failed",i);return}let g=Ue.from(await v.arrayBuffer());if(g.byteLength>VT){Wm(t,502,"Instance supervisor response exceeded its resource limit",i);return}let P={...en(i),"content-length":String(g.byteLength)};v.headers.forEach((R,j)=>{let Y=j.toLowerCase();!f$.has(Y)&&Y!=="content-length"&&(P[Y]=R)}),P["cache-control"]="no-store",t.writeHead(v.status,P),t.end(g)}function gO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hO(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:"Alias control body must be valid JSON."}}return!gO(t)||typeof t.basePath!="string"?{ok:!1,error:'Alias control body must contain a string "basePath" field.'}:{ok:!0,basePath:t.basePath}}function wt(e,t,r,o=void 0,n={}){e.writeHead(r,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...n}),e.end(JSON.stringify({canonicalBasePath:t.canonicalBasePath,aliases:t.list(),runtimeScoped:!0,...o}))}async function vO(e,t,r){if(!qm(e.socket.remoteAddress)){e.resume(),wt(t,r,403,{error:"Base Path aliases can only be managed from the local machine."});return}if(!P$({path:e.url??m$,basePath:"",method:e.method,host:e.headers.host,origin:e.headers.origin,secFetchSite:tt(e.headers["sec-fetch-site"]),csrfToken:tt(e.headers[Ja])})){e.resume(),wt(t,r,403,{error:"Browser mutation requires same-origin CSRF proof."});return}let o=(e.method??"GET").toUpperCase();if(o==="GET"){e.resume(),wt(t,r,200);return}if(o!=="POST"&&o!=="DELETE"){e.resume(),wt(t,r,405,{error:"Alias control supports GET, POST, and DELETE."},{allow:"GET, POST, DELETE"});return}let n=await pO(e);if(!n.ok){wt(t,r,n.status,{error:n.error});return}let i=hO(n.body);if(!i.ok){wt(t,r,400,{error:i.error});return}let a=o==="POST"?r.add(i.basePath):r.remove(i.basePath);if(a.ok){wt(t,r,o==="POST"?201:200,{basePath:a.basePath});return}let s=a.code==="duplicate"||a.code==="overlap"?409:a.code==="not-found"?404:400;wt(t,r,s,{code:a.code,error:a.error})}function Qt(e,t,r,o={},n=void 0){e.writeHead(t,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...o}),e.end(JSON.stringify(r),n)}function yO(e,t,r,o){if(e.resume(),o===void 0){Qt(t,404,{error:"Control endpoint not found"});return}if(!tO(tt(e.headers[da]),o.controlToken)){Qt(t,403,{error:"Instance control access denied"});return}let i=(e.method??"GET").toUpperCase();if(r===kt){if(i!=="GET"){Qt(t,405,{error:"Instance identity supports GET only"},{allow:"GET"});return}Qt(t,200,{schemaVersion:1,backend:o.backend??"typescript",name:o.name,instanceId:o.instanceId,launchId:o.launchId,supervisorPid:o.supervisorPid,startedAt:o.startedAt,publicPort:o.publicPort,upstreamPort:o.upstreamPort});return}if(i!=="POST"){Qt(t,405,{error:"Instance shutdown supports POST only"},{allow:"POST"});return}Qt(t,202,{accepted:!0,launchId:o.launchId},{},()=>{process.nextTick(o.requestShutdown)})}function bO(e){return e===so||e.startsWith(`${so}/`)}function w$(e){let t=Ym(e.allowedUiOrigins?.join(","));if(t.rejected.length>0)return Promise.reject(new Error(`Unsafe UI origins are not accepted: ${t.rejected.join(", ")}. Only exact loopback HTTP(S) origins are supported.`));let r=rO(e.publicOrigin);if(r===null)return Promise.reject(new Error("publicOrigin must be an exact HTTP(S) origin without credentials, path, or query."));let o={...e,allowedUiOrigins:t.origins,publicOrigin:r};return new Promise((n,i)=>{let a=l$.createServer(),s=e.aliasRegistry??WT(oe(process.env)),u={acceptingRequests:!0,activeRequests:0,drainWaiters:new Set};Xm.set(a,u),a.on("connection",l=>{let d=l.remotePort;d!==void 0&&d>0&&Bm(d).catch(()=>null)}),a.on("request",(l,d)=>{if(!u.acceptingRequests){d.writeHead(503,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",connection:"close","retry-after":"5"}),d.end(JSON.stringify({error:"Agent Inspector is shutting down"})),l.resume();return}u.activeRequests+=1;let p=!1,f=()=>{if(!p&&(p=!0,u.activeRequests=Math.max(0,u.activeRequests-1),u.activeRequests===0)){for(let v of u.drainWaiters)v();u.drainWaiters.clear()}};d.once("finish",f),d.once("close",f),$O(l,d,o,s).catch(v=>{let g=v instanceof Error?v.message:String(v);d.headersSent||d.writeHead(502,{"content-type":"text/plain"}),d.end(`Identity proxy error: ${g}`)})}),a.once("error",i),a.listen(e.listenPort,e.listenHost,()=>{a.removeListener("error",i),n(a)})})}function Va(e){let t=Xm.get(e);t!==void 0&&(t.acceptingRequests=!1)}async function _O(e){let t=Xm.get(e);t===void 0||t.activeRequests===0||await new Promise(r=>{t.drainWaiters.add(r)})}async function Qm(e){Va(e);let t=new Promise(r=>{if(!e.listening){r();return}e.close(()=>r())});await Promise.all([t,_O(e)])}function R$(e){Va(e),e.closeAllConnections(),e.close()}async function $O(e,t,r,o){let n=new URL(e.url??"/","http://localhost");if(!oO(e.headers.host,r)){t.writeHead(400,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),t.end(JSON.stringify({error:"Untrusted Host header"})),e.resume();return}if(n.pathname===m$){await vO(e,t,o);return}if(n.pathname===kt||n.pathname===la){yO(e,t,n.pathname,r.managedInstance);return}if(bO(n.pathname)){e.resume(),Qt(t,404,{error:"Control endpoint not found"});return}let i=qT(o,e.url??"/"),a=i.effectiveBasePath,s=i.upstreamPath,u=new URL(s,"http://localhost").pathname,l=e.headers.origin,d=_$(e,r),p=l!==void 0&&!k$(l,e.headers.host,d),f=p?x$(l,r.allowedUiOrigins):null;if(p&&Km(u)){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),t.end(JSON.stringify({error:"Cross-origin browser access to the model proxy is forbidden."})),e.resume();return}if(p&&u==="/api/mcp"){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),t.end(JSON.stringify({error:"Browser CORS is not enabled for the MCP endpoint."})),e.resume();return}if(p&&c$(u)){if(f===null){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),t.end(JSON.stringify({error:"UI origin is not allowed by this Agent Inspector runtime."})),e.resume();return}if((e.method??"GET").toUpperCase()==="OPTIONS"){uO(e,t,f);return}}if(a.length>0&&n.pathname.startsWith("/assets/")){t.writeHead(307,{location:`${a}${n.pathname}${n.search}`,"cache-control":"no-store"}),t.end(),e.resume();return}if(!P$({path:e.url??"/",basePath:a,method:e.method,host:e.headers.host,origin:e.headers.origin,secFetchSite:tt(e.headers["sec-fetch-site"]),csrfToken:tt(e.headers[Ja]),allowedUiOrigins:r.allowedUiOrigins,publicOrigin:d})){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(f)}),t.end(JSON.stringify({error:"Browser mutation requires same-origin CSRF proof"})),e.resume();return}if(!dO({path:e.url??"/",basePath:a,remoteAddress:e.socket.remoteAddress,authorization:e.headers.authorization,proxyAuthorization:e.headers["proxy-authorization"],proxyTokenHeader:tt(e.headers[FT]),options:r})){t.writeHead(403,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(f)}),t.end(JSON.stringify({error:"Remote access requires a credential scoped to this endpoint."})),e.resume();return}if(await eO(e,t,r,u,a,o.canonicalBasePath))return;let v=e.socket.remotePort,g=null;if(v!==void 0&&v>0)try{g=await Bm(v)}catch{g=null}let P=u$(r.maxRequestBytes,GT),R=S$(e.headers["content-length"]);if(R!==null&&(!Number.isFinite(R)||R<0)){t.writeHead(400,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(f)}),t.end(JSON.stringify({error:"Invalid Content-Length header"})),e.resume();return}if(R!==null&&R>P){t.writeHead(413,{"content-type":"application/json; charset=utf-8","cache-control":"no-store",...en(f)}),t.end(JSON.stringify({error:`Request body exceeds ${String(P)} bytes`})),e.resume();return}let j={};for(let[G,Q]of Object.entries(e.headers)){let ae=G.toLowerCase();f$.has(ae)||a.length>0&&(ae==="accept-encoding"||ae==="range"||ae==="if-range")||ae.startsWith(BT)&&!ZT.has(ae)||ae==="authorization"&&!Km(u)||Q!==void 0&&(j[G]=Q)}j[Ey]=a.length===0?"/":a,j[Ny]=d;let Y=e.socket.localPort;Y!==void 0&&Y>0&&Y<=65535&&(j[Ay]=String(Y)),g!==null&&g.pid!==null&&(j[Ba.pid]=String(g.pid),g.port!==null&&(j[Ba.port]=String(g.port)),g.cwd!==null&&(j[Ba.cwd]=g.cwd),g.projectFolder!==null&&(j[Ba.projectFolder]=g.projectFolder));let E=!1,z=u$(r.requestTimeoutMs,JT);if(r.instanceApiHandler!==void 0&&I$(u)){await fO(e,t,r.instanceApiHandler,s,d,f,P,z);return}let w=l$.request({hostname:r.upstreamHost,port:r.upstreamPort,path:s,method:e.method,headers:j},G=>{if(E||t.destroyed){G.destroy();return}let Q=()=>{G.destroy(),G.socket.destroy(),w.destroy()},ae=()=>{t.removeListener("close",Q),t.removeListener("error",Q),e.socket.removeListener("close",Q)};t.once("close",Q),t.once("error",Q),e.socket.once("close",Q),G.once("end",ae),G.once("close",ae);let ge={},Ot=tt(G.headers["content-type"]),nn=a.length>0&&Ot?.toLowerCase().includes("text/html")===!0,go=a.length>0&&(Ot?.toLowerCase().includes("javascript")===!0||s.split("?",1)[0]?.endsWith(".js")===!0),Yn=nn||go;for(let[V,ne]of Object.entries(G.headers)){let je=V.toLowerCase();KT.has(je)||Yn&&(je==="content-length"||je==="content-range"||je==="accept-ranges"||je==="etag"||je==="last-modified"||je==="content-md5"||je==="digest")||ne!==void 0&&(je==="location"&&a.length>0&&typeof ne=="string"&&ne.startsWith("/")&&!ne.startsWith("//")?ge[V]=Ha(ne,a,o.canonicalBasePath):ge[V]=ne)}for(let[V,ne]of Object.entries(g$))ge[V]=ne;ge[aa]=r.backendImplementation??"typescript",f!==null&&c$(u)&&(ge["access-control-allow-origin"]=f,ge["access-control-expose-headers"]="Content-Disposition",ge.vary=sO(ge.vary,"Origin")),Ot?.toLowerCase().includes("text/html")===!0&&(ge["content-security-policy"]=h$);let se=Yn&&G.statusCode===206?200:G.statusCode??502;if(t.writeHead(se,ge),Yn){let V=[];G.on("data",ne=>{V.push(Ga(ne))}),G.on("end",()=>{let ne=Ue.concat(V).toString("utf8");t.write(nn?y$(ne,a,o.canonicalBasePath):b$(ne,a,o.canonicalBasePath)),t.end()}),G.on("error",()=>{t.writableEnded||t.destroy()});return}G.pipe(t)}),M=setTimeout(()=>{Pe(408,"Request body deadline exceeded")},z);M.unref();function Se(){clearTimeout(M)}function Pe(G,Q){E||(E=!0,Se(),w.destroy(),t.headersSent?t.destroy():(t.writeHead(G,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),t.end(JSON.stringify({error:Q}))),e.resume())}w.on("error",G=>{E||(E=!0,Se(),t.headersSent||t.writeHead(502,{"content-type":"text/plain"}),t.end(`Upstream error: ${G.message}`))}),w.on("drain",()=>e.resume()),t.once("close",()=>{Se(),w.destroy()});let we=0;e.on("data",G=>{if(E)return;let Q=Ga(G);if(we+=Q.byteLength,we>P){Pe(413,`Request body exceeds ${String(P)} bytes`);return}Q.byteLength>0&&!w.write(Q)&&e.pause()}),e.on("end",()=>{E||(Se(),w.end())}),e.on("aborted",()=>{Pe(400,"Client aborted request body")}),e.on("error",()=>{Pe(400,"Request body stream failed")})}function Ga(e){return Ue.isBuffer(e)?e:typeof e=="string"?Ue.from(e):e instanceof ArrayBuffer?Ue.from(e):e instanceof Uint8Array?Ue.from(e.buffer,e.byteOffset,e.byteLength):Ue.alloc(0)}ka();Wr();var fA=lA(import.meta.url),pf=dA(fA),$f=9527,kf=9527,mf=9529,Nk="127.0.0.1",Xa=5e3,gA="agent-inspector.exe",hA="simple",vA=15e3,yA=2e3,Mk=1e4,bA=100,_A=1e4,$A=6e4,Ck="AGENT_INSPECTOR_BACKGROUND_SUPERVISOR";process.title="Agent Inspector";var ff=process.argv[2];function Bk(){console.log(`agent-inspector ${lt.version} - Agent observability and knowledge capture
|
|
1061
1061
|
|
|
1062
1062
|
Usage:
|
|
1063
1063
|
agent-inspector [start] [options]
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{AsyncLocalStorage as Re}from"node:async_hooks";import{H as Ie,t as Ne}from"../_libs/h3-v2.mjs";import{q as $e,s as Ee,u as De,v as ze,w as A,x as Ue,y as re,z as _e,A as z,C as Je,D as Be,E as Ge,F as We,G as Ke,H as Ve,I as oe,J as Xe,K as Ye,L as Ze,M as Qe,N as et,O as tt,P as Ce}from"../_libs/tanstack__router-core.mjs";import{i as rt,P as ie,s as nt}from"../_libs/seroval.mjs";import{c as st}from"../_libs/tanstack__history.mjs";import{j as xe}from"../_libs/react.mjs";import{r as ot,R as it}from"../_libs/tanstack__react-router.mjs";import"../_libs/rou3.mjs";import"../_libs/srvx.mjs";import"node:http";import"node:stream";import"node:stream/promises";import"node:https";import"node:http2";import"../_libs/cookie-es.mjs";import"../_libs/seroval-plugins.mjs";import"node:stream/web";import"../_libs/react-dom.mjs";import"util";import"crypto";import"async_hooks";import"stream";import"../_libs/isbot.mjs";function at(e){return xe.jsx(it,{router:e.router})}var ct=Ye(({request:e,router:t,responseHeaders:r})=>ot({request:e,router:t,responseHeaders:r,children:xe.jsx(at,{router:t})})),G=Symbol.for("tanstack-start:event-storage"),W=globalThis;W[G]||(W[G]=new Re);var ke=W[G];function ut(e){return typeof e.then=="function"}function ae(e){const t=e;if(typeof t.getSetCookie=="function")return t.getSetCookie();const r=e.get("set-cookie");return r?[r]:[]}function ce(e,t){if(e.ok)return;const r=ae(t.res.headers);if(r.length===0)return;const n=ae(e.headers);e.headers.delete("set-cookie");for(const s of n)e.headers.append("set-cookie",s);for(const s of r)e.headers.append("set-cookie",s)}function ft(e,t){return ut(e)?e.then(r=>(r instanceof Response&&ce(r,t),r)):(e instanceof Response&&ce(e,t),e)}function lt(e){return(t,r)=>{let n;try{n=new Ie(t)}catch(s){if(s instanceof URIError)return new Response(null,{status:400,statusText:"Bad Request"});throw s}return Ne(ft(ke.run({h3Event:n},()=>e(t,r)),n),n)}}function pt(){const e=ke.getStore();if(!e)throw new Error("No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.");return e.h3Event}function ue(){return pt().res}var dt={TSS_SHELL:"X-TSS_SHELL"};async function ht(e){const{tsrStartManifest:t}=await import("../_tanstack-start-manifest_v-D7cKwKzM.mjs"),r=t();let n=r.routes;n[Ge];const s={};for(const o in n){const i=n[o],a={};i.preloads&&i.preloads.length>0&&(a.preloads=i.preloads),i.scripts&&i.scripts.length>0&&(a.scripts=i.scripts),i.css?.length&&(a.css=i.css),(a.preloads||a.scripts||a.css)&&(s[o]=a)}return{...r.scriptFormat?{scriptFormat:r.scriptFormat}:{},...r.inlineCss?{inlineCss:r.inlineCss}:{},routes:s}}const yt={};async function Oe(e,t){const r=yt[e];if(!r)throw new Error("Server function info not found for "+e);const n=r.module??await r.importer();if(!n)throw new Error("Server function module not resolved for "+e);const s=n[r.functionName];if(!s)throw new Error("Server function module export not resolved for serverFn ID: "+e);return s}var fe="__TSS_CONTEXT",le=Symbol.for("TSS_SERVER_FUNCTION"),U="x-tss-serialized",mt="x-tss-raw",gt="application/x-tss-framed",P={JSON:0,CHUNK:1,END:2,ERROR:3},pe=9,wt=`${gt}; v=1`;function K(e){return e!=="__proto__"&&e!=="constructor"&&e!=="prototype"}function M(e,t){const r=Object.create(null);if(e)for(const n of Object.keys(e))K(n)&&(r[n]=e[n]);if(t&&typeof t=="object")for(const n of Object.keys(t))K(n)&&(r[n]=t[n]);return r}function de(e){if(!e)return Object.create(null);const t=Object.create(null);for(const r of Object.keys(e))K(r)&&(t[r]=e[r]);return t}var V=Symbol.for("tanstack-start:start-storage-context"),X=globalThis;X[V]||(X[V]=new Re);var He=X[V];async function he(e,t){return He.run(e,t)}function Y(e){const t=He.getStore();if(!t&&e?.throwIfNotFound!==!1)throw new Error("No Start context found in AsyncLocalStorage. Make sure you are using the function within the server runtime.");return t}var vt=()=>Y().startOptions;function Z(e,t=100){const r=new Set,n=[],s=(o,i)=>{if(i>t)throw new Error(`Middleware nesting depth exceeded maximum of ${t}. Check for circular references.`);o.forEach(a=>{a.options.middleware&&s(a.options.middleware,i+1),r.has(a)||(r.add(a),n.push(a))})};return s(e,0),n}var q=(e,t)=>{const r={type:"request",...t||e},n=s=>q({},Object.assign(r,{validator:s,inputValidator:s}));return{options:r,middleware:s=>q({},Object.assign(r,{middleware:s})),validator:n,inputValidator:n,client:s=>q({},Object.assign(r,{client:s})),server:s=>q({},Object.assign(r,{server:s}))}},St=(e={})=>q().server(async t=>{const r=t;return e.filter&&!await e.filter(r)||await Et(e,r)?t.next():Ot(e,r)}),Rt=St;async function Et(e,t){const r=await Ct(e,t);return r===!0||r===void 0&&e.allowRequestsWithoutOriginCheck===!0}async function Ct(e,t){const r=t.request.headers.get("Sec-Fetch-Site");if(r!==null)return _(e.secFetchSite??"same-origin",r,t);const n=t.request.headers.get("Origin");if(n!==null)return e.origin?_(e.origin,n,t):n===new URL(t.request.url).origin;const s=t.request.headers.get("Referer");if(!(s===null||e.referer===!1)){if(typeof e.referer=="function")return e.referer(s,t);if(e.origin){const o=xt(s);return o!==void 0&&_(e.origin,o,t)}return kt(s,new URL(t.request.url).origin)}}async function _(e,t,r){return typeof e=="function"?e(t,r):Array.isArray(e)?e.includes(t):t===e}function xt(e){try{return new URL(e).origin}catch{return}}function kt(e,t){if(e===t)return!0;if(!e.startsWith(t))return!1;if(e.length===t.length)return!0;const r=e.charCodeAt(t.length);return r===47||r===63||r===35}async function Ot(e,t){return typeof e.failureResponse=="function"?e.failureResponse(t):e.failureResponse?.clone()??new Response("Forbidden",{status:403})}function Ht(){return[...vt()?.serializationAdapters?.map(Qe)??[],...Ze]}var Te=new TextEncoder,Tt=new Uint8Array(0);function j(e,t,r){const n=new Uint8Array(pe+r.length);return n[0]=e,n[1]=t>>>24&255,n[2]=t>>>16&255,n[3]=t>>>8&255,n[4]=t&255,n[5]=r.length>>>24&255,n[6]=r.length>>>16&255,n[7]=r.length>>>8&255,n[8]=r.length&255,n.set(r,pe),n}function bt(e){return j(P.JSON,0,Te.encode(e))}function Lt(e,t){return j(P.CHUNK,e,t)}function Ft(e){return j(P.END,e,Tt)}function qt(e,t){const r=t instanceof Error?t.message:String(t??"Unknown error");return j(P.ERROR,e,Te.encode(r))}function At(e,t,r){let n,s=!1;const o=[],i=l=>{if(s)return!1;try{return n.enqueue(l),!0}catch{return!1}},a=l=>{if(!s){s=!0;try{n.error(l)}catch{}for(const f of o)f.cancel().catch(()=>{})}};async function c(l,f){const p=f.getReader();o.push(p);try{for(;!s;){const{done:d,value:v}=await p.read();if(d){i(Ft(l));return}if(!i(Lt(l,v)))return}}catch(d){i(qt(l,d))}finally{p.releaseLock()}}async function u(){const l=e.getReader();o.push(l);try{for(;!s;){const{done:f,value:p}=await l.read();if(f||!i(bt(p)))return}}catch(f){throw a(f),f}finally{l.releaseLock()}}async function y(){if(!r)return[];const l=[],f=r.getReader();o.push(f);try{for(;!s;){const{done:p,value:d}=await f.read();if(p)break;l.push(c(d.id,d.stream))}}finally{f.releaseLock()}return l}return new ReadableStream({async start(l){n=l;const f=[u()];for(const[p,d]of t)f.push(c(p,d));r&&f.push(y());try{const p=(await Promise.all(f)).find(Array.isArray);if(p&&p.length>0&&await Promise.all(p),!s)try{n.close()}catch{}}catch{}},cancel(){s=!0;for(const l of o)l.cancel().catch(()=>{});o.length=0}})}var L=void 0,Mt=["multipart/form-data","application/x-www-form-urlencoded"],Pt=1e6,jt=async({request:e,context:t,serverFnId:r})=>{const n=e.method.toUpperCase(),s=new URL(e.url),o=await Oe(r);if(o.method&&n!==o.method)return new Response(`expected ${o.method} method. Got ${n}`,{status:405,headers:{Allow:o.method}});const i=e.headers.get("x-tsr-serverFn")==="true";L||(L=Ht());const a=e.headers.get("Content-Type");function c(u){return ie(u,{plugins:L})}return await(async()=>{try{let u=function(f){let p;const d=ue();if(f!==void 0){const v=new Map;let C=!0,h,E;const g=[],R=[Ke((w,m)=>{if(C){v.set(w,m);return}if(h){h.write({id:w,stream:m}).catch(()=>{});return}g.push({id:w,stream:m})}),...L||[]];let k=!1;const S={onParse:w=>{p=w},onDone:()=>{k=!0},onError:w=>{throw w}};if(rt(f,{refs:new Map,plugins:R,onParse(w){S.onParse(w)},onDone(){S.onDone()},onError:w=>{S.onError(w)}}),C=!1,k&&v.size===0)return new Response(p?JSON.stringify(p):void 0,{status:d.status,statusText:d.statusText,headers:{"Content-Type":"application/json",[U]:"true"}});const{readable:I,writable:N}=new TransformStream;E=I,h=N.getWriter();for(const w of g)h.write(w).catch(()=>{});g.length=0;const $=At(new ReadableStream({start(w){S.onParse=m=>{w.enqueue(JSON.stringify(m)+`
|
|
2
|
-
`)},S.onDone=()=>{try{w.close()}catch{}h?.close().catch(()=>{}).finally(()=>{h=void 0})},S.onError=m=>{w.error(m),h?.abort(m).catch(()=>{}).finally(()=>{h=void 0})},p!==void 0&&S.onParse(p),k&&S.onDone()},cancel(){h?.abort().catch(()=>{}),h=void 0}}),v,E);return new Response($,{status:d.status,statusText:d.statusText,headers:{"Content-Type":wt,[U]:"true"}})}return new Response(void 0,{status:d.status,statusText:d.statusText})},y=await(async()=>{if(Mt.some(d=>a&&a.includes(d))){n==="GET"&&Ve();const d=await e.formData(),v=d.get(fe);d.delete(fe);const C={context:t,data:d,method:n};if(typeof v=="string")try{const h=ie(JSON.parse(v),{plugins:L});typeof h=="object"&&h&&(C.context=M(h,t))}catch{}return await o(C)}if(n==="GET"){const d=s.searchParams.get("payload");if(d&&d.length>Pt)throw new Error("Payload too large");const v=d?c(JSON.parse(d)):{};return v.context=M(v.context,t),v.method=n,await o(v)}let f;a?.includes("application/json")&&(f=await e.json());const p=f?c(f):{};return p.context=M(p.context,t),p.method=n,await o(p)})();const l=y.result||y.error;return oe(y)&&(y=ye(y)),i?l instanceof Response?(re(l)||l.headers.set(mt,"true"),l):u(y):l}catch(u){if(u instanceof Response)return u;if(oe(u))return ye(u);console.info(),console.info("Server Fn Error!"),console.info(),console.error(u),console.info();const y=JSON.stringify(await Promise.resolve(nt(u,{refs:new Map,plugins:L}))),l=ue();return new Response(y,{status:l.status??500,statusText:l.statusText,headers:{"Content-Type":"application/json",[U]:"true"}})}})()};function ye(e){const{headers:t,...r}=e;return new Response(JSON.stringify(r),{status:404,headers:{"Content-Type":"application/json",...t||{}}})}var It=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Nt=new Set(["fetch","font","image","script","style","track"]);function b(e,t){return t===void 0?e:It.test(t)?`${e}=${t}`:`${e}=${JSON.stringify(t)}`}function be(e){const t=[`<${e.href}>`,b("rel",e.rel)];return e.as&&t.push(b("as",e.as)),e.crossOrigin!==void 0&&t.push(b("crossorigin",e.crossOrigin||void 0)),e.type&&t.push(b("type",e.type)),e.integrity&&t.push(b("integrity",e.integrity)),e.referrerPolicy&&t.push(b("referrerpolicy",e.referrerPolicy)),e.fetchPriority&&t.push(b("fetchpriority",e.fetchPriority)),t.join("; ")}function H(e,t,r){const n=e?.[t]??(r?e?.[r]:void 0);return typeof n=="string"?n:void 0}function $t(e){const t=H(e,"as");return t&&Nt.has(t)?t:void 0}function Dt(e,t){const r=H(t,"crossOrigin","crossorigin"),n=H(t,"type"),s=H(t,"integrity"),o=H(t,"referrerPolicy","referrerpolicy"),i=H(t,"fetchPriority","fetchpriority");r!==void 0&&(e.crossOrigin=r),n&&(e.type=n),s&&(e.integrity=s),o&&(e.referrerPolicy=o),i&&(e.fetchPriority=i)}function zt(e){const t=H(e,"href"),r=H(e,"rel");if(!t||!r)return;const n=r.split(/\s+/);let s,o;if(n.includes("modulepreload"))s="modulepreload",o="script";else if(n.includes("stylesheet"))s="preload",o="style";else if(n.includes("preload")){if(o=$t(e),!o)return;s="preload"}else n.includes("preconnect")?(s="preconnect",o=void 0):n.includes("dns-prefetch")&&(s="dns-prefetch",o=void 0);if(!s)return;const i={href:t,rel:s};return o&&(i.as=o),Dt(i,e),i}function Ut(e,t){const r=[];for(const n of t){const s=e.routes[n.id];if(s){for(const o of s.preloads??[]){const i=et(e,o),a={href:i.href,rel:i.rel,as:"script"};i.crossOrigin!==void 0&&(a.crossOrigin=i.crossOrigin),r.push(a)}for(const o of s.css??[]){const i=tt(o);if(e.inlineCss?.styles[i]!==void 0)continue;const a=Ee(o),c={href:i,rel:"preload",as:"style"};a.crossOrigin!==void 0&&(c.crossOrigin=a.crossOrigin),r.push(c)}}}return r}function _t(e){const t=[];for(const r of e){const n=r.links;if(Array.isArray(n))for(const s of n){const o=zt(s);o&&t.push(o)}}return t}function Jt(e){const t=[],r=[];for(const n of e.hints){const s=be(n);e.sentLinks.has(s)||(e.sentLinks.add(s),e.sentHints.push(n),t.push(n),r.push(s))}if(!(!t.length&&e.phase!=="dynamic"))return{phase:e.phase,hints:t,links:r,allHints:e.sentHints.slice(),allLinks:Array.from(e.sentLinks)}}function Bt(e){for(const t of e.hints){const r=be(t);e.sentLinks.has(r)||(e.sentLinks.add(r),e.entries.push({phase:e.phase,hint:t,link:r}))}}function Gt(e){if(!e.filter)return e.entries.map(t=>t.link);try{const t=[];for(const r of e.entries)e.filter(r)&&t.push(r.link);return t}catch(t){return console.error("Error filtering response Link headers:",t),[]}}function Wt(e,t,r){try{const n=r(t);n&&Promise.resolve(n).catch(s=>{console.error(`Error sending ${e} early hints:`,s)})}catch(n){console.error(`Error sending ${e} early hints:`,n)}}function Kt(e){if(typeof e=="object")return e.filter}function Vt(e){for(const t of Gt(e))e.responseHeaders.append("Link",t)}function Xt(e){for(let t=0;t<e.event.hints.length;t++)e.entries.push({phase:e.phase,hint:e.event.hints[t],link:e.event.links[t]})}function me(e){const t=e.onEarlyHints?Jt({phase:e.phase,hints:e.hints,sentLinks:e.sentLinks,sentHints:e.sentHints}):void 0;if(t&&Wt(e.phase,t,e.onEarlyHints),!!e.responseLinkHeaderEntries){if(t){Xt({phase:e.phase,event:t,entries:e.responseLinkHeaderEntries});return}Bt({phase:e.phase,hints:e.hints,sentLinks:e.sentLinks,entries:e.responseLinkHeaderEntries})}}function Yt(e){if(!e?.onEarlyHints&&!e?.responseLinkHeader)return;const t=new Set,r=e.onEarlyHints?new Array:void 0,n=e.responseLinkHeader?new Array:void 0,s=Kt(e.responseLinkHeader);return{collectStatic:({manifest:o,matchedRoutes:i})=>{i?.length&&me({phase:"static",hints:Ut(o,i),sentLinks:t,sentHints:r,onEarlyHints:e.onEarlyHints,responseLinkHeaderEntries:n})},collectDynamic:o=>{me({phase:"dynamic",hints:_t(o),sentLinks:t,sentHints:r,onEarlyHints:e.onEarlyHints,responseLinkHeaderEntries:n})},appendResponseHeaders:o=>{n?.length&&Vt({responseHeaders:o,entries:n,filter:s})}}}function Q(e){return typeof e=="string"?{href:e}:e}function Zt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\a ").replace(/\r/g,"\\d ").replace(/\f/g,"\\c ")}async function Qt(e){const{strings:t,urls:r}=e.template;if(t.length!==r.length+1)throw new Error(`TanStack Start inlineCss template for ${e.stylesheetHref} is invalid`);let n=t[0];for(let s=0;s<r.length;s++){const o=Q(await e.transformFn({kind:"css-url",url:r[s],stylesheetHref:e.stylesheetHref}));n+=Zt(o.href)+t[s+1]}return n}async function er(e,t){const r={},n=await Promise.all(Object.entries(e.styles).map(async([s,o])=>{const i=e.templates?.[s];return[s,i?await Qt({stylesheetHref:s,template:i,transformFn:t}):o]}));for(const[s,o]of n)r[s]=o;return{styles:r,...e.templates?{templates:e.templates}:{}}}function tr(e,t){if(e)return typeof e=="string"?e:e[t]}function rr(e){return"prefix"in e}function nr(e){if(typeof e=="string"){const t=e;return{type:"transform",transformFn:({url:r})=>({href:`${t}${r}`}),cache:!0}}if(typeof e=="function")return{type:"transform",transformFn:e,cache:!0};if(rr(e)){const{prefix:t,crossOrigin:r}=e;return{type:"transform",transformFn:({url:n,kind:s})=>{const o=`${t}${n}`;if(s==="css-url")return{href:o};const i=tr(r,s);return i?{href:o,crossOrigin:i}:{href:o}},cache:!0}}return"createTransform"in e&&e.createTransform?{type:"createTransform",createTransform:e.createTransform,cache:e.cache!==!1}:{type:"transform",transformFn:typeof e.transform=="string"?(({url:t})=>({href:`${e.transform}${t}`})):e.transform,cache:e.cache!==!1}}function ge(e,t){if(typeof e=="string")return t.crossOrigin?t:t.href;const r={...e,href:t.href};return t.crossOrigin?r.crossOrigin=t.crossOrigin:delete r.crossOrigin,r}async function sr(e,t,r){const n=structuredClone(e),s=r?.inlineCss!==!1,o=new Map,i=a=>{const c=o.get(a);if(c)return c;const u=Promise.resolve(t({url:a,kind:"script"})).then(Q);return o.set(a,u),u};s?n.inlineCss&&(n.inlineCss=await er(n.inlineCss,t)):delete n.inlineCss;for(const a of Object.values(n.routes))if(a.preloads?.length&&(a.preloads=await Promise.all(a.preloads.map(async c=>{const u=await i($e(c).href);return ge(c,{href:u.href,crossOrigin:u.crossOrigin})}))),a.css?.length&&!n.inlineCss&&(a.css=await Promise.all(a.css.map(async c=>{const u=Q(await t({url:Ee(c).href,kind:"stylesheet"}));return ge(c,{href:u.href,crossOrigin:u.crossOrigin})}))),a.scripts?.length)for(const c of a.scripts){const u=c.attrs?.src;if(typeof u!="string")continue;const y=await i(u);c.attrs={...c.attrs,src:y.href},y.crossOrigin?c.attrs.crossOrigin=y.crossOrigin:delete c.attrs.crossOrigin}return n}function or(e,t){return{...e.scriptFormat?{scriptFormat:e.scriptFormat}:{},...t?.inlineCss!==!1&&e.inlineCss?{inlineCss:structuredClone(e.inlineCss)}:{},routes:{...e.routes}}}function ir(e){if(typeof e!="function")return e??!0}async function ar(e){return e.requestInlineCss!==void 0?e.requestInlineCss:typeof e.handlerInlineCss=="function"?await e.handlerInlineCss({request:e.request}):e.handlerInlineCss??!0}function cr(e){let t;return()=>(t||(t=e().catch(r=>{throw t=void 0,r})),t)}function ur(e,t){const r=e!==void 0?nr(e):void 0,n=r?r.cache:!0,s=!!e&&typeof e=="object"&&"warmup"in e&&e.warmup===!0;let o;const i=()=>{o=void 0};return{cache:n,warmup:s,clearCachedCreateTransform:i,getTransformFn:async a=>{if(r)return r.type!=="createTransform"?r.transformFn:n?(o||(o=Promise.resolve(r.createTransform(a)).catch(c=>{throw i(),c})),o):r.createTransform(a)}}}function fr(e){const t=new Map,r=ur(e.transformAssets),n=ir(e.inlineCss),s=async i=>{const a=await r.getTransformFn({warmup:!1,request:i.request}),c=await ar({request:i.request,handlerInlineCss:e.inlineCss,requestInlineCss:i.requestInlineCss});return{getBaseManifest:i.getBaseManifest,transformFn:a,cache:r.cache,inlineCss:c}},o=async(i,a)=>pr({...await s(i),finalManifestCache:a});return{warmup:({getBaseManifest:i})=>dr({enabled:r.warmup,handlerDefaultInlineCss:n,cache:r.cache,finalManifestCache:t,getBaseManifest:i,getTransformFn:()=>r.getTransformFn({warmup:!0}),onError:r.clearCachedCreateTransform}),resolveCached:i=>o(i,t),resolveUncached:i=>o(i,void 0)}}function Le(e){return e?"inline-css":"linked-css"}function lr(e,t,r){const n=r.catch(s=>{throw e.get(t)===n&&e.delete(t),s});return e.set(t,n),n}function Fe(e,t,r){return e.get(t)||lr(e,t,Promise.resolve().then(r))}async function qe(e){return e.transformFn?await sr(e.base,e.transformFn,{inlineCss:e.inlineCss}):or(e.base,{inlineCss:e.inlineCss})}async function pr(e){const t=async()=>qe({base:await e.getBaseManifest(),transformFn:e.transformFn,inlineCss:e.inlineCss});return e.finalManifestCache&&(!e.transformFn||e.cache)?Fe(e.finalManifestCache,Le(e.inlineCss),t):t()}function dr(e){if(!e.enabled||e.handlerDefaultInlineCss===void 0||!e.cache)return;const t=e.handlerDefaultInlineCss,r=Fe(e.finalManifestCache,Le(t),async()=>{const[n,s]=await Promise.all([e.getBaseManifest(),e.getTransformFn()]);return qe({base:n,transformFn:s,inlineCss:t})});return e.onError&&r.catch(e.onError),r}var hr=We({key:"$TSS/serverfn",test:e=>typeof e!="function"||!(le in e)?!1:!!e[le],toSerializable:({serverFnMeta:e})=>({functionId:e.id}),fromSerializable:({functionId:e})=>async(t,r)=>(await(await Oe(e))(t??{},r)).result});function yr(e){return Xe({"Content-Type":"text/html; charset=utf-8"},...e.router.stores.matches.get().map(t=>t.headers))}var J,mr=Rt({filter:e=>e.handlerType==="serverFn"}),gr=cr(()=>ht()),wr=()=>gr(),we=wr,vr=Yt;async function Sr(){const[e,t,r]=await Promise.all([import("./router-C1qBqYEd.mjs"),import("./start-PDVGOqUN.mjs"),import("./empty-plugin-adapters-C3Q1xu4u.mjs")]);return{routerEntry:e,startEntry:t,pluginAdapters:r}}function Rr(){return J||(J=Sr()),J}var Er="/",B="/_serverFn/",ve=process.env.TSS_PRERENDERING==="true",Cr=process.env.TSS_SHELL==="true",xr="Internal Server Error",kr="Internal Server Error";function ne(){throw new Error(xr)}function Or(){throw new Error(kr)}function Ae(e){return e instanceof Response||re(e)}function Hr(e){return Ce(e)||Ae(e)?{response:e}:e}async function ee(e,t){let r=-1,n;const s=c=>{if(Ce(c)){c.serverSsrCleanup==="stream"&&(n=c),t.response=c.response;return}t.response=c},o=async c=>{const u=n;if(!u)return;n=void 0;const y=t.response;(y===u.response||y instanceof Response&&u.response.body!==null&&y.body===u.response.body)&&(t.response=void 0),await u.dispose(c)},i=async()=>{const c=t.response;return c||ne(),n?c===n.response?n:n.response.body!==null&&c.body===n.response.body?{...n,response:c}:(await o("middleware response replaced"),c):c},a=async c=>{if(c){c.context&&(t.context=M(t.context,c.context));for(const f of Object.keys(c))f==="response"?s(c.response):f!=="context"&&(t[f]=c[f])}r++;const u=e[r];if(!u)return t;let y;try{y=await u({...t,next:a})}catch(f){if(Ae(f))return s(f),t;throw await o("middleware error"),f}const l=Hr(y);return l&&(l.response!==void 0&&s(l.response),l.context&&(t.context=M(t.context,l.context))),t};return await a(),{ctx:t,response:await i()}}function Se(e,t=!1){return t?e:async r=>{const n=await e({...r,next:Or});return n||ne(),n}}function Tr(e){const t=typeof e=="function"?{}:e,r=typeof e=="function"?e:e.handler,n=fr({...t}),s=n.resolveCached;return n.warmup({getBaseManifest:()=>we()}),lt(async(o,i)=>{let a=null,c=!1;try{const{url:u,handledProtocolRelativeURL:y}=De(o.url),l=u.pathname+u.search+u.hash,f=ze(o);if(y)return Response.redirect(u,308);const p=await Rr(),d=!!p.startEntry.startInstance,v=await p.startEntry.startInstance?.getOptions()||{},{hasPluginAdapters:C,pluginSerializationAdapters:h}=p.pluginAdapters,E=[...v.serializationAdapters||[],...C?h:[],hr],g={...v,requestMiddleware:d?v.requestMiddleware:[mr],serializationAdapters:E},R=g.requestMiddleware?Z(g.requestMiddleware):[],k=new Set(R),S=async()=>{if(a)return a;a=await p.routerEntry.getRouter();let m=Cr;ve&&!m&&(m=o.headers.get(dt.TSS_SHELL)==="true");const x=st({initialEntries:[l]});return a.update({history:x,isShell:m,isPrerendering:ve,origin:a.options.origin??f,defaultSsr:g.defaultSsr,serializationAdapters:[...g.serializationAdapters,...a.options.serializationAdapters||[]],basepath:Er}),a};if(B&&u.pathname.startsWith(B)){const m=u.pathname.slice(B.length).split("/")[0];if(!m)throw new Error("Invalid server action param for serverFnId");const x=async({context:T})=>he({getRouter:S,startOptions:g,contextAfterGlobalMiddlewares:T,request:o,executedRequestMiddlewares:k,handlerType:"serverFn"},()=>jt({request:o,context:i?.context,serverFnId:m})),{response:D}=await ee([...R.map(T=>T.options.server),x],{request:o,pathname:u.pathname,handlerType:"serverFn",context:de(i?.context)}),F=await te(D,o,S);return c=F.serverSsrCleanup==="stream",F.response}const I=async(m,x)=>{const D=(o.headers.get("Accept")||"*/*").split(",");if(!["*/*","text/html"].some(Pe=>D.some(je=>je.trim().startsWith(Pe))))return A(Response.json({error:"Only HTML requests are supported here"},{status:500}));const F=await s({request:o,requestInlineCss:i?.inlineCss,getBaseManifest:()=>we(x)}),T=vr({onEarlyHints:i?.onEarlyHints,responseLinkHeader:i?.responseLinkHeader});T?.collectStatic({manifest:F,matchedRoutes:x});const O=await S();if(Ue({router:O,manifest:F,getRequestAssets:()=>Y({throwIfNotFound:!1})?.requestAssets}),O.options.additionalContext={serverContext:m},await O.load(),O.state.redirect)return A(O.state.redirect);T?.collectDynamic(O.stores.matches.get());const Me=Y({throwIfNotFound:!1});await O.serverSsr.dehydrate({requestAssets:Me?.requestAssets});const se=yr({router:O});return T?.appendResponseHeaders(se),A(await r({request:o,router:O,responseHeaders:se}))},N=async({context:m})=>he({getRouter:S,startOptions:g,contextAfterGlobalMiddlewares:m,request:o,executedRequestMiddlewares:k,handlerType:"router"},async()=>{try{return await br({getRouter:S,request:o,url:u,executeRouter:I,context:m,executedRequestMiddlewares:k})}catch(x){if(x instanceof Response)return x;throw x}}),{response:$}=await ee([...R.map(m=>m.options.server),N],{request:o,pathname:u.pathname,handlerType:"router",context:de(i?.context)}),w=await te($,o,S);return c=w.serverSsrCleanup==="stream",w.response}finally{a?.serverSsr&&!c&&a.serverSsr.cleanup(),a=null}})}async function te(e,t,r){const n=A(e);if(!re(n.response))return n;if(_e(n.response))return t.headers.get("x-tsr-serverFn")==="true"?z(n,Response.json({...n.response.options,isSerializedRedirect:!0},{headers:n.response.headers}),"redirect response replaced"):n;const s=n.response.options;if(s.to&&typeof s.to=="string"&&!s.to.startsWith("/"))throw new Error(`Server side redirects must use absolute paths via the 'href' or 'to' options. The redirect() method's "to" property accepts an internal path only. Use the "href" property to provide an external URL. Received: ${JSON.stringify(s)}`);if(["params","search","hash"].some(i=>typeof s[i]=="function"))throw new Error(`Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(s).filter(i=>typeof s[i]=="function").map(i=>`"${i}"`).join(", ")}`);const o=(await r()).resolveRedirect(n.response);return t.headers.get("x-tsr-serverFn")==="true"?z(n,Response.json({...n.response.options,isSerializedRedirect:!0},{headers:n.response.headers}),"redirect response replaced"):z(n,o,"redirect response replaced")}async function br({getRouter:e,request:t,url:r,executeRouter:n,context:s,executedRequestMiddlewares:o}){const i=await e(),a=Je(i.rewrite,r).pathname,{matchedRoutes:c,foundRoute:u,routeParams:y}=i.getMatchedRoutes(a),l=u&&y["**"]===void 0,f=[];for(const h of c){const E=h.options.server?.middleware;if(E){const g=Z(E);for(const R of g)o.has(R)||f.push(R.options.server)}}const p=u?.options.server;let d=!1;if(p?.handlers&&l){const h=typeof p.handlers=="function"?p.handlers({createHandlers:R=>R}):p.handlers,E=t.method.toUpperCase(),g=E==="HEAD"?h.HEAD??h.GET??h.ANY:h[E]??h.ANY;if(d=E==="HEAD"&&g!==void 0&&!h.HEAD,g){const R=!!u.options.component;if(typeof g=="function")f.push(Se(g,R));else{if(g.middleware?.length){const k=Z(g.middleware);for(const S of k)f.push(S.options.server)}g.handler&&f.push(Se(g.handler,R))}}}f.push((h=>n(h.context,c)));const{ctx:v,response:C}=await ee(f,{request:t,context:s,params:y,pathname:a,handlerType:"router"});return d?(v.response||ne(),Be(await te(C,t,e),"HEAD body stripped")):A(C)}const Lr=Tr(ct);function Fr(e){return{async fetch(...t){return await e.fetch(...t)}}}const tn=Fr({fetch:Lr});export{q as c,Fr as createServerEntry,tn as default};
|
|
2
|
+
`)},S.onDone=()=>{try{w.close()}catch{}h?.close().catch(()=>{}).finally(()=>{h=void 0})},S.onError=m=>{w.error(m),h?.abort(m).catch(()=>{}).finally(()=>{h=void 0})},p!==void 0&&S.onParse(p),k&&S.onDone()},cancel(){h?.abort().catch(()=>{}),h=void 0}}),v,E);return new Response($,{status:d.status,statusText:d.statusText,headers:{"Content-Type":wt,[U]:"true"}})}return new Response(void 0,{status:d.status,statusText:d.statusText})},y=await(async()=>{if(Mt.some(d=>a&&a.includes(d))){n==="GET"&&Ve();const d=await e.formData(),v=d.get(fe);d.delete(fe);const C={context:t,data:d,method:n};if(typeof v=="string")try{const h=ie(JSON.parse(v),{plugins:L});typeof h=="object"&&h&&(C.context=M(h,t))}catch{}return await o(C)}if(n==="GET"){const d=s.searchParams.get("payload");if(d&&d.length>Pt)throw new Error("Payload too large");const v=d?c(JSON.parse(d)):{};return v.context=M(v.context,t),v.method=n,await o(v)}let f;a?.includes("application/json")&&(f=await e.json());const p=f?c(f):{};return p.context=M(p.context,t),p.method=n,await o(p)})();const l=y.result||y.error;return oe(y)&&(y=ye(y)),i?l instanceof Response?(re(l)||l.headers.set(mt,"true"),l):u(y):l}catch(u){if(u instanceof Response)return u;if(oe(u))return ye(u);console.info(),console.info("Server Fn Error!"),console.info(),console.error(u),console.info();const y=JSON.stringify(await Promise.resolve(nt(u,{refs:new Map,plugins:L}))),l=ue();return new Response(y,{status:l.status??500,statusText:l.statusText,headers:{"Content-Type":"application/json",[U]:"true"}})}})()};function ye(e){const{headers:t,...r}=e;return new Response(JSON.stringify(r),{status:404,headers:{"Content-Type":"application/json",...t||{}}})}var It=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Nt=new Set(["fetch","font","image","script","style","track"]);function b(e,t){return t===void 0?e:It.test(t)?`${e}=${t}`:`${e}=${JSON.stringify(t)}`}function be(e){const t=[`<${e.href}>`,b("rel",e.rel)];return e.as&&t.push(b("as",e.as)),e.crossOrigin!==void 0&&t.push(b("crossorigin",e.crossOrigin||void 0)),e.type&&t.push(b("type",e.type)),e.integrity&&t.push(b("integrity",e.integrity)),e.referrerPolicy&&t.push(b("referrerpolicy",e.referrerPolicy)),e.fetchPriority&&t.push(b("fetchpriority",e.fetchPriority)),t.join("; ")}function H(e,t,r){const n=e?.[t]??(r?e?.[r]:void 0);return typeof n=="string"?n:void 0}function $t(e){const t=H(e,"as");return t&&Nt.has(t)?t:void 0}function Dt(e,t){const r=H(t,"crossOrigin","crossorigin"),n=H(t,"type"),s=H(t,"integrity"),o=H(t,"referrerPolicy","referrerpolicy"),i=H(t,"fetchPriority","fetchpriority");r!==void 0&&(e.crossOrigin=r),n&&(e.type=n),s&&(e.integrity=s),o&&(e.referrerPolicy=o),i&&(e.fetchPriority=i)}function zt(e){const t=H(e,"href"),r=H(e,"rel");if(!t||!r)return;const n=r.split(/\s+/);let s,o;if(n.includes("modulepreload"))s="modulepreload",o="script";else if(n.includes("stylesheet"))s="preload",o="style";else if(n.includes("preload")){if(o=$t(e),!o)return;s="preload"}else n.includes("preconnect")?(s="preconnect",o=void 0):n.includes("dns-prefetch")&&(s="dns-prefetch",o=void 0);if(!s)return;const i={href:t,rel:s};return o&&(i.as=o),Dt(i,e),i}function Ut(e,t){const r=[];for(const n of t){const s=e.routes[n.id];if(s){for(const o of s.preloads??[]){const i=et(e,o),a={href:i.href,rel:i.rel,as:"script"};i.crossOrigin!==void 0&&(a.crossOrigin=i.crossOrigin),r.push(a)}for(const o of s.css??[]){const i=tt(o);if(e.inlineCss?.styles[i]!==void 0)continue;const a=Ee(o),c={href:i,rel:"preload",as:"style"};a.crossOrigin!==void 0&&(c.crossOrigin=a.crossOrigin),r.push(c)}}}return r}function _t(e){const t=[];for(const r of e){const n=r.links;if(Array.isArray(n))for(const s of n){const o=zt(s);o&&t.push(o)}}return t}function Jt(e){const t=[],r=[];for(const n of e.hints){const s=be(n);e.sentLinks.has(s)||(e.sentLinks.add(s),e.sentHints.push(n),t.push(n),r.push(s))}if(!(!t.length&&e.phase!=="dynamic"))return{phase:e.phase,hints:t,links:r,allHints:e.sentHints.slice(),allLinks:Array.from(e.sentLinks)}}function Bt(e){for(const t of e.hints){const r=be(t);e.sentLinks.has(r)||(e.sentLinks.add(r),e.entries.push({phase:e.phase,hint:t,link:r}))}}function Gt(e){if(!e.filter)return e.entries.map(t=>t.link);try{const t=[];for(const r of e.entries)e.filter(r)&&t.push(r.link);return t}catch(t){return console.error("Error filtering response Link headers:",t),[]}}function Wt(e,t,r){try{const n=r(t);n&&Promise.resolve(n).catch(s=>{console.error(`Error sending ${e} early hints:`,s)})}catch(n){console.error(`Error sending ${e} early hints:`,n)}}function Kt(e){if(typeof e=="object")return e.filter}function Vt(e){for(const t of Gt(e))e.responseHeaders.append("Link",t)}function Xt(e){for(let t=0;t<e.event.hints.length;t++)e.entries.push({phase:e.phase,hint:e.event.hints[t],link:e.event.links[t]})}function me(e){const t=e.onEarlyHints?Jt({phase:e.phase,hints:e.hints,sentLinks:e.sentLinks,sentHints:e.sentHints}):void 0;if(t&&Wt(e.phase,t,e.onEarlyHints),!!e.responseLinkHeaderEntries){if(t){Xt({phase:e.phase,event:t,entries:e.responseLinkHeaderEntries});return}Bt({phase:e.phase,hints:e.hints,sentLinks:e.sentLinks,entries:e.responseLinkHeaderEntries})}}function Yt(e){if(!e?.onEarlyHints&&!e?.responseLinkHeader)return;const t=new Set,r=e.onEarlyHints?new Array:void 0,n=e.responseLinkHeader?new Array:void 0,s=Kt(e.responseLinkHeader);return{collectStatic:({manifest:o,matchedRoutes:i})=>{i?.length&&me({phase:"static",hints:Ut(o,i),sentLinks:t,sentHints:r,onEarlyHints:e.onEarlyHints,responseLinkHeaderEntries:n})},collectDynamic:o=>{me({phase:"dynamic",hints:_t(o),sentLinks:t,sentHints:r,onEarlyHints:e.onEarlyHints,responseLinkHeaderEntries:n})},appendResponseHeaders:o=>{n?.length&&Vt({responseHeaders:o,entries:n,filter:s})}}}function Q(e){return typeof e=="string"?{href:e}:e}function Zt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\a ").replace(/\r/g,"\\d ").replace(/\f/g,"\\c ")}async function Qt(e){const{strings:t,urls:r}=e.template;if(t.length!==r.length+1)throw new Error(`TanStack Start inlineCss template for ${e.stylesheetHref} is invalid`);let n=t[0];for(let s=0;s<r.length;s++){const o=Q(await e.transformFn({kind:"css-url",url:r[s],stylesheetHref:e.stylesheetHref}));n+=Zt(o.href)+t[s+1]}return n}async function er(e,t){const r={},n=await Promise.all(Object.entries(e.styles).map(async([s,o])=>{const i=e.templates?.[s];return[s,i?await Qt({stylesheetHref:s,template:i,transformFn:t}):o]}));for(const[s,o]of n)r[s]=o;return{styles:r,...e.templates?{templates:e.templates}:{}}}function tr(e,t){if(e)return typeof e=="string"?e:e[t]}function rr(e){return"prefix"in e}function nr(e){if(typeof e=="string"){const t=e;return{type:"transform",transformFn:({url:r})=>({href:`${t}${r}`}),cache:!0}}if(typeof e=="function")return{type:"transform",transformFn:e,cache:!0};if(rr(e)){const{prefix:t,crossOrigin:r}=e;return{type:"transform",transformFn:({url:n,kind:s})=>{const o=`${t}${n}`;if(s==="css-url")return{href:o};const i=tr(r,s);return i?{href:o,crossOrigin:i}:{href:o}},cache:!0}}return"createTransform"in e&&e.createTransform?{type:"createTransform",createTransform:e.createTransform,cache:e.cache!==!1}:{type:"transform",transformFn:typeof e.transform=="string"?(({url:t})=>({href:`${e.transform}${t}`})):e.transform,cache:e.cache!==!1}}function ge(e,t){if(typeof e=="string")return t.crossOrigin?t:t.href;const r={...e,href:t.href};return t.crossOrigin?r.crossOrigin=t.crossOrigin:delete r.crossOrigin,r}async function sr(e,t,r){const n=structuredClone(e),s=r?.inlineCss!==!1,o=new Map,i=a=>{const c=o.get(a);if(c)return c;const u=Promise.resolve(t({url:a,kind:"script"})).then(Q);return o.set(a,u),u};s?n.inlineCss&&(n.inlineCss=await er(n.inlineCss,t)):delete n.inlineCss;for(const a of Object.values(n.routes))if(a.preloads?.length&&(a.preloads=await Promise.all(a.preloads.map(async c=>{const u=await i($e(c).href);return ge(c,{href:u.href,crossOrigin:u.crossOrigin})}))),a.css?.length&&!n.inlineCss&&(a.css=await Promise.all(a.css.map(async c=>{const u=Q(await t({url:Ee(c).href,kind:"stylesheet"}));return ge(c,{href:u.href,crossOrigin:u.crossOrigin})}))),a.scripts?.length)for(const c of a.scripts){const u=c.attrs?.src;if(typeof u!="string")continue;const y=await i(u);c.attrs={...c.attrs,src:y.href},y.crossOrigin?c.attrs.crossOrigin=y.crossOrigin:delete c.attrs.crossOrigin}return n}function or(e,t){return{...e.scriptFormat?{scriptFormat:e.scriptFormat}:{},...t?.inlineCss!==!1&&e.inlineCss?{inlineCss:structuredClone(e.inlineCss)}:{},routes:{...e.routes}}}function ir(e){if(typeof e!="function")return e??!0}async function ar(e){return e.requestInlineCss!==void 0?e.requestInlineCss:typeof e.handlerInlineCss=="function"?await e.handlerInlineCss({request:e.request}):e.handlerInlineCss??!0}function cr(e){let t;return()=>(t||(t=e().catch(r=>{throw t=void 0,r})),t)}function ur(e,t){const r=e!==void 0?nr(e):void 0,n=r?r.cache:!0,s=!!e&&typeof e=="object"&&"warmup"in e&&e.warmup===!0;let o;const i=()=>{o=void 0};return{cache:n,warmup:s,clearCachedCreateTransform:i,getTransformFn:async a=>{if(r)return r.type!=="createTransform"?r.transformFn:n?(o||(o=Promise.resolve(r.createTransform(a)).catch(c=>{throw i(),c})),o):r.createTransform(a)}}}function fr(e){const t=new Map,r=ur(e.transformAssets),n=ir(e.inlineCss),s=async i=>{const a=await r.getTransformFn({warmup:!1,request:i.request}),c=await ar({request:i.request,handlerInlineCss:e.inlineCss,requestInlineCss:i.requestInlineCss});return{getBaseManifest:i.getBaseManifest,transformFn:a,cache:r.cache,inlineCss:c}},o=async(i,a)=>pr({...await s(i),finalManifestCache:a});return{warmup:({getBaseManifest:i})=>dr({enabled:r.warmup,handlerDefaultInlineCss:n,cache:r.cache,finalManifestCache:t,getBaseManifest:i,getTransformFn:()=>r.getTransformFn({warmup:!0}),onError:r.clearCachedCreateTransform}),resolveCached:i=>o(i,t),resolveUncached:i=>o(i,void 0)}}function Le(e){return e?"inline-css":"linked-css"}function lr(e,t,r){const n=r.catch(s=>{throw e.get(t)===n&&e.delete(t),s});return e.set(t,n),n}function Fe(e,t,r){return e.get(t)||lr(e,t,Promise.resolve().then(r))}async function qe(e){return e.transformFn?await sr(e.base,e.transformFn,{inlineCss:e.inlineCss}):or(e.base,{inlineCss:e.inlineCss})}async function pr(e){const t=async()=>qe({base:await e.getBaseManifest(),transformFn:e.transformFn,inlineCss:e.inlineCss});return e.finalManifestCache&&(!e.transformFn||e.cache)?Fe(e.finalManifestCache,Le(e.inlineCss),t):t()}function dr(e){if(!e.enabled||e.handlerDefaultInlineCss===void 0||!e.cache)return;const t=e.handlerDefaultInlineCss,r=Fe(e.finalManifestCache,Le(t),async()=>{const[n,s]=await Promise.all([e.getBaseManifest(),e.getTransformFn()]);return qe({base:n,transformFn:s,inlineCss:t})});return e.onError&&r.catch(e.onError),r}var hr=We({key:"$TSS/serverfn",test:e=>typeof e!="function"||!(le in e)?!1:!!e[le],toSerializable:({serverFnMeta:e})=>({functionId:e.id}),fromSerializable:({functionId:e})=>async(t,r)=>(await(await Oe(e))(t??{},r)).result});function yr(e){return Xe({"Content-Type":"text/html; charset=utf-8"},...e.router.stores.matches.get().map(t=>t.headers))}var J,mr=Rt({filter:e=>e.handlerType==="serverFn"}),gr=cr(()=>ht()),wr=()=>gr(),we=wr,vr=Yt;async function Sr(){const[e,t,r]=await Promise.all([import("./router-CylQ5CaO.mjs"),import("./start-PDVGOqUN.mjs"),import("./empty-plugin-adapters-C3Q1xu4u.mjs")]);return{routerEntry:e,startEntry:t,pluginAdapters:r}}function Rr(){return J||(J=Sr()),J}var Er="/",B="/_serverFn/",ve=process.env.TSS_PRERENDERING==="true",Cr=process.env.TSS_SHELL==="true",xr="Internal Server Error",kr="Internal Server Error";function ne(){throw new Error(xr)}function Or(){throw new Error(kr)}function Ae(e){return e instanceof Response||re(e)}function Hr(e){return Ce(e)||Ae(e)?{response:e}:e}async function ee(e,t){let r=-1,n;const s=c=>{if(Ce(c)){c.serverSsrCleanup==="stream"&&(n=c),t.response=c.response;return}t.response=c},o=async c=>{const u=n;if(!u)return;n=void 0;const y=t.response;(y===u.response||y instanceof Response&&u.response.body!==null&&y.body===u.response.body)&&(t.response=void 0),await u.dispose(c)},i=async()=>{const c=t.response;return c||ne(),n?c===n.response?n:n.response.body!==null&&c.body===n.response.body?{...n,response:c}:(await o("middleware response replaced"),c):c},a=async c=>{if(c){c.context&&(t.context=M(t.context,c.context));for(const f of Object.keys(c))f==="response"?s(c.response):f!=="context"&&(t[f]=c[f])}r++;const u=e[r];if(!u)return t;let y;try{y=await u({...t,next:a})}catch(f){if(Ae(f))return s(f),t;throw await o("middleware error"),f}const l=Hr(y);return l&&(l.response!==void 0&&s(l.response),l.context&&(t.context=M(t.context,l.context))),t};return await a(),{ctx:t,response:await i()}}function Se(e,t=!1){return t?e:async r=>{const n=await e({...r,next:Or});return n||ne(),n}}function Tr(e){const t=typeof e=="function"?{}:e,r=typeof e=="function"?e:e.handler,n=fr({...t}),s=n.resolveCached;return n.warmup({getBaseManifest:()=>we()}),lt(async(o,i)=>{let a=null,c=!1;try{const{url:u,handledProtocolRelativeURL:y}=De(o.url),l=u.pathname+u.search+u.hash,f=ze(o);if(y)return Response.redirect(u,308);const p=await Rr(),d=!!p.startEntry.startInstance,v=await p.startEntry.startInstance?.getOptions()||{},{hasPluginAdapters:C,pluginSerializationAdapters:h}=p.pluginAdapters,E=[...v.serializationAdapters||[],...C?h:[],hr],g={...v,requestMiddleware:d?v.requestMiddleware:[mr],serializationAdapters:E},R=g.requestMiddleware?Z(g.requestMiddleware):[],k=new Set(R),S=async()=>{if(a)return a;a=await p.routerEntry.getRouter();let m=Cr;ve&&!m&&(m=o.headers.get(dt.TSS_SHELL)==="true");const x=st({initialEntries:[l]});return a.update({history:x,isShell:m,isPrerendering:ve,origin:a.options.origin??f,defaultSsr:g.defaultSsr,serializationAdapters:[...g.serializationAdapters,...a.options.serializationAdapters||[]],basepath:Er}),a};if(B&&u.pathname.startsWith(B)){const m=u.pathname.slice(B.length).split("/")[0];if(!m)throw new Error("Invalid server action param for serverFnId");const x=async({context:T})=>he({getRouter:S,startOptions:g,contextAfterGlobalMiddlewares:T,request:o,executedRequestMiddlewares:k,handlerType:"serverFn"},()=>jt({request:o,context:i?.context,serverFnId:m})),{response:D}=await ee([...R.map(T=>T.options.server),x],{request:o,pathname:u.pathname,handlerType:"serverFn",context:de(i?.context)}),F=await te(D,o,S);return c=F.serverSsrCleanup==="stream",F.response}const I=async(m,x)=>{const D=(o.headers.get("Accept")||"*/*").split(",");if(!["*/*","text/html"].some(Pe=>D.some(je=>je.trim().startsWith(Pe))))return A(Response.json({error:"Only HTML requests are supported here"},{status:500}));const F=await s({request:o,requestInlineCss:i?.inlineCss,getBaseManifest:()=>we(x)}),T=vr({onEarlyHints:i?.onEarlyHints,responseLinkHeader:i?.responseLinkHeader});T?.collectStatic({manifest:F,matchedRoutes:x});const O=await S();if(Ue({router:O,manifest:F,getRequestAssets:()=>Y({throwIfNotFound:!1})?.requestAssets}),O.options.additionalContext={serverContext:m},await O.load(),O.state.redirect)return A(O.state.redirect);T?.collectDynamic(O.stores.matches.get());const Me=Y({throwIfNotFound:!1});await O.serverSsr.dehydrate({requestAssets:Me?.requestAssets});const se=yr({router:O});return T?.appendResponseHeaders(se),A(await r({request:o,router:O,responseHeaders:se}))},N=async({context:m})=>he({getRouter:S,startOptions:g,contextAfterGlobalMiddlewares:m,request:o,executedRequestMiddlewares:k,handlerType:"router"},async()=>{try{return await br({getRouter:S,request:o,url:u,executeRouter:I,context:m,executedRequestMiddlewares:k})}catch(x){if(x instanceof Response)return x;throw x}}),{response:$}=await ee([...R.map(m=>m.options.server),N],{request:o,pathname:u.pathname,handlerType:"router",context:de(i?.context)}),w=await te($,o,S);return c=w.serverSsrCleanup==="stream",w.response}finally{a?.serverSsr&&!c&&a.serverSsr.cleanup(),a=null}})}async function te(e,t,r){const n=A(e);if(!re(n.response))return n;if(_e(n.response))return t.headers.get("x-tsr-serverFn")==="true"?z(n,Response.json({...n.response.options,isSerializedRedirect:!0},{headers:n.response.headers}),"redirect response replaced"):n;const s=n.response.options;if(s.to&&typeof s.to=="string"&&!s.to.startsWith("/"))throw new Error(`Server side redirects must use absolute paths via the 'href' or 'to' options. The redirect() method's "to" property accepts an internal path only. Use the "href" property to provide an external URL. Received: ${JSON.stringify(s)}`);if(["params","search","hash"].some(i=>typeof s[i]=="function"))throw new Error(`Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(s).filter(i=>typeof s[i]=="function").map(i=>`"${i}"`).join(", ")}`);const o=(await r()).resolveRedirect(n.response);return t.headers.get("x-tsr-serverFn")==="true"?z(n,Response.json({...n.response.options,isSerializedRedirect:!0},{headers:n.response.headers}),"redirect response replaced"):z(n,o,"redirect response replaced")}async function br({getRouter:e,request:t,url:r,executeRouter:n,context:s,executedRequestMiddlewares:o}){const i=await e(),a=Je(i.rewrite,r).pathname,{matchedRoutes:c,foundRoute:u,routeParams:y}=i.getMatchedRoutes(a),l=u&&y["**"]===void 0,f=[];for(const h of c){const E=h.options.server?.middleware;if(E){const g=Z(E);for(const R of g)o.has(R)||f.push(R.options.server)}}const p=u?.options.server;let d=!1;if(p?.handlers&&l){const h=typeof p.handlers=="function"?p.handlers({createHandlers:R=>R}):p.handlers,E=t.method.toUpperCase(),g=E==="HEAD"?h.HEAD??h.GET??h.ANY:h[E]??h.ANY;if(d=E==="HEAD"&&g!==void 0&&!h.HEAD,g){const R=!!u.options.component;if(typeof g=="function")f.push(Se(g,R));else{if(g.middleware?.length){const k=Z(g.middleware);for(const S of k)f.push(S.options.server)}g.handler&&f.push(Se(g.handler,R))}}}f.push((h=>n(h.context,c)));const{ctx:v,response:C}=await ee(f,{request:t,context:s,params:y,pathname:a,handlerType:"router"});return d?(v.response||ne(),Be(await te(C,t,e),"HEAD body stripped")):A(C)}const Lr=Tr(ct);function Fr(e){return{async fetch(...t){return await e.fetch(...t)}}}const tn=Fr({fetch:Lr});export{q as c,Fr as createServerEntry,tn as default};
|
|
@@ -201,7 +201,7 @@ ${e}`,"","Inspector ChatBI context:",wA(t)].join(`
|
|
|
201
201
|
`).trim()}function RA(e){const t=e.replace(/<think>[\s\S]*?<\/think>/gi,"").trim();return t!==""?t:e.trim()}function CA(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n!==void 0&&n.role==="assistant")return n}return null}function $A(e){const t=(e.history??[]).slice(-12).map(n=>`${n.role}: ${n.content.slice(0,lA)}`);return t.length>0?t.join(`
|
|
202
202
|
|
|
203
203
|
`):"No prior conversation in this request."}function AA(e,t){return{systemPrompt:jh(),messages:[{role:"user",content:["Bounded conversation history:",$A(e),"",kA(e.question,t)].join(`
|
|
204
|
-
`),timestamp:Date.now()}]}}async function MA(e,t,n){const{Agent:r}=await import("../_libs/mariozechner__pi-agent-core.mjs"),s=TA(e),o=new r({initialState:{model:s,systemPrompt:jh(),tools:[]},getApiKey:()=>e.provider.apiKey,sessionId:e.provider.id,maxRetryDelayMs:1e4}),i=AA(t,n);await o.prompt(i.messages);const a=CA(o.state.messages);if(a===null)return o.state.errorMessage??"Inspector Assistant returned no assistant message.";const c=PA(a);return c!==""?RA(c):a.errorMessage??"Inspector Assistant received an empty provider response."}async function EA(e){const t=await vA(e),n=fA(e);if(n===null)return{answer:"Inspector Assistant needs at least one Provider with OpenAI Responses, OpenAI Chat, or Anthropic Messages configured.",providerId:"",providerName:"No provider",model:"",protocol:"openaiChat",logCount:t.queryStats.matchedLogs,evidence:t.evidence,summary:t.summary,queryStats:t.queryStats};let r;try{r=await MA(n,e,t)}catch(s){r=`Inspector Assistant provider request failed: ${s instanceof Error?s.message:String(s)}`}return{answer:r,providerId:n.provider.id,providerName:n.provider.name,model:n.modelName,protocol:n.protocol,logCount:t.queryStats.matchedLogs,evidence:t.evidence,summary:t.summary,queryStats:t.queryStats}}const OA=M("/api/pi-agent")({server:{handlers:{POST:async({request:e})=>{let t;try{t=await e.json()}catch{return Response.json({error:"Invalid JSON body"},{status:400})}const n=MC.safeParse(t);if(!n.success)return Response.json({error:"Invalid Pi-agent request",details:n.error.format()},{status:400});const r=await EA(n.data);return Response.json(r)}}}}),NA=M("/api/models")({server:{handlers:{GET:()=>Response.json(tS())}}}),jA="@tonyclaw/agent-inspector",LA="4.0.13",St={name:jA,version:LA},_s=$(["typescript","rust"]);function UA(e){if(e===void 0)return"typescript";const t=_s.safeParse(e.trim().toLowerCase());return t.success?t.data:null}const yt=1;function BA(e){const t=is(e);return t!==null&&(t.length===0?"/":t)===e}const qA=$(["running","stopped","conflict"]),DA=$(["identity_mismatch","port_conflict"]),Lh=p({ui:Se(),api:Se(),health:Se(),proxy:Se(),openai:Se(),mcp:Se()}).strict(),gi=p({schemaVersion:R(yt),name:u().min(1),instanceId:u().min(1),state:qA,stateReason:DA.nullable(),checkedAt:Os(),createdAt:Os(),updatedAt:Os(),launch:p({launchId:u().min(1),startedAt:Os()}).strict(),host:u().min(1),publicPort:g().int().min(1).max(65535),upstreamPort:g().int().min(1).max(65535),basePath:u().refine(BA,"Invalid public Base Path"),captureMode:$(["simple","full"]),backend:_s.default("typescript"),uiEnabled:j(),dataDir:u().min(1),supervisorPid:g().int().positive().nullable(),urls:Lh}).strict(),FA=p({ui:p({enabled:j(),baseUrl:Se().nullable()}).strict(),control:p({baseUrl:Se()}).strict(),agent:p({baseUrl:Se()}).strict()}).strict(),GA=p({schemaVersion:R(yt),uiEnabled:j(),instance:gi,surfaces:FA,baseUrl:Se(),endpoints:Lh,environment:p({ANTHROPIC_BASE_URL:Se(),LLM_BASE_URL:Se(),OPENAI_BASE_URL:Se(),AGENT_INSPECTOR_MCP_URL:Se()}).strict(),mcp:p({serverName:u().min(1),transport:R("streamable-http"),url:Se()}).strict(),codex:p({providerName:u().min(1),baseUrl:Se(),wireApi:R("responses")}).strict()}).strict(),Ss=p({port:g().int().min(1).max(65535).optional(),basePath:u().min(1).max(2048).refine(e=>is(e)!==null,"Base Path must use URL-safe path segments without traversal, encoded separators, or markup characters").optional(),host:u().min(1).max(253).refine(e=>e.trim()===e&&!e.includes("://")&&!e.includes("/")&&!e.includes("\\")&&!/\s/u.test(e),"Host must be a hostname or IP address without protocol, path, or whitespace").optional(),captureMode:$(["simple","full"]).optional(),backend:_s.optional(),uiEnabled:j().optional(),dataDir:u().trim().min(1).max(32767).optional()}).strict(),Uh=p({}).strict(),zA=$(["start","stop","restart"]),WA=$(["created","started","already_running","stopped","already_stopped","restarted"]),qc=p({schemaVersion:R(yt),operation:zA,outcome:WA,instance:gi}).strict(),Bh=p({schemaVersion:R(yt),instances:b(gi)}).strict(),HA=$(["argument_invalid","config_mismatch","data_dir_conflict","data_dir_invalid","identity_mismatch","instance_not_found","launch_failed","launch_unavailable","lock_not_owned","lock_timeout","name_invalid","port_conflict","port_exhausted","port_invalid","record_invalid","registry_io","restart_failed_degraded","restart_failed_rolled_back","self_lifecycle_unsupported","shutdown_failed"]),JA=p({code:HA,message:u().min(1),retryable:j()}).strict(),KA=p({schemaVersion:R(yt),error:JA}).strict();function VA(e){switch(e){case"launch_failed":case"launch_unavailable":case"lock_timeout":case"port_exhausted":case"registry_io":case"restart_failed_degraded":case"restart_failed_rolled_back":case"shutdown_failed":return!0;case"argument_invalid":case"config_mismatch":case"data_dir_conflict":case"data_dir_invalid":case"identity_mismatch":case"instance_not_found":case"lock_not_owned":case"name_invalid":case"port_conflict":case"port_invalid":case"record_invalid":case"self_lifecycle_unsupported":return!1}}function XA(e){return{schemaVersion:yt,error:e}}function Lt(e){const t=process.env[e];if(t===void 0)return null;const n=t.trim();return n.length===0?null:n}function YA(){return{groupId:Lt("INSPECTOR_GROUP_ID"),runId:Lt("INSPECTOR_RUN_ID"),sessionId:Lt("INSPECTOR_SESSION_ID"),model:Lt("INSPECTOR_MODEL"),provider:Lt("INSPECTOR_PROVIDER"),agent:Lt("INSPECTOR_AGENT"),project:Lt("INSPECTOR_PROJECT"),task:Lt("INSPECTOR_TASK"),metadata:{},updatedAt:new Date().toISOString()}}let er=YA();function qh(){return er}function QA(e){return er={...er,...e,metadata:e.metadata===void 0?er.metadata:{...er.metadata,...e.metadata},updatedAt:new Date().toISOString()},er}const Dh="AGENT_INSPECTOR_MCP_INSTANCE_WRITES";function Zd(e){if(e===void 0)return null;switch(e.trim().toLowerCase()){case"1":case"true":case"yes":case"on":return!0;case"0":case"false":case"no":case"off":return!1;default:return null}}function Fh(){return Zd(process.env.AGENT_INSPECTOR_MCP_READONLY)===!0?!1:Zd(process.env.AGENT_INSPECTOR_MCP_WRITES)===!0}function Gh(){return process.env[Dh]==="1"}function zh(){const e=Gh();return{writeMode:e?"enabled":"readonly",writesEnabled:e,env:{AGENT_INSPECTOR_MCP_INSTANCE_WRITES:process.env[Dh]??null},note:e?"Named-instance lifecycle tools passed the instance-specific opt-in. General MCP writes must also be enabled.":"Named-instance lifecycle tools require AGENT_INSPECTOR_MCP_INSTANCE_WRITES=1 in addition to general MCP writes."}}function hi(){const e=Fh();return{writeMode:e?"enabled":"readonly",writesEnabled:e,env:{AGENT_INSPECTOR_MCP_READONLY:process.env.AGENT_INSPECTOR_MCP_READONLY??null,AGENT_INSPECTOR_MCP_WRITES:process.env.AGENT_INSPECTOR_MCP_WRITES??null},note:e?"MCP write/action tools are enabled explicitly by AGENT_INSPECTOR_MCP_WRITES=1.":"MCP is readonly by default. Read tools/resources still work; set AGENT_INSPECTOR_MCP_WRITES=1 to enable mutations."}}const ZA=6e4,Wh=u().trim().min(1).max(64),ep=Ss.extend({name:Wh}),ca=p({name:Wh}).strict();function tp(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function np(e){return{content:[{type:"text",text:e}],isError:!0}}async function eM(e){try{return await e.json()}catch{return null}}async function Rr(e,t,n){const r=await eM(e);if(!e.ok){const o=KA.safeParse(r);return o.success?{...tp(o.data),isError:!0}:np(`${n} returned HTTP ${String(e.status)} with an invalid error body`)}const s=t.safeParse(r);return s.success?tp(s.data):np(`${n} returned an invalid public instance document`)}function xs(e,t=""){return`/api/instances/${encodeURIComponent(e)}${t}`}function Dc(e){return{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify(e),timeoutMs:ZA}}function Hh(e){return{port:e.port,basePath:e.basePath,host:e.host,captureMode:e.captureMode,backend:e.backend,uiEnabled:e.uiEnabled,dataDir:e.dataDir}}async function Jh(e){const t=await e("/api/instances",{headers:{accept:"application/json"}});return Rr(t,Bh,"GET /api/instances")}async function Kh(e,t){const n=xs(t),r=await e(n,{headers:{accept:"application/json"}});return Rr(r,gi,`GET ${n}`)}async function Vh(e,t){const n=xs(t,"/connection"),r=await e(n,{headers:{accept:"application/json"}});return Rr(r,GA,`GET ${n}`)}async function tM(e,t){const n=xs(t.name,"/start"),r=Hh(t),s=await e(n,Dc(Ss.parse(r)));return Rr(s,qc,`POST ${n}`)}async function nM(e,t){const n=xs(t,"/stop"),r=await e(n,Dc(Uh.parse({})));return Rr(r,qc,`POST ${n}`)}async function rM(e,t){const n=xs(t.name,"/restart"),r=Hh(t),s=await e(n,Dc(Ss.parse(r)));return Rr(s,qc,`POST ${n}`)}function yi(e){return P(fe(),"evidence","groups",e)}function sM(e){return P(yi(e),"evidence.json")}function oM(e){return P(yi(e),"evidence.md")}function iM(e){return P(yi(e),"evidence.html")}function aM(e){return e.replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function rp(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Nr(e){return e==null||e.length===0?"n/a":e}function zn(e){return e==null?"n/a":String(e)}function sp(e){const t=new Set;for(const n of e)n!=null&&n.length>0&&t.add(n);return[...t].sort()}function uM(e,t){return t===null?e:{input:e.input+t.tokenUsage.input,output:e.output+t.tokenUsage.output,cacheCreate:e.cacheCreate+t.tokenUsage.cacheCreate,cacheRead:e.cacheRead+t.tokenUsage.cacheRead,total:e.total+t.tokenUsage.total}}function vi(e){return e.member.status!==null?e.member.status:e.run!==null?e.run.status:e.session?.status??"unknown"}function cM(e){return vi(e)==="completed"}function lM(e){const t=vi(e);return t==="failed"||t==="cancelled"}function dM(e){const t=vi(e);return t==="running"||t==="active"}function la(e,t){if(e===null)return null;for(const n of e.latestLogs){const r=n[t];if(r!=null)return r}return null}function pM(e){const t=e.reduce((o,i)=>uM(o,i.session),{input:0,output:0,cacheCreate:0,cacheRead:0,total:0}),n=e.filter(o=>o.session!==null).length,r=e.reduce((o,i)=>o+(i.session?.requestCount??0),0),s=e.reduce((o,i)=>o+(i.session?.errorCount??0),0);return{memberCount:e.length,sessionsWithData:n,missingSessions:e.length-n,requestCount:r,errorCount:s,tokenUsage:t,models:sp(e.flatMap(o=>[o.member.model,...o.session?.models??[]])),providers:sp(e.flatMap(o=>[o.member.provider,...o.session?.providers??[]])),completedMembers:e.filter(cM).length,failedMembers:e.filter(lM).length,runningMembers:e.filter(dM).length}}function mM(e,t){return t.failedMembers>0||t.errorCount>0||e.status==="failed"?{status:"FAIL",summary:`[FAIL] ${t.failedMembers} failed members, ${t.errorCount} captured errors.`,markdown:`# Jenkins Report: ${e.title}
|
|
204
|
+
`),timestamp:Date.now()}]}}async function MA(e,t,n){const{Agent:r}=await import("../_libs/mariozechner__pi-agent-core.mjs"),s=TA(e),o=new r({initialState:{model:s,systemPrompt:jh(),tools:[]},getApiKey:()=>e.provider.apiKey,sessionId:e.provider.id,maxRetryDelayMs:1e4}),i=AA(t,n);await o.prompt(i.messages);const a=CA(o.state.messages);if(a===null)return o.state.errorMessage??"Inspector Assistant returned no assistant message.";const c=PA(a);return c!==""?RA(c):a.errorMessage??"Inspector Assistant received an empty provider response."}async function EA(e){const t=await vA(e),n=fA(e);if(n===null)return{answer:"Inspector Assistant needs at least one Provider with OpenAI Responses, OpenAI Chat, or Anthropic Messages configured.",providerId:"",providerName:"No provider",model:"",protocol:"openaiChat",logCount:t.queryStats.matchedLogs,evidence:t.evidence,summary:t.summary,queryStats:t.queryStats};let r;try{r=await MA(n,e,t)}catch(s){r=`Inspector Assistant provider request failed: ${s instanceof Error?s.message:String(s)}`}return{answer:r,providerId:n.provider.id,providerName:n.provider.name,model:n.modelName,protocol:n.protocol,logCount:t.queryStats.matchedLogs,evidence:t.evidence,summary:t.summary,queryStats:t.queryStats}}const OA=M("/api/pi-agent")({server:{handlers:{POST:async({request:e})=>{let t;try{t=await e.json()}catch{return Response.json({error:"Invalid JSON body"},{status:400})}const n=MC.safeParse(t);if(!n.success)return Response.json({error:"Invalid Pi-agent request",details:n.error.format()},{status:400});const r=await EA(n.data);return Response.json(r)}}}}),NA=M("/api/models")({server:{handlers:{GET:()=>Response.json(tS())}}}),jA="@tonyclaw/agent-inspector",LA="4.0.14",St={name:jA,version:LA},_s=$(["typescript","rust"]);function UA(e){if(e===void 0)return"typescript";const t=_s.safeParse(e.trim().toLowerCase());return t.success?t.data:null}const yt=1;function BA(e){const t=is(e);return t!==null&&(t.length===0?"/":t)===e}const qA=$(["running","stopped","conflict"]),DA=$(["identity_mismatch","port_conflict"]),Lh=p({ui:Se(),api:Se(),health:Se(),proxy:Se(),openai:Se(),mcp:Se()}).strict(),gi=p({schemaVersion:R(yt),name:u().min(1),instanceId:u().min(1),state:qA,stateReason:DA.nullable(),checkedAt:Os(),createdAt:Os(),updatedAt:Os(),launch:p({launchId:u().min(1),startedAt:Os()}).strict(),host:u().min(1),publicPort:g().int().min(1).max(65535),upstreamPort:g().int().min(1).max(65535),basePath:u().refine(BA,"Invalid public Base Path"),captureMode:$(["simple","full"]),backend:_s.default("typescript"),uiEnabled:j(),dataDir:u().min(1),supervisorPid:g().int().positive().nullable(),urls:Lh}).strict(),FA=p({ui:p({enabled:j(),baseUrl:Se().nullable()}).strict(),control:p({baseUrl:Se()}).strict(),agent:p({baseUrl:Se()}).strict()}).strict(),GA=p({schemaVersion:R(yt),uiEnabled:j(),instance:gi,surfaces:FA,baseUrl:Se(),endpoints:Lh,environment:p({ANTHROPIC_BASE_URL:Se(),LLM_BASE_URL:Se(),OPENAI_BASE_URL:Se(),AGENT_INSPECTOR_MCP_URL:Se()}).strict(),mcp:p({serverName:u().min(1),transport:R("streamable-http"),url:Se()}).strict(),codex:p({providerName:u().min(1),baseUrl:Se(),wireApi:R("responses")}).strict()}).strict(),Ss=p({port:g().int().min(1).max(65535).optional(),basePath:u().min(1).max(2048).refine(e=>is(e)!==null,"Base Path must use URL-safe path segments without traversal, encoded separators, or markup characters").optional(),host:u().min(1).max(253).refine(e=>e.trim()===e&&!e.includes("://")&&!e.includes("/")&&!e.includes("\\")&&!/\s/u.test(e),"Host must be a hostname or IP address without protocol, path, or whitespace").optional(),captureMode:$(["simple","full"]).optional(),backend:_s.optional(),uiEnabled:j().optional(),dataDir:u().trim().min(1).max(32767).optional()}).strict(),Uh=p({}).strict(),zA=$(["start","stop","restart"]),WA=$(["created","started","already_running","stopped","already_stopped","restarted"]),qc=p({schemaVersion:R(yt),operation:zA,outcome:WA,instance:gi}).strict(),Bh=p({schemaVersion:R(yt),instances:b(gi)}).strict(),HA=$(["argument_invalid","config_mismatch","data_dir_conflict","data_dir_invalid","identity_mismatch","instance_not_found","launch_failed","launch_unavailable","lock_not_owned","lock_timeout","name_invalid","port_conflict","port_exhausted","port_invalid","record_invalid","registry_io","restart_failed_degraded","restart_failed_rolled_back","self_lifecycle_unsupported","shutdown_failed"]),JA=p({code:HA,message:u().min(1),retryable:j()}).strict(),KA=p({schemaVersion:R(yt),error:JA}).strict();function VA(e){switch(e){case"launch_failed":case"launch_unavailable":case"lock_timeout":case"port_exhausted":case"registry_io":case"restart_failed_degraded":case"restart_failed_rolled_back":case"shutdown_failed":return!0;case"argument_invalid":case"config_mismatch":case"data_dir_conflict":case"data_dir_invalid":case"identity_mismatch":case"instance_not_found":case"lock_not_owned":case"name_invalid":case"port_conflict":case"port_invalid":case"record_invalid":case"self_lifecycle_unsupported":return!1}}function XA(e){return{schemaVersion:yt,error:e}}function Lt(e){const t=process.env[e];if(t===void 0)return null;const n=t.trim();return n.length===0?null:n}function YA(){return{groupId:Lt("INSPECTOR_GROUP_ID"),runId:Lt("INSPECTOR_RUN_ID"),sessionId:Lt("INSPECTOR_SESSION_ID"),model:Lt("INSPECTOR_MODEL"),provider:Lt("INSPECTOR_PROVIDER"),agent:Lt("INSPECTOR_AGENT"),project:Lt("INSPECTOR_PROJECT"),task:Lt("INSPECTOR_TASK"),metadata:{},updatedAt:new Date().toISOString()}}let er=YA();function qh(){return er}function QA(e){return er={...er,...e,metadata:e.metadata===void 0?er.metadata:{...er.metadata,...e.metadata},updatedAt:new Date().toISOString()},er}const Dh="AGENT_INSPECTOR_MCP_INSTANCE_WRITES";function Zd(e){if(e===void 0)return null;switch(e.trim().toLowerCase()){case"1":case"true":case"yes":case"on":return!0;case"0":case"false":case"no":case"off":return!1;default:return null}}function Fh(){return Zd(process.env.AGENT_INSPECTOR_MCP_READONLY)===!0?!1:Zd(process.env.AGENT_INSPECTOR_MCP_WRITES)===!0}function Gh(){return process.env[Dh]==="1"}function zh(){const e=Gh();return{writeMode:e?"enabled":"readonly",writesEnabled:e,env:{AGENT_INSPECTOR_MCP_INSTANCE_WRITES:process.env[Dh]??null},note:e?"Named-instance lifecycle tools passed the instance-specific opt-in. General MCP writes must also be enabled.":"Named-instance lifecycle tools require AGENT_INSPECTOR_MCP_INSTANCE_WRITES=1 in addition to general MCP writes."}}function hi(){const e=Fh();return{writeMode:e?"enabled":"readonly",writesEnabled:e,env:{AGENT_INSPECTOR_MCP_READONLY:process.env.AGENT_INSPECTOR_MCP_READONLY??null,AGENT_INSPECTOR_MCP_WRITES:process.env.AGENT_INSPECTOR_MCP_WRITES??null},note:e?"MCP write/action tools are enabled explicitly by AGENT_INSPECTOR_MCP_WRITES=1.":"MCP is readonly by default. Read tools/resources still work; set AGENT_INSPECTOR_MCP_WRITES=1 to enable mutations."}}const ZA=6e4,Wh=u().trim().min(1).max(64),ep=Ss.extend({name:Wh}),ca=p({name:Wh}).strict();function tp(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function np(e){return{content:[{type:"text",text:e}],isError:!0}}async function eM(e){try{return await e.json()}catch{return null}}async function Rr(e,t,n){const r=await eM(e);if(!e.ok){const o=KA.safeParse(r);return o.success?{...tp(o.data),isError:!0}:np(`${n} returned HTTP ${String(e.status)} with an invalid error body`)}const s=t.safeParse(r);return s.success?tp(s.data):np(`${n} returned an invalid public instance document`)}function xs(e,t=""){return`/api/instances/${encodeURIComponent(e)}${t}`}function Dc(e){return{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify(e),timeoutMs:ZA}}function Hh(e){return{port:e.port,basePath:e.basePath,host:e.host,captureMode:e.captureMode,backend:e.backend,uiEnabled:e.uiEnabled,dataDir:e.dataDir}}async function Jh(e){const t=await e("/api/instances",{headers:{accept:"application/json"}});return Rr(t,Bh,"GET /api/instances")}async function Kh(e,t){const n=xs(t),r=await e(n,{headers:{accept:"application/json"}});return Rr(r,gi,`GET ${n}`)}async function Vh(e,t){const n=xs(t,"/connection"),r=await e(n,{headers:{accept:"application/json"}});return Rr(r,GA,`GET ${n}`)}async function tM(e,t){const n=xs(t.name,"/start"),r=Hh(t),s=await e(n,Dc(Ss.parse(r)));return Rr(s,qc,`POST ${n}`)}async function nM(e,t){const n=xs(t,"/stop"),r=await e(n,Dc(Uh.parse({})));return Rr(r,qc,`POST ${n}`)}async function rM(e,t){const n=xs(t.name,"/restart"),r=Hh(t),s=await e(n,Dc(Ss.parse(r)));return Rr(s,qc,`POST ${n}`)}function yi(e){return P(fe(),"evidence","groups",e)}function sM(e){return P(yi(e),"evidence.json")}function oM(e){return P(yi(e),"evidence.md")}function iM(e){return P(yi(e),"evidence.html")}function aM(e){return e.replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function rp(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Nr(e){return e==null||e.length===0?"n/a":e}function zn(e){return e==null?"n/a":String(e)}function sp(e){const t=new Set;for(const n of e)n!=null&&n.length>0&&t.add(n);return[...t].sort()}function uM(e,t){return t===null?e:{input:e.input+t.tokenUsage.input,output:e.output+t.tokenUsage.output,cacheCreate:e.cacheCreate+t.tokenUsage.cacheCreate,cacheRead:e.cacheRead+t.tokenUsage.cacheRead,total:e.total+t.tokenUsage.total}}function vi(e){return e.member.status!==null?e.member.status:e.run!==null?e.run.status:e.session?.status??"unknown"}function cM(e){return vi(e)==="completed"}function lM(e){const t=vi(e);return t==="failed"||t==="cancelled"}function dM(e){const t=vi(e);return t==="running"||t==="active"}function la(e,t){if(e===null)return null;for(const n of e.latestLogs){const r=n[t];if(r!=null)return r}return null}function pM(e){const t=e.reduce((o,i)=>uM(o,i.session),{input:0,output:0,cacheCreate:0,cacheRead:0,total:0}),n=e.filter(o=>o.session!==null).length,r=e.reduce((o,i)=>o+(i.session?.requestCount??0),0),s=e.reduce((o,i)=>o+(i.session?.errorCount??0),0);return{memberCount:e.length,sessionsWithData:n,missingSessions:e.length-n,requestCount:r,errorCount:s,tokenUsage:t,models:sp(e.flatMap(o=>[o.member.model,...o.session?.models??[]])),providers:sp(e.flatMap(o=>[o.member.provider,...o.session?.providers??[]])),completedMembers:e.filter(cM).length,failedMembers:e.filter(lM).length,runningMembers:e.filter(dM).length}}function mM(e,t){return t.failedMembers>0||t.errorCount>0||e.status==="failed"?{status:"FAIL",summary:`[FAIL] ${t.failedMembers} failed members, ${t.errorCount} captured errors.`,markdown:`# Jenkins Report: ${e.title}
|
|
205
205
|
|
|
206
206
|
Status: FAIL
|
|
207
207
|
|