@code-yeongyu/senpi 2026.10.25-2 → 2026.10.25-4
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/CHANGELOG.md +37 -0
- package/dist/bundle/chunks/{args-JXULI4EH.js → args-B444OQBK.js} +1 -1
- package/dist/bundle/chunks/{auth-4NUNUSTF.js → auth-C77UQA55.js} +1 -1
- package/dist/bundle/chunks/{chunk-XBUSVKWC.js → chunk-2RB5EL4X.js} +1 -1
- package/dist/bundle/chunks/{chunk-KUE4AQN6.js → chunk-3QCYBOKN.js} +1 -1
- package/dist/bundle/chunks/{chunk-2EFVQWXZ.js → chunk-4MOZXOJX.js} +5 -5
- package/dist/bundle/chunks/{chunk-MXZPAUFB.js → chunk-5JJDR6XI.js} +1 -1
- package/dist/bundle/chunks/chunk-6VWIMHMH.js +2 -0
- package/dist/bundle/chunks/{chunk-Y5OTHMXO.js → chunk-7CNOCJCN.js} +1 -1
- package/dist/bundle/chunks/chunk-AX72VNRS.js +27 -0
- package/dist/bundle/chunks/{chunk-VNN2V74Y.js → chunk-BZ7726QO.js} +1 -1
- package/dist/bundle/chunks/{chunk-J2U5VDG7.js → chunk-C2MQ4QXN.js} +30 -30
- package/dist/bundle/chunks/{chunk-JRXKLIEQ.js → chunk-DODH3N6U.js} +5 -5
- package/dist/bundle/chunks/{chunk-EHQXLHRB.js → chunk-E6D4RIT7.js} +2 -2
- package/dist/bundle/chunks/chunk-J37GRED2.js +5 -0
- package/dist/bundle/chunks/chunk-JMOUU75H.js +2 -0
- package/dist/bundle/chunks/chunk-JPGT64RV.js +2 -0
- package/dist/bundle/chunks/chunk-KKD4CYCI.js +3 -0
- package/dist/bundle/chunks/{chunk-YN7ELQ43.js → chunk-KNVNKDER.js} +1 -1
- package/dist/bundle/chunks/chunk-KXB5WIS5.js +4 -0
- package/dist/bundle/chunks/chunk-L73UYAH5.js +3 -0
- package/dist/bundle/chunks/{chunk-G2UETS2R.js → chunk-LOIF6PHI.js} +4 -4
- package/dist/bundle/chunks/chunk-LTU6UFEX.js +2 -0
- package/dist/bundle/chunks/chunk-N7IN46Q5.js +27 -0
- package/dist/bundle/chunks/{chunk-LYGAV6KU.js → chunk-PT6JJUN2.js} +1 -1
- package/dist/bundle/chunks/{chunk-WFXUCVIR.js → chunk-SBGIXMX3.js} +2 -5
- package/dist/bundle/chunks/{chunk-W2BKZBYJ.js → chunk-STMXIBXF.js} +2 -2
- package/dist/bundle/chunks/chunk-TBU6VYHN.js +13 -0
- package/dist/bundle/chunks/{chunk-RXKNOEQQ.js → chunk-V2UYXTRR.js} +1 -1
- package/dist/bundle/chunks/{chunk-U67ML6CQ.js → chunk-WD6WBYC5.js} +1 -1
- package/dist/bundle/chunks/chunk-WJOT3DFL.js +2 -0
- package/dist/bundle/chunks/chunk-XMJKZK5H.js +2 -0
- package/dist/bundle/chunks/chunk-YI7SPFDN.js +5 -0
- package/dist/bundle/chunks/cli-main-YYH3IBC6.js +3 -0
- package/dist/bundle/chunks/{client-KWTLTKVV.js → client-WTYEICLH.js} +3 -3
- package/dist/bundle/chunks/dispatch-MXG5YWLV.js +9 -0
- package/dist/bundle/chunks/{help-fast-path-ZHZGXAUG.js → help-fast-path-3Z26DQSV.js} +1 -1
- package/dist/bundle/chunks/host-command-TDLLHXVI.js +2 -0
- package/dist/bundle/chunks/host-lifecycle-3VHHIGDL.js +3 -0
- package/dist/bundle/chunks/host-lifecycle.js +8 -6
- package/dist/bundle/chunks/host-session-command-56XF6ACS.js +20 -0
- package/dist/bundle/chunks/{host-socket-request-AS2OCRLP.js → host-socket-request-QL2WEZTN.js} +1 -1
- package/dist/bundle/chunks/interactive-mode-OEPULLZK.js +2 -0
- package/dist/bundle/chunks/mcp-presenter-bootstrap-XUSCQVRC.js +2 -0
- package/dist/bundle/chunks/{multi-session-host-VTTY5MFT.js → multi-session-host-Z2CW4SDM.js} +12 -9
- package/dist/bundle/chunks/{package-manager-cli-DZFOC3MF.js → package-manager-cli-N55U6PEO.js} +1 -1
- package/dist/bundle/chunks/rotation-stream-CBGCBYHV.js +2 -0
- package/dist/bundle/chunks/rpc-mode-ETXQWEB2.js +2 -0
- package/dist/bundle/chunks/{rpc-monitor-source-B5NQ4ZVH.js → rpc-monitor-source-AE3C6EQV.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-SLISTG4V.js → schedule-command-VS7CZC2J.js} +1 -1
- package/dist/bundle/chunks/session-control-endpoint-4LEIDIVI.js +3 -0
- package/dist/bundle/chunks/session-picker-E4KUJDLO.js +2 -0
- package/dist/bundle/chunks/session-worker.js +292 -278
- package/dist/bundle/chunks/{stdio-IEC635SY.js → stdio-YXDKKKQZ.js} +1 -1
- package/dist/bundle/chunks/{streamableHttp-KJI5KE4K.js → streamableHttp-DKIBUWVY.js} +1 -1
- package/dist/bundle/chunks/{types-LLNV23LW.js → types-BJUEQ4II.js} +1 -1
- package/dist/bundle/chunks/zod-compat-RJDXCU7S.js +2 -0
- package/dist/bundle/cli.js +2 -2
- package/dist/bundle/host-supervisor.js +8 -6
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/cli/args.d.ts +2 -0
- package/dist/cli/args.js +9 -0
- package/dist/cli/host-command-args.d.ts +1 -0
- package/dist/cli/host-command-args.js +7 -1
- package/dist/cli/host-command.js +3 -1
- package/dist/core/agent-session.js +22 -7
- package/dist/core/extensions/builtin/goal/index.js +1 -0
- package/dist/core/extensions/builtin/goal/lifecycle-facts.d.ts +3 -0
- package/dist/core/extensions/builtin/mcp/catalog.d.ts +3 -1
- package/dist/core/extensions/builtin/mcp/catalog.js +2 -0
- package/dist/core/extensions/builtin/mcp/connection.d.ts +1 -0
- package/dist/core/extensions/builtin/mcp/connection.js +46 -1
- package/dist/core/extensions/builtin/mcp/elicitation.d.ts +6 -1
- package/dist/core/extensions/builtin/mcp/elicitation.js +54 -2
- package/dist/core/extensions/builtin/mcp/expose/call.js +6 -2
- package/dist/core/extensions/builtin/mcp/expose/session.d.ts +4 -1
- package/dist/core/extensions/builtin/mcp/expose/session.js +7 -0
- package/dist/core/extensions/builtin/mcp/health.js +5 -0
- package/dist/core/extensions/builtin/mcp/host-registry.js +7 -1
- package/dist/core/extensions/builtin/mcp/index.js +2 -0
- package/dist/core/extensions/builtin/mcp/modern/client.d.ts +5 -0
- package/dist/core/extensions/builtin/mcp/modern/client.js +15 -0
- package/dist/core/extensions/builtin/mcp/modern/consent-queue.d.ts +2 -0
- package/dist/core/extensions/builtin/mcp/modern/consent-queue.js +59 -0
- package/dist/core/extensions/builtin/mcp/modern/diagnostics.d.ts +4 -0
- package/dist/core/extensions/builtin/mcp/modern/diagnostics.js +39 -0
- package/dist/core/extensions/builtin/mcp/modern/dispatch.js +21 -11
- package/dist/core/extensions/builtin/mcp/modern/elicitation.d.ts +14 -0
- package/dist/core/extensions/builtin/mcp/modern/elicitation.js +145 -0
- package/dist/core/extensions/builtin/mcp/modern/errors.d.ts +21 -0
- package/dist/core/extensions/builtin/mcp/modern/errors.js +23 -0
- package/dist/core/extensions/builtin/mcp/modern/form-schema.d.ts +20 -0
- package/dist/core/extensions/builtin/mcp/modern/form-schema.js +153 -0
- package/dist/core/extensions/builtin/mcp/modern/http-fetch.d.ts +3 -1
- package/dist/core/extensions/builtin/mcp/modern/http-fetch.js +8 -2
- package/dist/core/extensions/builtin/mcp/modern/inputs.d.ts +11 -0
- package/dist/core/extensions/builtin/mcp/modern/inputs.js +65 -0
- package/dist/core/extensions/builtin/mcp/modern/parameter-headers.d.ts +11 -0
- package/dist/core/extensions/builtin/mcp/modern/parameter-headers.js +109 -0
- package/dist/core/extensions/builtin/mcp/modern/request.d.ts +20 -0
- package/dist/core/extensions/builtin/mcp/modern/request.js +292 -0
- package/dist/core/extensions/builtin/mcp/modern/stdio-probe.d.ts +1 -1
- package/dist/core/extensions/builtin/mcp/modern/stdio-probe.js +54 -6
- package/dist/core/extensions/builtin/mcp/modern/transport.js +80 -14
- package/dist/core/extensions/builtin/mcp/modern/wire.js +11 -7
- package/dist/core/extensions/builtin/mcp/prompts.d.ts +5 -1
- package/dist/core/extensions/builtin/mcp/prompts.js +6 -1
- package/dist/core/extensions/builtin/mcp/request-origin.d.ts +47 -0
- package/dist/core/extensions/builtin/mcp/request-origin.js +59 -0
- package/dist/core/extensions/builtin/mcp/resources.d.ts +4 -1
- package/dist/core/extensions/builtin/mcp/resources.js +19 -4
- package/dist/core/extensions/builtin/mcp/sdk.lazy.d.ts +3 -1
- package/dist/core/extensions/builtin/mcp/sdk.lazy.js +3 -1
- package/dist/core/extensions/builtin/mcp/service-register.d.ts +4 -1
- package/dist/core/extensions/builtin/mcp/service-register.js +3 -0
- package/dist/core/extensions/builtin/mcp/service-types.d.ts +2 -1
- package/dist/core/extensions/builtin/mcp/service.d.ts +1 -0
- package/dist/core/extensions/builtin/mcp/service.js +79 -4
- package/dist/core/extensions/builtin/mcp/shared-connection.js +36 -2
- package/dist/core/extensions/builtin/mcp/shared-lease.d.ts +1 -0
- package/dist/core/extensions/builtin/mcp/shared-lease.js +9 -0
- package/dist/core/extensions/builtin/mcp/transport-sdk.d.ts +3 -2
- package/dist/core/extensions/builtin/mcp/transport-sdk.js +56 -25
- package/dist/core/extensions/builtin/mcp/wrap.d.ts +7 -0
- package/dist/core/extensions/builtin/mcp/wrap.js +6 -0
- package/dist/core/extensions/runner.js +3 -2
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/lifecycle-ledger.d.ts +1 -0
- package/dist/core/lifecycle-ledger.js +7 -2
- package/dist/core/lifecycle-record.js +3 -0
- package/dist/core/lifecycle-session-binding.d.ts +11 -1
- package/dist/core/lifecycle-session-binding.js +29 -2
- package/dist/core/lifecycle-stop.d.ts +41 -0
- package/dist/core/lifecycle-stop.js +92 -0
- package/dist/core/mcp-form-types.d.ts +89 -0
- package/dist/core/mcp-form-types.js +23 -0
- package/dist/core/mcp-mrtr-presentations.d.ts +15 -0
- package/dist/core/mcp-mrtr-presentations.js +17 -0
- package/dist/core/session-control-actions.js +0 -2
- package/dist/core/session-lifecycle-types.d.ts +15 -0
- package/dist/core/session-lifecycle.d.ts +17 -1
- package/dist/core/session-lifecycle.js +40 -2
- package/dist/main.js +5 -1
- package/dist/modes/interactive/components/extension-selector.d.ts +1 -0
- package/dist/modes/interactive/components/extension-selector.js +4 -0
- package/dist/modes/interactive/interactive-mode.d.ts +4 -0
- package/dist/modes/interactive/interactive-mode.js +34 -8
- package/dist/modes/interactive/mcp-local-presenter.d.ts +5 -0
- package/dist/modes/interactive/mcp-local-presenter.js +109 -0
- package/dist/modes/interactive/session-control-attach.d.ts +20 -0
- package/dist/modes/interactive/session-control-attach.js +13 -0
- package/dist/modes/interactive/session-control-commands.js +16 -6
- package/dist/modes/interactive/session-control-registry.d.ts +2 -1
- package/dist/modes/interactive/session-control-registry.js +3 -2
- package/dist/modes/interactive/session-control-rpc-commands.d.ts +4 -2
- package/dist/modes/interactive/session-control-rpc-commands.js +114 -4
- package/dist/modes/interactive/session-control-server.js +9 -3
- package/dist/modes/rpc/connection-handler.d.ts +1 -0
- package/dist/modes/rpc/connection-handler.js +13 -41
- package/dist/modes/rpc/custom-capability.d.ts +6 -0
- package/dist/modes/rpc/custom-capability.js +6 -0
- package/dist/modes/rpc/get-entries-command.d.ts +13 -0
- package/dist/modes/rpc/get-entries-command.js +61 -0
- package/dist/modes/rpc/get-entries-page.d.ts +22 -0
- package/dist/modes/rpc/get-entries-page.js +41 -2
- package/dist/modes/rpc/host-capabilities.d.ts +1 -0
- package/dist/modes/rpc/host-capabilities.js +6 -2
- package/dist/modes/rpc/host-ensure-start.js +13 -2
- package/dist/modes/rpc/host-ensure-types.d.ts +2 -0
- package/dist/modes/rpc/host-ensure.js +1 -0
- package/dist/modes/rpc/host-handoff.d.ts +2 -0
- package/dist/modes/rpc/host-handover-wire.d.ts +2 -0
- package/dist/modes/rpc/host-handover-wire.js +1 -0
- package/dist/modes/rpc/host-lifecycle-launch.d.ts +1 -0
- package/dist/modes/rpc/host-lifecycle-launch.js +43 -2
- package/dist/modes/rpc/host-observe-request.d.ts +2 -1
- package/dist/modes/rpc/host-observe-request.js +4 -1
- package/dist/modes/rpc/host-runner.d.ts +2 -0
- package/dist/modes/rpc/host-runner.js +8 -6
- package/dist/modes/rpc/host-successor.js +11 -1
- package/dist/modes/rpc/mcp-form-dialog.d.ts +45 -0
- package/dist/modes/rpc/mcp-form-dialog.js +159 -0
- package/dist/modes/rpc/mcp-form-worker.d.ts +14 -0
- package/dist/modes/rpc/mcp-form-worker.js +167 -0
- package/dist/modes/rpc/mcp-presenter-authority.d.ts +53 -0
- package/dist/modes/rpc/mcp-presenter-authority.js +309 -0
- package/dist/modes/rpc/mcp-presenter-bootstrap.d.ts +8 -0
- package/dist/modes/rpc/mcp-presenter-bootstrap.js +111 -0
- package/dist/modes/rpc/mcp-presenter-control.d.ts +24 -0
- package/dist/modes/rpc/mcp-presenter-control.js +330 -0
- package/dist/modes/rpc/multi-session-host.d.ts +3 -0
- package/dist/modes/rpc/multi-session-host.js +36 -1
- package/dist/modes/rpc/rpc-read-response-types.d.ts +2 -0
- package/dist/modes/rpc/rpc-session-command-types.d.ts +8 -1
- package/dist/modes/rpc/session-binding.js +6 -1
- package/dist/modes/rpc/session-event-writer.d.ts +14 -0
- package/dist/modes/rpc/session-event-writer.js +128 -1
- package/dist/modes/rpc/session-router-routing.js +1 -0
- package/dist/modes/rpc/session-worker-client.d.ts +3 -0
- package/dist/modes/rpc/session-worker-client.js +89 -0
- package/dist/modes/rpc/session-worker-protocol.d.ts +41 -0
- package/dist/modes/rpc/session-worker.js +9 -0
- package/docs/extensions.md +5 -0
- package/docs/mcp.md +20 -3
- package/docs/rpc.md +151 -8
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-3LNSLJ7N.js +0 -2
- package/dist/bundle/chunks/chunk-B6TPQDBW.js +0 -5
- package/dist/bundle/chunks/chunk-CDRFFHLL.js +0 -4
- package/dist/bundle/chunks/chunk-HPCS4HM4.js +0 -27
- package/dist/bundle/chunks/chunk-KJZAY5YH.js +0 -27
- package/dist/bundle/chunks/chunk-MSQCTH6V.js +0 -2
- package/dist/bundle/chunks/chunk-OI4NMCKP.js +0 -3
- package/dist/bundle/chunks/chunk-SCVRKIFK.js +0 -2
- package/dist/bundle/chunks/cli-main-SWKFMTZQ.js +0 -3
- package/dist/bundle/chunks/dispatch-DEP4PEDZ.js +0 -10
- package/dist/bundle/chunks/host-command-BC6UWP33.js +0 -2
- package/dist/bundle/chunks/host-lifecycle-TN5NEGNF.js +0 -3
- package/dist/bundle/chunks/host-session-command-MGVBLBRV.js +0 -20
- package/dist/bundle/chunks/interactive-mode-SCSROHD5.js +0 -2
- package/dist/bundle/chunks/rotation-stream-U7YQMC7H.js +0 -2
- package/dist/bundle/chunks/rpc-mode-TOXYD4XA.js +0 -2
- package/dist/bundle/chunks/session-control-endpoint-HFFMBALG.js +0 -3
- package/dist/bundle/chunks/session-picker-465FVXQG.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{isTuiControlSocket}from"./chunk-
|
|
2
|
+
import{isTuiControlSocket}from"./chunk-KKD4CYCI.js";import{HOST_DAEMON_LAYOUT,createHostDaemonPaths,hostDaemonDirectoryPaths,parseJson,readFileOrUndefined,socketNamesDirectory}from"./chunk-4WZRVZNX.js";import{readdir}from"node:fs/promises";import{basename,join}from"node:path";var ENDPOINT_DIRECTORY_NAME=/^[0-9a-f]{16}$/;async function listHostEndpoints(agentDir){let flatDir=join(agentDir,"rpc-host-daemon");if(parseJson(await readFileOrUndefined(join(flatDir,"layout.json")).catch(()=>{}))?.layout!==HOST_DAEMON_LAYOUT)return[];let dirs=(await readdir(flatDir,{withFileTypes:!0}).catch(()=>[])).filter(entry=>entry.isDirectory()&&ENDPOINT_DIRECTORY_NAME.test(entry.name)).map(entry=>join(flatDir,entry.name)).sort(),endpoints=[];for(let dir of dirs)endpoints.push(await identifyEndpoint(dir));return endpoints}async function identifyEndpoint(dir){let paths=hostDaemonDirectoryPaths(dir),named=await recordNaming(paths.endpointFile,dir);if(named!==void 0)return{socket:named.socket,dir,identity:"endpoint",endpoint_kind:endpointKindOf(named.record)};let booted=await recordNaming(paths.settingsFile,dir);if(booted!==void 0)return{socket:booted.socket,dir,identity:"settings",endpoint_kind:"rpc_host"};let generations=await readdir(paths.generationsDir).catch(()=>[]);for(let instanceId of generations.sort()){let recorded=await recordNaming(join(paths.generationsDir,instanceId,"settings.json"),dir);if(recorded!==void 0)return{socket:recorded.socket,dir,identity:"generation-settings",endpoint_kind:"rpc_host"}}return{socket:null,dir,identity:"unknown",endpoint_kind:"rpc_host"}}async function endpointKindOfSocket(socket,agentDir){if(isTuiControlSocket(socket))return"tui";let paths=createHostDaemonPaths({socket,agentDir}),named=await recordNaming(paths.endpointFile,paths.dir);return named===void 0?"rpc_host":endpointKindOf(named.record)}function endpointKindOf(record){return record.endpoint_kind==="tui"?"tui":"rpc_host"}async function recordNaming(file,dir){let record=parseJson(await readFileOrUndefined(file).catch(()=>{})),socket=record?.socket;if(!(record===void 0||typeof socket!="string"||socket===""))return socketNamesDirectory(socket,basename(dir))?{socket,record}:void 0}export{listHostEndpoints,endpointKindOfSocket};
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{ProcessIdentityUnreadableError,processMatchesPidFile,readProcessStartTime}from"./chunk-O5RYI3IW.js";var HOST_GENERATION_ENV="SENPI_RPC_HOST_GENERATION",HOST_INSTANCE_ID_ENV="SENPI_RPC_HOST_INSTANCE_ID";import{
|
|
3
|
-
`}var MAX_RPC_LINE_CHARACTERS=16*1024*1024;function attachJsonlLineReader(stream,onLine,options={}){let decoder=new StringDecoder("utf8"),maxLineLength=options.maxLineLength??Number.POSITIVE_INFINITY;if(!(maxLineLength>0))throw new Error("maxLineLength must be greater than zero.");let buffer="",discardingOversizedLine=!1,consume=text=>{let offset=0;for(;offset<text.length;){if(discardingOversizedLine){let newlineIndex2=text.indexOf(`
|
|
4
|
-
`,offset);if(newlineIndex2===-1)return;discardingOversizedLine=!1,offset=newlineIndex2+1;continue}let newlineIndex=text.indexOf(`
|
|
5
|
-
`,offset);if(newlineIndex===-1){let remainder=text.slice(offset);buffer.length+remainder.length>maxLineLength?(buffer="",discardingOversizedLine=!0,options.onOversizedLine?.()):buffer+=remainder;return}let segment=text.slice(offset,newlineIndex);if(buffer.length+segment.length>maxLineLength)options.onOversizedLine?.();else{let line=buffer+segment;onLine(line.endsWith("\r")?line.slice(0,-1):line)}buffer="",offset=newlineIndex+1}},onData=chunk=>{consume(typeof chunk=="string"?chunk:decoder.write(chunk))},onEnd=()=>{consume(decoder.end()),!discardingOversizedLine&&buffer.length>0&&onLine(buffer.endsWith("\r")?buffer.slice(0,-1):buffer),buffer="",discardingOversizedLine=!1};return stream.on("data",onData),stream.on("end",onEnd),()=>{stream.off("data",onData),stream.off("end",onEnd)}}import{createHmac,timingSafeEqual}from"node:crypto";var RPC_AUTH_CAPABILITY="socket_auth",RPC_AUTH_HEX=/^[a-f0-9]{64}$/,RPC_LAUNCH_ID=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;function rpcAuthProof(key,label,...parts){return createHmac("sha256",key).update([`senpi-rpc-${label}`,...parts].join(`
|
|
2
|
+
import{ProcessIdentityUnreadableError,processMatchesPidFile,readProcessStartTime}from"./chunk-O5RYI3IW.js";var HOST_GENERATION_ENV="SENPI_RPC_HOST_GENERATION",HOST_INSTANCE_ID_ENV="SENPI_RPC_HOST_INSTANCE_ID";import{createHmac,timingSafeEqual}from"node:crypto";var RPC_AUTH_CAPABILITY="socket_auth",RPC_AUTH_HEX=/^[a-f0-9]{64}$/,RPC_LAUNCH_ID=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;function rpcAuthProof(key,label,...parts){return createHmac("sha256",key).update([`senpi-rpc-${label}`,...parts].join(`
|
|
6
3
|
`),"utf8").digest("hex")}function rpcProofMatches(expected,received){return typeof received=="string"&&RPC_AUTH_HEX.test(received)&&timingSafeEqual(Buffer.from(expected,"hex"),Buffer.from(received,"hex"))}var RpcEndpointAuthError=class extends Error{constructor(code,detail,options){super(`${code}: ${detail}`,options),this.code=code,this.name="RpcEndpointAuthError"}};function authRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}import{randomBytes,randomUUID}from"node:crypto";import{constants,unlinkSync}from"node:fs";import*as fs from"node:fs/promises";import{join}from"node:path";var MAX_KEY_RECORD_BYTES=4096;async function checkRpcKeyDirectory(path,privateKeys=!1){let checked=privateKeys?path:await fs.realpath(path),problem=keyDirectoryProblem(await fs.lstat(checked),checked,privateKeys);if(problem!==void 0)throw new RpcEndpointAuthError("unsafe_key_record",`${checked} ${problem}`)}function keyDirectoryProblem(info,path,privateKeys){if(!info.isDirectory())return"is not a directory";if(info.uid!==process.getuid?.())return"is not owned by this user";let mode=info.mode&4095;return privateKeys?mode===448?void 0:`must be mode 0700 (is 0${mode.toString(8)}); run: chmod 700 ${path}`:(mode&18)===0?void 0:`is writable by group or others; run: chmod go-w ${path}`}async function checkRpcKeyParents(root){await checkRpcKeyDirectory(root),await checkRpcKeyDirectory(join(root,"rpc"))}async function readRpcKeyRecord(root,launchId){if(!RPC_LAUNCH_ID.test(launchId))throw new RpcEndpointAuthError("unsafe_key_record",`invalid launch id under ${root}`);let path=join(root,"rpc","keys",launchId);try{await checkRpcKeyParents(root),await checkRpcKeyDirectory(join(root,"rpc","keys"),!0);let handle=await fs.open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{let info=await handle.stat();if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&4095)!==384||info.size>MAX_KEY_RECORD_BYTES)throw new RpcEndpointAuthError("unsafe_key_record",path);let record=authRecord(JSON.parse(await handle.readFile("utf8")));if(record?.version!==1||record.launch_id!==launchId||typeof record.key!="string"||!RPC_AUTH_HEX.test(record.key))throw new RpcEndpointAuthError("unsafe_key_record",path);return record}finally{await handle.close()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause instanceof RpcEndpointAuthError?cause:new RpcEndpointAuthError("unsafe_key_record",path,{cause})}}var RpcPublicEndpoint=class{constructor(agentDir,endpoint){this.key=randomBytes(32),this.launchId=randomUUID(),this.publication=Promise.withResolvers(),this.created=!1,this.exitCleanup=()=>{if(this.created)try{unlinkSync(this.recordPath)}catch(cause){cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"||process.stderr.write(`senpi rpc host: could not remove own endpoint key record
|
|
7
|
-
`)}},this.agentDir=agentDir,this.endpoint=endpoint,this.recordPath=join(agentDir,"rpc","keys",this.launchId),this.ready=this.publication.promise,this.ready.catch(()=>{})}async publish(){try{await fs.mkdir(join(this.agentDir,"rpc"),{recursive:!0,mode:448}),await checkRpcKeyParents(this.agentDir);let keys=join(this.agentDir,"rpc","keys");await fs.mkdir(keys,{recursive:!0,mode:448});let directory=await fs.lstat(keys);if(!directory.isDirectory()||directory.uid!==process.getuid?.())throw new RpcEndpointAuthError("unsafe_key_record",keys);(directory.mode&4095)!==448&&await fs.chmod(keys,448),await checkRpcKeyDirectory(keys,!0);let handle=await fs.open(this.recordPath,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,384);this.created=!0,process.once("exit",this.exitCleanup);try{await handle.writeFile(JSON.stringify({version:1,launch_id:this.launchId,key:this.key.toString("hex"),pid:process.pid,process_start:await readProcessStartTime(process.pid)??null,endpoint:this.endpoint,created_at:new Date().toISOString()})),await handle.sync();let info=await handle.stat();if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&4095)!==384)throw new RpcEndpointAuthError("unsafe_key_record",this.recordPath)}finally{await handle.close()}this.publication.resolve()}catch(cause){let error=new RpcEndpointAuthError("key_publication_failed",cause instanceof RpcEndpointAuthError?cause.message:this.recordPath,{cause});throw this.publication.reject(error),error}}async dispose(){process.off("exit",this.exitCleanup),this.created&&(this.created=!1,await fs.unlink(this.recordPath).catch(cause=>{if(!(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"))throw cause}))}};async function gcRpcPublicKeys(agentDir,budget={}){let keys=join(agentDir,"rpc","keys");try{await checkRpcKeyParents(agentDir),await checkRpcKeyDirectory(keys,!0)}catch(cause){if(cause instanceof RpcEndpointAuthError||cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause}let names=await fs.readdir(keys).catch(cause=>{if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return[];throw cause}),examined=0;for(let name of names){if(Date.now()>=(budget.deadline??1/0)||examined>=(budget.maxRecords??1/0))break;if(RPC_LAUNCH_ID.test(name)){examined++;try{let record=await readRpcKeyRecord(agentDir,name);if(record===void 0||typeof record.pid!="number"||!Number.isSafeInteger(record.pid)||record.pid<=0||!(record.process_start===null||typeof record.process_start=="string")||await processMatchesPidFile({pid:record.pid,processStartTime:record.process_start}))continue;await fs.unlink(join(keys,name))}catch(cause){if(cause instanceof ProcessIdentityUnreadableError||cause instanceof RpcEndpointAuthError||cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")continue;throw cause}}}}var OBSERVE_REQUEST_FIELD="observe",ORIGIN_HOST_INSTANCE_FIELD="origin_host_instance",OBSERVING_COMMANDS=new Set(["get_protocol_info","list_sessions","subscribe_sessions","unsubscribe_sessions","get_effect_status","get_pending_inputs","get_subscription_limits"]);function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record=request;return record.type==="warm"||record.type==="authenticate"?!0:record[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record.type)}function originHostInstance(env=process.env){let instance=env[HOST_INSTANCE_ID_ENV]?.trim();return instance||void 0}function requestOriginHostInstance(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let origin=Reflect.get(request,ORIGIN_HOST_INSTANCE_FIELD);return typeof origin=="string"&&origin.length>0?origin:void 0}export{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV,OBSERVE_REQUEST_FIELD,ORIGIN_HOST_INSTANCE_FIELD,isObservingRequest,originHostInstance,requestOriginHostInstance,
|
|
4
|
+
`)}},this.agentDir=agentDir,this.endpoint=endpoint,this.recordPath=join(agentDir,"rpc","keys",this.launchId),this.ready=this.publication.promise,this.ready.catch(()=>{})}async publish(){try{await fs.mkdir(join(this.agentDir,"rpc"),{recursive:!0,mode:448}),await checkRpcKeyParents(this.agentDir);let keys=join(this.agentDir,"rpc","keys");await fs.mkdir(keys,{recursive:!0,mode:448});let directory=await fs.lstat(keys);if(!directory.isDirectory()||directory.uid!==process.getuid?.())throw new RpcEndpointAuthError("unsafe_key_record",keys);(directory.mode&4095)!==448&&await fs.chmod(keys,448),await checkRpcKeyDirectory(keys,!0);let handle=await fs.open(this.recordPath,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,384);this.created=!0,process.once("exit",this.exitCleanup);try{await handle.writeFile(JSON.stringify({version:1,launch_id:this.launchId,key:this.key.toString("hex"),pid:process.pid,process_start:await readProcessStartTime(process.pid)??null,endpoint:this.endpoint,created_at:new Date().toISOString()})),await handle.sync();let info=await handle.stat();if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&4095)!==384)throw new RpcEndpointAuthError("unsafe_key_record",this.recordPath)}finally{await handle.close()}this.publication.resolve()}catch(cause){let error=new RpcEndpointAuthError("key_publication_failed",cause instanceof RpcEndpointAuthError?cause.message:this.recordPath,{cause});throw this.publication.reject(error),error}}async dispose(){process.off("exit",this.exitCleanup),this.created&&(this.created=!1,await fs.unlink(this.recordPath).catch(cause=>{if(!(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT"))throw cause}))}};async function gcRpcPublicKeys(agentDir,budget={}){let keys=join(agentDir,"rpc","keys");try{await checkRpcKeyParents(agentDir),await checkRpcKeyDirectory(keys,!0)}catch(cause){if(cause instanceof RpcEndpointAuthError||cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return;throw cause}let names=await fs.readdir(keys).catch(cause=>{if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return[];throw cause}),examined=0;for(let name of names){if(Date.now()>=(budget.deadline??1/0)||examined>=(budget.maxRecords??1/0))break;if(RPC_LAUNCH_ID.test(name)){examined++;try{let record=await readRpcKeyRecord(agentDir,name);if(record===void 0||typeof record.pid!="number"||!Number.isSafeInteger(record.pid)||record.pid<=0||!(record.process_start===null||typeof record.process_start=="string")||await processMatchesPidFile({pid:record.pid,processStartTime:record.process_start}))continue;await fs.unlink(join(keys,name))}catch(cause){if(cause instanceof ProcessIdentityUnreadableError||cause instanceof RpcEndpointAuthError||cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")continue;throw cause}}}}var OBSERVE_REQUEST_FIELD="observe",ORIGIN_HOST_INSTANCE_FIELD="origin_host_instance",OBSERVING_COMMANDS=new Set(["get_protocol_info","list_sessions","subscribe_sessions","unsubscribe_sessions","get_effect_status","get_pending_inputs","get_subscription_limits","get_state","get_entries"]);function isObservingRequest(line){let request;try{request=JSON.parse(line)}catch{return!1}if(typeof request!="object"||request===null||Array.isArray(request))return!1;let record=request;return record.type==="warm"||record.type==="authenticate"?!0:record[OBSERVE_REQUEST_FIELD]===!0&&OBSERVING_COMMANDS.has(record.type)}function originHostInstance(env=process.env){let instance=env[HOST_INSTANCE_ID_ENV]?.trim();return instance||void 0}function requestOriginHostInstance(line){let request;try{request=JSON.parse(line)}catch{return}if(typeof request!="object"||request===null||Array.isArray(request))return;let origin=Reflect.get(request,ORIGIN_HOST_INSTANCE_FIELD);return typeof origin=="string"&&origin.length>0?origin:void 0}export{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV,OBSERVE_REQUEST_FIELD,ORIGIN_HOST_INSTANCE_FIELD,isObservingRequest,originHostInstance,requestOriginHostInstance,RPC_AUTH_CAPABILITY,RPC_AUTH_HEX,RPC_LAUNCH_ID,rpcAuthProof,rpcProofMatches,RpcEndpointAuthError,authRecord,readRpcKeyRecord,RpcPublicEndpoint,gcRpcPublicKeys};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import{listHostEndpoints}from"./chunk-LYGAV6KU.js";import{parseArgs,resolveSessionRuntime}from"./chunk-U67ML6CQ.js";import{PROBE_REQUEST_ID,connectAndAsk,isRecord as isRecord2,readAnswer,requestOnSocket}from"./chunk-YN7ELQ43.js";import{acquireOwnershipSafeLock,claimOwnerIsLive,hostChildAlive,isGenerationId,logUnknownHostIdentity,provenOwner,readDrainWatch,readGenerationRegistration,readHostRegistration,readSessionPathClaims,releaseGeneration,resolveHostPolicy,writeDrainRequest,writeStopIntent}from"./chunk-VNN2V74Y.js";import{HOST_DAEMON_LAYOUT,canonicalEndpointPath,createHostDaemonPaths,generationPaths,hostDaemonDirectoryPaths,isRecord,parseJson,readFileOrUndefined,sameEndpoint,writeStateFile}from"./chunk-4WZRVZNX.js";import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV,OBSERVE_REQUEST_FIELD,gcRpcPublicKeys}from"./chunk-WFXUCVIR.js";import{readSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{APP_NAME,VERSION,getAgentDir,isBunBinary}from"./chunk-7YO7VQZW.js";import{ProcessIdentityUnreadableError,parseDaemonPidFile,processIsLive,processMatchesPidFile,processStartTimeMs,readProcessStartTime}from"./chunk-O5RYI3IW.js";var CALVER=/^(\d+)\.(\d+)\.(\d+)(?:-(\d+))?/;function engineBuildIdentityFrom(build){let match=CALVER.exec(build.version),epoch=Number.isSafeInteger(build.epoch)&&build.epoch!==void 0&&build.epoch>0?build.epoch:0,sha7=build.sha7??"";return{text:epoch===0?build.version:`${build.version}+${epoch}${sha7===""?"":`.${sha7}`}`,ordinal:[match?Number(match[1]):0,match?Number(match[2]):0,match?Number(match[3]):0,match?.[4]?Number(match[4]):0,epoch],scheme:epoch===0?"nodef":"epoch"}}var BUILT=engineBuildIdentityFrom({version:VERSION,epoch:typeof SENPI_BUILD_EPOCH=="number"?SENPI_BUILD_EPOCH:0,sha7:typeof SENPI_BUILD_SHA7=="string"?SENPI_BUILD_SHA7:""});function engineBuildIdentity(){return BUILT}function compareEngineOrdinal(a,b){for(let index=0;index<4;index++)if(a.ordinal[index]!==b.ordinal[index])return a.ordinal[index]>b.ordinal[index]?1:-1;return a.scheme!=="epoch"||b.scheme!=="epoch"||a.ordinal[4]===b.ordinal[4]?0:a.ordinal[4]>b.ordinal[4]?1:-1}import*as crypto from"node:crypto";var CUSTOM_UNSUPPORTED_CAPABILITY="custom_unsupported",EXTENSION_EVENTS_CAPABILITY="extension_events",EVAL_CELLS_CAPABILITY="eval_cells",AUTO_TITLE_SESSIONS_CAPABILITY="auto_title_sessions",CONTINUE_FROM_LEAF_CAPABILITY="continue_from_leaf",SESSION_HELD_CAPABILITY="session_held",RESUME_SESSION_CAPABILITY="resume_session",ATTENDED_CAPABILITY="attended",MEDIA_PLACEHOLDERS_CAPABILITY="media_placeholders",QUESTION_CAPABILITY="question",TOOL_BARRIER_CAPABILITY="tool_barrier",SESSION_RELOCATION_CAPABILITY="session_relocation",RETAIN_ON_DISCONNECT_CAPABILITY="retain_on_disconnect",DETACH_CONNECTION_CAPABILITY="detach_connection",INTERACTIVE_USER_CAPABILITY="interactive_user",TASK_PARENT_CAPABILITY="task_parent",SESSION_CONTEXT_CAPABILITY="session_context",SESSION_KIND_CAPABILITY="session_kind",SESSION_STATUS_CAPABILITY="session_status",AUTO_TITLE_PER_SESSION_CAPABILITY="auto_title_per_session",WARM_CAPABILITY="warm",DURABLE_SESSION_ID_CAPABILITY="durable_session_id",MOVED_PATH_GUARD_CAPABILITY="moved_path_guard",PROMPT_SURFACE_CAPABILITY="prompt_surface",BROWSER_ENGINE_CAPABILITY="browser_engine",RETRY_FALLBACK_PROFILE_CAPABILITY="retry_fallback_profile",RETRY_FALLBACK_COMMAND_CAPABILITY="retry_fallback_command",PROMPT_SURFACE_CHAT_CAPABILITY="prompt_surface_chat",RPC_CLIENT_CAPABILITIES_ENV="SENPI_RPC_CLIENT_CAPABILITIES";function parseClientCapabilities(value){return value?value.split(",").map(part=>part.trim()).filter(part=>part.length>0):[]}var DEFAULT_CUSTOM_EXTENSION_LABEL="custom UI component";function buildCustomUnsupportedRequest(capabilities,extensionName){if(!capabilities?.includes(CUSTOM_UNSUPPORTED_CAPABILITY))return;let name=extensionName.trim()||DEFAULT_CUSTOM_EXTENSION_LABEL;return{type:"extension_ui_request",id:crypto.randomUUID(),method:"custom_unsupported",extensionName:name}}var AUTH_KEY_VERIFY_CAPABILITY="auth_key_verify",QUEUED_MESSAGE_REVISION_CAPABILITY="queued_message_revision";import{createHash}from"node:crypto";import{existsSync}from"node:fs";import{readdir,readFile,realpath,stat}from"node:fs/promises";import{basename,dirname,join,relative,sep}from"node:path";import{fileURLToPath}from"node:url";var RUNTIME_IDENTITY_HANDOVER_CAPABILITY="runtime_identity_handover",RUNTIME_BUILD_ID=/^sha256:[0-9a-f]{64}$/,EXCLUDED_FILE=/\.(?:d\.[cm]?ts|map)$/,EXCLUDED_NAMES=new Set(["node_modules","runtime-manifest.json","runtime-snapshot.json"]),READ_CONCURRENCY=32;function parseRuntimeBuildId(value){return typeof value=="string"&&RUNTIME_BUILD_ID.test(value)?value:void 0}async function computeRuntimeBuildId(input){let source=input.source??loadedRuntimeSource(),plugins=await Promise.all(input.profile.extensions.map(path=>extensionDigest(path))),manifest={schema:1,flavour:source.flavour,platform:input.platform??process.platform,arch:input.arch??process.arch,engine:input.engine??engineBuildIdentity().text,runtime:await treeDigest(source.root),plugins:plugins.sort(),profile:{multi_session:input.profile.multi_session,session_runtime:input.profile.session_runtime}};return`sha256:${sha256(JSON.stringify(manifest))}`}function loadedRuntimeSource(){if(isBunBinary)return{flavour:"compiled",root:process.execPath};let moduleDir=dirname(fileURLToPath(import.meta.url)),packageRoot=nearestPackageRoot(moduleDir),[top,next]=relative(packageRoot,moduleDir).split(sep);return top==="dist"?{flavour:"packaged",root:join(packageRoot,next==="bundle"?join("dist","bundle"):"dist")}:{flavour:"dev",root:join(packageRoot,top??"")}}function nearestPackageRoot(start){for(let dir=start;;dir=dirname(dir)){if(existsSync(join(dir,"package.json")))return dir;if(dirname(dir)===dir)return start}}function extensionDigest(path){let name=basename(path);return name.startsWith(BUILTIN_PATH_PREFIX)?Promise.resolve(sha256(name)):treeDigest(path)}async function treeDigest(root){let files=[];(await stat(root)).isFile()?files.push(["",root]):await collect(await realpath(root),"",files,new Set);let digests=await mapLimited(files,READ_CONCURRENCY,async([path,file])=>[path,sha256(await readFile(file))]);return digests.sort(([a],[b])=>a<b?-1:a>b?1:0),sha256(JSON.stringify(digests))}async function collect(dir,prefix,files,seen){if(seen.has(dir))return;seen.add(dir);let entries=(await readdir(dir,{withFileTypes:!0})).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);for(let entry of entries){if(entry.name.startsWith(".")||EXCLUDED_NAMES.has(entry.name))continue;let path=join(dir,entry.name),name=prefix===""?entry.name:`${prefix}/${entry.name}`,kind=entry.isSymbolicLink()?await stat(path).catch(()=>{}):entry;kind!==void 0&&(kind.isDirectory()?await collect(await realpath(path),name,files,seen):kind.isFile()&&!EXCLUDED_FILE.test(entry.name)&&files.push([name,path]))}}async function mapLimited(items,limit,map){let results=new Array(items.length),next=0,worker=async()=>{for(let index=next++;index<items.length;index=next++)results[index]=await map(items[index])};return await Promise.all(Array.from({length:Math.min(limit,items.length)},worker)),results}function sha256(data){return createHash("sha256").update(data).digest("hex")}function parseHostProtocolInfo(data){if(!isRecord3(data)||typeof data.serverVersion!="string"||!Array.isArray(data.capabilities)||!data.capabilities.every(entry=>typeof entry=="string"))return;let ordinal=parseOrdinal(data.engineOrdinal),launchProfile=parseLaunchProfile(data.launch_profile),runtimeBuildId=parseRuntimeBuildId(data.runtimeBuildId);return{protocolVersion:typeof data.protocolVersion=="number"?data.protocolVersion:0,serverVersion:data.serverVersion,capabilities:data.capabilities,...(data.lifecycle==="ready"||data.lifecycle==="stopping")&&{lifecycle:data.lifecycle},...typeof data.instanceId=="string"&&{instanceId:data.instanceId},...typeof data.generation=="number"&&Number.isSafeInteger(data.generation)&&{generation:data.generation},...typeof data.engineVersion=="string"&&{engineVersion:data.engineVersion},...ordinal&&{engineOrdinal:ordinal},...launchProfile&&{launch_profile:launchProfile},...typeof data.memory_pressure=="boolean"&&{memory_pressure:data.memory_pressure},...runtimeBuildId!==void 0&&{runtimeBuildId},...typeof data.agentDir=="string"&&data.agentDir!==""&&{agentDir:data.agentDir},...isRecord3(data.handover)&&{handover:data.handover}}}function parseOrdinal(value){if(!(!Array.isArray(value)||value.length!==5||!value.every(part=>typeof part=="number")))return[value[0],value[1],value[2],value[3],value[4]]}function parseLaunchProfile(value){if(!isRecord3(value)||typeof value.profile_id!="string"||!isRecord3(value.core))return;let{extensions,multi_session,session_runtime}=value.core;if(!(!Array.isArray(extensions)||!extensions.every(entry=>typeof entry=="string"))&&typeof multi_session=="boolean"&&!(session_runtime!=="in-process"&&session_runtime!=="worker"))return{profile_id:value.profile_id,core:{extensions,multi_session,session_runtime}}}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function describeHostHolder(holder){let engine=holder.engineVersion===null?"an unrecorded engine":`engine ${holder.engineVersion}`,profile=holder.launchProfileId===null?"":`, launch profile ${holder.launchProfileId}`,writer=holder.writerPid===null||holder.writerPid===holder.pid?"":`, started by pid ${holder.writerPid}`;return`pid ${holder.pid}, ${engine}${profile}${writer}`}var HOST_PROTOCOL_VERSION=1,GENERATION_HANDOFF_CAPABILITY="generation_handoff",REQUIRED_HOST_CAPABILITIES=["multi_session",EXTENSION_EVENTS_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY],HostEnsureRefusedError=class extends Error{constructor(socket,reason,host,detail,holder){let heldBy=holder?` (held by ${describeHostHolder(holder)})`:"";super(`RPC socket ${socket} refused: ${reason} - ${refusalDetail(reason,host)}${detail?`: ${detail}`:""}${heldBy}`),this.name="HostEnsureRefusedError",this.socket=socket,this.reason=reason,this.detail=detail,this.holder=holder}};function refusalDetail(reason,host){switch(reason){case"protocol":return`the running host speaks protocol version ${host?.protocolVersion??"unknown"}, this build speaks ${HOST_PROTOCOL_VERSION}`;case"capability":{let missing=REQUIRED_HOST_CAPABILITIES.filter(capability=>!host?.capabilities.includes(capability));return`the running host is missing ${JSON.stringify(missing)}; it owns the socket, so no second host is started`}case"foreign_writer":return"another process registered the host on this socket; it accepts connections but did not answer as a host, and this one may not signal it - stop that host explicitly (host stop --force), then ensure again";case"legacy_host":return"a host from before the per-socket daemon directory is still running; it is drained and replaced only while it holds no session, and no second host is started beside it";case"host_busy":return"its socket accepts connections but did not answer inside the probe budget: a live host under load, which is never ended to make room for a replacement";case"host_stopping":return"this generation is stopping; wait for its exit before launching a successor";case"endpoint_occupied":return"another process accepts connections on this socket but does not answer as a host, and no host registration names it; it is never removed while it listens, so quit the process holding it and ensure again";case"host_stalled":return"nothing reaches its socket, but its process is alive and its own loop-lag watchdog measured a recent stall: a stalled host is still serving its sessions, so it is neither stopped nor replaced";default:return assertNever(reason)}}function decideHostAction(client,host,policy){if(host===void 0)return{action:"start",reason:client.startedByUs?"restart_own_host":"no_host",upgradeable:!1};if(host.lifecycle==="stopping")return{action:"refuse",reason:"host_stopping",upgradeable:!1};if(host.protocolVersion!==client.protocolVersion)return{action:"refuse",reason:"protocol",upgradeable:!1};if(!client.requiredCapabilities.every(capability=>host.capabilities.includes(capability)))return policy==="fallback"?{action:"fallback",reason:"capability",upgradeable:!1}:{action:"refuse",reason:"capability",upgradeable:!1};let upgradeable=client.platform!=="win32"&&host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY);if(policy==="fallback"&&host.engineVersion!==client.identity.text)return{action:"fallback",reason:"engine_mismatch",upgradeable};let warning=profileWarning(client,host);return client.platform==="win32"?{action:"reuse",reason:"win32_attach_only",upgradeable:!1,...warning&&{warning}}:upgradeable?policy==="upgrade"&&client.launchProfile&&host.launch_profile&&supersedes(client,host)?{action:"handoff",reason:sameRelease(client.identity.ordinal,host.engineOrdinal)?"profile":"newer_engine",upgradeable:!0}:{action:"reuse",reason:"compatible",upgradeable,...warning&&{warning}}:{action:"reuse",reason:"handoff_unsupported",upgradeable:!1,...warning&&{warning}}}function supersedes(client,host){if(host.engineOrdinal===void 0)return!1;let hostIdentity={text:host.engineVersion??"",ordinal:host.engineOrdinal,scheme:host.engineOrdinal[4]>0?"epoch":"nodef"};return compareEngineOrdinal(client.identity,hostIdentity)<=0?!1:covers(client.launchProfile,host.launch_profile)}function profileWarning(client,host){if(client.launchProfile===void 0||host.launch_profile===void 0)return"profile_mismatch_attached";if(client.launchProfile.profile_id===host.launch_profile.profile_id)return;let clientCoversHost=covers(client.launchProfile,host.launch_profile);if(!(clientCoversHost&&covers(host.launch_profile,client.launchProfile)))return clientCoversHost?"profile_mismatch_attached":"profile_narrower_attached"}function extensionRole(extension){let segments=extension.split(/[\\/]+/),pluginAt=segments.lastIndexOf("plugin");return pluginAt<0?extension:segments.slice(pluginAt).join("/")}function covers(candidate,running){if(candidate===void 0||running===void 0)return!1;let candidateRoles=new Set(candidate.core.extensions.map(extensionRole));return running.core.extensions.every(extension=>candidateRoles.has(extensionRole(extension)))}function sameRelease(candidate,running){return running!==void 0&&candidate.slice(0,4).every((part,index)=>part===running[index])}function assertNever(value){throw new Error(`unreachable host decision: ${JSON.stringify(value)}`)}import{createHash as createHash2,randomUUID as randomUUID2}from"node:crypto";import{resolve}from"node:path";var INSTANCE_ID=resolveInstanceId(process.env[HOST_INSTANCE_ID_ENV]);function resolveInstanceId(value){return value!==void 0&&value.trim()!==""?value:randomUUID2()}function hostInstanceId(){return INSTANCE_ID}var cachedProfile;function hostGeneration(env){let value=env[HOST_GENERATION_ENV];return value!==void 0&&/^\d+$/.test(value)?Number(value):0}function hostLaunchProfile(argv,cwd){let parsed=parseArgs([...argv],{grokNeoEnabled:!1}),core={extensions:[...new Set((parsed.extensions??[]).map(path=>resolve(cwd,path)))].sort(),multi_session:parsed.multiSession===!0,session_runtime:resolveSessionRuntime(parsed)},canonical=JSON.stringify({extensions:core.extensions,multi_session:core.multi_session,session_runtime:core.session_runtime});return{profile_id:createHash2("sha256").update(canonical).digest("hex"),core}}function socketHostLaunchProfile(hostArgs,cwd){return hostLaunchProfile(["--mode","rpc","--multi-session","--listen","unix://",...hostArgs],cwd)}function protocolIdentity(agentDir=resolve(getAgentDir())){cachedProfile??=hostLaunchProfile(process.argv.slice(2),process.cwd());let build=engineBuildIdentity();return{instanceId:INSTANCE_ID,generation:hostGeneration(process.env),engineVersion:build.text,engineOrdinal:build.ordinal,launch_profile:cachedProfile,agentDir}}function holdAttachment(socket){return socket.removeAllListeners("data"),socket.resume(),socket.on("error",()=>socket.destroy()),socket.unref(),{release:()=>socket.destroy()}}var DEFAULT_PROBE_TIMEOUT_MS=1e4;function probeHost(options){return probeProtocolInfo(options.socket,options.timeoutMs??DEFAULT_PROBE_TIMEOUT_MS,options)}async function probeProtocolInfo(socketPath,timeoutMs,options={}){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info"},timeoutMs,options);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function observeProtocolInfo(socketPath,timeoutMs,options={}){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},timeoutMs,options);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function holdProtocolInfo(socketPath,timeoutMs,options={}){let outcome=await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"get_protocol_info"},timeoutMs,!0,options),info=outcome.answer===void 0?void 0:parseHostProtocolInfo(outcome.answer);if(outcome.kept===void 0)return;let hold=holdAttachment(outcome.kept);if(info!==void 0)return{info,hold};hold.release()}async function probeSocketReachable(socketPath,timeoutMs,options={}){return(await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"get_protocol_info"},timeoutMs,!1,options)).connected}async function probeSessionCount(socketPath,timeoutMs,options={}){return sessionCountOf(await requestOnSocket(socketPath,{type:"list_sessions",include_workers:!0},timeoutMs,options))}async function holdSessionCount(socketPath,timeoutMs,options={}){let outcome=await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"list_sessions",include_workers:!0},timeoutMs,!0,options),kept=outcome.kept;if(kept===void 0)return;let sessions=sessionCountOf(outcome.answer);if(sessions===void 0){kept.destroy();return}let asked=0;return{sessions,recount:recountTimeoutMs=>askAgain(kept,`${PROBE_REQUEST_ID}-recount-${++asked}`,recountTimeoutMs),close:()=>kept.destroy()}}function askAgain(socket,id,timeoutMs){return new Promise(resolveCount=>{let buffer="",finish=count=>{clearTimeout(timeout),socket.off("data",onData),socket.off("close",onClose),resolveCount(count)},onClose=()=>finish(void 0),onData=chunk=>{buffer+=chunk.toString("utf8");for(let newline=buffer.indexOf(`
|
|
2
|
+
import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import{listHostEndpoints}from"./chunk-PT6JJUN2.js";import{parseArgs,resolveSessionRuntime}from"./chunk-WD6WBYC5.js";import{PROBE_REQUEST_ID,connectAndAsk,isRecord as isRecord2,readAnswer,requestOnSocket}from"./chunk-KNVNKDER.js";import{acquireOwnershipSafeLock,claimOwnerIsLive,hostChildAlive,isGenerationId,logUnknownHostIdentity,provenOwner,readDrainWatch,readGenerationRegistration,readHostRegistration,readSessionPathClaims,releaseGeneration,resolveHostPolicy,writeDrainRequest,writeStopIntent}from"./chunk-BZ7726QO.js";import{HOST_DAEMON_LAYOUT,canonicalEndpointPath,createHostDaemonPaths,generationPaths,hostDaemonDirectoryPaths,isRecord,parseJson,readFileOrUndefined,sameEndpoint,writeStateFile}from"./chunk-4WZRVZNX.js";import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV,OBSERVE_REQUEST_FIELD,gcRpcPublicKeys}from"./chunk-SBGIXMX3.js";import{readSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{APP_NAME,VERSION,getAgentDir,isBunBinary}from"./chunk-7YO7VQZW.js";import{ProcessIdentityUnreadableError,parseDaemonPidFile,processIsLive,processMatchesPidFile,processStartTimeMs,readProcessStartTime}from"./chunk-O5RYI3IW.js";var CALVER=/^(\d+)\.(\d+)\.(\d+)(?:-(\d+))?/;function engineBuildIdentityFrom(build){let match=CALVER.exec(build.version),epoch=Number.isSafeInteger(build.epoch)&&build.epoch!==void 0&&build.epoch>0?build.epoch:0,sha7=build.sha7??"";return{text:epoch===0?build.version:`${build.version}+${epoch}${sha7===""?"":`.${sha7}`}`,ordinal:[match?Number(match[1]):0,match?Number(match[2]):0,match?Number(match[3]):0,match?.[4]?Number(match[4]):0,epoch],scheme:epoch===0?"nodef":"epoch"}}var BUILT=engineBuildIdentityFrom({version:VERSION,epoch:typeof SENPI_BUILD_EPOCH=="number"?SENPI_BUILD_EPOCH:0,sha7:typeof SENPI_BUILD_SHA7=="string"?SENPI_BUILD_SHA7:""});function engineBuildIdentity(){return BUILT}function compareEngineOrdinal(a,b){for(let index=0;index<4;index++)if(a.ordinal[index]!==b.ordinal[index])return a.ordinal[index]>b.ordinal[index]?1:-1;return a.scheme!=="epoch"||b.scheme!=="epoch"||a.ordinal[4]===b.ordinal[4]?0:a.ordinal[4]>b.ordinal[4]?1:-1}import*as crypto from"node:crypto";var CUSTOM_UNSUPPORTED_CAPABILITY="custom_unsupported",EXTENSION_EVENTS_CAPABILITY="extension_events",EVAL_CELLS_CAPABILITY="eval_cells",AUTO_TITLE_SESSIONS_CAPABILITY="auto_title_sessions",CONTINUE_FROM_LEAF_CAPABILITY="continue_from_leaf",SESSION_HELD_CAPABILITY="session_held",RESUME_SESSION_CAPABILITY="resume_session",ATTENDED_CAPABILITY="attended",MEDIA_PLACEHOLDERS_CAPABILITY="media_placeholders",QUESTION_CAPABILITY="question",TOOL_BARRIER_CAPABILITY="tool_barrier",SESSION_RELOCATION_CAPABILITY="session_relocation",RETAIN_ON_DISCONNECT_CAPABILITY="retain_on_disconnect",DETACH_CONNECTION_CAPABILITY="detach_connection",INTERACTIVE_USER_CAPABILITY="interactive_user",OBSERVE_READS_CAPABILITY="observe_reads",ENTRIES_TAIL_CAPABILITY="entries_tail",TUI_OBSERVER_CAPABILITY="tui_observer",TASK_PARENT_CAPABILITY="task_parent",SESSION_CONTEXT_CAPABILITY="session_context",SESSION_KIND_CAPABILITY="session_kind",SESSION_STATUS_CAPABILITY="session_status",AUTO_TITLE_PER_SESSION_CAPABILITY="auto_title_per_session",WARM_CAPABILITY="warm",DURABLE_SESSION_ID_CAPABILITY="durable_session_id",MOVED_PATH_GUARD_CAPABILITY="moved_path_guard",PROMPT_SURFACE_CAPABILITY="prompt_surface",BROWSER_ENGINE_CAPABILITY="browser_engine",RETRY_FALLBACK_PROFILE_CAPABILITY="retry_fallback_profile",RETRY_FALLBACK_COMMAND_CAPABILITY="retry_fallback_command",PROMPT_SURFACE_CHAT_CAPABILITY="prompt_surface_chat",RPC_CLIENT_CAPABILITIES_ENV="SENPI_RPC_CLIENT_CAPABILITIES";function parseClientCapabilities(value){return value?value.split(",").map(part=>part.trim()).filter(part=>part.length>0):[]}var DEFAULT_CUSTOM_EXTENSION_LABEL="custom UI component";function buildCustomUnsupportedRequest(capabilities,extensionName){if(!capabilities?.includes(CUSTOM_UNSUPPORTED_CAPABILITY))return;let name=extensionName.trim()||DEFAULT_CUSTOM_EXTENSION_LABEL;return{type:"extension_ui_request",id:crypto.randomUUID(),method:"custom_unsupported",extensionName:name}}var AUTH_KEY_VERIFY_CAPABILITY="auth_key_verify",QUEUED_MESSAGE_REVISION_CAPABILITY="queued_message_revision";import{createHash}from"node:crypto";import{existsSync}from"node:fs";import{readdir,readFile,realpath,stat}from"node:fs/promises";import{basename,dirname,join,relative,sep}from"node:path";import{fileURLToPath}from"node:url";var RUNTIME_IDENTITY_HANDOVER_CAPABILITY="runtime_identity_handover",RUNTIME_BUILD_ID=/^sha256:[0-9a-f]{64}$/,EXCLUDED_FILE=/\.(?:d\.[cm]?ts|map)$/,EXCLUDED_NAMES=new Set(["node_modules","runtime-manifest.json","runtime-snapshot.json"]),READ_CONCURRENCY=32;function parseRuntimeBuildId(value){return typeof value=="string"&&RUNTIME_BUILD_ID.test(value)?value:void 0}async function computeRuntimeBuildId(input){let source=input.source??loadedRuntimeSource(),plugins=await Promise.all(input.profile.extensions.map(path=>extensionDigest(path))),manifest={schema:1,flavour:source.flavour,platform:input.platform??process.platform,arch:input.arch??process.arch,engine:input.engine??engineBuildIdentity().text,runtime:await treeDigest(source.root),plugins:plugins.sort(),profile:{multi_session:input.profile.multi_session,session_runtime:input.profile.session_runtime}};return`sha256:${sha256(JSON.stringify(manifest))}`}function loadedRuntimeSource(){if(isBunBinary)return{flavour:"compiled",root:process.execPath};let moduleDir=dirname(fileURLToPath(import.meta.url)),packageRoot=nearestPackageRoot(moduleDir),[top,next]=relative(packageRoot,moduleDir).split(sep);return top==="dist"?{flavour:"packaged",root:join(packageRoot,next==="bundle"?join("dist","bundle"):"dist")}:{flavour:"dev",root:join(packageRoot,top??"")}}function nearestPackageRoot(start){for(let dir=start;;dir=dirname(dir)){if(existsSync(join(dir,"package.json")))return dir;if(dirname(dir)===dir)return start}}function extensionDigest(path){let name=basename(path);return name.startsWith(BUILTIN_PATH_PREFIX)?Promise.resolve(sha256(name)):treeDigest(path)}async function treeDigest(root){let files=[];(await stat(root)).isFile()?files.push(["",root]):await collect(await realpath(root),"",files,new Set);let digests=await mapLimited(files,READ_CONCURRENCY,async([path,file])=>[path,sha256(await readFile(file))]);return digests.sort(([a],[b])=>a<b?-1:a>b?1:0),sha256(JSON.stringify(digests))}async function collect(dir,prefix,files,seen){if(seen.has(dir))return;seen.add(dir);let entries=(await readdir(dir,{withFileTypes:!0})).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);for(let entry of entries){if(entry.name.startsWith(".")||EXCLUDED_NAMES.has(entry.name))continue;let path=join(dir,entry.name),name=prefix===""?entry.name:`${prefix}/${entry.name}`,kind=entry.isSymbolicLink()?await stat(path).catch(()=>{}):entry;kind!==void 0&&(kind.isDirectory()?await collect(await realpath(path),name,files,seen):kind.isFile()&&!EXCLUDED_FILE.test(entry.name)&&files.push([name,path]))}}async function mapLimited(items,limit,map){let results=new Array(items.length),next=0,worker=async()=>{for(let index=next++;index<items.length;index=next++)results[index]=await map(items[index])};return await Promise.all(Array.from({length:Math.min(limit,items.length)},worker)),results}function sha256(data){return createHash("sha256").update(data).digest("hex")}function parseHostProtocolInfo(data){if(!isRecord3(data)||typeof data.serverVersion!="string"||!Array.isArray(data.capabilities)||!data.capabilities.every(entry=>typeof entry=="string"))return;let ordinal=parseOrdinal(data.engineOrdinal),launchProfile=parseLaunchProfile(data.launch_profile),runtimeBuildId=parseRuntimeBuildId(data.runtimeBuildId);return{protocolVersion:typeof data.protocolVersion=="number"?data.protocolVersion:0,serverVersion:data.serverVersion,capabilities:data.capabilities,...(data.lifecycle==="ready"||data.lifecycle==="stopping")&&{lifecycle:data.lifecycle},...typeof data.instanceId=="string"&&{instanceId:data.instanceId},...typeof data.generation=="number"&&Number.isSafeInteger(data.generation)&&{generation:data.generation},...typeof data.engineVersion=="string"&&{engineVersion:data.engineVersion},...ordinal&&{engineOrdinal:ordinal},...launchProfile&&{launch_profile:launchProfile},...typeof data.memory_pressure=="boolean"&&{memory_pressure:data.memory_pressure},...runtimeBuildId!==void 0&&{runtimeBuildId},...typeof data.agentDir=="string"&&data.agentDir!==""&&{agentDir:data.agentDir},...isRecord3(data.handover)&&{handover:data.handover}}}function parseOrdinal(value){if(!(!Array.isArray(value)||value.length!==5||!value.every(part=>typeof part=="number")))return[value[0],value[1],value[2],value[3],value[4]]}function parseLaunchProfile(value){if(!isRecord3(value)||typeof value.profile_id!="string"||!isRecord3(value.core))return;let{extensions,multi_session,session_runtime}=value.core;if(!(!Array.isArray(extensions)||!extensions.every(entry=>typeof entry=="string"))&&typeof multi_session=="boolean"&&!(session_runtime!=="in-process"&&session_runtime!=="worker"))return{profile_id:value.profile_id,core:{extensions,multi_session,session_runtime}}}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function describeHostHolder(holder){let engine=holder.engineVersion===null?"an unrecorded engine":`engine ${holder.engineVersion}`,profile=holder.launchProfileId===null?"":`, launch profile ${holder.launchProfileId}`,writer=holder.writerPid===null||holder.writerPid===holder.pid?"":`, started by pid ${holder.writerPid}`;return`pid ${holder.pid}, ${engine}${profile}${writer}`}var HOST_PROTOCOL_VERSION=1,GENERATION_HANDOFF_CAPABILITY="generation_handoff",REQUIRED_HOST_CAPABILITIES=["multi_session",EXTENSION_EVENTS_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY],HostEnsureRefusedError=class extends Error{constructor(socket,reason,host,detail,holder){let heldBy=holder?` (held by ${describeHostHolder(holder)})`:"";super(`RPC socket ${socket} refused: ${reason} - ${refusalDetail(reason,host)}${detail?`: ${detail}`:""}${heldBy}`),this.name="HostEnsureRefusedError",this.socket=socket,this.reason=reason,this.detail=detail,this.holder=holder}};function refusalDetail(reason,host){switch(reason){case"protocol":return`the running host speaks protocol version ${host?.protocolVersion??"unknown"}, this build speaks ${HOST_PROTOCOL_VERSION}`;case"capability":{let missing=REQUIRED_HOST_CAPABILITIES.filter(capability=>!host?.capabilities.includes(capability));return`the running host is missing ${JSON.stringify(missing)}; it owns the socket, so no second host is started`}case"foreign_writer":return"another process registered the host on this socket; it accepts connections but did not answer as a host, and this one may not signal it - stop that host explicitly (host stop --force), then ensure again";case"legacy_host":return"a host from before the per-socket daemon directory is still running; it is drained and replaced only while it holds no session, and no second host is started beside it";case"host_busy":return"its socket accepts connections but did not answer inside the probe budget: a live host under load, which is never ended to make room for a replacement";case"host_stopping":return"this generation is stopping; wait for its exit before launching a successor";case"endpoint_occupied":return"another process accepts connections on this socket but does not answer as a host, and no host registration names it; it is never removed while it listens, so quit the process holding it and ensure again";case"host_stalled":return"nothing reaches its socket, but its process is alive and its own loop-lag watchdog measured a recent stall: a stalled host is still serving its sessions, so it is neither stopped nor replaced";default:return assertNever(reason)}}function decideHostAction(client,host,policy){if(host===void 0)return{action:"start",reason:client.startedByUs?"restart_own_host":"no_host",upgradeable:!1};if(host.lifecycle==="stopping")return{action:"refuse",reason:"host_stopping",upgradeable:!1};if(host.protocolVersion!==client.protocolVersion)return{action:"refuse",reason:"protocol",upgradeable:!1};if(!client.requiredCapabilities.every(capability=>host.capabilities.includes(capability)))return policy==="fallback"?{action:"fallback",reason:"capability",upgradeable:!1}:{action:"refuse",reason:"capability",upgradeable:!1};let upgradeable=client.platform!=="win32"&&host.capabilities.includes(GENERATION_HANDOFF_CAPABILITY);if(policy==="fallback"&&host.engineVersion!==client.identity.text)return{action:"fallback",reason:"engine_mismatch",upgradeable};let warning=profileWarning(client,host);return client.platform==="win32"?{action:"reuse",reason:"win32_attach_only",upgradeable:!1,...warning&&{warning}}:upgradeable?policy==="upgrade"&&client.launchProfile&&host.launch_profile&&supersedes(client,host)?{action:"handoff",reason:sameRelease(client.identity.ordinal,host.engineOrdinal)?"profile":"newer_engine",upgradeable:!0}:{action:"reuse",reason:"compatible",upgradeable,...warning&&{warning}}:{action:"reuse",reason:"handoff_unsupported",upgradeable:!1,...warning&&{warning}}}function supersedes(client,host){if(host.engineOrdinal===void 0)return!1;let hostIdentity={text:host.engineVersion??"",ordinal:host.engineOrdinal,scheme:host.engineOrdinal[4]>0?"epoch":"nodef"};return compareEngineOrdinal(client.identity,hostIdentity)<=0?!1:covers(client.launchProfile,host.launch_profile)}function profileWarning(client,host){if(client.launchProfile===void 0||host.launch_profile===void 0)return"profile_mismatch_attached";if(client.launchProfile.profile_id===host.launch_profile.profile_id)return;let clientCoversHost=covers(client.launchProfile,host.launch_profile);if(!(clientCoversHost&&covers(host.launch_profile,client.launchProfile)))return clientCoversHost?"profile_mismatch_attached":"profile_narrower_attached"}function extensionRole(extension){let segments=extension.split(/[\\/]+/),pluginAt=segments.lastIndexOf("plugin");return pluginAt<0?extension:segments.slice(pluginAt).join("/")}function covers(candidate,running){if(candidate===void 0||running===void 0)return!1;let candidateRoles=new Set(candidate.core.extensions.map(extensionRole));return running.core.extensions.every(extension=>candidateRoles.has(extensionRole(extension)))}function sameRelease(candidate,running){return running!==void 0&&candidate.slice(0,4).every((part,index)=>part===running[index])}function assertNever(value){throw new Error(`unreachable host decision: ${JSON.stringify(value)}`)}import{createHash as createHash2,randomUUID as randomUUID2}from"node:crypto";import{resolve}from"node:path";var INSTANCE_ID=resolveInstanceId(process.env[HOST_INSTANCE_ID_ENV]);function resolveInstanceId(value){return value!==void 0&&value.trim()!==""?value:randomUUID2()}function hostInstanceId(){return INSTANCE_ID}var cachedProfile;function hostGeneration(env){let value=env[HOST_GENERATION_ENV];return value!==void 0&&/^\d+$/.test(value)?Number(value):0}function hostLaunchProfile(argv,cwd){let parsed=parseArgs([...argv],{grokNeoEnabled:!1}),core={extensions:[...new Set((parsed.extensions??[]).map(path=>resolve(cwd,path)))].sort(),multi_session:parsed.multiSession===!0,session_runtime:resolveSessionRuntime(parsed)},canonical=JSON.stringify({extensions:core.extensions,multi_session:core.multi_session,session_runtime:core.session_runtime});return{profile_id:createHash2("sha256").update(canonical).digest("hex"),core}}function socketHostLaunchProfile(hostArgs,cwd){return hostLaunchProfile(["--mode","rpc","--multi-session","--listen","unix://",...hostArgs],cwd)}function protocolIdentity(agentDir=resolve(getAgentDir())){cachedProfile??=hostLaunchProfile(process.argv.slice(2),process.cwd());let build=engineBuildIdentity();return{instanceId:INSTANCE_ID,generation:hostGeneration(process.env),engineVersion:build.text,engineOrdinal:build.ordinal,launch_profile:cachedProfile,agentDir}}function holdAttachment(socket){return socket.removeAllListeners("data"),socket.resume(),socket.on("error",()=>socket.destroy()),socket.unref(),{release:()=>socket.destroy()}}var DEFAULT_PROBE_TIMEOUT_MS=1e4;function probeHost(options){return probeProtocolInfo(options.socket,options.timeoutMs??DEFAULT_PROBE_TIMEOUT_MS,options)}async function probeProtocolInfo(socketPath,timeoutMs,options={}){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info"},timeoutMs,options);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function observeProtocolInfo(socketPath,timeoutMs,options={}){let reply=await requestOnSocket(socketPath,{type:"get_protocol_info",[OBSERVE_REQUEST_FIELD]:!0},timeoutMs,options);return reply===void 0?void 0:parseHostProtocolInfo(reply)}async function holdProtocolInfo(socketPath,timeoutMs,options={}){let outcome=await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"get_protocol_info"},timeoutMs,!0,options),info=outcome.answer===void 0?void 0:parseHostProtocolInfo(outcome.answer);if(outcome.kept===void 0)return;let hold=holdAttachment(outcome.kept);if(info!==void 0)return{info,hold};hold.release()}async function probeSocketReachable(socketPath,timeoutMs,options={}){return(await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"get_protocol_info"},timeoutMs,!1,options)).connected}async function probeSessionCount(socketPath,timeoutMs,options={}){return sessionCountOf(await requestOnSocket(socketPath,{type:"list_sessions",include_workers:!0},timeoutMs,options))}async function holdSessionCount(socketPath,timeoutMs,options={}){let outcome=await connectAndAsk(socketPath,{id:PROBE_REQUEST_ID,type:"list_sessions",include_workers:!0},timeoutMs,!0,options),kept=outcome.kept;if(kept===void 0)return;let sessions=sessionCountOf(outcome.answer);if(sessions===void 0){kept.destroy();return}let asked=0;return{sessions,recount:recountTimeoutMs=>askAgain(kept,`${PROBE_REQUEST_ID}-recount-${++asked}`,recountTimeoutMs),close:()=>kept.destroy()}}function askAgain(socket,id,timeoutMs){return new Promise(resolveCount=>{let buffer="",finish=count=>{clearTimeout(timeout),socket.off("data",onData),socket.off("close",onClose),resolveCount(count)},onClose=()=>finish(void 0),onData=chunk=>{buffer+=chunk.toString("utf8");for(let newline=buffer.indexOf(`
|
|
3
3
|
`);newline!==-1;newline=buffer.indexOf(`
|
|
4
4
|
`)){let answer=readAnswer(buffer.slice(0,newline),id);if(buffer=buffer.slice(newline+1),answer!==void 0){finish(sessionCountOf(answer));return}}},timeout=setTimeout(()=>finish(void 0),timeoutMs);if(socket.destroyed){finish(void 0);return}socket.on("data",onData),socket.once("close",onClose),socket.write(`${JSON.stringify({id,type:"list_sessions",include_workers:!0})}
|
|
5
5
|
`)})}function sessionCountOf(reply){return isRecord2(reply)&&Array.isArray(reply.sessions)?reply.sessions.length:void 0}import{createHash as createHash3}from"node:crypto";import{mkdir,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{dirname as dirname2,join as join2}from"node:path";var LOCK_BUSY_WAIT_MS=100;function hostEnsureLockTarget(socket){return join2(tmpdir(),"senpi-rpc-host-locks",createSocketLockName(socket))}async function acquireHostEnsureLock(socket,waitMs){let lockTarget=hostEnsureLockTarget(socket);return await mkdir(dirname2(lockTarget),{recursive:!0}),await writeFile(lockTarget,"",{flag:"a",mode:384}),acquireOwnershipSafeLock(`${lockTarget}.lock`,hostEnsureLockOptions(waitMs))}function hostEnsureLockOptions(waitMs){return{retries:{retries:Math.ceil(waitMs/LOCK_BUSY_WAIT_MS),minTimeout:20,maxTimeout:LOCK_BUSY_WAIT_MS}}}function createSocketLockName(socket){return createHash3("sha256").update(socketLockAddress(socket),"utf8").digest("hex").slice(0,32)}function socketLockAddress(socket){return process.platform==="win32"||socket.startsWith("\0")?resolveSocketTransportAddress(socket,process.platform):canonicalEndpointPath(socket)}import{randomUUID as randomUUID3}from"node:crypto";import{access,link,readdir as readdir2,rm}from"node:fs/promises";async function electPointer(paths,options={}){let text=await readFileOrUndefined(paths.pointerFile).catch(()=>{});if(text!==void 0){let instanceId=parseJson(text)?.instance_id;return typeof instanceId=="string"?{state:"current",instanceId,candidates:[]}:{state:"missing",instanceId:null,candidates:[]}}let candidates=await provenLiveGenerations(paths),ids=candidates.map(candidate=>candidate.instanceId),[only]=candidates;return only===void 0||candidates.length>1||options.write===!1?{state:"missing",instanceId:null,candidates:ids}:await linkPointer(paths,only)?{state:"elected",instanceId:only.instanceId,candidates:ids}:electPointer(paths,{write:!1})}async function provenLiveGenerations(paths){let found=[];for(let instanceId of(await readdir2(paths.generationsDir).catch(()=>[])).sort()){let generation=generationPaths(paths,instanceId);if(await exists(generation.stopIntentFile)||await exists(generation.drainRequestFile))continue;let text=await readFileOrUndefined(generation.pidFile).catch(()=>{}),record=text===void 0?void 0:parseDaemonPidFile(text),parsed=parseJson(text);if(record===void 0||record.processStartTime===null||parsed?.instance_id!==instanceId||typeof parsed.socket!="string"||!sameEndpoint(parsed.socket,paths.socket))continue;let identity={pid:record.pid,processStartTime:record.processStartTime};await processMatchesPidFile(identity,readProcessStartTime).catch(()=>!1)&&found.push({instanceId,writer:parsed.writer})}return found}async function linkPointer(paths,candidate){let staged=`${paths.pointerFile}.elect-${process.pid}-${randomUUID3()}.tmp`;try{return await writeStateFile(staged,{layout:HOST_DAEMON_LAYOUT,instance_id:candidate.instanceId,generation_dir:generationPaths(paths,candidate.instanceId).relativeDir,...isRecord(candidate.writer)&&{writer:candidate.writer}}),await link(staged,paths.pointerFile),!0}catch{return!1}finally{await rm(staged,{force:!0}).catch(()=>{})}}async function exists(path){return access(path).then(()=>!0,()=>!1)}import{dirname as dirname3,join as join3}from"node:path";var LEGACY_PROBE_TIMEOUT_MS=1e4,DRAIN_POLL_MS=50;async function retireIdleLegacyHost(paths,probe,drainTimeoutMs=LEGACY_PROBE_TIMEOUT_MS){let judged=await judgeLegacyHost(paths,probe);if(judged.verdict==="absent")return;if(judged.verdict==="held")return judged.detail;let{record,socket}=judged.host;if(!await drainAndWait(record,probe,drainTimeoutMs))return`pid ${record.pid} (${socket}) was asked to drain and is still running after ${drainTimeoutMs}ms; retry once it exits`}async function readLegacyHost(paths){let text=await readFileOrUndefined(paths.legacyPidFile),record=text===void 0?void 0:parseDaemonPidFile(text);if(record===void 0)return;let stamped=parseJson(text)?.socket;return{record,socket:typeof stamped=="string"?stamped:join3(dirname3(paths.flatDir),"rpc","rpc.sock")}}async function provenLegacyOwner(paths,socket){let legacy=await readLegacyHost(paths),startTime=legacy?.record.processStartTime;if(!legacy||startTime===null||startTime===void 0||!sameEndpoint(legacy.socket,socket))return;let identity={pid:legacy.record.pid,processStartTime:startTime};return await processMatchesPidFile(identity,readProcessStartTime).catch(error=>(error instanceof ProcessIdentityUnreadableError&&logUnknownHostIdentity("legacy_host.pid",identity.pid),!1))?identity:void 0}async function judgeLegacyHost(paths,probe,platform=process.platform){let host=await readLegacyHost(paths);if(host===void 0)return{verdict:"absent"};let{pid}=host.record,identity=await processMatchesPidFile(host.record,probe).then(owns=>owns?"proven":"gone",error=>{if(error instanceof ProcessIdentityUnreadableError)return"unreadable";throw error});if(identity==="gone")return{verdict:"absent"};let where=`pid ${pid} (${host.socket})`;if(identity==="unreadable")return logUnknownHostIdentity("legacy_host.pid",pid),{verdict:"held",detail:`${where} cannot be proven to be the process its record names; stop it by hand`};if(platform==="win32")return{verdict:"held",detail:`${where} cannot be drained on win32; it exits once idle, then retry`};let protocol=await probeProtocolInfo(host.socket,LEGACY_PROBE_TIMEOUT_MS);if(!protocol?.capabilities.includes(GENERATION_HANDOFF_CAPABILITY))return{verdict:"held",detail:`${where} ${protocol?"cannot drain":"does not answer"}; it is never signalled - stop it by hand, then retry`};let sessions=await probeSessionCount(host.socket,LEGACY_PROBE_TIMEOUT_MS);return sessions===0?{verdict:"idle",host}:{verdict:"held",detail:busyLegacyHostDetail(pid,host.socket,sessions)}}function busyLegacyHostDetail(pid,socket,sessions){return`pid ${pid} (${socket}) holds ${describeSessions(sessions)}; run \`${APP_NAME} host stop --drain --socket ${socket}\` to let it finish that work and exit, then retry`}function describeSessions(sessions){return sessions===void 0?"an unknown number of sessions":`${sessions} open session${sessions===1?"":"s"}`}async function drainAndWait(record,probe,timeoutMs){try{process.kill(record.pid,"SIGUSR1")}catch(error){if(!(error instanceof Error&&"code"in error&&error.code==="ESRCH"))throw error}let stillRunning=()=>processMatchesPidFile(record,probe,processIsLive,{attempts:1}).catch(error=>{if(error instanceof ProcessIdentityUnreadableError)return!0;throw error}),deadline=Date.now()+timeoutMs;for(;await stillRunning();){if(Date.now()>deadline)return!1;await new Promise(resolve2=>setTimeout(resolve2,DRAIN_POLL_MS))}return!0}var EXIT_POLL_MS=100;async function drainHost(paths,options){let named=options.instanceId;if(named!==void 0&&!isGenerationId(named))return{action:"refuse",reason:"unknown_owner"};let registered=named===void 0?await readHostRegistration(paths):await readGenerationRegistration(paths,named),owner=await provenOwner(registered,options.socket);if(owner!==void 0){let generation=generationPaths(paths,owner.instanceId);if((await readDrainWatch(generation.drainWatchFile))?.pid===owner.pid)return await writeDrainRequest(generation.drainRequestFile,{sender:{pid:process.pid,kind:"stop"},reason:"operator_drain"}).catch(cause=>{if(cause.code!=="ENOENT")throw cause}),drained({...owner},options.waitMs)}if(named!==void 0&&owner===void 0)return{action:"refuse",reason:"unknown_owner"};let pid=owner?.pid??(await provenLegacyOwner(paths,options.socket))?.pid;if(pid===void 0)return{action:"refuse",reason:"unknown_owner"};let host=await probeProtocolInfo(options.socket,options.timeoutMs??1e4),answersAsTarget=named===void 0||host?.instanceId===named;return!host?.capabilities.includes(GENERATION_HANDOFF_CAPABILITY)||!answersAsTarget||process.platform==="win32"?{action:"refuse",reason:"drain_unsupported"}:(signalDrain(pid),drained(owner??{pid,processStartTime:void 0},options.waitMs))}async function drained(owner,waitMs){let base={action:"drained",pid:owner.pid,...owner.instanceId&&{instanceId:owner.instanceId}};return waitMs===void 0?base:{...base,exited:await waitForExit(owner,waitMs)}}async function waitForExit(owner,waitMs){let deadline=Date.now()+waitMs;for(;;){if(await exitedNow(owner))return!0;if(Date.now()>=deadline)return!1;await new Promise(resolve2=>setTimeout(resolve2,EXIT_POLL_MS))}}async function exitedNow(owner){if(!processIsLive(owner.pid))return!0;if(owner.processStartTime===void 0)return!1;let identity={pid:owner.pid,processStartTime:owner.processStartTime};return processMatchesPidFile(identity,readProcessStartTime).then(same=>!same,error=>{if(error instanceof ProcessIdentityUnreadableError)return!1;throw error})}function signalDrain(pid){try{process.kill(pid,"SIGUSR1")}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ESRCH")return;throw error}}import{stat as stat2}from"node:fs/promises";function processStartTimeIsUnreadable(){return process.platform==="win32"}var STOP_START_TIME_BUDGET_MS=1e4;function readLiveStartTime(pid){return readProcessStartTime(pid,process.platform,STOP_START_TIME_BUDGET_MS)}async function startedBeforeRegistration(pid,registrationFile){let live=await readLiveStartTime(pid).catch(()=>{}),startedMs=live===void 0?void 0:processStartTimeMs(live);if(startedMs===void 0)return!1;let written=await stat2(registrationFile).catch(()=>{});return written!==void 0&&startedMs<=written.mtimeMs}function parseHostStopGeneration(text){let value=parseJson(text);if(!(!value||typeof value.instanceId!="string"||value.instanceId.length===0||typeof value.generation!="number"||!Number.isSafeInteger(value.generation)||value.generation<0||typeof value.pid!="number"||!Number.isSafeInteger(value.pid)||value.pid<=0||!(value.processStartTime===null||typeof value.processStartTime=="string"&&value.processStartTime.length>0)))return{instanceId:value.instanceId,generation:value.generation,pid:value.pid,processStartTime:value.processStartTime}}function compareStopGeneration(registered,expected){if(registered?.instanceId!==expected.instanceId||registered.generation!==expected.generation||registered.record.pid!==expected.pid)return"stale";let recorded=registered.record.processStartTime;return recorded!==null&&expected.processStartTime!==null?recorded===expected.processStartTime?"proven":"stale":recorded===null&&expected.processStartTime===null&&processStartTimeIsUnreadable()?"bound_without_start_time":"unprovable"}async function stopHost(options){if(options.expectedGeneration!==void 0&&options.drain===!0)throw new TypeError("stopHost: expectedGeneration binds a hard stop and cannot be combined with drain");if(options.expectedGeneration===void 0)return stopHostLocked(options);let release=await acquireHostEnsureLock(options.socket,3e4);try{return await stopHostLocked(options)}finally{await release()}}async function stopHostLocked(options){let paths=createHostDaemonPaths({socket:options.socket,...options.agentDir?{agentDir:options.agentDir}:{}});await electPointer(paths);let expected=options.expectedGeneration;if(expected!==void 0){let refusal=generationRefusal(compareStopGeneration(await readHostRegistration(paths),expected));if(refusal!==void 0)return refusal}if(options.drain===!0)return drainHost(paths,{socket:options.socket,...options.instanceId!==void 0&&{instanceId:options.instanceId},...options.waitMs!==void 0&&{waitMs:options.waitMs},...options.timeoutMs!==void 0&&{timeoutMs:options.timeoutMs}});let owner=expected===void 0?await provenOwner(await readHostRegistration(paths),options.socket):void 0;if(expected===void 0&&!owner)return{action:"refuse",reason:"unknown_owner"};let host=await probeProtocolInfo(options.socket,options.timeoutMs??1e4),sessions=await probeSessionCount(options.socket,options.timeoutMs??1e4);if(options.force!==!0&&host!==void 0&&sessions!==void 0&&sessions>0)return{action:"refuse",reason:"sessions_live"};if(options.requireAnswer===!0&&(host===void 0||sessions===void 0))return{action:"refuse",reason:"sessions_live"};let target=expected===void 0?owner:await recheckedTarget(paths,options.socket,expected,host);return target===void 0?{action:"refuse",reason:"unknown_owner"}:"action"in target?target:(await writeStopIntent(generationPaths(paths,target.instanceId),{sender:{pid:process.pid,kind:"stop"},targetPid:target.pid,reason:"operator_stop",signal:"SIGTERM",at:new Date().toISOString()}),signalGeneration(target.pid,"SIGTERM")||await releaseGeneration(paths,{instanceId:target.instanceId,pid:target.pid}),{action:"stopped",pid:target.pid})}function generationRefusal(match){if(match==="stale")return{action:"refuse",reason:"stale_generation"};if(match==="unprovable")return{action:"refuse",reason:"unknown_owner"}}async function staleStopGeneration(socket,agentDir,expected){let paths=createHostDaemonPaths({socket,...agentDir?{agentDir}:{}});return generationRefusal(compareStopGeneration(await readHostRegistration(paths),expected))}async function recheckedTarget(paths,socket,expected,host){let current=await readHostRegistration(paths),match=compareStopGeneration(current,expected),refusal=generationRefusal(match);if(refusal!==void 0)return refusal;if(!(match==="proven"&&!await provenOwner(current,socket))){if(match==="bound_without_start_time"){if(current?.socket!==void 0&&!sameEndpoint(current.socket,socket)||!await startedBeforeRegistration(expected.pid,generationPaths(paths,expected.instanceId).pidFile))return;if(host?.instanceId!==void 0&&host.instanceId!==expected.instanceId)return{action:"refuse",reason:"stale_generation"}}return{pid:expected.pid,instanceId:expected.instanceId}}}function signalGeneration(pid,signal){try{return process.kill(pid,signal),!0}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ESRCH")return!1;throw error}}import{lstat as lstat2,rm as rm2}from"node:fs/promises";import{dirname as dirname5,join as join6}from"node:path";import{lstat,readdir as readdir3}from"node:fs/promises";import{createConnection}from"node:net";import{basename as basename2,dirname as dirname4,join as join4}from"node:path";var SOCKET_PROBE_TIMEOUT_MS=2e3;async function endpointInUse(paths,socket){if(await anyGenerationLive(paths))return{inUse:"live_generation"};for(let claim of await readSessionPathClaims(paths.reservationsDir))if(await claimOwnerIsLive(claim.owner))return{inUse:"live_claim"};let silence=await socketSilence(socket);if(silence===void 0)return{inUse:"reachable"};let successors=(await socketSiblings(socket)).filter(name=>name.startsWith(`${basename2(socket)}.next-`));for(let successor of successors)if(await socketSilence(join4(dirname4(socket),successor))===void 0)return{inUse:"reachable"};return{inUse:void 0,silence}}async function socketSiblings(socket){let name=basename2(socket);return(await readdir3(dirname4(socket)).catch(()=>[])).filter(entry=>entry.startsWith(`${name}.next-`)||entry.startsWith(`${name}.shield-`))}async function anyGenerationLive(paths){for(let instanceId of await readdir3(paths.generationsDir).catch(()=>[])){if(await hostChildAlive(generationPaths(paths,instanceId)))return!0;let record=generationRecord(await readFileOrUndefined(generationPaths(paths,instanceId).pidFile));if(record!==void 0&&await recordIsLive(record))return!0}return!1}function generationRecord(text){if(text===void 0)return;let record=parseDaemonPidFile(text);if(record!==void 0)return record;let pid=parseJson(text)?.pid;return typeof pid=="number"&&Number.isInteger(pid)&&pid>0?{pid,processStartTime:null}:void 0}async function recordIsLive(record){try{return await processMatchesPidFile(record)}catch(error){if(error instanceof ProcessIdentityUnreadableError)return!0;throw error}}async function socketSilence(socket){let secret;return process.platform==="win32"&&(secret=await readSocketSecret(socketSecretPath(socket)).catch(()=>{}),secret===void 0)?"socket_absent":new Promise(resolveProbe=>{let connection=createConnection(resolveSocketTransportAddress(socket,process.platform,secret)),finish=value=>{clearTimeout(timeout),connection.destroy(),resolveProbe(value)},timeout=setTimeout(()=>finish(void 0),SOCKET_PROBE_TIMEOUT_MS);connection.once("connect",()=>finish(void 0)),connection.once("error",error=>{error.code==="ECONNREFUSED"?refusedBySocket(socket).then(finish):error.code==="ENOENT"?finish("socket_absent"):finish(void 0)})})}async function refusedBySocket(socket){if(process.platform==="win32"||socket.startsWith("\0"))return"socket_refused";try{return(await lstat(socket)).isSocket()?"socket_refused":void 0}catch(error){return error instanceof Error&&"code"in error&&error.code==="ENOENT"?"socket_absent":void 0}}import{execFile}from"node:child_process";import{readdir as readdir4,readFile as readFile2,readlink,realpath as realpath2}from"node:fs/promises";import{join as join5}from"node:path";var LSOF_TIMEOUT_MS=2e3,LINUX_ACCEPTCON_FLAG=65536;async function countPublicClients(supervisorPid,socket){let names=new Set([socket,await realpath2(socket).catch(()=>socket)]),descriptors=process.platform==="darwin"?await darwinDescriptors(supervisorPid,names):process.platform==="linux"?await linuxDescriptors(supervisorPid,names):void 0;if(!(descriptors===void 0||descriptors.listeners===0))return descriptors.total-descriptors.listeners}function darwinDescriptors(pid,names){return new Promise(resolve2=>{execFile("lsof",["-a","-p",String(pid),"-U","-w","-F","n"],{timeout:LSOF_TIMEOUT_MS},(error,stdout)=>{if(error)return resolve2(void 0);let total=stdout.split(`
|
|
6
6
|
`).filter(line=>line.startsWith("n")&&names.has(line.slice(1))).length;resolve2({total,listeners:total>0?1:0})})})}async function linuxDescriptors(pid,names){try{let inodes=new Set;for(let fd of await readdir4(join5("/proc",String(pid),"fd"))){let target=await readlink(join5("/proc",String(pid),"fd",fd)).catch(()=>""),inode=/^socket:\[(\d+)\]$/.exec(target)?.[1];inode!==void 0&&inodes.add(inode)}let total=0,listeners=0;for(let line of(await readFile2("/proc/net/unix","utf8")).split(`
|
|
7
|
-
`).slice(1)){let fields=line.trim().split(/\s+/),[flags,inode,path]=[fields[3],fields[6],fields[7]];inode===void 0||path===void 0||!inodes.has(inode)||!names.has(path)||(total+=1,(Number.parseInt(flags??"0",16)&LINUX_ACCEPTCON_FLAG)!==0&&(listeners+=1))}return{total,listeners}}catch{return}}var STALE_ENGINE_GRACE_MS=10*6e4,PROBE_TIMEOUT_MS=2e3;async function judgeStaleEngine(socket,agentDir,client,options={}){let paths=createHostDaemonPaths({socket,agentDir}),owner=await provenOwner(await readHostRegistration(paths),socket);if(owner===void 0)return keep("stale_unproven_owner");let clients=await countPublicClients(owner.pid,socket),info=await observeProtocolInfo(socket,PROBE_TIMEOUT_MS);if(info===void 0)return keep("stale_unreachable");let hostOrdinal=info.engineOrdinal,hostIdentity=hostOrdinal===void 0?void 0:{text:info.engineVersion??"",ordinal:hostOrdinal,scheme:hostOrdinal[4]>0?"epoch":"nodef"};if(hostIdentity===void 0||compareEngineOrdinal(hostIdentity,client)!==-1)return keep("stale_not_older");let policy=resolveHostPolicy(parseJson(await readFileOrUndefined(paths.settingsFile)),{});if(policy.coldStart==="persistent")return keep("stale_persistent");if(await observedSessionCount(socket)!==0)return keep("stale_sessions");if((await readSessionPathClaims(paths.reservationsDir)).length>0)return keep("stale_claims");let startedAt=processStartTimeMs(owner.processStartTime),now=(options.now??Date.now)();return startedAt===void 0||now-startedAt<policy.idleExitMs+(options.graceMs??STALE_ENGINE_GRACE_MS)?keep("stale_young"):clients!==0?keep("stale_clients"):{stale:!0,pid:owner.pid}}function keep(reason){return{stale:!1,reason}}async function observedSessionCount(socket){let reply=await requestOnSocket(socket,{type:"list_sessions",include_workers:!0,[OBSERVE_REQUEST_FIELD]:!0},PROBE_TIMEOUT_MS);if(typeof reply!="object"||reply===null)return;let sessions=Reflect.get(reply,"sessions");return Array.isArray(sessions)?sessions.length:void 0}var GC_LOCK_WAIT_MS=2e3;async function gcHostEndpoints(agentDir,options={}){process.platform!=="win32"&&await gcRpcPublicKeys(agentDir);let removed=[],stopped=[],kept=[],wanted=kind=>options.kinds===void 0||options.kinds.includes(kind),legacy=wanted("rpc_host")?await legacyFlatDirectory(agentDir):void 0;legacy!==void 0&&kept.push({socket:null,dir:legacy,reason:"legacy_layout"});for(let endpoint of await listHostEndpoints(agentDir)){if(!wanted(endpoint.endpoint_kind))continue;if(endpoint.socket===null){kept.push({socket:null,dir:endpoint.dir,reason:"unknown_identity"});continue}let entry={socket:endpoint.socket,dir:endpoint.dir};try{let outcome=await gcEndpoint(endpoint.socket,endpoint.dir,options);"stopped"in outcome?stopped.push({...entry,reason:"stale_old_engine",pid:outcome.pid}):outcome.removed?outcome.skipped.length===0?removed.push({...entry,reason:outcome.reason}):removed.push({...entry,reason:outcome.reason,skipped:outcome.skipped}):kept.push({...entry,reason:outcome.reason})}catch(error){kept.push({...entry,reason:"failed",error:error instanceof Error?error.message:String(error)})}}return stopped.length===0?{removed,kept}:{removed,stopped,kept}}async function gcEndpoint(socket,dir,options){let release=await acquireEnsureLock(socket);if(release===void 0)return{removed:!1,reason:"locked"};try{await options._test?.afterLockAcquired?.(socket);let evidence=await endpointInUse(hostDaemonDirectoryPaths(dir),socket);if(evidence.inUse==="live_claim"||evidence.inUse!==void 0&&options.staleEngine===void 0)return{removed:!1,reason:evidence.inUse};if(evidence.inUse!==void 0)return await stopIfStale(socket,dir,evidence.inUse,options.staleEngine??{});let skipped=await removeEndpoint(socket,dir);return{removed:!0,reason:evidence.silence,skipped}}finally{await release()}}var NOT_A_CANDIDATE=new Set(["stale_unproven_owner","stale_unreachable","stale_not_older"]),STALE_STOP_TIMEOUT_MS=2e3;async function stopIfStale(socket,dir,inUse,options){let agentDir=dirname5(dirname5(dir)),verdict=await judgeStaleEngine(socket,agentDir,options.client??engineBuildIdentity(),options);if(!verdict.stale)return{removed:!1,reason:NOT_A_CANDIDATE.has(verdict.reason)?inUse:verdict.reason};let result=await stopHost({socket,agentDir,timeoutMs:STALE_STOP_TIMEOUT_MS,requireAnswer:!0});return result.action==="refuse"?{removed:!1,reason:result.reason==="unknown_owner"?"stale_unproven_owner":"stale_sessions"}:{removed:!1,stopped:!0,pid:result.pid}}async function removeEndpoint(socket,dir){let skipped=[];for(let sibling of await socketSiblings(socket)){let path=join6(dirname5(socket),sibling),entry=await lstat2(path).catch(error=>{if(!(error instanceof Error&&"code"in error&&error.code==="ENOENT"))throw error});entry?.isDirectory()?skipped.push({path,type:"directory"}):entry!==void 0&&await rm2(path,{force:!0})}return await rm2(socket,{force:!0}),await rm2(dir,{recursive:!0,force:!0}),skipped}async function acquireEnsureLock(socket){return acquireHostEnsureLock(socket,GC_LOCK_WAIT_MS).catch(()=>{})}async function legacyFlatDirectory(agentDir){let flatDir=join6(agentDir,"rpc-host-daemon");return parseJson(await readFileOrUndefined(join6(flatDir,"layout.json")).catch(()=>{}))?.layout===HOST_DAEMON_LAYOUT?void 0:await readFileOrUndefined(join6(flatDir,"host.pid")).catch(()=>{})!==void 0?flatDir:void 0}export{engineBuildIdentityFrom,engineBuildIdentity,compareEngineOrdinal,CUSTOM_UNSUPPORTED_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,EVAL_CELLS_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,SESSION_HELD_CAPABILITY,RESUME_SESSION_CAPABILITY,ATTENDED_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,QUESTION_CAPABILITY,TOOL_BARRIER_CAPABILITY,SESSION_RELOCATION_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,DETACH_CONNECTION_CAPABILITY,INTERACTIVE_USER_CAPABILITY,TASK_PARENT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_STATUS_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,WARM_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,PROMPT_SURFACE_CAPABILITY,BROWSER_ENGINE_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RETRY_FALLBACK_COMMAND_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,RPC_CLIENT_CAPABILITIES_ENV,parseClientCapabilities,DEFAULT_CUSTOM_EXTENSION_LABEL,buildCustomUnsupportedRequest,AUTH_KEY_VERIFY_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,computeRuntimeBuildId,parseHostProtocolInfo,HOST_PROTOCOL_VERSION,GENERATION_HANDOFF_CAPABILITY,REQUIRED_HOST_CAPABILITIES,HostEnsureRefusedError,decideHostAction,hostInstanceId,hostGeneration,hostLaunchProfile,socketHostLaunchProfile,protocolIdentity,DEFAULT_PROBE_TIMEOUT_MS,probeHost,probeProtocolInfo,observeProtocolInfo,holdProtocolInfo,probeSocketReachable,holdSessionCount,hostEnsureLockTarget,acquireHostEnsureLock,hostEnsureLockOptions,anyGenerationLive,judgeStaleEngine,electPointer,retireIdleLegacyHost,provenLegacyOwner,busyLegacyHostDetail,describeSessions,parseHostStopGeneration,stopHost,staleStopGeneration,signalGeneration,gcHostEndpoints,gcEndpoint};
|
|
7
|
+
`).slice(1)){let fields=line.trim().split(/\s+/),[flags,inode,path]=[fields[3],fields[6],fields[7]];inode===void 0||path===void 0||!inodes.has(inode)||!names.has(path)||(total+=1,(Number.parseInt(flags??"0",16)&LINUX_ACCEPTCON_FLAG)!==0&&(listeners+=1))}return{total,listeners}}catch{return}}var STALE_ENGINE_GRACE_MS=10*6e4,PROBE_TIMEOUT_MS=2e3;async function judgeStaleEngine(socket,agentDir,client,options={}){let paths=createHostDaemonPaths({socket,agentDir}),owner=await provenOwner(await readHostRegistration(paths),socket);if(owner===void 0)return keep("stale_unproven_owner");let clients=await countPublicClients(owner.pid,socket),info=await observeProtocolInfo(socket,PROBE_TIMEOUT_MS);if(info===void 0)return keep("stale_unreachable");let hostOrdinal=info.engineOrdinal,hostIdentity=hostOrdinal===void 0?void 0:{text:info.engineVersion??"",ordinal:hostOrdinal,scheme:hostOrdinal[4]>0?"epoch":"nodef"};if(hostIdentity===void 0||compareEngineOrdinal(hostIdentity,client)!==-1)return keep("stale_not_older");let policy=resolveHostPolicy(parseJson(await readFileOrUndefined(paths.settingsFile)),{});if(policy.coldStart==="persistent")return keep("stale_persistent");if(await observedSessionCount(socket)!==0)return keep("stale_sessions");if((await readSessionPathClaims(paths.reservationsDir)).length>0)return keep("stale_claims");let startedAt=processStartTimeMs(owner.processStartTime),now=(options.now??Date.now)();return startedAt===void 0||now-startedAt<policy.idleExitMs+(options.graceMs??STALE_ENGINE_GRACE_MS)?keep("stale_young"):clients!==0?keep("stale_clients"):{stale:!0,pid:owner.pid}}function keep(reason){return{stale:!1,reason}}async function observedSessionCount(socket){let reply=await requestOnSocket(socket,{type:"list_sessions",include_workers:!0,[OBSERVE_REQUEST_FIELD]:!0},PROBE_TIMEOUT_MS);if(typeof reply!="object"||reply===null)return;let sessions=Reflect.get(reply,"sessions");return Array.isArray(sessions)?sessions.length:void 0}var GC_LOCK_WAIT_MS=2e3;async function gcHostEndpoints(agentDir,options={}){process.platform!=="win32"&&await gcRpcPublicKeys(agentDir);let removed=[],stopped=[],kept=[],wanted=kind=>options.kinds===void 0||options.kinds.includes(kind),legacy=wanted("rpc_host")?await legacyFlatDirectory(agentDir):void 0;legacy!==void 0&&kept.push({socket:null,dir:legacy,reason:"legacy_layout"});for(let endpoint of await listHostEndpoints(agentDir)){if(!wanted(endpoint.endpoint_kind))continue;if(endpoint.socket===null){kept.push({socket:null,dir:endpoint.dir,reason:"unknown_identity"});continue}let entry={socket:endpoint.socket,dir:endpoint.dir};try{let outcome=await gcEndpoint(endpoint.socket,endpoint.dir,options);"stopped"in outcome?stopped.push({...entry,reason:"stale_old_engine",pid:outcome.pid}):outcome.removed?outcome.skipped.length===0?removed.push({...entry,reason:outcome.reason}):removed.push({...entry,reason:outcome.reason,skipped:outcome.skipped}):kept.push({...entry,reason:outcome.reason})}catch(error){kept.push({...entry,reason:"failed",error:error instanceof Error?error.message:String(error)})}}return stopped.length===0?{removed,kept}:{removed,stopped,kept}}async function gcEndpoint(socket,dir,options){let release=await acquireEnsureLock(socket);if(release===void 0)return{removed:!1,reason:"locked"};try{await options._test?.afterLockAcquired?.(socket);let evidence=await endpointInUse(hostDaemonDirectoryPaths(dir),socket);if(evidence.inUse==="live_claim"||evidence.inUse!==void 0&&options.staleEngine===void 0)return{removed:!1,reason:evidence.inUse};if(evidence.inUse!==void 0)return await stopIfStale(socket,dir,evidence.inUse,options.staleEngine??{});let skipped=await removeEndpoint(socket,dir);return{removed:!0,reason:evidence.silence,skipped}}finally{await release()}}var NOT_A_CANDIDATE=new Set(["stale_unproven_owner","stale_unreachable","stale_not_older"]),STALE_STOP_TIMEOUT_MS=2e3;async function stopIfStale(socket,dir,inUse,options){let agentDir=dirname5(dirname5(dir)),verdict=await judgeStaleEngine(socket,agentDir,options.client??engineBuildIdentity(),options);if(!verdict.stale)return{removed:!1,reason:NOT_A_CANDIDATE.has(verdict.reason)?inUse:verdict.reason};let result=await stopHost({socket,agentDir,timeoutMs:STALE_STOP_TIMEOUT_MS,requireAnswer:!0});return result.action==="refuse"?{removed:!1,reason:result.reason==="unknown_owner"?"stale_unproven_owner":"stale_sessions"}:{removed:!1,stopped:!0,pid:result.pid}}async function removeEndpoint(socket,dir){let skipped=[];for(let sibling of await socketSiblings(socket)){let path=join6(dirname5(socket),sibling),entry=await lstat2(path).catch(error=>{if(!(error instanceof Error&&"code"in error&&error.code==="ENOENT"))throw error});entry?.isDirectory()?skipped.push({path,type:"directory"}):entry!==void 0&&await rm2(path,{force:!0})}return await rm2(socket,{force:!0}),await rm2(dir,{recursive:!0,force:!0}),skipped}async function acquireEnsureLock(socket){return acquireHostEnsureLock(socket,GC_LOCK_WAIT_MS).catch(()=>{})}async function legacyFlatDirectory(agentDir){let flatDir=join6(agentDir,"rpc-host-daemon");return parseJson(await readFileOrUndefined(join6(flatDir,"layout.json")).catch(()=>{}))?.layout===HOST_DAEMON_LAYOUT?void 0:await readFileOrUndefined(join6(flatDir,"host.pid")).catch(()=>{})!==void 0?flatDir:void 0}export{engineBuildIdentityFrom,engineBuildIdentity,compareEngineOrdinal,CUSTOM_UNSUPPORTED_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,EVAL_CELLS_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,SESSION_HELD_CAPABILITY,RESUME_SESSION_CAPABILITY,ATTENDED_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,QUESTION_CAPABILITY,TOOL_BARRIER_CAPABILITY,SESSION_RELOCATION_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,DETACH_CONNECTION_CAPABILITY,INTERACTIVE_USER_CAPABILITY,OBSERVE_READS_CAPABILITY,ENTRIES_TAIL_CAPABILITY,TUI_OBSERVER_CAPABILITY,TASK_PARENT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_STATUS_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,WARM_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,PROMPT_SURFACE_CAPABILITY,BROWSER_ENGINE_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RETRY_FALLBACK_COMMAND_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,RPC_CLIENT_CAPABILITIES_ENV,parseClientCapabilities,DEFAULT_CUSTOM_EXTENSION_LABEL,buildCustomUnsupportedRequest,AUTH_KEY_VERIFY_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,computeRuntimeBuildId,parseHostProtocolInfo,HOST_PROTOCOL_VERSION,GENERATION_HANDOFF_CAPABILITY,REQUIRED_HOST_CAPABILITIES,HostEnsureRefusedError,decideHostAction,hostInstanceId,hostGeneration,hostLaunchProfile,socketHostLaunchProfile,protocolIdentity,DEFAULT_PROBE_TIMEOUT_MS,probeHost,probeProtocolInfo,observeProtocolInfo,holdProtocolInfo,probeSocketReachable,holdSessionCount,hostEnsureLockTarget,acquireHostEnsureLock,hostEnsureLockOptions,anyGenerationLive,judgeStaleEngine,electPointer,retireIdleLegacyHost,provenLegacyOwner,busyLegacyHostDetail,describeSessions,parseHostStopGeneration,stopHost,staleStopGeneration,signalGeneration,gcHostEndpoints,gcEndpoint};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{McpMrtrError,bindMcpFormPresented,enums,isRecord,privateMcpForms,queuedForm,validValue,validateMrtrForm}from"./chunk-JPGT64RV.js";import{redactResolvedReferenceValues}from"./chunk-DLAY7CIU.js";import{getAgentDir}from"./chunk-7YO7VQZW.js";var McpError=class extends Error{constructor(kind,name,message,options={}){super(message),this.name=name,this.kind=kind,this.phase=options.phase,this.retriable=options.retriable,this.serverName=options.serverName,options.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:options.cause,writable:!1}),Object.setPrototypeOf(this,new.target.prototype)}},ConnectError=class extends McpError{constructor(message,options={}){super("connect","ConnectError",message,options)}};var ToolExecError=class extends McpError{constructor(message,options={}){super("tool_exec","ToolExecError",message,options)}},AuthError=class extends McpError{constructor(message,options={}){super("auth","AuthError",message,options)}},TimeoutError=class extends McpError{constructor(message,options={}){super("timeout","TimeoutError",message,options)}},SessionExpiredError=class extends McpError{constructor(message,options={}){super("session_expired","SessionExpiredError",message,options)}},RETRIABLE_STATUS_CODES=new Set([404,502,503]),RETRIABLE_NUMERIC_CODES=new Set([-32001]),RETRIABLE_TEXT=["econnrefused","connection refused","transport closed"];function isRetriableMcpError(error){if(error instanceof McpError&&error.retriable===!0||isMcpSessionExpiredError(error)||hasRetriableNumericSignal(error,new Set))return!0;let text=collectText(error,new Set).join(" ").toLowerCase();return RETRIABLE_TEXT.some(needle=>text.includes(needle))?!0:/\b(?:404|502|503)\b/.test(text)}function isMcpSessionExpiredError(error){if(hasSessionExpiredNumericSignal(error,new Set))return!0;let text=collectText(error,new Set).join(" ").toLowerCase();return/\b404\b/.test(text)||text.includes("-32000")&&text.includes("session")||text.includes("session expired")||text.includes("session not found")||text.includes("mcp-session-id")}function hasRetriableNumericSignal(value,seen){if(typeof value!="object"||value===null||seen.has(value))return!1;seen.add(value);let code=numberFromUnknown(getProperty(value,"code"));if(code!==void 0&&RETRIABLE_NUMERIC_CODES.has(code))return!0;let status=numberFromUnknown(getProperty(value,"status"));if(status!==void 0&&RETRIABLE_STATUS_CODES.has(status))return!0;let statusCode=numberFromUnknown(getProperty(value,"statusCode"));return statusCode!==void 0&&RETRIABLE_STATUS_CODES.has(statusCode)?!0:hasRetriableNumericSignal(getProperty(value,"response"),seen)||hasRetriableNumericSignal(getProperty(value,"cause"),seen)}function hasSessionExpiredNumericSignal(value,seen){if(typeof value!="object"||value===null||seen.has(value))return!1;seen.add(value);let code=numberFromUnknown(getProperty(value,"code"));if(code===-32001)return!0;if(code===-32e3){let message=getProperty(value,"message");if(typeof message=="string"&&message.toLowerCase().includes("session"))return!0}return numberFromUnknown(getProperty(value,"status"))===404||numberFromUnknown(getProperty(value,"statusCode"))===404?!0:hasSessionExpiredNumericSignal(getProperty(value,"response"),seen)||hasSessionExpiredNumericSignal(getProperty(value,"cause"),seen)}function collectText(value,seen){if(typeof value=="string")return[value];if(typeof value=="number")return[String(value)];if(typeof value!="object"||value===null)return[];if(seen.has(value))return[];seen.add(value);let parts=[];value instanceof Error&&parts.push(value.message,value.name);for(let key of["message","code","status","statusCode"]){let property=getProperty(value,key);(typeof property=="string"||typeof property=="number")&&parts.push(String(property))}return parts.push(...collectText(getProperty(value,"response"),seen)),parts.push(...collectText(getProperty(value,"cause"),seen)),parts}function numberFromUnknown(value){if(typeof value=="number")return value;if(typeof value!="string"||value.trim()==="")return;let parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0}function getProperty(value,key){if(!(typeof value!="object"||value===null))return value[key]}import{chmodSync,closeSync,openSync,renameSync,rmSync,statSync}from"node:fs";var LOG_SINK_RETRY_MS=5e3,ROTATION_LOCK_STALE_MS=1e4;function errorCode(error){return typeof error=="object"&&error!==null&&"code"in error&&typeof error.code=="string"?error.code:void 0}function exceedsCap(filePath,incomingBytes,maxBytes){try{return statSync(filePath).size+incomingBytes>maxBytes}catch(error){if(errorCode(error)==="ENOENT")return!1;throw error}}function clearStaleLock(lockPath){try{Date.now()-statSync(lockPath).mtimeMs>ROTATION_LOCK_STALE_MS&&rmSync(lockPath,{force:!0})}catch(error){if(errorCode(error)!=="ENOENT")throw error}}function rotateLogIfNeeded(filePath,incomingBytes,maxBytes){if(!exceedsCap(filePath,incomingBytes,maxBytes))return;let lockPath=`${filePath}.rotate-lock`,lock;try{lock=openSync(lockPath,"wx",384)}catch(error){if(errorCode(error)!=="EEXIST")throw error;clearStaleLock(lockPath);return}try{if(!exceedsCap(filePath,incomingBytes,maxBytes))return;try{renameSync(filePath,`${filePath}.1`)}catch(error){if(errorCode(error)==="ENOENT")return;throw error}chmodSync(`${filePath}.1`,384)}finally{closeSync(lock),rmSync(lockPath,{force:!0})}}import{closeSync as closeSync3,fchmodSync,mkdirSync as mkdirSync2,openSync as openSync3,writeSync as writeSync2}from"node:fs";import{dirname,join as join2}from"node:path";import{createHmac,randomBytes,randomUUID}from"node:crypto";import{closeSync as closeSync2,constants,fstatSync,fsyncSync,linkSync,mkdirSync,openSync as openSync2,readSync,rmSync as rmSync2,writeSync}from"node:fs";import{join}from"node:path";var KEY_FILE="config-identity.key",KEY_BYTES=32,EPHEMERAL_PREFIX="ephemeral:",processKey=randomBytes(KEY_BYTES),installationKeys=new Map,warnedPaths=new Set;function keyedIdentity(agentDir,payload){let key=installationKey(agentDir??getAgentDir());return key===void 0?`${EPHEMERAL_PREFIX}${hmac(processKey,payload)}`:hmac(key,payload)}function isEphemeralIdentity(identity){return identity?.startsWith(EPHEMERAL_PREFIX)===!0}function keyedFingerprint(value){return hmac(installationKey(getAgentDir())??processKey,value).slice(0,8)}function hmac(key,payload){return createHmac("sha256",key).update(payload).digest("hex")}function installationKey(agentDir){return installationKeys.has(agentDir)||installationKeys.set(agentDir,loadOrPublishKey(agentDir)),installationKeys.get(agentDir)}function loadOrPublishKey(agentDir){let path=join(agentDir,KEY_FILE),existing=readKey(path);return existing.kind==="valid"?existing.key:existing.kind==="missing"?publishKey(agentDir,path):void 0}function readKey(path){let fd;try{fd=openSync2(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0))}catch(error){return isErrno(error,"ENOENT")?{kind:"missing"}:invalidKey(path,"cannot open safely","repair access and ensure it is a regular file, not a symlink")}try{let stat=fstatSync(fd);if(!stat.isFile())return invalidKey(path,"not a regular file","restore the original private key file");if(stat.size!==KEY_BYTES)return invalidKey(path,`wrong size (${stat.size} bytes)`,"restore the original 32-byte key from backup");if(process.platform!=="win32"){if(stat.uid!==process.getuid?.())return invalidKey(path,"wrong owner","chown the key file to your current user");if((stat.mode&511)!==384)return invalidKey(path,"wrong mode","chmod 600 the key file")}let key=Buffer.alloc(KEY_BYTES);return readSync(fd,key,0,KEY_BYTES,0)===KEY_BYTES?{kind:"valid",key}:invalidKey(path,"incomplete read","restore the original 32-byte key from backup")}finally{closeSync2(fd)}}function invalidKey(path,problem,repair){return warnedPaths.has(path)||(warnedPaths.add(path),console.warn(`MCP identity key ${path}: ${problem}; persistent catalog cache is disabled. To fix: ${repair}, then restart senpi. The file was left unchanged.`)),{kind:"invalid"}}function publishKey(agentDir,path){let temporary=`${path}.${process.pid}.${randomUUID()}.tmp`;try{mkdirSync(agentDir,{recursive:!0,mode:448});let key=randomBytes(KEY_BYTES),fd=openSync2(temporary,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY,384);try{writeSync(fd,key),fsyncSync(fd)}finally{closeSync2(fd)}return linkSync(temporary,path),syncDirectory(agentDir),key}catch(error){if(!isErrno(error,"EEXIST"))return;let published=readKey(path);return published.kind==="valid"?published.key:void 0}finally{rmSync2(temporary,{force:!0})}}function syncDirectory(directory){if(process.platform==="win32")return;let fd=openSync2(directory,constants.O_RDONLY);try{fsyncSync(fd)}finally{closeSync2(fd)}}function isErrno(error,code){return error instanceof Error&&"code"in error&&error.code===code}var DEFAULT_MAX_FILE_BYTES=1024*1024,MAX_RING_LINES=200,SENSITIVE_KEY_PATTERN=/(?:^|[_-])(?:api[_-]?key|key|token|secret|password|client_secret|auth|authorization)(?:$|[_-])/i,QUERY_SECRET_PATTERN=/([?&][^=\s&"'<>]*(?:key|token|secret|password|client_secret|auth)[^=\s&"'<>]*=)([^&\s"'<>]+)/gi,AUTHORIZATION_VALUE_PATTERN=/((?:"|')?\bAuthorization(?:"|')?\s*[:=]\s*(?:"|')?(?:[A-Za-z][A-Za-z0-9+.-]*\s+)?)(?!<redacted:)([^"',\s}\]&]+)/gi,BEARER_VALUE_PATTERN=/(\bBearer\s+)(?!<redacted:)([A-Za-z0-9._~+/=-]+)/gi,KEY_VALUE_PATTERN=/((?:"|')?[^"'\s:=,{}]*(?:api[_-]?key|key|token|secret|password|client_secret|auth)[^"'\s:=,{}]*(?:"|')?\s*[:=]\s*(?:"|')?)([^"',\s}\]&]+)/gi,MCP_LOG_LEVELS={emergency:{level:"emergency",severity:0},alert:{level:"alert",severity:1},critical:{level:"critical",severity:2},crit:{level:"critical",severity:2},error:{level:"error",severity:3},err:{level:"error",severity:3},warning:{level:"warning",severity:4},warn:{level:"warning",severity:4},notice:{level:"notice",severity:5},informational:{level:"info",severity:6},info:{level:"info",severity:6},debug:{level:"debug",severity:7}};function createMcpLogger(server,options={}){return new FileMcpLogger(server,options)}function getMcpLogDir(){return join2(getAgentDir(),"logs","mcp")}function fingerprintSecret(secret){return keyedFingerprint(secret)}function redactMcpLogText(text){return redactMcpLogTextWithContext(text,{seen:new WeakSet,secrets:new Set})}function redactMcpLogTextWithContext(text,context){return text.replace(AUTHORIZATION_VALUE_PATTERN,(_match,prefix,secret)=>`${prefix}${redactionForSecret(secret,context)}`).replace(BEARER_VALUE_PATTERN,(_match,prefix,secret)=>`${prefix}${redactionForSecret(secret,context)}`).replace(QUERY_SECRET_PATTERN,(_match,prefix,secret)=>`${prefix}${redactionForSecret(secret,context)}`).replace(KEY_VALUE_PATTERN,(match,prefix,secret)=>secret.startsWith("<redacted:")||/\bAuthorization\b/i.test(prefix)?match:`${prefix}${redactionForSecret(secret,context)}`)}function mapMcpLogLevel(level){return{...MCP_LOG_LEVELS[level]??MCP_LOG_LEVELS.info}}var FileMcpLogger=class{#server;#maxFileBytes;#ring=[];#fileSinkRetryAt=0;constructor(server,options){this.#server=server,this.#maxFileBytes=options.maxFileBytes??DEFAULT_MAX_FILE_BYTES,this.filePath=join2(options.logDir??getMcpLogDir(),`${sanitizeServerName(server)}.log`)}debug(message,data){this.log("debug",message,data)}info(message,data){this.log("info",message,data)}warn(message,data){this.log("warning",message,data)}error(message,data){this.log("error",message,data)}stderr(message,data){this.log("info",message,data,"stderr")}log(level,message,data,channel="server"){let line=this.#formatLine(level,message,data,channel);this.#pushRing(line),this.#writeFile(line)}getRingBuffer(){return[...this.#ring]}#formatLine(level,message,data,channel){let context={seen:new WeakSet,secrets:new Set},mapped=mapMcpLogLevel(level),redactedData=data===void 0?void 0:redactMcpLogData(data,context),entry={timestamp:new Date().toISOString(),server:this.#server,level:mapped.level,severity:mapped.severity,channel,message:redactMcpLogTextWithContext(message,context),data:redactedData};return redactResolvedReferenceValues(redactKnownSecrets(JSON.stringify(entry),context))}#pushRing(line){this.#ring.push(line),this.#ring.length>MAX_RING_LINES&&this.#ring.splice(0,this.#ring.length-MAX_RING_LINES)}#writeFile(line){if(!(Date.now()<this.#fileSinkRetryAt))try{mkdirSync2(dirname(this.filePath),{recursive:!0,mode:448});let bytes=Buffer.byteLength(`${line}
|
|
3
|
+
`);this.#maxFileBytes>0&&rotateLogIfNeeded(this.filePath,bytes,this.#maxFileBytes);let fd=openSync3(this.filePath,"a",384);try{writeSync2(fd,`${line}
|
|
4
|
+
`),fchmodSync(fd,384)}finally{closeSync3(fd)}}catch{this.#fileSinkRetryAt=Date.now()+LOG_SINK_RETRY_MS,this.#pushRing(this.#formatLine("warning","file sink disabled after write failure",void 0,"file"))}}};function redactMcpLogData(value,context){return typeof value=="string"?redactMcpLogTextWithContext(value,context):typeof value=="bigint"?value.toString():typeof value!="object"||value===null?value:context.seen.has(value)?"[Circular]":(context.seen.add(value),value instanceof Error?redactMcpLogError(value,context):Array.isArray(value)?value.map(item=>redactMcpLogData(item,context)):redactMcpLogEntries(value,context))}function redactMcpLogError(error,context){let redacted=redactMcpLogEntries(error,context);return redacted.name=redactMcpLogTextWithContext(error.name,context),redacted.message=redactKnownSecrets(redactMcpLogTextWithContext(error.message,context),context),error.stack!==void 0&&(redacted.stack=redactKnownSecrets(redactMcpLogTextWithContext(error.stack,context),context)),redacted}function redactMcpLogEntries(value,context){let redacted={};for(let[key,item]of Object.entries(value))SENSITIVE_KEY_PATTERN.test(key)?redacted[key]=redactionForSecret(stringifySecretValue(item),context):redacted[key]=redactMcpLogData(item,context);return redacted}function stringifySecretValue(value){if(typeof value=="string")return value;if(typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return String(value);let seen=new WeakSet;return JSON.stringify(value,(_key,item)=>typeof item=="bigint"?item.toString():typeof item!="object"||item===null?item:seen.has(item)?"[Circular]":(seen.add(item),item))??String(value)}function redactionForSecret(secret,context){return secret.length>0&&!secret.startsWith("<redacted:")&&context.secrets.add(secret),redactionFor(secret)}function redactKnownSecrets(text,context){for(let secret of[...context.secrets].sort((left,right)=>right.length-left.length))text=text.split(secret).join(redactionFor(secret));return text}function redactionFor(secret){return`<redacted:${fingerprintSecret(secret)}>`}function sanitizeServerName(server){return server.replace(/[^A-Za-z0-9._-]+/g,"_")||"server"}var mcpElapsedClock={now:()=>performance.now(),schedule:setTimeout,cancel:clearTimeout};function wrapAsync(scope,fn,sink){return async(...args)=>{try{await fn(...args)}catch(error){let caughtError=error instanceof Error?error:normalizeCaughtError(error);await reportMcpAsyncError(scope,caughtError,sink)}}}function safeTimer(scope,delayMs,fn,sink){let wrapped=wrapAsync(scope,fn,sink),timer=setTimeout(()=>{wrapped()},delayMs);return timer.unref(),timer}function safeInterval(scope,delayMs,fn,sink){let wrapped=wrapAsync(scope,fn,sink),timer=setInterval(()=>{wrapped()},delayMs);return timer.unref(),timer}function safeDelay(delayMs){return new Promise(resolve=>{setTimeout(resolve,delayMs)})}function safeOn(emitter,eventName,scope,listener,sink){let wrapped=wrapAsync(scope,listener,sink);return emitter.on(eventName,wrapped),()=>{emitter.off(eventName,wrapped)}}function safeEventBusOn(bus,channel,handler){return bus.on(channel,handler)}async function reportMcpAsyncError(scope,error,sink){let normalized=normalizeError(error);if(logError(scope,normalized,sink.logger),!!sink.notify)try{await sink.notify(`MCP ${scope} failed: ${normalized.message}`,normalized)}catch(notifyError){let caughtNotifyError=notifyError instanceof Error?notifyError:normalizeCaughtError(notifyError);logError(`${scope}.notify`,caughtNotifyError,sink.logger)}}function logError(scope,error,logger){try{logger.error(scope,serializeError(error))}catch{let redactedScope=redactMcpLogText(scope);console.error(`MCP ${redactedScope} logger failed; suppressed async error details`)}}function serializeError(error){let serialized={name:error.name,message:error.message};return error.stack&&(serialized.stack=error.stack),serialized}function normalizeError(error){return error instanceof Error?error:normalizeCaughtError(error)}function normalizeCaughtError(error){return typeof error=="string"?new Error(error):new Error(safeStringify(error))}function safeStringify(value){try{return JSON.stringify(value)??String(value)}catch{return String(value)}}function memoizeLoader(load){let loaded,loading;return()=>loaded!==void 0?Promise.resolve(loaded):(loading??=load().then(module=>(loaded=module,module)).finally(()=>{loading=void 0}),loading)}var loadMcpSdkClient=memoizeLoader(()=>import("./client-WTYEICLH.js")),loadMcpSdkZodCompat=memoizeLoader(()=>import("./zod-compat-RJDXCU7S.js")),loadMcpSdkStdioTransport=memoizeLoader(()=>import("./stdio-YXDKKKQZ.js")),loadMcpSdkTypes=memoizeLoader(()=>import("./types-BJUEQ4II.js")),authModule,loadMcpSdkAuth=memoizeLoader(async()=>{let module=await import("./auth-C77UQA55.js");return authModule=module,module}),loadMcpSdkStreamableHttpTransport=memoizeLoader(async()=>{let[module]=await Promise.all([import("./streamableHttp-DKIBUWVY.js"),loadMcpSdkAuth()]);return module});function isMcpSdkUnauthorizedError(error){return authModule!==void 0&&error instanceof authModule.UnauthorizedError}var OAuthFlowError=class extends AuthError{constructor(oauthKind,message,options={}){super(message,options),this.name="OAuthFlowError",this.oauthKind=oauthKind,this.terminal=TERMINAL_KINDS.has(oauthKind)}},TERMINAL_KINDS=new Set(["s256_unsupported","needs_auth","invalid_grant","state_mismatch","expired_code","no_verifier","headless","missing_env"]),TERMINAL_OAUTH_CODES=new Set(["invalid_grant","invalid_token","invalid_client","unauthorized_client"]),TRANSIENT_OAUTH_CODES=new Set(["temporarily_unavailable","server_error","slow_down"]);function isInvalidGrant(error){let code=oauthErrorCode(error);if(code!==void 0)return TERMINAL_OAUTH_CODES.has(code);let text=errorText(error).toLowerCase();return text.includes("invalid_grant")||text.includes("invalid_token")}function isTransientTokenError(error){if(isInvalidGrant(error))return!1;let code=oauthErrorCode(error);if(code!==void 0&&TRANSIENT_OAUTH_CODES.has(code))return!0;let text=errorText(error).toLowerCase();return/\b(?:500|502|503|504)\b/.test(text)||text.includes("econnrefused")||text.includes("network")}function oauthErrorCode(error){if(typeof error!="object"||error===null)return;let code=error.errorCode;return typeof code=="string"?code:void 0}function errorText(error){return error instanceof Error?`${error.name} ${error.message}`:String(error)}var MAX_CAUSE_DEPTH=5;function isMcpNeedsAuthError(error,depth=0){return isMcpSdkUnauthorizedError(error)?!0:error instanceof OAuthFlowError?error.terminal:depth<MAX_CAUSE_DEPTH&&error!==null&&typeof error=="object"&&"cause"in error?isMcpNeedsAuthError(error.cause,depth+1):!1}var originOption=Symbol("mcp-request-origin"),origins=new WeakSet,aliases=new WeakMap,physicalMcpClient=client=>aliases.get(client)??client;function registerMcpClientAlias(alias,physical){aliases.set(alias,physical)}var legacyOperations=new WeakMap;function beginLegacyMcpOperation(client,origin,caller){let lifetime=new AbortController,operation={origin,signal:AbortSignal.any([origin.signal,lifetime.signal,...caller?[caller]:[]])},operations=legacyOperations.get(client);return operations||(operations=new Set,legacyOperations.set(client,operations)),operations.add(operation),()=>{operations.delete(operation),lifetime.abort(),operations.size===0&&legacyOperations.delete(client)}}function legacyMcpOperation(client){let operations=legacyOperations.get(client);if(operations&&operations.size>1)return"ambiguous";if(operations?.size!==1)return;let operation=operations.values().next().value;return operation&&!operation.signal.aborted&&operation.origin.isCurrent()?operation:void 0}function createMcpRequestOrigin(origin){return origins.add(origin),origin}function mcpRequestOptions(origin,options={}){return origin===void 0?options:{...options,[originOption]:origin}}function takeMcpRequestOrigin(options,client){let supplied=options,origin=supplied?.[originOption],{[originOption]:_origin,...sdkOptions}=supplied??{};if(origin!==void 0){if(!origins.has(origin)||!origin.isCurrent())throw new McpMrtrError("MCP_MRTR_CONTEXT_CHANGED");let candidate=origin.connection.client;if(physicalMcpClient(candidate)!==client)throw new McpMrtrError("MCP_MRTR_CONTEXT_CHANGED")}return{origin,sdkOptions}}var MCP_CLIENT_ELICITATION_CAPABILITY={elicitation:{}};function mcpClientCapabilities(elicitationEnabled=!0){return elicitationEnabled?MCP_CLIENT_ELICITATION_CAPABILITY:{}}var MCP_ELICITATION_TIMEOUT_MS=300*1e3,legacyUiProvider;async function rejectElicitation(){let{ErrorCode,McpError:McpError2}=await loadMcpSdkTypes();throw new McpError2(ErrorCode.InternalError,"Elicitation cannot be processed")}function legacyMcpFormEligible(provider,enabled){if(!enabled)return!1;if(provider?.eligible)return provider.eligible();let ui=provider?.(),binding=ui===void 0?void 0:privateMcpForms(ui);return binding===void 0||binding.capture()?.ready()===!0}async function rejectPrivateElicitation(){let{ErrorCode,McpError:McpError2}=await loadMcpSdkTypes();throw new McpError2(ErrorCode.InternalError,"Elicitation processing unavailable")}async function privateElicitation(client,params,signal,requestId,timeoutMs){let operation=legacyMcpOperation(client);if(operation==="ambiguous")return rejectPrivateElicitation();let presenter=operation?.origin.privateForm;if(!isRecord(params)||typeof params.message!="string"||params.mode!==void 0&¶ms.mode!=="form"||!operation||!presenter?.ready()||!validateMrtrForm(params.requestedSchema))return rejectPrivateElicitation();let outcome=await presenter.present({operationId:String(requestId),inputId:String(requestId),round:0,server:{label:operation.origin.serverLabel,source:operation.origin.serverSource??"user"},message:params.message,schema:params.requestedSchema,operationSignal:AbortSignal.any([operation.signal,signal]),presentationSignal:presenter.signal,deadlineMs:timeoutMs});return outcome.kind!=="result"||operation.signal.aborted||!operation.origin.isCurrent()?rejectPrivateElicitation():outcome.result}async function configureMcpElicitation(client,owner=legacyUiProvider,timeoutMs=MCP_ELICITATION_TIMEOUT_MS,elicitationEnabled=!0){if(!elicitationEnabled){let{ErrorCode,McpError:McpError2}=await loadMcpSdkTypes();client.fallbackRequestHandler=async request=>{if(request.method==="elicitation/create")return typeof owner=="function"&&owner.enforced?.()?rejectPrivateElicitation():rejectElicitation();throw new McpError2(ErrorCode.MethodNotFound,"Method not found")};return}let{ElicitRequestSchema}=await loadMcpSdkTypes();if(typeof owner=="function"&&owner.enforced?.()){client.setRequestHandler(ElicitRequestSchema.omit({params:!0}).passthrough(),(request,extra)=>privateElicitation(client,request.params,extra.signal,extra.requestId,timeoutMs));return}client.setRequestHandler(ElicitRequestSchema,async(request,extra)=>{let params=request.params;if(!("requestedSchema"in params))return rejectElicitation();let ui=typeof owner=="function"?owner():owner?.getMcpElicitationUi();return typeof owner=="function"&&owner.enforced?.()||ui!==void 0&&privateMcpForms(ui)!==void 0?privateElicitation(client,params,extra.signal,extra.requestId,timeoutMs):ui===void 0?rejectElicitation():await runElicitationForm(ui,params.message,params.requestedSchema,timeoutMs)})}async function runElicitationForm(ui,message,requestedSchema,timeoutMs=MCP_ELICITATION_TIMEOUT_MS){let timer,timeout=new Promise(resolve=>{timer=safeTimer("mcp.elicitation.timeout",timeoutMs,()=>resolve({action:"cancel"}),{logger:createMcpLogger("elicitation")})});try{return await Promise.race([collectForm(ui,message,requestedSchema),timeout])}finally{timer!==void 0&&clearTimeout(timer)}}async function collectForm(ui,message,requestedSchema){let content={},required=new Set(requestedSchema.required??[]);for(let[name,property]of Object.entries(requestedSchema.properties??{})){let title=`${message} - ${property.title??name}`;if(property.type==="boolean"){let picked=await ui.select(property.description?`${title}
|
|
5
|
+
${property.description}`:title,["Yes","No"]);if(picked===void 0)return{action:"cancel"};switch(picked.trim().toLowerCase()){case"yes":case"y":case"true":content[name]=!0;break;case"no":case"n":case"false":content[name]=!1;break;default:return rejectElicitation()}continue}if(Array.isArray(property.enum)&&property.enum.length>0){let picked=await ui.select(title,property.enum.map(String));if(picked===void 0)return{action:"cancel"};content[name]=picked;continue}let answer=await ui.input(title,property.description);if(answer===void 0)return{action:"cancel"};if(answer.length===0){if(required.has(name))return rejectElicitation();continue}if(property.type==="number"||property.type==="integer"){let parsed=Number(answer);if(!Number.isFinite(parsed))return rejectElicitation();content[name]=parsed;continue}content[name]=answer}return Object.keys(content).length===0&&await ui.select(message,["Submit"])!=="Submit"?{action:"cancel"}:{action:"accept",content}}import{stripVTControlCharacters}from"node:util";var own=(value,key)=>Object.hasOwn(value,key),inert=value=>stripVTControlCharacters(value).replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g,"");async function collectMrtrForm(presentation,serverLabel,params,signal){if(!validateMrtrForm(params.requestedSchema))throw new McpMrtrError("MCP_MRTR_INVALID_INPUT");let schema=params.requestedSchema,abort=new AbortController,combined=AbortSignal.any([signal,presentation.signal,abort.signal]),opts={signal:combined,ephemeral:!0};bindMcpFormPresented(opts,presentation.presented);let heading=`MCP server: ${inert(serverLabel)}
|
|
6
|
+
${inert(params.message)}`,select=async(title,choices)=>{if(combined.aborted)return;let result=await presentation.ui.select(title,choices,opts);return combined.aborted?void 0:result},content=Object.create(null),finish=result=>(combined.aborted||presentation.admit?.(),result),required=new Set(schema.required??[]),entries=Object.entries(schema.properties),field=async(name,property)=>{let title=`${heading}
|
|
7
|
+
${inert(String(property.title??name))}${typeof property.description=="string"?`
|
|
8
|
+
${inert(property.description)}`:""}`;for(;;){let actions=["Enter value"];required.has(name)||actions.push("Leave unset"),own(property,"default")&&actions.push("Use default");let action="Enter value";if(actions.length>1){let chosen=await select(title,actions);if(chosen===void 0)return!1;action=chosen}if(action==="Leave unset")return delete content[name],!0;if(action==="Use default")return content[name]=structuredClone(property.default),!0;let value;if(property.type==="boolean"){let chosen=await select(title,["true","false"]);if(chosen===void 0)return!1;value=chosen==="true"}else if(property.type==="array"||enums(property)){let choices=property.type==="array"&&isRecord(property.items)?enums(property.items):enums(property);if(choices===void 0)return!1;let values=[];for(;;){let labels=choices.map((choice2,index2)=>`${index2+1}. ${inert(choice2.label)}${values.includes(choice2.value)?" [selected]":""}`);property.type==="array"&&labels.push("Done");let chosen=await select(title,labels);if(chosen===void 0)return!1;if(chosen==="Done"){value=values;break}let index=labels.indexOf(chosen),choice=choices[index];if(!choice)continue;if(property.type!=="array"){value=choice.value;break}let existing=values.indexOf(choice.value);existing>=0?values.splice(existing,1):values.push(choice.value)}}else{if(combined.aborted)return!1;let text=await presentation.ui.input(title,void 0,opts);if(text===void 0||combined.aborted)return!1;value=property.type==="number"||property.type==="integer"?text.trim()===""?NaN:Number(text):text}if(validValue(property,value))return content[name]=value,!0;if(await select(`${title}
|
|
9
|
+
Value does not satisfy this field.`,["Try again","Cancel"])!=="Try again")return!1}};try{let begin=await select(heading,["Continue","Decline","Cancel"]);if(begin!=="Continue")return finish({action:begin==="Decline"?"decline":"cancel"});for(let[name,property]of entries)if(!await field(name,property))return finish({action:"cancel"});for(;;){let review=entries.map(([name])=>`${inert(name)}: ${own(content,name)?inert(JSON.stringify(content[name])):"(unset)"}`).join(`
|
|
10
|
+
`),action=await select(`${heading}
|
|
11
|
+
Review
|
|
12
|
+
${review}`,["Submit","Edit field","Decline","Cancel"]);if(action==="Submit"&&!combined.aborted)return finish({action:"accept",content:structuredClone(content)});if(action!=="Edit field")return finish({action:action==="Decline"?"decline":"cancel"});let labels=entries.map(([name],index)=>`${index+1}. ${inert(name)}`),chosen=await select(`${heading}
|
|
13
|
+
Edit field`,labels),entry=chosen===void 0?void 0:entries[labels.indexOf(chosen)];if(!entry||!await field(...entry))return finish({action:"cancel"})}}finally{bindMcpFormPresented(opts,void 0),abort.abort();for(let key of Object.keys(content))delete content[key]}}var own2=(value,key)=>Object.hasOwn(value,key),byteSize=value=>Buffer.byteLength(JSON.stringify(value),"utf8");function parseInputs(result){if(!own2(result,"requestState")&&!own2(result,"inputRequests"))throw new McpMrtrError("MCP_MRTR_INVALID_INPUT");if(own2(result,"requestState")&&typeof result.requestState!="string")throw new McpMrtrError("MCP_MRTR_INVALID_INPUT");if(byteSize(result)>512*1024||typeof result.requestState=="string"&&Buffer.byteLength(result.requestState)>64*1024)throw new McpMrtrError("MCP_MRTR_INPUT_LIMIT");if(!own2(result,"inputRequests"))return;if(!isRecord(result.inputRequests))throw new McpMrtrError("MCP_MRTR_INVALID_INPUT");let entries=Object.entries(result.inputRequests);if(entries.length>32)throw new McpMrtrError("MCP_MRTR_INPUT_LIMIT");for(let[,input]of entries)if(isRecord(input)&&["roots/list","sampling/createMessage"].includes(String(input.method)))throw new McpMrtrError("MCP_MRTR_UNSUPPORTED_INPUT");let inputs=new Map,checkStrings=value=>{if(typeof value=="string"&&Buffer.byteLength(value)>16*1024)throw new McpMrtrError("MCP_MRTR_INPUT_LIMIT");if(Array.isArray(value))for(let entry of value)checkStrings(entry);else if(isRecord(value))for(let[key,entry]of Object.entries(value))checkStrings(key),checkStrings(entry)};for(let[key,input]of entries){if(checkStrings(key),!isRecord(input)||input.method!=="elicitation/create"||!isRecord(input.params)||typeof input.params.message!="string")throw new McpMrtrError("MCP_MRTR_INVALID_INPUT");let params=input.params;if(checkStrings(params),params.mode==="url")throw typeof params.url!="string"||typeof params.elicitationId!="string"?new McpMrtrError("MCP_MRTR_INVALID_INPUT"):new McpMrtrError("MCP_MRTR_UNSUPPORTED_INPUT");if(params.mode!==void 0&¶ms.mode!=="form")throw new McpMrtrError("MCP_MRTR_INVALID_INPUT");if(isRecord(params.requestedSchema)&&isRecord(params.requestedSchema.properties)&&Object.keys(params.requestedSchema.properties).length>64)throw new McpMrtrError("MCP_MRTR_INPUT_LIMIT");if(!validateMrtrForm(params.requestedSchema))throw new McpMrtrError("MCP_MRTR_INVALID_INPUT");inputs.set(key,input)}return inputs}var MAX_MCP_MRTR_ROUNDS=8,capableMethods=new Set(["tools/call","resources/read","prompts/get"]),capabilitiesKey="io.modelcontextprotocol/clientCapabilities",modernDispatchGuard=Symbol("mcp-modern-dispatch"),states=new WeakMap,isModernMcpClient=client=>states.get(physicalMcpClient(client))?.version!==void 0,legacyMcpFormsAdvertised=client=>states.get(physicalMcpClient(client))?.legacyFormEligible,own3=(value,key)=>Object.hasOwn(value,key),byteSize2=value=>Buffer.byteLength(JSON.stringify(value),"utf8");function getModernDispatchGuard(params){return isRecord(params)?params[modernDispatchGuard]:void 0}function installModernRequestAdapter(client,protocol,clock=mcpElapsedClock,readCredential=()=>{}){let sdkRequest=client.request.bind(client);states.set(client,protocol);let requestWithMrtr=async(request,schema,options)=>{if(request.method==="initialize")return sdkRequest(request,schema,options);let{origin,sdkOptions}=takeMcpRequestOrigin(options,client);if(protocol.version===void 0){let end=request.method==="tools/call"&&origin?beginLegacyMcpOperation(client,origin,sdkOptions.signal):void 0;try{return await sdkRequest(request,schema,sdkOptions)}finally{end?.()}}if(own3(request.params??{},"requestState")||own3(request.params??{},"inputResponses")||options?.task)throw new McpMrtrError("MCP_MRTR_INVALID_INPUT");let params=structuredClone(request.params??{}),start=clock.now(),timeout=sdkOptions.timeout??6e4,duration=Math.min(sdkOptions.maxTotalTimeout??1/0,9*timeout+3e5),deadline=start+duration,operation=new AbortController,credential=readCredential(),authority,authorityCaptured=!1,controller=origin?.connection,generation=controller?.generation,presentationLost=origin?.presentation===void 0||origin.presentation.signal.aborted,consentSpent=0,continuation={},failure,stop=code=>{failure??=new McpMrtrError(code),operation.abort(failure)},onCallerAbort=()=>stop("MCP_MRTR_CANCELLED"),onOwnerAbort=()=>stop("MCP_MRTR_CONTEXT_CHANGED"),onPresentationLost=()=>{presentationLost=!0},check=()=>{if(clock.now()>=deadline&&stop("MCP_MRTR_TIMEOUT"),origin&&(!origin.isCurrent()||origin.signal.aborted||controller?.generation!==generation||controller?.state!=="connected")&&stop("MCP_MRTR_CONTEXT_CHANGED"),failure)throw failure},resolveAuthority=async()=>{if(check(),origin){await origin.privateForm?.synchronize?.();let snapshot=JSON.stringify(await interrupted(origin.resolveAuthority(operation.signal),operation.signal));authorityCaptured?authority!==snapshot&&stop("MCP_MRTR_CONTEXT_CHANGED"):(authority=snapshot,authorityCaptured=!0)}check()},off=controller?.onStateChange(()=>{try{check()}catch{}});sdkOptions.signal?.addEventListener("abort",onCallerAbort,{once:!0}),origin?.signal.addEventListener("abort",onOwnerAbort,{once:!0}),origin?.presentation?.signal.addEventListener("abort",onPresentationLost,{once:!0});let timer=clock.schedule(()=>stop("MCP_MRTR_TIMEOUT"),Math.max(0,duration));sdkOptions.signal?.aborted&&onCallerAbort(),origin?.signal.aborted&&onOwnerAbort();try{let{safeParse}=await interrupted(loadMcpSdkZodCompat(),operation.signal),{ResultSchema}=await interrupted(loadMcpSdkTypes(),operation.signal);for(let round=0;;round++){await resolveAuthority();let remaining=deadline-clock.now(),attempt=new AbortController,forward=()=>attempt.abort("MCP request canceled");operation.signal.addEventListener("abort",forward,{once:!0});let metadata=isRecord(params._meta)?params._meta:{},capabilities=origin?.privateFormsEnforced?origin.privateForm?.ready()?{elicitation:{}}:{}:!presentationLost&&origin?.presentation?{elicitation:{}}:{},outgoing={...params,...continuation,_meta:{...metadata,[capabilitiesKey]:capabilities},[modernDispatchGuard]:snapshot=>{if(check(),(snapshot??readCredential())!==credential)throw new McpMrtrError("MCP_MRTR_CONTEXT_CHANGED")}},result;try{check(),result=await sdkRequest({method:request.method,params:outgoing},ResultSchema,{...sdkOptions,signal:attempt.signal,timeout:Math.min(timeout,remaining),maxTotalTimeout:remaining,onprogress:sdkOptions.onprogress?progress=>{check(),!(!Number.isFinite(progress.progress)||progress.total!==void 0&&!Number.isFinite(progress.total))&&sdkOptions.onprogress?.({progress:progress.progress,...progress.total===void 0?{}:{total:progress.total}})}:void 0})}finally{operation.signal.removeEventListener("abort",forward)}check();let type=own3(result,"resultType")?result.resultType:"complete";if(type==="complete"){if(["requestState","inputRequests","inputResponses"].some(key=>own3(result,key)))throw new McpMrtrError("MCP_MRTR_INVALID_RESULT");let parsed=safeParse(schema,result);if(!parsed.success)throw new McpMrtrError("MCP_MRTR_INVALID_RESULT");return parsed.data}if(type!=="input_required"||!capableMethods.has(request.method))throw new McpMrtrError("MCP_MRTR_INVALID_RESULT");if(round>=MAX_MCP_MRTR_ROUNDS)throw new McpMrtrError("MCP_MRTR_ROUND_LIMIT");let inputs=parseInputs(result);if(continuation=own3(result,"requestState")?{requestState:result.requestState}:{},inputs){let responses=Object.create(null),cancelled=!1;for(let[key,input]of inputs){if(await resolveAuthority(),input.params.mode==="url")throw new McpMrtrError("MCP_MRTR_UNSUPPORTED_INPUT");if(cancelled)throw new McpMrtrError("MCP_MRTR_CANCELLED");if(consentSpent>=3e5)throw new McpMrtrError("MCP_MRTR_PROCESSING_UNAVAILABLE");if(origin?.privateFormsEnforced){let presenter=origin.privateForm,schema2=input.params.requestedSchema;if(!presenter?.ready()||!validateMrtrForm(schema2))throw new McpMrtrError("MCP_MRTR_PROCESSING_UNAVAILABLE");let began=clock.now(),outcome=await presenter.present({operationId:String(start),inputId:key,round,server:{label:origin.serverLabel,source:origin.serverSource??"user"},message:input.params.message,schema:schema2,operationSignal:operation.signal,presentationSignal:presenter.signal,deadlineMs:Math.max(0,3e5-consentSpent)});if(consentSpent+=clock.now()-began,check(),outcome.kind!=="result")throw new McpMrtrError(outcome.kind==="operation_aborted"?"MCP_MRTR_CANCELLED":"MCP_MRTR_PROCESSING_UNAVAILABLE");responses[key]=outcome.result,cancelled=outcome.result.action!=="accept"}else{if(presentationLost||!origin?.presentation)throw new McpMrtrError("MCP_MRTR_PROCESSING_UNAVAILABLE");{let consent=new AbortController,began=clock.now(),consentTimer=clock.schedule(()=>consent.abort(),Math.max(0,3e5-consentSpent)),signal=AbortSignal.any([operation.signal,origin.presentation.signal,consent.signal]),presented=!1;try{let answer=await interrupted(queuedForm(origin.binding,signal,()=>(presented=!0,collectMrtrForm(origin.presentation,origin.serverLabel,{message:input.params.message,requestedSchema:input.params.requestedSchema},signal))),operation.signal);if(check(),!presented)throw new McpMrtrError("MCP_MRTR_PROCESSING_UNAVAILABLE");responses[key]=answer,cancelled=answer.action!=="accept"}finally{consentSpent+=clock.now()-began,clock.cancel(consentTimer),consent.abort()}}}}if(byteSize2(responses)>512*1024)throw new McpMrtrError("MCP_MRTR_INPUT_LIMIT");continuation.inputResponses=responses}}}catch(error){if(check(),error instanceof McpMrtrError||error instanceof AuthError)throw error;let remoteCode=isRecord(error)&&typeof error.code=="number"?error.code:void 0;throw new McpMrtrError("MCP_MRTR_TRANSPORT_FAILED",remoteCode)}finally{continuation={},clock.cancel(timer),off?.(),sdkOptions.signal?.removeEventListener("abort",onCallerAbort),origin?.signal.removeEventListener("abort",onOwnerAbort),origin?.presentation?.signal.removeEventListener("abort",onPresentationLost)}};protocol.activateRequests=()=>{client.request=requestWithMrtr},(protocol.privateForms||protocol.version!==void 0)&&protocol.activateRequests()}function interrupted(work,signal){return new Promise((resolve,reject)=>{let onabort=()=>reject(signal.reason);signal.addEventListener("abort",onabort,{once:!0}),signal.aborted&&onabort(),work.then(resolve,reject).finally(()=>signal.removeEventListener("abort",onabort))})}import{execFile}from"node:child_process";import{promisify}from"node:util";var execFileAsync=promisify(execFile);async function collectProcessTree(rootPid){let seen=new Set,queue=[rootPid];for(let index=0;index<queue.length;index++){let pid=queue[index];if(!seen.has(pid)){seen.add(pid);for(let childPid of await childPids(pid))seen.has(childPid)||queue.push(childPid)}}return[...seen]}async function reapProcessTree(rootPid,options){let knownPids=new Set(await collectProcessTree(rootPid));if(someProcessAlive(knownPids)){killPids(knownPids,"SIGTERM"),await waitForDead(knownPids,options.termWaitMs);for(let pid of await collectProcessTree(rootPid))knownPids.add(pid);someProcessAlive(knownPids)&&(killPids(knownPids,"SIGKILL"),await waitForDead(knownPids,options.killWaitMs))}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error){return!1}}function delay(ms){return safeDelay(ms)}async function childPids(parentPid){if(!["darwin","linux"].includes(process.platform))return[];try{let{stdout}=await execFileAsync("pgrep",["-P",String(parentPid),"."],{timeout:1e3});return stdout.split(/\s+/).map(Number).filter(pid=>Number.isInteger(pid)&&pid>0)}catch(error){return[]}}function killPids(pids,signal){for(let pid of[...pids].reverse())if(!(!Number.isInteger(pid)||pid<=1))try{process.kill(pid,signal)}catch(error){}}async function waitForDead(pids,timeoutMs){let deadline=Date.now()+timeoutMs;for(;Date.now()<deadline;){if(!someProcessAlive(pids))return;await delay(25)}}function someProcessAlive(pids){for(let pid of pids)if(isProcessAlive(pid))return!0;return!1}export{LOG_SINK_RETRY_MS,rotateLogIfNeeded,keyedIdentity,isEphemeralIdentity,createMcpLogger,fingerprintSecret,redactMcpLogText,mcpElapsedClock,wrapAsync,safeTimer,safeInterval,safeDelay,safeOn,safeEventBusOn,reportMcpAsyncError,ConnectError,ToolExecError,AuthError,TimeoutError,SessionExpiredError,isRetriableMcpError,isMcpSessionExpiredError,OAuthFlowError,isInvalidGrant,isTransientTokenError,loadMcpSdkClient,loadMcpSdkStdioTransport,loadMcpSdkAuth,loadMcpSdkStreamableHttpTransport,isMcpNeedsAuthError,registerMcpClientAlias,createMcpRequestOrigin,mcpRequestOptions,mcpClientCapabilities,legacyMcpFormEligible,configureMcpElicitation,collectMrtrForm,modernDispatchGuard,isModernMcpClient,legacyMcpFormsAdvertised,getModernDispatchGuard,installModernRequestAdapter,reapProcessTree,delay};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{listHostEndpoints}from"./chunk-
|
|
2
|
+
import{listHostEndpoints}from"./chunk-PT6JJUN2.js";import{randomBytes}from"node:crypto";var MONITOR_ID_ALPHABET="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function allocateMonitorId(){let id="mon_",buffer=0,bits=0;for(let byte of randomBytes(10))for(buffer=buffer<<8|byte,bits+=8;bits>=5;)bits-=5,id+=MONITOR_ID_ALPHABET[buffer>>bits&31];return id}var STATUS_KINDS=new Set(["session_status","effect_status"]);function parseRpcTarget(target,selfDurableId){let trimmed=target.trim();return trimmed===""?{error:'target is empty; pass "children", "all" or a session id, path or st_ task id'}:trimmed==="children"?selfDurableId===void 0?{error:'target "children" needs a session with a durable id; save the session first, or watch "all"'}:{kind:"children",parent:selfDurableId}:trimmed==="all"?{kind:"all"}:trimmed.startsWith("st_")?{kind:"task",taskId:trimmed}:{kind:"id",id:trimmed}}function defaultEvents(target){return target.kind==="children"?["session_status","effect_status"]:["session_status"]}function subscriptionFor(target,events){let sessions=target.kind==="children"?{childrenOf:target.parent}:target.kind==="id"?{ids:[target.id]}:"all",content=events==="all"?"all":events.filter(kind=>!STATUS_KINDS.has(kind)),mirror=content==="all"?"all":content.length===0?void 0:content;return{sessions,include_workers:!0,include_context:target.kind==="children"||target.kind==="task",effects:events==="all"||events.includes("effect_status"),...mirror===void 0?{}:{mirror}}}function wantsRecord(events,exclude,type){return exclude.includes(type)?!1:events==="all"||events.includes(type)}function matchesTask(target,row){return target.kind!=="task"?!0:row.context?.task_id===target.taskId}async function endpointSockets(agentDir){return(await listHostEndpoints(agentDir)).map(endpoint=>endpoint.socket).filter(socket=>socket!==null)}export{allocateMonitorId,parseRpcTarget,defaultEvents,subscriptionFor,wantsRecord,matchesTask,endpointSockets};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{source_default}from"./chunk-26UBFF6N.js";import{legacyProviderIdRejection}from"./chunk-6AOVUTUR.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,ENV_SESSION_DIR,brandEnvNames,envValue}from"./chunk-7YO7VQZW.js";function isSpawnedBy(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&"parentSessionId"in value&&typeof value.parentSessionId=="string"&&value.parentSessionId.length>0&&"rootSessionId"in value&&typeof value.rootSessionId=="string"&&value.rootSessionId.length>0&&"taskId"in value&&typeof value.taskId=="string"&&value.taskId.length>0}function isGrokNeoEnabled(env=process.env){let value=envValue("ENABLE_GROK_NEO",env);if(value===void 0)return!1;let normalized=value.trim().toLowerCase();return normalized==="1"||normalized==="true"||normalized==="yes"}var TOOL_RUNTIMES=["in-process","child"];function isToolRuntimeKind(value){return TOOL_RUNTIMES.some(kind=>kind===value)}var TOOL_RUNTIME_ENV_SUFFIX="TOOL_RUNTIME",TOOL_CHILD_PLACEMENTS=["launch-barrier","job-policy","hostcall","offload","terminal"],OFFLOAD_API_CAPABILITY="offload_api";function toolRuntimeCapabilities(runtime){return[toolRuntimeCapability(runtime),...runtime==="child"?TOOL_CHILD_PLACEMENTS.map(name=>`placement:${name}`):[],OFFLOAD_API_CAPABILITY]}function isHostOwnedToolRuntimeCapability(capability){return capability.startsWith("tool_runtime:")||capability.startsWith("placement:")||capability===OFFLOAD_API_CAPABILITY}function toolRuntimeCapability(runtime){return`tool_runtime:${runtime}`}var TOOL_RUNTIME_UNSUPPORTED_HOST="tool_runtime_unsupported_host";function toolRuntimeHostRefusal(runtime,platform=process.platform,hasFfi=()=>process.getBuiltinModule("bun:ffi")!==void 0){if(!(runtime!=="child"||platform!=="win32"||hasFfi()))return`${TOOL_RUNTIME_UNSUPPORTED_HOST}: --tool-runtime child on Windows needs the Bun runtime (bun:ffi holds the tool child in a Job Object); run senpi under Bun or use in-process`}var ToolRuntimeUnsupportedHostError=class extends Error{constructor(message){super(message),this.code=TOOL_RUNTIME_UNSUPPORTED_HOST,this.name="ToolRuntimeUnsupportedHostError"}};function resolveToolRuntime(parsed,env=process.env,platform=process.platform,hasFfi){let resolved=resolveRequestedToolRuntime(parsed,env);if(!resolved.ok)return resolved;let refusal=toolRuntimeHostRefusal(resolved.value,platform,hasFfi);return refusal===void 0?resolved:{ok:!1,message:refusal}}function resolveRequestedToolRuntime(parsed,env){if(parsed.toolRuntime!==void 0)return{ok:!0,value:parsed.toolRuntime};let fromEnv=envValue(TOOL_RUNTIME_ENV_SUFFIX,env);return fromEnv===void 0||fromEnv===""?{ok:!0,value:"in-process"}:isToolRuntimeKind(fromEnv)?{ok:!0,value:fromEnv}:{ok:!1,message:`${brandEnvNames(TOOL_RUNTIME_ENV_SUFFIX).find(candidate=>env[candidate]!==void 0)??TOOL_RUNTIME_ENV_SUFFIX} (--tool-runtime) must be in-process or child, got ${JSON.stringify(fromEnv)}`}}var SESSION_RUNTIMES=["in-process","worker"];function isSessionRuntimeKind(value){return SESSION_RUNTIMES.includes(value)}function resolveSessionRuntime(parsed){return parsed.sessionRuntime?parsed.sessionRuntime:parsed.listen!==void 0&&parsed.listen!=="stdio://"?"in-process":"worker"}var VALID_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isValidThinkingLevel(level){return VALID_THINKING_LEVELS.includes(level)}function normalizeSessionName(value){let name=value.trim();return name.length>0?name:void 0}function parseArgs(args,options={}){let grokNeoEnabled=options.grokNeoEnabled??isGrokNeoEnabled(),result={messages:[],fileArgs:[],unknownFlags:new Map,diagnostics:[]};if(args[0]==="app-server")return result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`}),result;let hasRetiredCommand=!1;for(let i=0;i<args.length;i++){let arg=args[i];if(arg==="--"){for(let positionalArg of args.slice(i+1))positionalArg.startsWith("@")?result.fileArgs.push(positionalArg.slice(1)):result.messages.push(positionalArg);break}else if(arg==="--help"||arg==="-h")result.help=!0;else if(arg==="--version"||arg==="-v")result.version=!0;else if(arg==="--mode"){let mode=args[i+1];if(mode===void 0||mode.startsWith("-")){result.diagnostics.push({type:"error",message:"--mode requires text, json, or rpc"});continue}if(i++,mode!=="text"&&mode!=="json"&&mode!=="rpc"){result.diagnostics.push({type:"error",message:`Invalid mode "${mode}". Valid values: text, json, rpc`});continue}result.mode=mode}else if(arg==="--continue"||arg==="-c")result.continue=!0;else if(arg==="--resume"||arg==="-r")result.resume=!0;else if(arg==="--provider"&&i+1<args.length){let typedProvider=args[++i],rejection=typedProvider===void 0?void 0:legacyProviderIdRejection(typedProvider);if(rejection)throw new Error(rejection);result.provider=typedProvider}else if(arg==="--model"&&i+1<args.length)result.model=args[++i];else if(arg==="--api-key"&&i+1<args.length)result.apiKey=args[++i];else if(arg==="--system-prompt"&&i+1<args.length)result.systemPrompt=args[++i];else if(arg==="--append-system-prompt"&&i+1<args.length)result.appendSystemPrompt=result.appendSystemPrompt??[],result.appendSystemPrompt.push(args[++i]);else if(arg==="--name"||arg==="-n")i+1<args.length?result.name=args[++i]:result.diagnostics.push({type:"error",message:"--name requires a value"});else if(arg==="--no-session")result.noSession=!0;else if(arg==="--session"&&i+1<args.length)result.session=args[++i];else if(arg==="--session-id"&&i+1<args.length)result.sessionId=args[++i];else if(arg==="--spawned-by"){let value=args[i+1];if(value===void 0||value.startsWith("-"))result.diagnostics.push({type:"error",message:"--spawned-by requires a JSON object"});else{i++;try{let ancestry=JSON.parse(value);isSpawnedBy(ancestry)?result.spawnedBy=ancestry:result.diagnostics.push({type:"error",message:"--spawned-by requires non-empty parentSessionId, rootSessionId, and taskId strings"})}catch(error){if(!(error instanceof SyntaxError))throw error;result.diagnostics.push({type:"error",message:"--spawned-by must be valid JSON"})}}}else if(arg==="--fork"&&i+1<args.length)result.fork=args[++i];else if(arg==="--rebind"&&i+1<args.length)result.rebind=args[++i];else if(arg==="--session-dir"&&i+1<args.length)result.sessionDir=args[++i];else if(arg==="--models"&&i+1<args.length)result.models=args[++i].split(",").map(s=>s.trim());else if(arg==="--no-tools"||arg==="-nt")result.noTools=!0;else if(arg==="--no-builtin-tools"||arg==="-nbt")result.noBuiltinTools=!0;else if((arg==="--tools"||arg==="-t")&&i+1<args.length)result.tools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if((arg==="--exclude-tools"||arg==="-xt")&&i+1<args.length)result.excludeTools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if(arg==="--thinking"&&i+1<args.length){let level=args[++i];isValidThinkingLevel(level)?result.thinking=level:result.diagnostics.push({type:"warning",message:`Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`})}else if(arg==="--print"||arg==="-p"){result.print=!0;let next=args[i+1];next!==void 0&&!next.startsWith("@")&&(!next.startsWith("-")||next.startsWith("---"))&&(result.messages.push(next),i++)}else if(arg==="--export"&&i+1<args.length)result.export=args[++i];else if((arg==="--extension"||arg==="-e")&&i+1<args.length)result.extensions=result.extensions??[],result.extensions.push(args[++i]);else if(arg==="--no-extensions"||arg==="-ne")result.noExtensions=!0;else if(arg==="--skill"&&i+1<args.length)result.skills=result.skills??[],result.skills.push(args[++i]);else if(arg==="--prompt-template"&&i+1<args.length)result.promptTemplates=result.promptTemplates??[],result.promptTemplates.push(args[++i]);else if(arg==="--theme"&&i+1<args.length)result.themes=result.themes??[],result.themes.push(args[++i]);else if(arg==="--use-theme"){let themeName=args[i+1];themeName===void 0||themeName.startsWith("-")?result.diagnostics.push({type:"error",message:"--use-theme requires a theme name"}):(result.useTheme=themeName,i++)}else if(arg==="--no-skills"||arg==="-ns")result.noSkills=!0;else if(arg==="--no-prompt-templates"||arg==="-np")result.noPromptTemplates=!0;else if(arg==="--no-themes")result.noThemes=!0;else if(arg==="--no-context-files"||arg==="-nc")result.noContextFiles=!0;else if(arg==="--print-prompt-sizes")result.printPromptSizes=!0;else if(arg==="--list-models")i+1<args.length&&!args[i+1].startsWith("-")&&!args[i+1].startsWith("@")?result.listModels=args[++i]:result.listModels=!0;else if(arg==="--list-tips")result.listTips=!0;else if(arg==="--tui-mode"){let mode=args[i+1];mode==="regular"||mode==="fullscreen"?(result.tuiMode=mode,i++):mode===void 0||mode.startsWith("-")?result.diagnostics.push({type:"error",message:"--tui-mode requires regular or fullscreen"}):(i++,result.diagnostics.push({type:"error",message:`Invalid TUI mode "${mode}". Valid values: regular, fullscreen`}))}else if(arg==="--verbose")result.verbose=!0;else if(arg==="--approve"||arg==="-a")result.projectTrustOverride=!0;else if(arg==="--no-approve"||arg==="-na")result.projectTrustOverride=!1;else if(arg==="--offline")result.offline=!0;else if(grokNeoEnabled&&arg==="--grok-neo")result.grokNeo=!0;else if(arg==="--multi-session")result.multiSession=!0;else if(arg==="--auto-title-sessions")result.autoTitleSessions=!0;else if(arg==="--session-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isSessionRuntimeKind(value)?result.sessionRuntime=value:result.diagnostics.push({type:"error",message:"--session-runtime must be in-process or worker"})}else if(arg==="--tool-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isToolRuntimeKind(value)?result.toolRuntime=value:result.diagnostics.push({type:"error",message:"--tool-runtime must be in-process or child"})}else if(arg==="--listen"&&result.mode==="rpc"){let value=args[i+1];value===void 0||value.startsWith("--")?result.diagnostics.push({type:"error",message:"--listen requires a value"}):(result.listen=value,result.multiSession=!0,i++)}else if(arg.startsWith("@"))result.fileArgs.push(arg.slice(1));else if(arg.startsWith("--")){let eqIndex=arg.indexOf("=");if(eqIndex!==-1)result.unknownFlags.set(arg.slice(2,eqIndex),arg.slice(eqIndex+1));else{let flagName=arg.slice(2),next=args[i+1];next!==void 0&&!next.startsWith("-")&&!next.startsWith("@")?(result.unknownFlags.set(flagName,next),i++):result.unknownFlags.set(flagName,!0)}}else arg==="-"?result.readStdin=!0:arg.startsWith("-")&&!arg.startsWith("--")?result.diagnostics.push({type:"error",message:`Unknown option: ${arg}`}):arg.startsWith("-")||(result.messages.length===0&&arg==="app-server"&&(hasRetiredCommand=!0),result.messages.push(arg))}return hasRetiredCommand&&result.mode===void 0&&!result.print&&(result.messages=[],result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`})),result}function printHelp(extensionFlags,grokNeoEnabled=isGrokNeoEnabled()){let extensionFlagsText=extensionFlags&&extensionFlags.length>0?`
|
|
2
|
+
import{source_default}from"./chunk-26UBFF6N.js";import{legacyProviderIdRejection}from"./chunk-6AOVUTUR.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,ENV_SESSION_DIR,brandEnvNames,envValue}from"./chunk-7YO7VQZW.js";function isSpawnedBy(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&"parentSessionId"in value&&typeof value.parentSessionId=="string"&&value.parentSessionId.length>0&&"rootSessionId"in value&&typeof value.rootSessionId=="string"&&value.rootSessionId.length>0&&"taskId"in value&&typeof value.taskId=="string"&&value.taskId.length>0}function isGrokNeoEnabled(env=process.env){let value=envValue("ENABLE_GROK_NEO",env);if(value===void 0)return!1;let normalized=value.trim().toLowerCase();return normalized==="1"||normalized==="true"||normalized==="yes"}var TOOL_RUNTIMES=["in-process","child"];function isToolRuntimeKind(value){return TOOL_RUNTIMES.some(kind=>kind===value)}var TOOL_RUNTIME_ENV_SUFFIX="TOOL_RUNTIME",TOOL_CHILD_PLACEMENTS=["launch-barrier","job-policy","hostcall","offload","terminal"],OFFLOAD_API_CAPABILITY="offload_api";function toolRuntimeCapabilities(runtime){return[toolRuntimeCapability(runtime),...runtime==="child"?TOOL_CHILD_PLACEMENTS.map(name=>`placement:${name}`):[],OFFLOAD_API_CAPABILITY]}function isHostOwnedToolRuntimeCapability(capability){return capability.startsWith("tool_runtime:")||capability.startsWith("placement:")||capability===OFFLOAD_API_CAPABILITY}function toolRuntimeCapability(runtime){return`tool_runtime:${runtime}`}var TOOL_RUNTIME_UNSUPPORTED_HOST="tool_runtime_unsupported_host";function toolRuntimeHostRefusal(runtime,platform=process.platform,hasFfi=()=>process.getBuiltinModule("bun:ffi")!==void 0){if(!(runtime!=="child"||platform!=="win32"||hasFfi()))return`${TOOL_RUNTIME_UNSUPPORTED_HOST}: --tool-runtime child on Windows needs the Bun runtime (bun:ffi holds the tool child in a Job Object); run senpi under Bun or use in-process`}var ToolRuntimeUnsupportedHostError=class extends Error{constructor(message){super(message),this.code=TOOL_RUNTIME_UNSUPPORTED_HOST,this.name="ToolRuntimeUnsupportedHostError"}};function resolveToolRuntime(parsed,env=process.env,platform=process.platform,hasFfi){let resolved=resolveRequestedToolRuntime(parsed,env);if(!resolved.ok)return resolved;let refusal=toolRuntimeHostRefusal(resolved.value,platform,hasFfi);return refusal===void 0?resolved:{ok:!1,message:refusal}}function resolveRequestedToolRuntime(parsed,env){if(parsed.toolRuntime!==void 0)return{ok:!0,value:parsed.toolRuntime};let fromEnv=envValue(TOOL_RUNTIME_ENV_SUFFIX,env);return fromEnv===void 0||fromEnv===""?{ok:!0,value:"in-process"}:isToolRuntimeKind(fromEnv)?{ok:!0,value:fromEnv}:{ok:!1,message:`${brandEnvNames(TOOL_RUNTIME_ENV_SUFFIX).find(candidate=>env[candidate]!==void 0)??TOOL_RUNTIME_ENV_SUFFIX} (--tool-runtime) must be in-process or child, got ${JSON.stringify(fromEnv)}`}}var SESSION_RUNTIMES=["in-process","worker"];function isSessionRuntimeKind(value){return SESSION_RUNTIMES.includes(value)}function resolveSessionRuntime(parsed){return parsed.sessionRuntime?parsed.sessionRuntime:parsed.listen!==void 0&&parsed.listen!=="stdio://"?"in-process":"worker"}var VALID_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isValidThinkingLevel(level){return VALID_THINKING_LEVELS.includes(level)}function normalizeSessionName(value){let name=value.trim();return name.length>0?name:void 0}function parseArgs(args,options={}){let grokNeoEnabled=options.grokNeoEnabled??isGrokNeoEnabled(),result={messages:[],fileArgs:[],unknownFlags:new Map,diagnostics:[]};if(args[0]==="app-server")return result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`}),result;let hasRetiredCommand=!1;for(let i=0;i<args.length;i++){let arg=args[i];if(arg==="--"){for(let positionalArg of args.slice(i+1))positionalArg.startsWith("@")?result.fileArgs.push(positionalArg.slice(1)):result.messages.push(positionalArg);break}else if(arg==="--help"||arg==="-h")result.help=!0;else if(arg==="--version"||arg==="-v")result.version=!0;else if(arg==="--mode"){let mode=args[i+1];if(mode===void 0||mode.startsWith("-")){result.diagnostics.push({type:"error",message:"--mode requires text, json, or rpc"});continue}if(i++,mode!=="text"&&mode!=="json"&&mode!=="rpc"){result.diagnostics.push({type:"error",message:`Invalid mode "${mode}". Valid values: text, json, rpc`});continue}result.mode=mode}else if(arg==="--continue"||arg==="-c")result.continue=!0;else if(arg==="--resume"||arg==="-r")result.resume=!0;else if(arg==="--provider"&&i+1<args.length){let typedProvider=args[++i],rejection=typedProvider===void 0?void 0:legacyProviderIdRejection(typedProvider);if(rejection)throw new Error(rejection);result.provider=typedProvider}else if(arg==="--model"&&i+1<args.length)result.model=args[++i];else if(arg==="--api-key"&&i+1<args.length)result.apiKey=args[++i];else if(arg==="--system-prompt"&&i+1<args.length)result.systemPrompt=args[++i];else if(arg==="--append-system-prompt"&&i+1<args.length)result.appendSystemPrompt=result.appendSystemPrompt??[],result.appendSystemPrompt.push(args[++i]);else if(arg==="--name"||arg==="-n")i+1<args.length?result.name=args[++i]:result.diagnostics.push({type:"error",message:"--name requires a value"});else if(arg==="--no-session")result.noSession=!0;else if(arg==="--session"&&i+1<args.length)result.session=args[++i];else if(arg==="--session-id"&&i+1<args.length)result.sessionId=args[++i];else if(arg==="--spawned-by"){let value=args[i+1];if(value===void 0||value.startsWith("-"))result.diagnostics.push({type:"error",message:"--spawned-by requires a JSON object"});else{i++;try{let ancestry=JSON.parse(value);isSpawnedBy(ancestry)?result.spawnedBy=ancestry:result.diagnostics.push({type:"error",message:"--spawned-by requires non-empty parentSessionId, rootSessionId, and taskId strings"})}catch(error){if(!(error instanceof SyntaxError))throw error;result.diagnostics.push({type:"error",message:"--spawned-by must be valid JSON"})}}}else if(arg==="--fork"&&i+1<args.length)result.fork=args[++i];else if(arg==="--rebind"&&i+1<args.length)result.rebind=args[++i];else if(arg==="--session-dir"&&i+1<args.length)result.sessionDir=args[++i];else if(arg==="--models"&&i+1<args.length)result.models=args[++i].split(",").map(s=>s.trim());else if(arg==="--no-tools"||arg==="-nt")result.noTools=!0;else if(arg==="--no-builtin-tools"||arg==="-nbt")result.noBuiltinTools=!0;else if((arg==="--tools"||arg==="-t")&&i+1<args.length)result.tools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if((arg==="--exclude-tools"||arg==="-xt")&&i+1<args.length)result.excludeTools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if(arg==="--thinking"&&i+1<args.length){let level=args[++i];isValidThinkingLevel(level)?result.thinking=level:result.diagnostics.push({type:"warning",message:`Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`})}else if(arg==="--print"||arg==="-p"){result.print=!0;let next=args[i+1];next!==void 0&&!next.startsWith("@")&&(!next.startsWith("-")||next.startsWith("---"))&&(result.messages.push(next),i++)}else if(arg==="--export"&&i+1<args.length)result.export=args[++i];else if((arg==="--extension"||arg==="-e")&&i+1<args.length)result.extensions=result.extensions??[],result.extensions.push(args[++i]);else if(arg==="--no-extensions"||arg==="-ne")result.noExtensions=!0;else if(arg==="--skill"&&i+1<args.length)result.skills=result.skills??[],result.skills.push(args[++i]);else if(arg==="--prompt-template"&&i+1<args.length)result.promptTemplates=result.promptTemplates??[],result.promptTemplates.push(args[++i]);else if(arg==="--theme"&&i+1<args.length)result.themes=result.themes??[],result.themes.push(args[++i]);else if(arg==="--use-theme"){let themeName=args[i+1];themeName===void 0||themeName.startsWith("-")?result.diagnostics.push({type:"error",message:"--use-theme requires a theme name"}):(result.useTheme=themeName,i++)}else if(arg==="--no-skills"||arg==="-ns")result.noSkills=!0;else if(arg==="--no-prompt-templates"||arg==="-np")result.noPromptTemplates=!0;else if(arg==="--no-themes")result.noThemes=!0;else if(arg==="--no-context-files"||arg==="-nc")result.noContextFiles=!0;else if(arg==="--print-prompt-sizes")result.printPromptSizes=!0;else if(arg==="--list-models")i+1<args.length&&!args[i+1].startsWith("-")&&!args[i+1].startsWith("@")?result.listModels=args[++i]:result.listModels=!0;else if(arg==="--list-tips")result.listTips=!0;else if(arg==="--tui-mode"){let mode=args[i+1];mode==="regular"||mode==="fullscreen"?(result.tuiMode=mode,i++):mode===void 0||mode.startsWith("-")?result.diagnostics.push({type:"error",message:"--tui-mode requires regular or fullscreen"}):(i++,result.diagnostics.push({type:"error",message:`Invalid TUI mode "${mode}". Valid values: regular, fullscreen`}))}else if(arg==="--verbose")result.verbose=!0;else if(arg==="--approve"||arg==="-a")result.projectTrustOverride=!0;else if(arg==="--no-approve"||arg==="-na")result.projectTrustOverride=!1;else if(arg==="--offline")result.offline=!0;else if(grokNeoEnabled&&arg==="--grok-neo")result.grokNeo=!0;else if(arg==="--multi-session")result.multiSession=!0;else if(arg==="--mcp-presenter-fd")args[++i]==="4"?result.presenterBootstrapFd=4:result.diagnostics.push({type:"error",message:"Invalid presenter bootstrap descriptor"});else if(arg==="--mcp-presenter-enforcement")result.mcpPresenterEnforcement=!0;else if(arg==="--auto-title-sessions")result.autoTitleSessions=!0;else if(arg==="--session-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isSessionRuntimeKind(value)?result.sessionRuntime=value:result.diagnostics.push({type:"error",message:"--session-runtime must be in-process or worker"})}else if(arg==="--tool-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isToolRuntimeKind(value)?result.toolRuntime=value:result.diagnostics.push({type:"error",message:"--tool-runtime must be in-process or child"})}else if(arg==="--listen"&&result.mode==="rpc"){let value=args[i+1];value===void 0||value.startsWith("--")?result.diagnostics.push({type:"error",message:"--listen requires a value"}):(result.listen=value,result.multiSession=!0,i++)}else if(arg.startsWith("@"))result.fileArgs.push(arg.slice(1));else if(arg.startsWith("--")){let eqIndex=arg.indexOf("=");if(eqIndex!==-1)result.unknownFlags.set(arg.slice(2,eqIndex),arg.slice(eqIndex+1));else{let flagName=arg.slice(2),next=args[i+1];next!==void 0&&!next.startsWith("-")&&!next.startsWith("@")?(result.unknownFlags.set(flagName,next),i++):result.unknownFlags.set(flagName,!0)}}else arg==="-"?result.readStdin=!0:arg.startsWith("-")&&!arg.startsWith("--")?result.diagnostics.push({type:"error",message:`Unknown option: ${arg}`}):arg.startsWith("-")||(result.messages.length===0&&arg==="app-server"&&(hasRetiredCommand=!0),result.messages.push(arg))}return hasRetiredCommand&&result.mode===void 0&&!result.print&&(result.messages=[],result.diagnostics.push({type:"error",message:`The app-server command has been removed. Use "${APP_NAME} --mode rpc" for process integration.`})),result}function printHelp(extensionFlags,grokNeoEnabled=isGrokNeoEnabled()){let extensionFlagsText=extensionFlags&&extensionFlags.length>0?`
|
|
3
3
|
${source_default.bold("Extension CLI Flags:")}
|
|
4
4
|
${extensionFlags.map(flag=>{let value=flag.type==="string"?" <value>":"",description=flag.description??`Registered by ${flag.extensionPath}`;return` --${flag.name}${value}`.padEnd(30)+description}).join(`
|
|
5
5
|
`)}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{$ZodAny,$ZodArray,$ZodBase64,$ZodBase64URL,$ZodBigInt,$ZodBoolean,$ZodCIDRv4,$ZodCIDRv6,$ZodCUID,$ZodCUID2,$ZodCatch,$ZodCheck,$ZodCustom,$ZodDate,$ZodDefault,$ZodDiscriminatedUnion,$ZodE164,$ZodEmail,$ZodEmoji,$ZodEnum,$ZodError,$ZodGUID,$ZodIPv4,$ZodIPv6,$ZodISODate,$ZodISODateTime,$ZodISODuration,$ZodISOTime,$ZodIntersection,$ZodJWT,$ZodKSUID,$ZodLiteral,$ZodNanoID,$ZodNever,$ZodNonOptional,$ZodNull,$ZodNullable,$ZodNumber,$ZodNumberFormat,$ZodObject,$ZodOptional,$ZodPipe,$ZodPrefault,$ZodReadonly,$ZodRecord,$ZodString,$ZodStringFormat,$ZodTransform,$ZodType,$ZodULID,$ZodURL,$ZodUUID,$ZodUnion,$ZodUnknown,$ZodXID,$constructor,_any,_array,_base64,_base64url,_boolean,_cidrv4,_cidrv6,_coercedBigint,_coercedBoolean,_coercedDate,_coercedNumber,_coercedString,_cuid,_cuid2,_custom,_e164,_email,_emoji,_endsWith,_gt,_gte,_guid,_includes,_int,_ipv4,_ipv6,_isoDate,_isoDateTime,_isoDuration,_isoTime,_jwt,_ksuid,_length,_lowercase,_lt,_lte,_maxLength,_minLength,_multipleOf,_nanoid,_never,_normalize,_null,_number,_overwrite,_parse,_parseAsync,_refine,_regex,_safeParse,_safeParseAsync,_startsWith,_string,_toLowerCase,_toUpperCase,_trim,_ulid,_unknown,_uppercase,_url,_uuid,_uuidv4,_uuidv6,_uuidv7,_xid,clone,config,flattenError,formatError,globalRegistry,joinValues,stringifyPrimitive,util_exports}from"./chunk-AX72VNRS.js";import{__export}from"./chunk-IKOFCODM.js";var parsedType=data=>{let t=typeof data;switch(t){case"number":return Number.isNaN(data)?"NaN":"number";case"object":{if(Array.isArray(data))return"array";if(data===null)return"null";if(Object.getPrototypeOf(data)!==Object.prototype&&data.constructor)return data.constructor.name}}return t},error=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let Nouns={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return issue=>{switch(issue.code){case"invalid_type":return`Invalid input: expected ${issue.expected}, received ${parsedType(issue.input)}`;case"invalid_value":return issue.values.length===1?`Invalid input: expected ${stringifyPrimitive(issue.values[0])}`:`Invalid option: expected one of ${joinValues(issue.values,"|")}`;case"too_big":{let adj=issue.inclusive?"<=":"<",sizing=getSizing(issue.origin);return sizing?`Too big: expected ${issue.origin??"value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit??"elements"}`:`Too big: expected ${issue.origin??"value"} to be ${adj}${issue.maximum.toString()}`}case"too_small":{let adj=issue.inclusive?">=":">",sizing=getSizing(issue.origin);return sizing?`Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`:`Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`}case"invalid_format":{let _issue=issue;return _issue.format==="starts_with"?`Invalid string: must start with "${_issue.prefix}"`:_issue.format==="ends_with"?`Invalid string: must end with "${_issue.suffix}"`:_issue.format==="includes"?`Invalid string: must include "${_issue.includes}"`:_issue.format==="regex"?`Invalid string: must match pattern ${_issue.pattern}`:`Invalid ${Nouns[_issue.format]??issue.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue.keys.length>1?"s":""}: ${joinValues(issue.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${issue.origin}`;default:return"Invalid input"}}};function en_default(){return{localeError:error()}}var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date,datetime:()=>datetime,duration:()=>duration,time:()=>time});var ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});function datetime(params){return _isoDateTime(ZodISODateTime,params)}var ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});function date(params){return _isoDate(ZodISODate,params)}var ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});function time(params){return _isoTime(ZodISOTime,params)}var ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)});function duration(params){return _isoDuration(ZodISODuration,params)}var initializer=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError",Object.defineProperties(inst,{format:{value:mapper=>formatError(inst,mapper)},flatten:{value:mapper=>flattenError(inst,mapper)},addIssue:{value:issue=>inst.issues.push(issue)},addIssues:{value:issues2=>inst.issues.push(...issues2)},isEmpty:{get(){return inst.issues.length===0}}})},ZodError=$constructor("ZodError",initializer),ZodRealError=$constructor("ZodError",initializer,{Parent:Error});var parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError);var ZodType=$constructor("ZodType",(inst,def)=>($ZodType.init(inst,def),inst.def=def,Object.defineProperty(inst,"_def",{value:def}),inst.check=(...checks)=>inst.clone({...def,checks:[...def.checks??[],...checks.map(ch=>typeof ch=="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),inst.clone=(def2,params)=>clone(inst,def2,params),inst.brand=()=>inst,inst.register=((reg,meta)=>(reg.add(inst,meta),inst)),inst.parse=(data,params)=>parse(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync(inst,data,params),inst.spa=inst.safeParseAsync,inst.refine=(check2,params)=>inst.check(refine(check2,params)),inst.superRefine=refinement=>inst.check(superRefine(refinement)),inst.overwrite=fn=>inst.check(_overwrite(fn)),inst.optional=()=>optional(inst),inst.nullable=()=>nullable(inst),inst.nullish=()=>optional(nullable(inst)),inst.nonoptional=params=>nonoptional(inst,params),inst.array=()=>array(inst),inst.or=arg=>union([inst,arg]),inst.and=arg=>intersection(inst,arg),inst.transform=tx=>pipe(inst,transform(tx)),inst.default=def2=>_default(inst,def2),inst.prefault=def2=>prefault(inst,def2),inst.catch=params=>_catch(inst,params),inst.pipe=target=>pipe(inst,target),inst.readonly=()=>readonly(inst),inst.describe=description=>{let cl=inst.clone();return globalRegistry.add(cl,{description}),cl},Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst.meta=(...args)=>{if(args.length===0)return globalRegistry.get(inst);let cl=inst.clone();return globalRegistry.add(cl,args[0]),cl},inst.isOptional=()=>inst.safeParse(void 0).success,inst.isNullable=()=>inst.safeParse(null).success,inst)),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,inst.regex=(...args)=>inst.check(_regex(...args)),inst.includes=(...args)=>inst.check(_includes(...args)),inst.startsWith=(...args)=>inst.check(_startsWith(...args)),inst.endsWith=(...args)=>inst.check(_endsWith(...args)),inst.min=(...args)=>inst.check(_minLength(...args)),inst.max=(...args)=>inst.check(_maxLength(...args)),inst.length=(...args)=>inst.check(_length(...args)),inst.nonempty=(...args)=>inst.check(_minLength(1,...args)),inst.lowercase=params=>inst.check(_lowercase(params)),inst.uppercase=params=>inst.check(_uppercase(params)),inst.trim=()=>inst.check(_trim()),inst.normalize=(...args)=>inst.check(_normalize(...args)),inst.toLowerCase=()=>inst.check(_toLowerCase()),inst.toUpperCase=()=>inst.check(_toUpperCase())}),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=params=>inst.check(_email(ZodEmail,params)),inst.url=params=>inst.check(_url(ZodURL,params)),inst.jwt=params=>inst.check(_jwt(ZodJWT,params)),inst.emoji=params=>inst.check(_emoji(ZodEmoji,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.uuid=params=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=params=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=params=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=params=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=params=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.cuid=params=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=params=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=params=>inst.check(_ulid(ZodULID,params)),inst.base64=params=>inst.check(_base64(ZodBase64,params)),inst.base64url=params=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=params=>inst.check(_xid(ZodXID,params)),inst.ksuid=params=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=params=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=params=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=params=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=params=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=params=>inst.check(_e164(ZodE164,params)),inst.datetime=params=>inst.check(datetime(params)),inst.date=params=>inst.check(date(params)),inst.time=params=>inst.check(time(params)),inst.duration=params=>inst.check(duration(params))});function string(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.int=params=>inst.check(int(params)),inst.safe=params=>inst.check(int(params)),inst.positive=params=>inst.check(_gt(0,params)),inst.nonnegative=params=>inst.check(_gte(0,params)),inst.negative=params=>inst.check(_lt(0,params)),inst.nonpositive=params=>inst.check(_lte(0,params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params)),inst.step=(value,params)=>inst.check(_multipleOf(value,params)),inst.finite=()=>inst;let bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??.5),inst.isFinite=!0,inst.format=bag.format??null});function number(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def)});function boolean(params){return _boolean(ZodBoolean,params)}var ZodBigInt=$constructor("ZodBigInt",(inst,def)=>{$ZodBigInt.init(inst,def),ZodType.init(inst,def),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.gt=(value,params)=>inst.check(_gt(value,params)),inst.gte=(value,params)=>inst.check(_gte(value,params)),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.lt=(value,params)=>inst.check(_lt(value,params)),inst.lte=(value,params)=>inst.check(_lte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params)),inst.positive=params=>inst.check(_gt(BigInt(0),params)),inst.negative=params=>inst.check(_lt(BigInt(0),params)),inst.nonpositive=params=>inst.check(_lte(BigInt(0),params)),inst.nonnegative=params=>inst.check(_gte(BigInt(0),params)),inst.multipleOf=(value,params)=>inst.check(_multipleOf(value,params));let bag=inst._zod.bag;inst.minValue=bag.minimum??null,inst.maxValue=bag.maximum??null,inst.format=bag.format??null});var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def)});function _null2(params){return _null(ZodNull,params)}var ZodAny=$constructor("ZodAny",(inst,def)=>{$ZodAny.init(inst,def),ZodType.init(inst,def)});function any(){return _any(ZodAny)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def)});function never(params){return _never(ZodNever,params)}var ZodDate=$constructor("ZodDate",(inst,def)=>{$ZodDate.init(inst,def),ZodType.init(inst,def),inst.min=(value,params)=>inst.check(_gte(value,params)),inst.max=(value,params)=>inst.check(_lte(value,params));let c=inst._zod.bag;inst.minDate=c.minimum?new Date(c.minimum):null,inst.maxDate=c.maximum?new Date(c.maximum):null});var ZodArray=$constructor("ZodArray",(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst.element=def.element,inst.min=(minLength,params)=>inst.check(_minLength(minLength,params)),inst.nonempty=params=>inst.check(_minLength(1,params)),inst.max=(maxLength,params)=>inst.check(_maxLength(maxLength,params)),inst.length=(len,params)=>inst.check(_length(len,params)),inst.unwrap=()=>inst.element});function array(element,params){return _array(ZodArray,element,params)}var ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObject.init(inst,def),ZodType.init(inst,def),util_exports.defineLazy(inst,"shape",()=>def.shape),inst.keyof=()=>_enum(Object.keys(inst._zod.def.shape)),inst.catchall=catchall=>inst.clone({...inst._zod.def,catchall}),inst.passthrough=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.loose=()=>inst.clone({...inst._zod.def,catchall:unknown()}),inst.strict=()=>inst.clone({...inst._zod.def,catchall:never()}),inst.strip=()=>inst.clone({...inst._zod.def,catchall:void 0}),inst.extend=incoming=>util_exports.extend(inst,incoming),inst.merge=other=>util_exports.merge(inst,other),inst.pick=mask=>util_exports.pick(inst,mask),inst.omit=mask=>util_exports.omit(inst,mask),inst.partial=(...args)=>util_exports.partial(ZodOptional,inst,args[0]),inst.required=(...args)=>util_exports.required(ZodNonOptional,inst,args[0])});function object(shape,params){let def={type:"object",get shape(){return util_exports.assignProp(this,"shape",{...shape}),this.shape},...util_exports.normalizeParams(params)};return new ZodObject(def)}function looseObject(shape,params){return new ZodObject({type:"object",get shape(){return util_exports.assignProp(this,"shape",{...shape}),this.shape},catchall:unknown(),...util_exports.normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def),ZodType.init(inst,def),inst.keyType=def.keyType,inst.valueType=def.valueType});function record(keyType,valueType,params){return new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst.enum=def.entries,inst.options=Object.values(def.entries);let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});function _enum(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.parse=(payload,_ctx)=>{payload.addIssue=issue=>{if(typeof issue=="string")payload.issues.push(util_exports.issue(issue,payload.value,def));else{let _issue=issue;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),_issue.continue??(_issue.continue=!0),payload.issues.push(util_exports.issue(_issue))}};let output=def.transform(payload.value,payload);return output instanceof Promise?output.then(output2=>(payload.value=output2,payload)):(payload.value=output,payload)}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():defaultValue}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():defaultValue}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:()=>catchValue})}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def)});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def)});function check(fn){let ch=new $ZodCheck({check:"custom"});return ch._zod.check=fn,ch}function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn){let ch=check(payload=>(payload.addIssue=issue=>{if(typeof issue=="string")payload.issues.push(util_exports.issue(issue,payload.value,ch._zod.def));else{let _issue=issue;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),_issue.input??(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(util_exports.issue(_issue))}},fn(payload.value,payload)));return ch}function preprocess(fn,schema){return pipe(transform(fn),schema)}var ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var coerce_exports={};__export(coerce_exports,{bigint:()=>bigint,boolean:()=>boolean2,date:()=>date2,number:()=>number2,string:()=>string2});function string2(params){return _coercedString(ZodString,params)}function number2(params){return _coercedNumber(ZodNumber,params)}function boolean2(params){return _coercedBoolean(ZodBoolean,params)}function bigint(params){return _coercedBigint(ZodBigInt,params)}function date2(params){return _coercedDate(ZodDate,params)}config(en_default());var LATEST_PROTOCOL_VERSION="2025-11-25",DEFAULT_NEGOTIATED_PROTOCOL_VERSION="2025-03-26",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=union([string(),number().int()]),CursorSchema=string(),TaskCreationParamsSchema=looseObject({ttl:number().optional(),pollInterval:number().optional()}),TaskMetadataSchema=object({ttl:number().optional()}),RelatedTaskMetadataSchema=object({taskId:string()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,RequestSchema=object({method:string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object({_meta:RequestMetaSchema.optional()}),NotificationSchema=object({method:string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string(),number().int()]),JSONRPCRequestSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=value=>JSONRPCRequestSchema.safeParse(value).success,JSONRPCNotificationSchema=object({jsonrpc:literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=value=>JSONRPCNotificationSchema.safeParse(value).success,JSONRPCResultResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=value=>JSONRPCResultResponseSchema.safeParse(value).success,isJSONRPCResponse=isJSONRPCResultResponse,ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=object({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:object({code:number().int(),message:string(),data:unknown().optional()})}).strict(),JSONRPCErrorSchema=JSONRPCErrorResponseSchema,isJSONRPCErrorResponse=value=>JSONRPCErrorResponseSchema.safeParse(value).success,isJSONRPCError=isJSONRPCErrorResponse,JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=object({src:string(),mimeType:string().optional(),sizes:array(string()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema=object({icons:array(IconSchema).optional()}),BaseMetadataSchema=object({name:string(),title:string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string(),websiteUrl:string().optional(),description:string().optional()}),FormElicitationCapabilitySchema=intersection(object({applyDefaults:boolean().optional()}),record(string(),unknown())),ElicitationCapabilitySchema=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string(),unknown()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object({experimental:record(string(),AssertObjectSchema).optional(),sampling:object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object({listChanged:boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal("initialize"),params:InitializeRequestParamsSchema}),isInitializeRequest=value=>InitializeRequestSchema.safeParse(value).success,ServerCapabilitiesSchema=object({experimental:record(string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object({listChanged:boolean().optional()}).optional(),resources:object({subscribe:boolean().optional(),listChanged:boolean().optional()}).optional(),tools:object({listChanged:boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()}),isInitializedNotification=value=>InitializedNotificationSchema.safeParse(value).success,PingRequestSchema=RequestSchema.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object({progress:number(),total:optional(number()),message:optional(string())}),ProgressNotificationParamsSchema=object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=object({taskId:string(),status:TaskStatusSchema,ttl:union([number(),_null2()]),createdAt:string(),lastUpdatedAt:string(),pollInterval:optional(number()),statusMessage:optional(string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object({uri:string(),mimeType:optional(string()),_meta:record(string(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string()}),Base64Schema=string().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum(["user","assistant"]),AnnotationsSchema=object({audience:array(RoleSchema).optional(),priority:number().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string(),description:optional(string()),mimeType:optional(string()),size:optional(number()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string(),description:optional(string()),mimeType:optional(string()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object({name:string(),description:optional(string()),required:optional(boolean())}),PromptSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string(),arguments:record(string(),string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=object({type:literal("text"),text:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ImageContentSchema=object({type:literal("image"),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),AudioContentSchema=object({type:literal("audio"),data:Base64Schema,mimeType:string(),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ToolUseContentSchema=object({type:literal("tool_use"),name:string(),id:string(),input:record(string(),unknown()),_meta:record(string(),unknown()).optional()}),EmbeddedResourceSchema=object({type:literal("resource"),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal("resource_link")}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object({title:string().optional(),readOnlyHint:boolean().optional(),destructiveHint:boolean().optional(),idempotentHint:boolean().optional(),openWorldHint:boolean().optional()}),ToolExecutionSchema=object({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema=object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string().optional(),inputSchema:object({type:literal("object"),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()),outputSchema:object({type:literal("object"),properties:record(string(),AssertObjectSchema).optional(),required:array(string()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string(),unknown()).optional(),isError:boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string(),arguments:record(string(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object({autoRefresh:boolean().default(!0),debounceMs:number().int().nonnegative().default(300)}),LoggingLevelSchema=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object({name:string().optional()}),ModelPreferencesSchema=object({hints:array(ModelHintSchema).optional(),costPriority:number().min(0).max(1).optional(),speedPriority:number().min(0).max(1).optional(),intelligencePriority:number().min(0).max(1).optional()}),ToolChoiceSchema=object({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema=object({type:literal("tool_result"),toolUseId:string().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema).default([]),structuredContent:object({}).loose().optional(),isError:boolean().optional(),_meta:record(string(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number().optional(),maxTokens:number().int(),stopSequences:array(string()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object({type:literal("boolean"),title:string().optional(),description:string().optional(),default:boolean().optional()}),StringSchemaSchema=object({type:literal("string"),title:string().optional(),description:string().optional(),minLength:number().optional(),maxLength:number().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string().optional()}),NumberSchemaSchema=object({type:_enum(["number","integer"]),title:string().optional(),description:string().optional(),minimum:number().optional(),maximum:number().optional(),default:number().optional()}),UntitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string().optional(),description:string().optional(),enum:array(string()),default:string().optional()}),TitledSingleSelectEnumSchemaSchema=object({type:literal("string"),title:string().optional(),description:string().optional(),oneOf:array(object({const:string(),title:string()})),default:string().optional()}),LegacyTitledEnumSchemaSchema=object({type:literal("string"),title:string().optional(),description:string().optional(),enum:array(string()),enumNames:array(string()).optional(),default:string().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object({type:literal("string"),enum:array(string())}),default:array(string()).optional()}),TitledMultiSelectEnumSchemaSchema=object({type:literal("array"),title:string().optional(),description:string().optional(),minItems:number().optional(),maxItems:number().optional(),items:object({anyOf:array(object({const:string(),title:string()}))}),default:array(string()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string(),requestedSchema:object({type:literal("object"),properties:record(string(),PrimitiveSchemaDefinitionSchema),required:array(string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string(),elicitationId:string(),url:string().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string(),union([string(),number(),boolean(),array(string())])).optional())}),ResourceTemplateReferenceSchema=object({type:literal("ref/resource"),uri:string()}),ResourceReferenceSchema=ResourceTemplateReferenceSchema,PromptReferenceSchema=object({type:literal("ref/prompt"),name:string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object({name:string(),value:string()}),context:object({arguments:record(string(),string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}var CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string()).max(100),total:optional(number().int()),hasMore:optional(boolean())})}),RootSchema=object({uri:string().startsWith("file://"),name:string().optional(),_meta:record(string(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{constructor(code,message,data){super(`MCP error ${code}: ${message}`),this.code=code,this.data=data,this.name="McpError"}static fromError(code,message,data){if(code===ErrorCode.UrlElicitationRequired&&data){let errorData=data;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code,message,data)}},UrlElicitationRequiredError=class extends McpError{constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};export{string,url,number,boolean,any,array,object,looseObject,literal,ZodIssueCode,coerce_exports,LATEST_PROTOCOL_VERSION,DEFAULT_NEGOTIATED_PROTOCOL_VERSION,SUPPORTED_PROTOCOL_VERSIONS,RELATED_TASK_META_KEY,JSONRPC_VERSION,ProgressTokenSchema,CursorSchema,TaskCreationParamsSchema,TaskMetadataSchema,RelatedTaskMetadataSchema,TaskAugmentedRequestParamsSchema,isTaskAugmentedRequestParams,RequestSchema,NotificationSchema,ResultSchema,RequestIdSchema,JSONRPCRequestSchema,isJSONRPCRequest,JSONRPCNotificationSchema,isJSONRPCNotification,JSONRPCResultResponseSchema,isJSONRPCResultResponse,isJSONRPCResponse,ErrorCode,JSONRPCErrorResponseSchema,JSONRPCErrorSchema,isJSONRPCErrorResponse,isJSONRPCError,JSONRPCMessageSchema,JSONRPCResponseSchema,EmptyResultSchema,CancelledNotificationParamsSchema,CancelledNotificationSchema,IconSchema,IconsSchema,BaseMetadataSchema,ImplementationSchema,ClientTasksCapabilitySchema,ServerTasksCapabilitySchema,ClientCapabilitiesSchema,InitializeRequestParamsSchema,InitializeRequestSchema,isInitializeRequest,ServerCapabilitiesSchema,InitializeResultSchema,InitializedNotificationSchema,isInitializedNotification,PingRequestSchema,ProgressSchema,ProgressNotificationParamsSchema,ProgressNotificationSchema,PaginatedRequestParamsSchema,PaginatedRequestSchema,PaginatedResultSchema,TaskStatusSchema,TaskSchema,CreateTaskResultSchema,TaskStatusNotificationParamsSchema,TaskStatusNotificationSchema,GetTaskRequestSchema,GetTaskResultSchema,GetTaskPayloadRequestSchema,GetTaskPayloadResultSchema,ListTasksRequestSchema,ListTasksResultSchema,CancelTaskRequestSchema,CancelTaskResultSchema,ResourceContentsSchema,TextResourceContentsSchema,BlobResourceContentsSchema,RoleSchema,AnnotationsSchema,ResourceSchema,ResourceTemplateSchema,ListResourcesRequestSchema,ListResourcesResultSchema,ListResourceTemplatesRequestSchema,ListResourceTemplatesResultSchema,ResourceRequestParamsSchema,ReadResourceRequestParamsSchema,ReadResourceRequestSchema,ReadResourceResultSchema,ResourceListChangedNotificationSchema,SubscribeRequestParamsSchema,SubscribeRequestSchema,UnsubscribeRequestParamsSchema,UnsubscribeRequestSchema,ResourceUpdatedNotificationParamsSchema,ResourceUpdatedNotificationSchema,PromptArgumentSchema,PromptSchema,ListPromptsRequestSchema,ListPromptsResultSchema,GetPromptRequestParamsSchema,GetPromptRequestSchema,TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,EmbeddedResourceSchema,ResourceLinkSchema,ContentBlockSchema,PromptMessageSchema,GetPromptResultSchema,PromptListChangedNotificationSchema,ToolAnnotationsSchema,ToolExecutionSchema,ToolSchema,ListToolsRequestSchema,ListToolsResultSchema,CallToolResultSchema,CompatibilityCallToolResultSchema,CallToolRequestParamsSchema,CallToolRequestSchema,ToolListChangedNotificationSchema,ListChangedOptionsBaseSchema,LoggingLevelSchema,SetLevelRequestParamsSchema,SetLevelRequestSchema,LoggingMessageNotificationParamsSchema,LoggingMessageNotificationSchema,ModelHintSchema,ModelPreferencesSchema,ToolChoiceSchema,ToolResultContentSchema,SamplingContentSchema,SamplingMessageContentBlockSchema,SamplingMessageSchema,CreateMessageRequestParamsSchema,CreateMessageRequestSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema,UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema,LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema,EnumSchemaSchema,PrimitiveSchemaDefinitionSchema,ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema,ElicitRequestParamsSchema,ElicitRequestSchema,ElicitationCompleteNotificationParamsSchema,ElicitationCompleteNotificationSchema,ElicitResultSchema,ResourceTemplateReferenceSchema,ResourceReferenceSchema,PromptReferenceSchema,CompleteRequestParamsSchema,CompleteRequestSchema,assertCompleteRequestPrompt,assertCompleteRequestResourceTemplate,CompleteResultSchema,RootSchema,ListRootsRequestSchema,ListRootsResultSchema,RootsListChangedNotificationSchema,ClientRequestSchema,ClientNotificationSchema,ClientResultSchema,ServerRequestSchema,ServerNotificationSchema,ServerResultSchema,McpError,UrlElicitationRequiredError};
|