{"version":3,"file":"program-C_Fcb28_.mjs","names":["F","_a","_zodDesc","util.jsonStringifyReplacer","initializer","core.$ZodAsyncError","util.finalizeIssue","core.config","errors.$ZodError","safeParse","errors.$ZodRealError","safeParseAsync","uuid","_emoji","date","string","number","boolean","_null","util.nullish","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","regexes.integer","util.codePointLength","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","content","version","version","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","util.hide","safeParse","safeParseAsync","regexes.string","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.nanoidOfLength","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","regexes.base64url","regexes.e164","regexes.number","regexes.boolean","regexes.null","util.prefixIssues","util.optionalKeys","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.finalizeIssue","core.config","util.cleanRegex","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","open","memo","util.parsedType","util.stringifyPrimitive","util.joinValues","util.normalizeParams","_null","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","process","process","regexes.number","regexes.integer","core.formatError","core.flattenError","util.jsonStringifyReplacer","en","core.memoizer","util.mergeDefs","core.clone","checks.overwrite","util.hide","core.standardProps","parse.parse","parse.parseAsync","parse.safeParse","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","number","core._number","core._int","processors.booleanProcessor","core._boolean","processors.nullProcessor","core._null","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.dateProcessor","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.recordProcessor","record","processors.enumProcessor","processors.literalProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","core.util.constantCatch","processors.pipeProcessor","processors.readonlyProcessor","processors.lazyProcessor","processors.customProcessor","core._refine","core._superRefine","core._coercedNumber","schemas.ZodNumber","core._coercedDate","schemas.ZodDate","z.string","z.object","z.array","z.number","z.enum","z.boolean","z.union","z.literal","z.discriminatedUnion","requireSemVer","z.null","z.coerce.date","z.coerce.number","z.record","z.unknown","utf8Length","z.lazy","redactValue","truncateUtf8","z.NEVER","truncate","z.object","z.number","z.boolean","z.string","fs","EventEmitter","path","assert","join","pathToFileURL","EventEmitter","fileURLToPath","isAbsolute","join","sep","createRequire","EventEmitter","EventEmitter","https","http","tls","URL","randomBytes","createHash","Duplex","EventEmitter","http","createHash","WebSocket","pino","logger$6","protocolError$1","WebSocket","defaultScheduler","execFileAsync$3","exchangeFeishuTenantToken","defaultSpawn","settlesWithin","isRecord$5","execFileAsync$2","logger$5","parseProviderConfiguration","mergeConfiguration","requireRecord","protocolError","requireUuid","fingerprint","deferred","requireString$1","requireIndex","record","requireArray","parseUsage","toJsonValue","validateFactoryRequest","validateConfiguration","parseMcpGatewayConfiguration","isNonNegativeNumber","execFileAsync$1","execFileAsync","resolveAccountHome","z.string","z.discriminatedUnion","z.object","z.literal","z.array","z.boolean","defaultExecFile","z.number","z.enum","logger$4","isRecord$3","isRecord$2","logger$3","isRecord$1","isNonEmptyString","semver","isFingerprint","logger$2","defaultSleep","logger$1","isRecord","logger","steerResult","positive","normalizeRetryPolicy","isAbortSignal","z.object","z.string","execFileAsync$2","pack","extract","execFileAsync$1","semver","shellSingleQuote","execFileAsync","MCP_GATEWAY_PATH$1","WebSocket","safeErrorDetail","defaultSleep","packageManifest.name","packageManifest.version","process","client.resolveOpenTagHome","client.OpenTagApi","client.readCredentials","client.readComputerIdentity","client.readMachineCredentials","client.AccessTokenProvider","optionalString","collect","optionalString","nextActionFor","commandPolicy.toCommandError","commandPolicy.presentCommand","commandPolicy.commandExitCode","commandPolicy.CommandError","commandPolicy.redactSecrets","commandPolicy.toCommandError","commandPolicy.presentCommand","commandPolicy.commandExitCode","commandPolicy.toCommandError","commandPolicy.presentCommand","commandPolicy.commandExitCode","client.readCredentials","client.readAccountIdentity","client.readComputerIdentity","client.readMachineCredentials","client.accountIdentityMatchesCredentials","client.normalizeServerUrl","client.resolveOpenTagHome","client.reportClientError","client.describePlatform","client.installProcessErrorReporting","client.createLogger","execFileAsync","execFileAsync","commandPolicy.presentCommand","commandPolicy.toCommandError","commandPolicy.commandExitCode","commandPolicy.CommandError","defaultChannelConfig","commandPolicy.toCommandError","commandPolicy.presentCommand","commandPolicy.commandExitCode"],"sources":["../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/parse.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/regexes.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/checks.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/doc.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/versions.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/schemas.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/memoizer.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/locales/en.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/api.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/core/json-schema-processors.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/errors.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/parse.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/schemas.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/coerce.js","../../../packages/shared/dist/task-BXtm5kVZ.mjs","../../../packages/shared/dist/index.mjs","../../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-helpers.js","../../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-proto.js","../../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err.js","../../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/err-with-cause.js","../../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/req.js","../../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/lib/res.js","../../../node_modules/.pnpm/pino-std-serializers@7.1.0/node_modules/pino-std-serializers/index.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/caller.js","../../../node_modules/.pnpm/@pinojs+redact@0.4.0/node_modules/@pinojs/redact/index.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/symbols.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/redaction.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/time.js","../../../node_modules/.pnpm/quick-format-unescaped@4.0.4/node_modules/quick-format-unescaped/index.js","../../../node_modules/.pnpm/atomic-sleep@1.0.0/node_modules/atomic-sleep/index.js","../../../node_modules/.pnpm/sonic-boom@4.2.1/node_modules/sonic-boom/index.js","../../../node_modules/.pnpm/on-exit-leak-free@2.1.2/node_modules/on-exit-leak-free/index.js","../../../node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/package.json","../../../node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/lib/wait.js","../../../node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/lib/indexes.js","../../../node_modules/.pnpm/thread-stream@4.2.0/node_modules/thread-stream/index.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/transport.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/tools.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/constants.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/levels.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/meta.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/proto.js","../../../node_modules/.pnpm/safe-stable-stringify@2.5.0/node_modules/safe-stable-stringify/index.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/lib/multistream.js","../../../node_modules/.pnpm/pino@10.3.1/node_modules/pino/pino.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/constants.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/buffer-util.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/limiter.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/permessage-deflate.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/validation.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/receiver.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/sender.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/event-target.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/extension.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/websocket.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/stream.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/subprotocol.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/websocket-server.js","../../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/debug.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/re.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/parse-options.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/identifiers.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/semver.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/parse.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/valid.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/clean.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/inc.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/diff.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/major.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/minor.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/patch.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/prerelease.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rcompare.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-loose.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/compare-build.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/sort.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/rsort.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gt.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lt.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/eq.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/neq.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/gte.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/lte.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/cmp.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/coerce.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/truncate.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/lrucache.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/range.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/classes/comparator.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/functions/satisfies.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/to-comparators.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/max-satisfying.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-satisfying.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/min-version.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/valid.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/outside.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/gtr.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/ltr.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/intersects.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/simplify.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/ranges/subset.js","../../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/index.js","../../../node_modules/.pnpm/events-universal@1.0.1/node_modules/events-universal/default.js","../../../node_modules/.pnpm/fast-fifo@1.3.2/node_modules/fast-fifo/fixed-size.js","../../../node_modules/.pnpm/fast-fifo@1.3.2/node_modules/fast-fifo/index.js","../../../node_modules/.pnpm/b4a@1.8.1/node_modules/b4a/index.js","../../../node_modules/.pnpm/text-decoder@1.2.7/node_modules/text-decoder/lib/pass-through-decoder.js","../../../node_modules/.pnpm/text-decoder@1.2.7/node_modules/text-decoder/lib/utf8-decoder.js","../../../node_modules/.pnpm/text-decoder@1.2.7/node_modules/text-decoder/index.js","../../../node_modules/.pnpm/streamx@2.28.0/node_modules/streamx/lib/errors.js","../../../node_modules/.pnpm/streamx@2.28.0/node_modules/streamx/index.js","../../../node_modules/.pnpm/tar-stream@3.2.0/node_modules/tar-stream/headers.js","../../../node_modules/.pnpm/tar-stream@3.2.0/node_modules/tar-stream/extract.js","../../../node_modules/.pnpm/tar-stream@3.2.0/node_modules/tar-stream/constants.js","../../../node_modules/.pnpm/tar-stream@3.2.0/node_modules/tar-stream/pack.js","../../../node_modules/.pnpm/tar-stream@3.2.0/node_modules/tar-stream/index.js","../../../packages/client/dist/cli-PfvjQunU.mjs","../../../packages/client/dist/index.mjs","../src/core/command/policy.ts","../package.json","../src/build-info.ts","../../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js","../../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js","../../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js","../../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js","../../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js","../../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js","../../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/index.js","../src/core/channel/config.ts","../src/core/channel/home-source.ts","../src/core/channel/environment.ts","../src/core/command/context.ts","../src/core/mcp/shared.ts","../src/core/mcp/operations.ts","../src/commands/mcp/options.ts","../src/commands/mcp/index.ts","../src/core/agent/formatting.ts","../src/core/agent/context.ts","../src/core/agent/mutations.ts","../src/commands/agent/bind.ts","../src/commands/agent/create.ts","../src/commands/agent/delete.ts","../src/core/agent/im.ts","../src/commands/agent/im.ts","../src/commands/agent/lifecycle.ts","../src/core/agent/queries.ts","../src/commands/agent/list.ts","../src/core/session/index.ts","../src/core/agent/self.ts","../src/commands/agent/self.ts","../src/commands/agent/show.ts","../src/commands/agent/update.ts","../src/commands/agent/index.ts","../src/core/daemon/paths.ts","../src/core/command/environment.ts","../src/core/daemon/process-lease.ts","../src/core/daemon/ownership.ts","../src/core/daemon/service/types.ts","../src/core/daemon/service/shared.ts","../src/core/daemon/service/launchd.ts","../src/core/daemon/service/systemd.ts","../src/core/daemon/service/index.ts","../src/core/computer/connect.ts","../src/core/computer/formatting.ts","../src/core/provider-cli/shared.ts","../src/core/provider-cli/ensure.ts","../src/core/computer/runtime-probe.ts","../src/core/computer/preparation.ts","../src/commands/computer/connect.ts","../src/core/computer/queries.ts","../src/commands/computer/list.ts","../src/core/computer/repair-local.ts","../src/commands/computer/repair-local.ts","../src/commands/computer/runtime-inspect.ts","../src/commands/computer/index.ts","../src/core/daemon/reconcile-service.ts","../src/commands/daemon/ensure-service.ts","../src/core/update/install-mode.ts","../src/core/update/updater-state.ts","../src/commands/daemon/shared.ts","../src/commands/daemon/install.ts","../src/commands/daemon/refresh-service.ts","../src/commands/daemon/restart.ts","../src/core/diagnostics/error-reporting.ts","../src/core/diagnostics/agent-error-reporting.ts","../src/core/update/portable-installer.ts","../src/core/update/auto-update.ts","../src/core/daemon/credential-mode.ts","../src/core/daemon/environment.ts","../src/core/daemon/web-tools.ts","../src/core/daemon/runtime.ts","../src/commands/daemon/service-run.ts","../src/commands/daemon/start.ts","../src/commands/daemon/status.ts","../src/commands/daemon/stop.ts","../src/commands/daemon/uninstall.ts","../src/commands/daemon/index.ts","../src/core/diagnostics/doctor.ts","../src/commands/doctor.ts","../src/core/auth/login.ts","../src/commands/login.ts","../src/core/diagnostics/logs.ts","../src/commands/logs.ts","../src/core/provider-cli/inspect.ts","../src/commands/provider-cli.ts","../src/commands/session/index.ts","../src/core/skill/context.ts","../src/core/skill/operations.ts","../src/core/skill/shared.ts","../src/commands/skill/index.ts","../src/core/update/manual-upgrade.ts","../src/commands/upgrade.ts","../src/cli/program.ts"],"sourcesContent":["import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n    return val;\n}\nexport function assertNotEqual(val) {\n    return val;\n}\nexport function toZod() {\n    return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n    throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n    const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n    const values = Object.entries(entries)\n        .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n        .map(([_, v]) => v);\n    return values;\n}\nexport function joinValues(array, separator = \"|\") {\n    return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n    if (typeof value === \"bigint\")\n        return value.toString();\n    return value;\n}\nexport function cached(getter) {\n    const set = false;\n    return {\n        get value() {\n            if (!set) {\n                const value = getter();\n                Object.defineProperty(this, \"value\", { value });\n                return value;\n            }\n            throw new Error(\"cached value already set\");\n        },\n    };\n}\nexport function nullish(input) {\n    return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n    const start = source.startsWith(\"^\") ? 1 : 0;\n    const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n    return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n    const ratio = val / step;\n    const roundedRatio = Math.round(ratio);\n    // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n    const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n    if (Math.abs(ratio - roundedRatio) < tolerance)\n        return 0;\n    return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n    let value = undefined;\n    Object.defineProperty(object, key, {\n        get() {\n            if (value === EVALUATING) {\n                // Circular reference detected, return undefined to break the cycle\n                return undefined;\n            }\n            if (value === undefined) {\n                value = EVALUATING;\n                value = getter();\n            }\n            return value;\n        },\n        set(v) {\n            Object.defineProperty(object, key, {\n                value: v,\n                // configurable: true,\n            });\n            // object[key] = v;\n        },\n        configurable: true,\n    });\n}\nexport function objectClone(obj) {\n    return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n    Object.defineProperty(target, prop, {\n        value,\n        writable: true,\n        enumerable: true,\n        configurable: true,\n    });\n}\nexport function mergeDefs(...defs) {\n    const mergedDescriptors = {};\n    for (const def of defs) {\n        const descriptors = Object.getOwnPropertyDescriptors(def);\n        Object.assign(mergedDescriptors, descriptors);\n    }\n    return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n    return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n    if (!path)\n        return obj;\n    return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n    const keys = Object.keys(promisesObj);\n    const promises = keys.map((key) => promisesObj[key]);\n    return Promise.all(promises).then((results) => {\n        const resolvedObj = {};\n        for (let i = 0; i < keys.length; i++) {\n            resolvedObj[keys[i]] = results[i];\n        }\n        return resolvedObj;\n    });\n}\nexport function randomString(length = 10) {\n    const chars = \"abcdefghijklmnopqrstuvwxyz\";\n    let str = \"\";\n    for (let i = 0; i < length; i++) {\n        str += chars[Math.floor(Math.random() * chars.length)];\n    }\n    return str;\n}\nexport function esc(str) {\n    return JSON.stringify(str);\n}\nexport function slugify(input) {\n    return input\n        .toLowerCase()\n        .trim()\n        .replace(/[^\\w\\s-]/g, \"\")\n        .replace(/[\\s_-]+/g, \"-\")\n        .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n    return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n    // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n    if (globalConfig.jitless) {\n        return false;\n    }\n    // @ts-ignore\n    if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n        return false;\n    }\n    try {\n        const F = Function;\n        new F(\"\");\n        return true;\n    }\n    catch (_) {\n        return false;\n    }\n});\nexport function isPlainObject(o) {\n    if (isObject(o) === false)\n        return false;\n    // modified constructor\n    const ctor = o.constructor;\n    if (ctor === undefined)\n        return true;\n    if (typeof ctor !== \"function\")\n        return true;\n    // modified prototype\n    const prot = ctor.prototype;\n    if (isObject(prot) === false)\n        return false;\n    // ctor doesn't have static `isPrototypeOf`\n    if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n        return false;\n    }\n    return true;\n}\nexport function shallowClone(o) {\n    if (isPlainObject(o))\n        return { ...o };\n    if (Array.isArray(o))\n        return [...o];\n    if (o instanceof Map)\n        return new Map(o);\n    if (o instanceof Set)\n        return new Set(o);\n    return o;\n}\nexport function numKeys(data) {\n    let keyCount = 0;\n    for (const key in data) {\n        if (Object.prototype.hasOwnProperty.call(data, key)) {\n            keyCount++;\n        }\n    }\n    return keyCount;\n}\nexport const getParsedType = (data) => {\n    const t = typeof data;\n    switch (t) {\n        case \"undefined\":\n            return \"undefined\";\n        case \"string\":\n            return \"string\";\n        case \"number\":\n            return Number.isNaN(data) ? \"nan\" : \"number\";\n        case \"boolean\":\n            return \"boolean\";\n        case \"function\":\n            return \"function\";\n        case \"bigint\":\n            return \"bigint\";\n        case \"symbol\":\n            return \"symbol\";\n        case \"object\":\n            if (Array.isArray(data)) {\n                return \"array\";\n            }\n            if (data === null) {\n                return \"null\";\n            }\n            if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n                return \"promise\";\n            }\n            if (typeof Map !== \"undefined\" && data instanceof Map) {\n                return \"map\";\n            }\n            if (typeof Set !== \"undefined\" && data instanceof Set) {\n                return \"set\";\n            }\n            if (typeof Date !== \"undefined\" && data instanceof Date) {\n                return \"date\";\n            }\n            // @ts-ignore\n            if (typeof File !== \"undefined\" && data instanceof File) {\n                return \"file\";\n            }\n            return \"object\";\n        default:\n            throw new Error(`Unknown data type: ${t}`);\n    }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n    \"string\",\n    \"number\",\n    \"bigint\",\n    \"boolean\",\n    \"symbol\",\n    \"undefined\",\n]);\nexport function escapeRegex(str) {\n    return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n    const cl = new inst._zod.constr(def ?? inst._zod.def);\n    if (!def || params?.parent)\n        cl._zod.parent = inst;\n    return cl;\n}\nexport function normalizeParams(_params) {\n    const params = _params;\n    if (!params)\n        return {};\n    if (typeof params === \"string\")\n        return { error: () => params };\n    if (params?.message !== undefined) {\n        if (params?.error !== undefined)\n            throw new Error(\"Cannot specify both `message` and `error` params\");\n        params.error = params.message;\n    }\n    delete params.message;\n    if (typeof params.error === \"string\")\n        return { ...params, error: () => params.error };\n    return params;\n}\nexport function createTransparentProxy(getter) {\n    let target;\n    return new Proxy({}, {\n        get(_, prop, receiver) {\n            target ?? (target = getter());\n            return Reflect.get(target, prop, receiver);\n        },\n        set(_, prop, value, receiver) {\n            target ?? (target = getter());\n            return Reflect.set(target, prop, value, receiver);\n        },\n        has(_, prop) {\n            target ?? (target = getter());\n            return Reflect.has(target, prop);\n        },\n        deleteProperty(_, prop) {\n            target ?? (target = getter());\n            return Reflect.deleteProperty(target, prop);\n        },\n        ownKeys(_) {\n            target ?? (target = getter());\n            return Reflect.ownKeys(target);\n        },\n        getOwnPropertyDescriptor(_, prop) {\n            target ?? (target = getter());\n            return Reflect.getOwnPropertyDescriptor(target, prop);\n        },\n        defineProperty(_, prop, descriptor) {\n            target ?? (target = getter());\n            return Reflect.defineProperty(target, prop, descriptor);\n        },\n    });\n}\nexport function stringifyPrimitive(value) {\n    if (typeof value === \"bigint\")\n        return value.toString() + \"n\";\n    if (typeof value === \"string\")\n        return `\"${value}\"`;\n    return `${value}`;\n}\nexport function optionalKeys(shape) {\n    return Object.keys(shape).filter((k) => {\n        return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n    });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n    safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n    int32: [-2147483648, 2147483647],\n    uint32: [0, 4294967295],\n    float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n    float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n    int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n    uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n    const currDef = schema._zod.def;\n    const checks = currDef.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const newShape = {};\n            // `for...in` skips symbols, so a symbol in the mask would select nothing\n            for (const key of Reflect.ownKeys(mask)) {\n                if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) {\n                    throw new Error(`Unrecognized key: \"${String(key)}\"`);\n                }\n                if (!mask[key])\n                    continue;\n                assignProp(newShape, key, currDef.shape[key]);\n            }\n            assignProp(this, \"shape\", newShape); // self-caching\n            return newShape;\n        },\n        checks: [],\n    });\n    return clone(schema, def);\n}\nexport function omit(schema, mask) {\n    const currDef = schema._zod.def;\n    const checks = currDef.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const newShape = { ...schema._zod.def.shape };\n            for (const key of Reflect.ownKeys(mask)) {\n                if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) {\n                    throw new Error(`Unrecognized key: \"${String(key)}\"`);\n                }\n                if (!mask[key])\n                    continue;\n                delete newShape[key];\n            }\n            assignProp(this, \"shape\", newShape); // self-caching\n            return newShape;\n        },\n        checks: [],\n    });\n    return clone(schema, def);\n}\nexport function extend(schema, shape) {\n    if (!isPlainObject(shape)) {\n        throw new Error(\"Invalid input to extend: expected a plain object\");\n    }\n    const checks = schema._zod.def.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n        const existingShape = schema._zod.def.shape;\n        for (const key of Reflect.ownKeys(shape)) {\n            if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n                throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n            }\n        }\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const _shape = { ...schema._zod.def.shape, ...shape };\n            assignProp(this, \"shape\", _shape); // self-caching\n            return _shape;\n        },\n    });\n    return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n    if (!isPlainObject(shape)) {\n        throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const _shape = { ...schema._zod.def.shape, ...shape };\n            assignProp(this, \"shape\", _shape); // self-caching\n            return _shape;\n        },\n    });\n    return clone(schema, def);\n}\nexport function merge(a, b) {\n    if (!b?._zod?.def) {\n        throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n    }\n    if (a._zod.def.checks?.length) {\n        throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n    }\n    const def = mergeDefs(a._zod.def, {\n        get shape() {\n            const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n            assignProp(this, \"shape\", _shape); // self-caching\n            return _shape;\n        },\n        get catchall() {\n            return b._zod.def.catchall;\n        },\n        checks: b._zod.def.checks ?? [],\n    });\n    return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n    const currDef = schema._zod.def;\n    const checks = currDef.checks;\n    const hasChecks = checks && checks.length > 0;\n    if (hasChecks) {\n        throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n    }\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const oldShape = schema._zod.def.shape;\n            const shape = { ...oldShape };\n            if (mask) {\n                for (const key of Reflect.ownKeys(mask)) {\n                    if (!Object.prototype.hasOwnProperty.call(oldShape, key)) {\n                        throw new Error(`Unrecognized key: \"${String(key)}\"`);\n                    }\n                    if (!mask[key])\n                        continue;\n                    // if (oldShape[key]!._zod.optin === \"optional\") continue;\n                    shape[key] = Class\n                        ? new Class({\n                            type: \"optional\",\n                            innerType: oldShape[key],\n                        })\n                        : oldShape[key];\n                }\n            }\n            else {\n                // the spread copies symbol keys; `for...in` would not reach them\n                for (const key of Reflect.ownKeys(oldShape)) {\n                    // if (oldShape[key]!._zod.optin === \"optional\") continue;\n                    shape[key] = Class\n                        ? new Class({\n                            type: \"optional\",\n                            innerType: oldShape[key],\n                        })\n                        : oldShape[key];\n                }\n            }\n            assignProp(this, \"shape\", shape); // self-caching\n            return shape;\n        },\n        checks: [],\n    });\n    return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n    const def = mergeDefs(schema._zod.def, {\n        get shape() {\n            const oldShape = schema._zod.def.shape;\n            const shape = { ...oldShape };\n            if (mask) {\n                for (const key of Reflect.ownKeys(mask)) {\n                    if (!Object.prototype.hasOwnProperty.call(shape, key)) {\n                        throw new Error(`Unrecognized key: \"${String(key)}\"`);\n                    }\n                    if (!mask[key])\n                        continue;\n                    // overwrite with non-optional\n                    shape[key] = new Class({\n                        type: \"nonoptional\",\n                        innerType: oldShape[key],\n                    });\n                }\n            }\n            else {\n                for (const key of Reflect.ownKeys(oldShape)) {\n                    // overwrite with non-optional\n                    shape[key] = new Class({\n                        type: \"nonoptional\",\n                        innerType: oldShape[key],\n                    });\n                }\n            }\n            assignProp(this, \"shape\", shape); // self-caching\n            return shape;\n        },\n    });\n    return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n    if (x.aborted === true)\n        return true;\n    for (let i = startIndex; i < x.issues.length; i++) {\n        if (x.issues[i]?.continue !== true) {\n            return true;\n        }\n    }\n    return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n    if (x.aborted === true)\n        return true;\n    for (let i = startIndex; i < x.issues.length; i++) {\n        if (x.issues[i]?.continue === false) {\n            return true;\n        }\n    }\n    return false;\n}\nexport function prefixIssues(path, issues) {\n    return issues.map((iss) => {\n        var _a;\n        (_a = iss).path ?? (_a.path = []);\n        iss.path.unshift(path);\n        return iss;\n    });\n}\nexport function unwrapMessage(message) {\n    return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\nexport function attachSchema(issues, start, inst) {\n    var _a;\n    for (let i = start; i < issues.length; i++) {\n        (_a = issues[i]).schema ?? (_a.schema = inst);\n    }\n}\nexport function finalizeIssue(iss, ctx, config) {\n    var _a;\n    // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n    const traits = iss.inst?._zod?.traits;\n    if (traits?.has(\"$ZodType\")) {\n        if (traits.has(\"$ZodCheck\"))\n            (_a = iss).schema ?? (_a.schema = iss.inst);\n        else\n            iss.schema = iss.inst;\n    }\n    // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n    const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n    const message = iss.message\n        ? iss.message\n        : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n            unwrapMessage(schemaError?.(iss)) ??\n            unwrapMessage(ctx?.error?.(iss)) ??\n            unwrapMessage(config.customError?.(iss)) ??\n            unwrapMessage(config.localeError?.(iss)) ??\n            \"Invalid input\");\n    const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss;\n    rest.path ?? (rest.path = []);\n    rest.message = message;\n    if (ctx?.reportInput) {\n        rest.input = _input;\n    }\n    return rest;\n}\nexport function getSizableOrigin(input) {\n    if (input instanceof Set)\n        return \"set\";\n    if (input instanceof Map)\n        return \"map\";\n    // @ts-ignore\n    if (input instanceof File)\n        return \"file\";\n    return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n    const units = str.length;\n    if (!highSurrogate.test(str))\n        return units;\n    let count = units;\n    for (let i = 0; i < units - 1; i++) {\n        if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n            count--;\n            i++;\n        }\n    }\n    return count;\n}\nexport function getLengthableOrigin(input) {\n    if (Array.isArray(input))\n        return \"array\";\n    if (typeof input === \"string\")\n        return \"string\";\n    return \"unknown\";\n}\nexport function parsedType(data) {\n    const t = typeof data;\n    switch (t) {\n        case \"number\": {\n            return Number.isNaN(data) ? \"nan\" : \"number\";\n        }\n        case \"object\": {\n            if (data === null) {\n                return \"null\";\n            }\n            if (Array.isArray(data)) {\n                return \"array\";\n            }\n            const obj = data;\n            if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n                return obj.constructor.name;\n            }\n        }\n    }\n    return t;\n}\nexport function issue(...args) {\n    const [iss, input, inst] = args;\n    if (typeof iss === \"string\") {\n        return {\n            message: iss,\n            code: \"custom\",\n            input,\n            inst,\n        };\n    }\n    return { ...iss };\n}\nexport function cleanEnum(obj) {\n    return Object.entries(obj)\n        .filter(([k, _]) => {\n        // return true if NaN, meaning it's not a number, thus a string key\n        return Number.isNaN(Number.parseInt(k, 10));\n    })\n        .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n    const binaryString = atob(base64);\n    const bytes = new Uint8Array(binaryString.length);\n    for (let i = 0; i < binaryString.length; i++) {\n        bytes[i] = binaryString.charCodeAt(i);\n    }\n    return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n    let binaryString = \"\";\n    for (let i = 0; i < bytes.length; i++) {\n        binaryString += String.fromCharCode(bytes[i]);\n    }\n    return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n    const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n    const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n    return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n    return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n    const cleanHex = hex.replace(/^0x/, \"\");\n    if (cleanHex.length % 2 !== 0) {\n        throw new Error(\"Invalid hex string length\");\n    }\n    const bytes = new Uint8Array(cleanHex.length / 2);\n    for (let i = 0; i < cleanHex.length; i += 2) {\n        bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n    }\n    return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n    return Array.from(bytes)\n        .map((b) => b.toString(16).padStart(2, \"0\"))\n        .join(\"\");\n}\n// instanceof\nexport class Class {\n    constructor(..._args) { }\n}\n//////////    PROTOTYPE INSTALLERS     //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n    for (const key in table) {\n        const desc = Object.getOwnPropertyDescriptor(table, key);\n        // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n        if (desc.get)\n            Object.defineProperty(proto, key, { ...desc, enumerable: false });\n        // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n        else\n            defineBound(proto, key, desc.value);\n    }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n    Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n    return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n    return own(inst, key, value, false);\n}\nfunction defineBound(proto, key, fn) {\n    Object.defineProperty(proto, key, {\n        configurable: true,\n        get() {\n            // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n            return this == null ? fn : own(this, key, fn.bind(this));\n        },\n        set(value) {\n            own(this, key, value);\n        },\n    });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n    const proto = Object.getPrototypeOf(inst);\n    // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n    return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n    configurable: true,\n    get() {\n        broke = true;\n        return undefined;\n    },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n    const proto = Object.getPrototypeOf(inst._zod);\n    if (key in proto && installing !== inst._zod) {\n        // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n        installing = undefined;\n        return;\n    }\n    installing = inst._zod;\n    Object.defineProperty(proto, key, {\n        configurable: true,\n        get() {\n            // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n            Object.defineProperty(this, key, breaker);\n            const outer = broke;\n            broke = false;\n            try {\n                const value = compute(this);\n                // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n                if (broke)\n                    delete this[key];\n                else\n                    Object.defineProperty(this, key, { configurable: true, writable: true, value });\n                broke = broke || outer;\n                return value;\n            }\n            catch (err) {\n                // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n                delete this[key];\n                broke = broke || outer;\n                throw err;\n            }\n        },\n        set(value) {\n            Object.defineProperty(this, key, { configurable: true, writable: true, value });\n        },\n    });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n    const proto = claim(inst, key);\n    if (!proto)\n        return;\n    Object.defineProperty(proto, key, {\n        configurable: true,\n        get() {\n            // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n            const desc = { configurable: true, writable: true, enumerable, value: undefined };\n            Object.defineProperty(this, key, desc);\n            // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n            desc.value = make(this);\n            Object.defineProperty(this, key, desc);\n            return desc.value;\n        },\n        set(value) {\n            Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n        },\n    });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n    const fn = () => value;\n    fn[CONSTANT_CATCH] = true;\n    return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n    status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n    const E = _E;\n    if (E) {\n        const saved = E.stackTraceLimit;\n        if (typeof saved === \"number\") {\n            try {\n                E.stackTraceLimit = 0;\n            }\n            catch {\n                _E = null;\n                return new Definition();\n            }\n            try {\n                return new Definition();\n            }\n            finally {\n                E.stackTraceLimit = saved;\n            }\n        }\n    }\n    return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n    // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n    const zodProto = {};\n    // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n    function Internals(def) {\n        this.def = def;\n        this.constr = _;\n        this.traits = new Set();\n    }\n    Internals.prototype = zodProto;\n    const protoMembers = proto;\n    // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n    const initialized = protoMembers && new WeakSet();\n    function init(inst, def) {\n        if (!inst._zod) {\n            _zodDesc.value = new Internals(def);\n            try {\n                Object.defineProperty(inst, \"_zod\", _zodDesc);\n            }\n            finally {\n                // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n                _zodDesc.value = undefined;\n            }\n        }\n        if (inst._zod.traits.has(name)) {\n            return;\n        }\n        inst._zod.traits.add(name);\n        initializer(inst, def);\n        if (initialized) {\n            // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n            const own = Object.getPrototypeOf(inst);\n            const ctorProto = inst._zod.constr.prototype;\n            let up = own;\n            while (up && up !== ctorProto)\n                up = Object.getPrototypeOf(up);\n            const target = up ?? own;\n            if (!initialized.has(target)) {\n                initialized.add(target);\n                installMembers(target, protoMembers);\n            }\n        }\n        // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n        const proto = _.prototype;\n        for (const k in proto) {\n            if (!Object.prototype.hasOwnProperty.call(proto, k))\n                continue;\n            if (!(k in inst)) {\n                inst[k] = proto[k].bind(inst);\n            }\n        }\n    }\n    // doesn't work if Parent has a constructor with arguments\n    const Parent = params?.Parent ?? Object;\n    class Definition extends Parent {\n    }\n    Object.defineProperty(Definition, \"name\", { value: name });\n    function _(def) {\n        const inst = params?.Parent ? newError(Definition) : this;\n        init(inst, def);\n        const deferred = inst._zod.deferred;\n        if (deferred) {\n            for (const fn of deferred) {\n                fn();\n            }\n            // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n            inst._zod.deferred = undefined;\n        }\n        // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n        const pp = globalThis.__zod_globalConfig?.postProcessor;\n        if (pp)\n            pp(inst);\n        return inst;\n    }\n    Object.defineProperty(_, \"init\", { value: init });\n    Object.defineProperty(_, Symbol.hasInstance, {\n        value: (inst) => {\n            if (params?.Parent && inst instanceof params.Parent)\n                return true;\n            return inst?._zod?.traits?.has(name);\n        },\n    });\n    Object.defineProperty(_, \"name\", { value: name });\n    return _;\n}\n//////////////////////////////   UTILITIES   ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n    constructor() {\n        super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n    }\n}\nexport class $ZodEncodeError extends Error {\n    constructor(name) {\n        super(`Encountered unidirectional transform during encode: ${name}`);\n        this.name = \"ZodEncodeError\";\n    }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n    if (newConfig)\n        Object.assign(globalConfig, newConfig);\n    return globalConfig;\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n    const internals = this._zod;\n    internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n    return internals.message;\n}\nfunction _setMessage(value) {\n    this._zod.message = value;\n}\nconst _messageDesc = {\n    get: _getMessage,\n    set: _setMessage,\n    enumerable: true,\n    configurable: true,\n};\nconst _zodDesc = { value: undefined, enumerable: false };\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n    inst.name = \"$ZodError\";\n    _zodDesc.value = inst._zod;\n    Object.defineProperty(inst, \"_zod\", _zodDesc);\n    _issuesDesc.value = def;\n    Object.defineProperty(inst, \"issues\", _issuesDesc);\n    // Clear the shared slots; a retained `value` pins the last error's issues.\n    _zodDesc.value = undefined;\n    _issuesDesc.value = undefined;\n    Object.defineProperty(inst, \"message\", _messageDesc);\n    /* `toString` lives as a non-enumerable lazy getter on the shared\n     * prototype; on first access it caches a per-instance closure so\n     * detached usage still works. */\n    const proto = Object.getPrototypeOf(inst);\n    if (!_installedToString.has(proto)) {\n        _installedToString.add(proto);\n        Object.defineProperty(proto, \"toString\", {\n            configurable: true,\n            enumerable: false,\n            get() {\n                const value = () => this.message;\n                Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n                return value;\n            },\n            set(value) {\n                Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n            },\n        });\n    }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n    Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n    if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n        if (key === \"__proto__\") {\n            Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n        }\n        else {\n            obj[key] = make();\n        }\n    }\n    return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n    const fieldErrors = {};\n    const formErrors = [];\n    for (const sub of error.issues) {\n        if (sub.path.length > 0) {\n            node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n        }\n        else {\n            formErrors.push(mapper(sub));\n        }\n    }\n    return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n    const fieldErrors = { _errors: [] };\n    const processError = (error, path = []) => {\n        for (const issue of error.issues) {\n            if (issue.code === \"invalid_union\" && issue.errors.length) {\n                issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n            }\n            else if (issue.code === \"invalid_key\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else if (issue.code === \"invalid_element\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else {\n                const fullpath = [...path, ...issue.path];\n                if (fullpath.length === 0) {\n                    fieldErrors._errors.push(mapper(issue));\n                }\n                else {\n                    let curr = fieldErrors;\n                    let i = 0;\n                    while (i < fullpath.length) {\n                        const el = fullpath[i];\n                        const terminal = i === fullpath.length - 1;\n                        // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n                        if (el === \"_errors\") {\n                            if (terminal)\n                                curr._errors.push(mapper(issue));\n                            i++;\n                            continue;\n                        }\n                        // A path element may collide with an inherited property name such as\n                        // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n                        // (so no node is created, then ._errors.push throws), and bracket\n                        // assignment of \"__proto__\" hits the setter instead of creating an\n                        // own key. Guard the read with hasOwnProperty and create the node\n                        // with defineProperty so any path element becomes a real own key.\n                        if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n                            Object.defineProperty(curr, el, {\n                                value: { _errors: [] },\n                                enumerable: true,\n                                writable: true,\n                                configurable: true,\n                            });\n                        }\n                        const node = curr[el];\n                        if (terminal) {\n                            node._errors.push(mapper(issue));\n                        }\n                        curr = node;\n                        i++;\n                    }\n                }\n            }\n        }\n    };\n    processError(error);\n    return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n    const result = { errors: [] };\n    const processError = (error, path = []) => {\n        var _a;\n        for (const issue of error.issues) {\n            if (issue.code === \"invalid_union\" && issue.errors.length) {\n                // regular union error\n                issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n            }\n            else if (issue.code === \"invalid_key\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else if (issue.code === \"invalid_element\") {\n                processError({ issues: issue.issues }, [...path, ...issue.path]);\n            }\n            else {\n                const fullpath = [...path, ...issue.path];\n                if (fullpath.length === 0) {\n                    result.errors.push(mapper(issue));\n                    continue;\n                }\n                let curr = result;\n                let i = 0;\n                while (i < fullpath.length) {\n                    const el = fullpath[i];\n                    const terminal = i === fullpath.length - 1;\n                    if (typeof el === \"string\") {\n                        curr.properties ?? (curr.properties = {});\n                        // el may collide with an inherited property name (\"__proto__\",\n                        // \"constructor\", ...); ??= reads the prototype so the node is never\n                        // created and curr.errors.push throws. Guard with hasOwnProperty and\n                        // create the node with defineProperty so \"__proto__\" becomes a real\n                        // own key rather than invoking the prototype setter.\n                        if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n                            Object.defineProperty(curr.properties, el, {\n                                value: { errors: [] },\n                                enumerable: true,\n                                writable: true,\n                                configurable: true,\n                            });\n                        }\n                        curr = curr.properties[el];\n                    }\n                    else {\n                        curr.items ?? (curr.items = []);\n                        (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n                        curr = curr.items[el];\n                    }\n                    if (terminal) {\n                        curr.errors.push(mapper(issue));\n                    }\n                    i++;\n                }\n            }\n        }\n    };\n    processError(error);\n    return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n *   issues: [\n *     {\n *       expected: 'string',\n *       code: 'invalid_type',\n *       path: [ 'username' ],\n *       message: 'Invalid input: expected string'\n *     },\n *     {\n *       expected: 'number',\n *       code: 'invalid_type',\n *       path: [ 'favoriteNumbers', 1 ],\n *       message: 'Invalid input: expected number'\n *     }\n *   ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n *   ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n *   ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n    const segs = [];\n    const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n    for (const seg of path) {\n        if (typeof seg === \"number\")\n            segs.push(`[${seg}]`);\n        else if (typeof seg === \"symbol\")\n            segs.push(`[${JSON.stringify(String(seg))}]`);\n        else if (/[^\\w$]/.test(seg))\n            segs.push(`[${JSON.stringify(seg)}]`);\n        else {\n            if (segs.length)\n                segs.push(\".\");\n            segs.push(seg);\n        }\n    }\n    return segs.join(\"\");\n}\nexport function prettifyError(error) {\n    const lines = [];\n    // sort by path length\n    const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n    // Process each issue\n    for (const issue of issues) {\n        lines.push(`✖ ${issue.message}`);\n        if (issue.path?.length)\n            lines.push(`  → at ${toDotPath(issue.path)}`);\n    }\n    // Convert Map to formatted string\n    return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n    return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n    const fn = (schema, value, _ctx, _params) => {\n        const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n        const result = schema._zod.run({ value, issues: [] }, ctx);\n        if (result instanceof Promise) {\n            throw new core.$ZodAsyncError();\n        }\n        if (result.issues.length) {\n            const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n            util.captureStackTrace(e, _params?.callee ?? fn);\n            throw e;\n        }\n        return result.value;\n    };\n    return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n    const fn = async (schema, value, _ctx, params) => {\n        const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n        let result = schema._zod.run({ value, issues: [] }, ctx);\n        if (result instanceof Promise)\n            result = await result;\n        if (result.issues.length) {\n            const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n            util.captureStackTrace(e, params?.callee ?? fn);\n            throw e;\n        }\n        return result.value;\n    };\n    return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n    const result = schema._zod.run({ value, issues: [] }, ctx);\n    if (result instanceof Promise) {\n        throw new core.$ZodAsyncError();\n    }\n    return result.issues.length\n        ? {\n            success: false,\n            error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n        }\n        : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n    let result = schema._zod.run({ value, issues: [] }, ctx);\n    if (result instanceof Promise)\n        result = await result;\n    return result.issues.length\n        ? {\n            success: false,\n            error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n        }\n        : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n    const validator = schema._zod.bag.validator;\n    if (validator !== undefined && validator(value) !== COMPILE_INVALID)\n        return true;\n    return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n    const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n    const fallbackRun = schema._zod.bag.fallbackRun;\n    let result;\n    if (fallbackRun) {\n        // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n        ctx[COMPILE_FALLBACK] = true;\n        result = fallbackRun({ value, issues: [] }, ctx);\n    }\n    else {\n        result = schema._zod.run({ value, issues: [] }, ctx);\n    }\n    if (result instanceof Promise) {\n        throw new core.$ZodAsyncError();\n    }\n    return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n    let result = schema._zod.run({ value, issues: [] }, ctx);\n    if (result instanceof Promise)\n        result = await result;\n    return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n    const parse = _parse(_Err);\n    const fn = (schema, value, _ctx, _params) => {\n        const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n        return parse(schema, value, ctx, finalizeParams(fn, _params));\n    };\n    return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n    const parse = _parse(_Err);\n    const fn = (schema, value, _ctx, _params) => {\n        return parse(schema, value, _ctx, finalizeParams(fn, _params));\n    };\n    return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n    const parseAsync = _parseAsync(_Err);\n    const fn = async (schema, value, _ctx, _params) => {\n        const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n        return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n    };\n    return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n    const parseAsync = _parseAsync(_Err);\n    const fn = async (schema, value, _ctx, _params) => {\n        return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n    };\n    return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n    return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n    return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n    const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n    return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n    return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n    return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n    if (!version)\n        return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n    return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match.\nconst _emoji = `^[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n    return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n    const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n    return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n    return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n    const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n    const regex = typeof args.precision === \"number\"\n        ? args.precision === -1\n            ? `${hhmm}`\n            : args.precision === 0\n                ? `${hhmm}:[0-5]\\\\d`\n                : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n        : args.seconds\n            ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n            : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n    return regex;\n}\nexport function time(args) {\n    return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n    const opts = [\"Z\"];\n    // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n    if (args.offset)\n        opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n    // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n    const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n    const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n    return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n    const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n    return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n    return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n    return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n    var _a;\n    inst._zod ?? (inst._zod = {});\n    inst._zod.def = def;\n    (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n    const val = payload.value;\n    return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n    const val = payload.value;\n    return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n    number: \"number\",\n    bigint: \"bigint\",\n    object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const origin = numericOriginMap[typeof def.value];\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n        if (def.value < curr) {\n            if (def.inclusive)\n                bag.maximum = def.value;\n            else\n                bag.exclusiveMaximum = def.value;\n        }\n    });\n    inst._zod.check = (payload) => {\n        if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n            return;\n        }\n        payload.issues.push({\n            origin: numericOriginMap[typeof payload.value] ?? origin,\n            code: \"too_big\",\n            maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n            input: payload.value,\n            inclusive: def.inclusive,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const origin = numericOriginMap[typeof def.value];\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n        if (def.value > curr) {\n            if (def.inclusive)\n                bag.minimum = def.value;\n            else\n                bag.exclusiveMinimum = def.value;\n        }\n    });\n    inst._zod.check = (payload) => {\n        if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n            return;\n        }\n        payload.issues.push({\n            origin: numericOriginMap[typeof payload.value] ?? origin,\n            code: \"too_small\",\n            minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n            input: payload.value,\n            inclusive: def.inclusive,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    inst._zod.onattach.push((inst) => {\n        var _a;\n        (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n    });\n    inst._zod.check = (payload) => {\n        if (typeof payload.value !== typeof def.value)\n            throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n        const isMultiple = typeof payload.value === \"bigint\"\n            ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n                def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n            : util.floatSafeRemainder(payload.value, def.value) === 0;\n        if (isMultiple)\n            return;\n        payload.issues.push({\n            origin: typeof payload.value,\n            code: \"not_multiple_of\",\n            divisor: def.value,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n    $ZodCheck.init(inst, def); // no format checks\n    def.format = def.format || \"float64\";\n    const isInt = def.format?.includes(\"int\");\n    const origin = isInt ? \"int\" : \"number\";\n    const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.format = def.format;\n        bag.minimum = minimum;\n        bag.maximum = maximum;\n        if (isInt)\n            bag.pattern = regexes.integer;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        if (isInt) {\n            if (!Number.isInteger(input)) {\n                // invalid_format issue\n                // payload.issues.push({\n                //   expected: def.format,\n                //   format: def.format,\n                //   code: \"invalid_format\",\n                //   input,\n                //   inst,\n                // });\n                // invalid_type issue\n                payload.issues.push({\n                    expected: origin,\n                    format: def.format,\n                    code: \"invalid_type\",\n                    continue: false,\n                    input,\n                    inst,\n                });\n                return;\n                // not_multiple_of issue\n                // payload.issues.push({\n                //   code: \"not_multiple_of\",\n                //   origin: \"number\",\n                //   input,\n                //   inst,\n                //   divisor: 1,\n                // });\n            }\n            if (!Number.isSafeInteger(input)) {\n                if (input > 0) {\n                    // too_big\n                    payload.issues.push({\n                        input,\n                        code: \"too_big\",\n                        maximum: Number.MAX_SAFE_INTEGER,\n                        note: \"Integers must be within the safe integer range.\",\n                        inst,\n                        origin,\n                        inclusive: true,\n                        continue: !def.abort,\n                    });\n                }\n                else {\n                    // too_small\n                    payload.issues.push({\n                        input,\n                        code: \"too_small\",\n                        minimum: Number.MIN_SAFE_INTEGER,\n                        note: \"Integers must be within the safe integer range.\",\n                        inst,\n                        origin,\n                        inclusive: true,\n                        continue: !def.abort,\n                    });\n                }\n                return;\n            }\n        }\n        if (input < minimum) {\n            payload.issues.push({\n                origin: \"number\",\n                input,\n                code: \"too_small\",\n                minimum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n        if (input > maximum) {\n            payload.issues.push({\n                origin: \"number\",\n                input,\n                code: \"too_big\",\n                maximum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n    $ZodCheck.init(inst, def); // no format checks\n    const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.format = def.format;\n        bag.minimum = minimum;\n        bag.maximum = maximum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        if (input < minimum) {\n            payload.issues.push({\n                origin: \"bigint\",\n                input,\n                code: \"too_small\",\n                minimum: minimum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n        if (input > maximum) {\n            payload.issues.push({\n                origin: \"bigint\",\n                input,\n                code: \"too_big\",\n                maximum,\n                inclusive: true,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n        if (def.maximum < curr)\n            inst._zod.bag.maximum = def.maximum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const size = input.size;\n        if (size <= def.maximum)\n            return;\n        payload.issues.push({\n            origin: util.getSizableOrigin(input),\n            code: \"too_big\",\n            maximum: def.maximum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n        if (def.minimum > curr)\n            inst._zod.bag.minimum = def.minimum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const size = input.size;\n        if (size >= def.minimum)\n            return;\n        payload.issues.push({\n            origin: util.getSizableOrigin(input),\n            code: \"too_small\",\n            minimum: def.minimum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.minimum = def.size;\n        bag.maximum = def.size;\n        bag.size = def.size;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const size = input.size;\n        if (size === def.size)\n            return;\n        const tooBig = size > def.size;\n        payload.issues.push({\n            origin: util.getSizableOrigin(input),\n            ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n            inclusive: true,\n            exact: true,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n        if (def.maximum < curr)\n            inst._zod.bag.maximum = def.maximum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const units = input.length;\n        // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n        const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n        if (length <= def.maximum)\n            return;\n        const origin = util.getLengthableOrigin(input);\n        payload.issues.push({\n            origin,\n            code: \"too_big\",\n            maximum: def.maximum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n    inst._zod.onattach.push((inst) => {\n        const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n        if (def.minimum > curr)\n            inst._zod.bag.minimum = def.minimum;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const units = input.length;\n        // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n        const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n            ? util.codePointLength(input)\n            : units;\n        if (length >= def.minimum)\n            return;\n        const origin = util.getLengthableOrigin(input);\n        payload.issues.push({\n            origin,\n            code: \"too_small\",\n            minimum: def.minimum,\n            inclusive: true,\n            input,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n    var _a;\n    $ZodCheck.init(inst, def);\n    (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.minimum = def.length;\n        bag.maximum = def.length;\n        bag.length = def.length;\n    });\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const units = input.length;\n        // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n        const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n            ? util.codePointLength(input)\n            : units;\n        if (length === def.length)\n            return;\n        const origin = util.getLengthableOrigin(input);\n        const tooBig = length > def.length;\n        payload.issues.push({\n            origin,\n            ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n            inclusive: true,\n            exact: true,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n    var _a, _b;\n    $ZodCheck.init(inst, def);\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.format = def.format;\n        if (def.pattern) {\n            bag.patterns ?? (bag.patterns = new Set());\n            bag.patterns.add(def.pattern);\n        }\n    });\n    if (def.pattern)\n        (_a = inst._zod).check ?? (_a.check = (payload) => {\n            def.pattern.lastIndex = 0;\n            if (def.pattern.test(payload.value))\n                return;\n            payload.issues.push({\n                origin: \"string\",\n                code: \"invalid_format\",\n                format: def.format,\n                input: payload.value,\n                ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n                inst,\n                continue: !def.abort,\n            });\n        });\n    else\n        (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n    $ZodCheckStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        def.pattern.lastIndex = 0;\n        if (def.pattern.test(payload.value))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"regex\",\n            input: payload.value,\n            pattern: def.pattern.toString(),\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.lowercase);\n    $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.uppercase);\n    $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const escapedRegex = util.escapeRegex(def.includes);\n    // `String.prototype.includes(sub, position)` matches `sub` at `position`\n    // OR LATER, so the pattern must allow at least `position` leading chars\n    // (`{N,}`), not exactly `position` chars (`{N}`).\n    const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n    def.pattern = pattern;\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.patterns ?? (bag.patterns = new Set());\n        bag.patterns.add(pattern);\n    });\n    inst._zod.check = (payload) => {\n        if (payload.value.includes(def.includes, def.position))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"includes\",\n            includes: def.includes,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n    def.pattern ?? (def.pattern = pattern);\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.patterns ?? (bag.patterns = new Set());\n        bag.patterns.add(pattern);\n    });\n    inst._zod.check = (payload) => {\n        if (payload.value.startsWith(def.prefix))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"starts_with\",\n            prefix: def.prefix,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n    def.pattern ?? (def.pattern = pattern);\n    inst._zod.onattach.push((inst) => {\n        const bag = inst._zod.bag;\n        bag.patterns ?? (bag.patterns = new Set());\n        bag.patterns.add(pattern);\n    });\n    inst._zod.check = (payload) => {\n        if (payload.value.endsWith(def.suffix))\n            return;\n        payload.issues.push({\n            origin: \"string\",\n            code: \"invalid_format\",\n            format: \"ends_with\",\n            suffix: def.suffix,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\n///////////////////////////////////\n/////    $ZodCheckProperty    /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n    if (result.issues.length) {\n        payload.issues.push(...util.prefixIssues(property, result.issues));\n    }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    inst._zod.check = (payload) => {\n        const result = def.schema._zod.run({\n            value: payload.value[def.property],\n            issues: [],\n        }, {});\n        if (result instanceof Promise) {\n            return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n        }\n        handleCheckPropertyResult(result, payload, def.property);\n        return;\n    };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    const mimeSet = new Set(def.mime);\n    inst._zod.onattach.push((inst) => {\n        inst._zod.bag.mime = def.mime;\n    });\n    inst._zod.check = (payload) => {\n        if (mimeSet.has(payload.value.type))\n            return;\n        payload.issues.push({\n            code: \"invalid_value\",\n            values: def.mime,\n            input: payload.value.type,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n    $ZodCheck.init(inst, def);\n    inst._zod.check = (payload) => {\n        payload.value = def.tx(payload.value);\n    };\n});\n","export class Doc {\n    constructor(args = [], closed = {}) {\n        this.content = [];\n        this.indent = 0;\n        this.args = args;\n        this.closed = closed;\n    }\n    indented(fn) {\n        this.indent += 1;\n        fn(this);\n        this.indent -= 1;\n    }\n    write(arg) {\n        if (typeof arg === \"function\") {\n            arg(this, { execution: \"sync\" });\n            arg(this, { execution: \"async\" });\n            return;\n        }\n        const content = arg;\n        const lines = content.split(\"\\n\").filter((x) => x);\n        const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n        const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n        for (const line of dedented) {\n            this.content.push(line);\n        }\n    }\n    compile() {\n        const F = Function;\n        const content = this?.content ?? [``];\n        const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n        return factory(...Object.values(this.closed));\n    }\n}\n","export const version = {\n    major: 4,\n    minor: 5,\n    patch: 4,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n    var _a;\n    inst ?? (inst = {});\n    inst._zod.def = def; // set _def property\n    inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n    inst._zod.version = version;\n    const defChecks = inst._zod.def.checks;\n    // if inst is itself a checks.$ZodCheck, run it as a check\n    const checks = inst._zod.traits.has(\"$ZodCheck\")\n        ? [inst, ...(defChecks ?? [])]\n        : defChecks?.length\n            ? [...defChecks]\n            : [];\n    for (const ch of checks) {\n        for (const fn of ch._zod.onattach) {\n            fn(inst);\n        }\n    }\n    if (checks.length === 0) {\n        // deferred initializer inst._zod.parse is not yet defined\n        (_a = inst._zod).deferred ?? (_a.deferred = []);\n        inst._zod.deferred?.push(() => {\n            inst._zod.run = inst._zod.parse;\n        });\n    }\n    else {\n        const runChecks = (payload, checks, ctx) => {\n            if (payload.memo)\n                return payload;\n            let isAborted = util.aborted(payload);\n            let asyncResult;\n            for (const ch of checks) {\n                if (ch._zod.def.when) {\n                    if (util.explicitlyAborted(payload))\n                        continue;\n                    const shouldRun = ch._zod.def.when(payload);\n                    if (!shouldRun)\n                        continue;\n                }\n                else if (isAborted) {\n                    continue;\n                }\n                const currLen = payload.issues.length;\n                const _ = ch._zod.check(payload);\n                if (_ instanceof Promise && ctx?.async === false) {\n                    throw new core.$ZodAsyncError();\n                }\n                if (asyncResult || _ instanceof Promise) {\n                    asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n                        await _;\n                        const nextLen = payload.issues.length;\n                        if (nextLen === currLen)\n                            return;\n                        util.attachSchema(payload.issues, currLen, inst);\n                        if (!isAborted)\n                            isAborted = util.aborted(payload, currLen);\n                    });\n                }\n                else {\n                    const nextLen = payload.issues.length;\n                    if (nextLen === currLen)\n                        continue;\n                    util.attachSchema(payload.issues, currLen, inst);\n                    if (!isAborted)\n                        isAborted = util.aborted(payload, currLen);\n                }\n            }\n            if (asyncResult) {\n                return asyncResult.then(() => {\n                    return payload;\n                });\n            }\n            return payload;\n        };\n        const handleCanaryResult = (canary, payload, ctx) => {\n            // abort if the canary is aborted\n            if (util.aborted(canary)) {\n                canary.aborted = true;\n                return canary;\n            }\n            // run checks first, then\n            const checkResult = runChecks(payload, checks, ctx);\n            if (checkResult instanceof Promise) {\n                if (ctx.async === false)\n                    throw new core.$ZodAsyncError();\n                return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n            }\n            return inst._zod.parse(checkResult, ctx);\n        };\n        inst._zod.run = (payload, ctx) => {\n            if (ctx.skipChecks) {\n                return inst._zod.parse(payload, ctx);\n            }\n            if (ctx.direction === \"backward\") {\n                // run canary initial pass (no checks)\n                const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n                if (canary instanceof Promise) {\n                    return canary.then((canary) => {\n                        return handleCanaryResult(canary, payload, ctx);\n                    });\n                }\n                return handleCanaryResult(canary, payload, ctx);\n            }\n            // forward\n            const result = inst._zod.parse(payload, ctx);\n            if (result instanceof Promise) {\n                if (ctx.async === false)\n                    throw new core.$ZodAsyncError();\n                return result.then((result) => runChecks(result, checks, ctx));\n            }\n            return runChecks(result, checks, ctx);\n        };\n    }\n}, {\n    // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n    get \"~standard\"() {\n        return util.hide(this, \"~standard\", standardProps(this));\n    },\n    set \"~standard\"(value) {\n        util.own(this, \"~standard\", value);\n    },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\nconst toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues };\nexport function standardProps(inst) {\n    return {\n        validate: (value) => {\n            try {\n                return toStandardResult(safeParse(inst, value));\n            }\n            catch (_) {\n                return safeParseAsync(inst, value).then(toStandardResult);\n            }\n        },\n        vendor: \"zod\",\n        version: 1,\n    };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n    inst._zod.parse = (payload, _) => {\n        if (def.coerce)\n            try {\n                payload.value = String(payload.value);\n            }\n            catch (_) { }\n        if (typeof payload.value === \"string\")\n            return payload;\n        payload.issues.push({\n            expected: \"string\",\n            code: \"invalid_type\",\n            input: payload.value,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n    // check initialization must come first\n    checks.$ZodCheckStringFormat.init(inst, def);\n    $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.guid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n    if (def.version) {\n        const versionMap = {\n            v1: 1,\n            v2: 2,\n            v3: 3,\n            v4: 4,\n            v5: 5,\n            v6: 6,\n            v7: 7,\n            v8: 8,\n        };\n        const v = versionMap[def.version];\n        if (v === undefined)\n            throw new Error(`Invalid UUID version: \"${def.version}\"`);\n        def.pattern ?? (def.pattern = regexes.uuid(v));\n    }\n    else\n        def.pattern ?? (def.pattern = regexes.uuid());\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.email);\n    $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL constructor rejected the input. */\nexport const URL_UNPARSEABLE = 2;\n/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */\nexport function parseURLObject(trimmed, def) {\n    // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n    if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n        return URL_BAD_FORMAT;\n    }\n    try {\n        // @ts-ignore\n        return new URL(trimmed);\n    }\n    catch {\n        return URL_UNPARSEABLE;\n    }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n    return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n    hostname.lastIndex = 0;\n    return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n    protocol.lastIndex = 0;\n    return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        try {\n            // Trim whitespace from input\n            const trimmed = payload.value.trim();\n            const url = parseURLObject(trimmed, def);\n            if (url === URL_BAD_FORMAT) {\n                payload.issues.push({\n                    code: \"invalid_format\",\n                    format: \"url\",\n                    note: \"Invalid URL format\",\n                    input: payload.value,\n                    inst,\n                    continue: !def.abort,\n                });\n                return;\n            }\n            if (url === URL_UNPARSEABLE) {\n                payload.issues.push({\n                    code: \"invalid_format\",\n                    format: \"url\",\n                    input: payload.value,\n                    inst,\n                    continue: !def.abort,\n                });\n                return;\n            }\n            if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n                payload.issues.push({\n                    code: \"invalid_format\",\n                    format: \"url\",\n                    note: \"Invalid hostname\",\n                    pattern: def.hostname.source,\n                    input: payload.value,\n                    inst,\n                    continue: !def.abort,\n                });\n            }\n            if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n                payload.issues.push({\n                    code: \"invalid_format\",\n                    format: \"url\",\n                    note: \"Invalid protocol\",\n                    pattern: def.protocol.source,\n                    input: payload.value,\n                    inst,\n                    continue: !def.abort,\n                });\n            }\n            // Set the output value based on normalize flag\n            payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n            return;\n        }\n        catch (_) {\n            payload.issues.push({\n                code: \"invalid_format\",\n                format: \"url\",\n                input: payload.value,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.emoji());\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n    if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n        throw new Error(`Invalid nanoid length: ${def.length}`);\n    def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n    $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cuid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cuid2);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ulid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.xid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ksuid);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.datetime(def));\n    $ZodStringFormat.init(inst, def);\n    // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema\n    if (def.local || def.precision === -1) {\n        inst._zod.bag.laxFormat = true;\n        inst._zod.onattach.push((s) => {\n            s._zod.bag.laxFormat = true;\n        });\n    }\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.date);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.time(def));\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.duration);\n    $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ipv4);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.format = `ipv4`;\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n    if (!ipv6Alphabet.test(value))\n        return false;\n    try {\n        // @ts-ignore\n        new URL(`http://[${value}]`);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.ipv6);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.format = `ipv6`;\n    inst._zod.check = (payload) => {\n        if (!isValidIPv6(payload.value)) {\n            payload.issues.push({\n                code: \"invalid_format\",\n                format: \"ipv6\",\n                input: payload.value,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cidrv4);\n    $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n    const parts = value.split(\"/\");\n    if (parts.length !== 2)\n        return false;\n    const [address, prefix] = parts;\n    if (!prefix)\n        return false;\n    const prefixNum = Number(prefix);\n    if (`${prefixNum}` !== prefix)\n        return false;\n    if (prefixNum < 0 || prefixNum > 128)\n        return false;\n    return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (!isValidCIDRv6(payload.value)) {\n            payload.issues.push({\n                code: \"invalid_format\",\n                format: \"cidrv6\",\n                input: payload.value,\n                inst,\n                continue: !def.abort,\n            });\n        }\n    };\n});\n//////////////////////////////   ZodBase64   //////////////////////////////\nexport function isValidBase64(data) {\n    if (data === \"\")\n        return true;\n    // atob ignores whitespace, so reject it up front.\n    if (/\\s/.test(data))\n        return false;\n    if (data.length % 4 !== 0)\n        return false;\n    try {\n        // @ts-ignore\n        atob(data);\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.base64);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.contentEncoding = \"base64\";\n    inst._zod.check = (payload) => {\n        if (isValidBase64(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"base64\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\n//////////////////////////////   ZodBase64   //////////////////////////////\nexport function isValidBase64URL(data) {\n    if (!regexes.base64url.test(data))\n        return false;\n    const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n    const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n    return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.base64url);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.bag.contentEncoding = \"base64url\";\n    inst._zod.check = (payload) => {\n        if (isValidBase64URL(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"base64url\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n    def.pattern ?? (def.pattern = regexes.e164);\n    $ZodStringFormat.init(inst, def);\n});\n//////////////////////////////   ZodCreditCard   //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n    let length = digits.length;\n    let bit = 1;\n    let sum = 0;\n    while (length) {\n        const value = +digits[--length];\n        bit ^= 1;\n        sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n    }\n    return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n    if (!regexes.creditCard.test(input))\n        return false;\n    return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n    // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n    def.pattern ?? (def.pattern = regexes.creditCard);\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (isValidCreditCard(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"credit_card\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\n//////////////////////////////   ZodJWT   //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n    try {\n        const tokensParts = token.split(\".\");\n        if (tokensParts.length !== 3)\n            return false;\n        const [header] = tokensParts;\n        if (!header)\n            return false;\n        // @ts-ignore\n        const parsedHeader = JSON.parse(atob(header));\n        if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n            return false;\n        if (!parsedHeader.alg)\n            return false;\n        if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n            return false;\n        return true;\n    }\n    catch {\n        return false;\n    }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (isValidJWT(payload.value, def.alg))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: \"jwt\",\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n    $ZodStringFormat.init(inst, def);\n    inst._zod.check = (payload) => {\n        if (def.fn(payload.value))\n            return;\n        payload.issues.push({\n            code: \"invalid_format\",\n            format: def.format,\n            input: payload.value,\n            inst,\n            continue: !def.abort,\n        });\n    };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce)\n            try {\n                payload.value = Number(payload.value);\n            }\n            catch (_) { }\n        const input = payload.value;\n        if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n            return payload;\n        }\n        const received = typeof input === \"number\"\n            ? Number.isNaN(input)\n                ? \"NaN\"\n                : !Number.isFinite(input)\n                    ? String(input)\n                    : undefined\n            : undefined;\n        payload.issues.push({\n            expected: \"number\",\n            code: \"invalid_type\",\n            input,\n            inst,\n            ...(received ? { received } : {}),\n        });\n        return payload;\n    };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n    checks.$ZodCheckNumberFormat.init(inst, def);\n    $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.boolean;\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce)\n            try {\n                payload.value = Boolean(payload.value);\n            }\n            catch (_) { }\n        const input = payload.value;\n        if (typeof input === \"boolean\")\n            return payload;\n        payload.issues.push({\n            expected: \"boolean\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.bigint;\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce)\n            try {\n                payload.value = BigInt(payload.value);\n            }\n            catch (_) { }\n        if (typeof payload.value === \"bigint\")\n            return payload;\n        payload.issues.push({\n            expected: \"bigint\",\n            code: \"invalid_type\",\n            input: payload.value,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n    checks.$ZodCheckBigIntFormat.init(inst, def);\n    $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (typeof input === \"symbol\")\n            return payload;\n        payload.issues.push({\n            expected: \"symbol\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.undefined;\n    inst._zod.values = new Set([undefined]);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (typeof input === \"undefined\")\n            return payload;\n        payload.issues.push({\n            expected: \"undefined\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.pattern = regexes.null;\n    inst._zod.values = new Set([null]);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (input === null)\n            return payload;\n        payload.issues.push({\n            expected: \"null\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        payload.issues.push({\n            expected: \"never\",\n            code: \"invalid_type\",\n            input: payload.value,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (typeof input === \"undefined\")\n            return payload;\n        payload.issues.push({\n            expected: \"void\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        if (def.coerce) {\n            try {\n                payload.value = new Date(payload.value);\n            }\n            catch (_err) { }\n        }\n        const input = payload.value;\n        const isDate = input instanceof Date;\n        const isValidDate = isDate && !Number.isNaN(input.getTime());\n        if (isValidDate)\n            return payload;\n        payload.issues.push({\n            expected: \"date\",\n            code: \"invalid_type\",\n            input,\n            ...(isDate ? { received: \"Invalid Date\" } : {}),\n            inst,\n        });\n        return payload;\n    };\n});\nfunction handleArrayResult(result, final, index) {\n    if (result.issues.length) {\n        final.issues.push(...util.prefixIssues(index, result.issues));\n    }\n    final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!Array.isArray(input)) {\n            payload.issues.push({\n                expected: \"array\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n        const proms = [];\n        for (let i = 0; i < input.length; i++) {\n            const item = input[i];\n            const result = def.element._zod.run({\n                value: item,\n                issues: [],\n            }, ctx);\n            if (result instanceof Promise) {\n                proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n            }\n            else {\n                handleArrayResult(result, payload, i);\n            }\n        }\n        if (proms.length) {\n            return Promise.all(proms).then(() => payload);\n        }\n        return payload; //handleArrayResultsAsync(parseResults, final);\n    };\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n    const isPresent = key in input;\n    const isOptionalOut = optout === \"optional\";\n    // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n    if (!isPresent && isOptionalOut && optin === \"optional\") {\n        return;\n    }\n    if (result.issues.length) {\n        // For optional-in/out schemas, ignore errors on absent keys.\n        if (optin !== undefined && isOptionalOut && !isPresent) {\n            return;\n        }\n        final.issues.push(...util.prefixIssues(key, result.issues));\n    }\n    if (!isPresent && optin === undefined) {\n        if (!result.issues.length) {\n            final.issues.push({\n                code: \"invalid_type\",\n                expected: \"nonoptional\",\n                input: undefined,\n                path: [key],\n            });\n        }\n        return;\n    }\n    if (result.value === undefined) {\n        if (isPresent) {\n            final.value[key] = undefined;\n        }\n    }\n    else {\n        final.value[key] = result.value;\n    }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n    const keys = Object.keys(def.shape);\n    const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n    const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n    // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n    const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n    for (const k of allKeys) {\n        if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n            throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n        }\n    }\n    const okeys = util.optionalKeys(def.shape);\n    return {\n        ...def,\n        allKeys,\n        symbolKeys,\n        // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n        keySet: new Set(keys),\n        numKeys: keys.length,\n        optionalKeys: new Set(okeys),\n    };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n    const unrecognized = [];\n    const keySet = def.keySet;\n    const _catchall = def.catchall._zod;\n    const t = _catchall.def.type;\n    const optin = _catchall.optin;\n    const optout = _catchall.optout;\n    for (const key in input) {\n        // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n        if (keySet.has(key))\n            continue;\n        // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n        if (key === \"__proto__\") {\n            if (t === \"never\")\n                unrecognized.push(key);\n            continue;\n        }\n        if (t === \"never\") {\n            unrecognized.push(key);\n            continue;\n        }\n        const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n        if (r instanceof Promise) {\n            proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n        }\n        else {\n            handlePropertyResult(r, payload, key, input, optin, optout);\n        }\n    }\n    if (unrecognized.length) {\n        payload.issues.push({\n            code: \"unrecognized_keys\",\n            keys: unrecognized,\n            input,\n            inst,\n            // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n            continue: true,\n        });\n    }\n    if (!proms.length)\n        return payload;\n    return Promise.all(proms).then(() => {\n        return payload;\n    });\n}\n// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed.\nconst propShapes = new WeakMap();\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n    // requires cast because technically $ZodObject doesn't extend\n    $ZodType.init(inst, def);\n    // const sh = def.shape;\n    const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n    if (!desc?.get) {\n        const sh = def.shape;\n        propShapes.set(def, sh);\n        Object.defineProperty(def, \"shape\", {\n            get: () => {\n                const newSh = { ...sh };\n                Object.defineProperty(def, \"shape\", {\n                    value: newSh,\n                });\n                propShapes.set(def, newSh);\n                return newSh;\n            },\n        });\n    }\n    const _normalized = util.cached(() => normalizeDef(def));\n    util.defineLazyInternal(inst, \"propValues\", (zod) => {\n        const shape = zod.def.shape;\n        const propValues = {};\n        for (const key in shape) {\n            const field = shape[key]._zod;\n            if (field.values) {\n                if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n                    util.assignProp(propValues, key, new Set());\n                }\n                for (const v of field.values)\n                    propValues[key].add(v);\n                // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n                if (field.optin !== undefined)\n                    propValues[key].add(undefined);\n            }\n        }\n        return propValues;\n    });\n    const isObject = util.isObject;\n    const catchall = def.catchall;\n    let value;\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        value ?? (value = _normalized.value);\n        const input = payload.value;\n        if (!isObject(input)) {\n            payload.issues.push({\n                expected: \"object\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n        const proms = [];\n        const shape = value.shape;\n        for (const key of value.allKeys) {\n            if (key === \"__proto__\")\n                continue;\n            const el = shape[key];\n            const optin = el._zod.optin;\n            const optout = el._zod.optout;\n            const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n            if (r instanceof Promise) {\n                proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n            }\n            else {\n                handlePropertyResult(r, payload, key, input, optin, optout);\n            }\n        }\n        if (!catchall) {\n            return proms.length ? Promise.all(proms).then(() => payload) : payload;\n        }\n        return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n    };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n    // requires cast because technically $ZodObject doesn't extend\n    $ZodObject.init(inst, def);\n    const superParse = inst._zod.parse;\n    const _normalized = util.cached(() => normalizeDef(def));\n    const memo = core.globalConfig.memoizer;\n    const generateFastpass = (shape) => {\n        const normalized = _normalized.value;\n        const syms = normalized.symbolKeys;\n        // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n        const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n        const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n        // Prefixes in place, like util.prefixIssues does for every interpreted path.\n        const prefixStr = (id, k) => `\n          for (let i = 0; i < ${id}.issues.length; i++) {\n            const iss = ${id}.issues[i];\n            iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n            payload.issues.push(iss);\n          }`;\n        doc.write(`const input = payload.value;`);\n        const ids = Object.create(null);\n        let counter = 0;\n        for (const key of normalized.allKeys) {\n            ids[key] = `key_${counter++}`;\n        }\n        // A: preserve key order {\n        doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n        for (const key of normalized.allKeys) {\n            if (key === \"__proto__\")\n                continue;\n            const id = ids[key];\n            const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n            const isPresent = `${k} in input`;\n            const schema = shape[key];\n            const optin = schema?._zod?.optin;\n            const isOptionalIn = optin !== undefined;\n            const isOptionalOut = schema?._zod?.optout === \"optional\";\n            doc.write(`const ${id} = ${parseStr(k)};`);\n            if (isOptionalIn && isOptionalOut) {\n                // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n                const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n                doc.write(`\n        const ${id}_present = ${isPresent};\n        if (!${id}.issues.length || ${id}_present) {\n          if (${id}.issues.length) {${prefixStr(id, k)}\n          }\n\n          if (${assign}) {\n            newResult[${k}] = ${id}.value;\n          }\n        }\n\n      `);\n            }\n            else if (!isOptionalIn) {\n                doc.write(`\n        const ${id}_present = ${isPresent};\n        if (${id}.issues.length) {${prefixStr(id, k)}\n        }\n        if (!${id}_present && !${id}.issues.length) {\n          payload.issues.push({\n            code: \"invalid_type\",\n            expected: \"nonoptional\",\n            input: undefined,\n            path: [${k}]\n          });\n        }\n\n        if (${id}_present) {\n          newResult[${k}] = ${id}.value;\n        }\n\n      `);\n            }\n            else {\n                doc.write(`\n        if (${id}.issues.length) {${prefixStr(id, k)}\n        }\n        \n        if (${id}.value === undefined) {\n          if (${isPresent}) {\n            newResult[${k}] = undefined;\n          }\n        } else {\n          newResult[${k}] = ${id}.value;\n        }\n\n      `);\n            }\n        }\n        doc.write(`payload.value = newResult;`);\n        doc.write(`return payload;`);\n        // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n        return doc.compile();\n    };\n    let fastpass;\n    const isObject = util.isObject;\n    const jit = !core.globalConfig.jitless;\n    const allowsEval = util.allowsEval;\n    const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n    const catchall = def.catchall;\n    let value;\n    inst._zod.parse = (payload, ctx) => {\n        value ?? (value = _normalized.value);\n        const input = payload.value;\n        if (!isObject(input)) {\n            payload.issues.push({\n                expected: \"object\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n            // always synchronous\n            if (!fastpass)\n                fastpass = generateFastpass(def.shape);\n            payload = fastpass(payload, ctx);\n            if (!catchall)\n                return payload;\n            return handleCatchall([], input, payload, ctx, value, inst);\n        }\n        return superParse(payload, ctx);\n    };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n    for (const result of results) {\n        if (result.issues.length === 0) {\n            final.value = result.value;\n            return final;\n        }\n    }\n    const nonaborted = results.filter((r) => !util.aborted(r));\n    if (nonaborted.length === 1) {\n        final.value = nonaborted[0].value;\n        return nonaborted[0];\n    }\n    final.issues.push({\n        code: \"invalid_union\",\n        input: final.value,\n        inst,\n        errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n    });\n    return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n        ? \"defaulted\"\n        : zod.def.options.some((o) => o._zod.optin !== undefined)\n            ? \"optional\"\n            : undefined);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n    util.defineLazyInternal(inst, \"values\", (zod) => {\n        if (zod.def.options.every((o) => o._zod.values)) {\n            return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n        }\n        return undefined;\n    });\n    util.defineLazyInternal(inst, \"pattern\", (zod) => {\n        if (zod.def.options.every((o) => o._zod.pattern)) {\n            const patterns = zod.def.options.map((o) => o._zod.pattern);\n            return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n        }\n        return undefined;\n    });\n    const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n    inst._zod.parse = (payload, ctx) => {\n        if (first) {\n            return first(payload, ctx);\n        }\n        let async = false;\n        const results = [];\n        for (const option of def.options) {\n            const result = option._zod.run({\n                value: payload.value,\n                issues: [],\n            }, ctx);\n            if (result instanceof Promise) {\n                results.push(result);\n                async = true;\n            }\n            else {\n                if (result.issues.length === 0)\n                    return result;\n                results.push(result);\n            }\n        }\n        if (!async)\n            return handleUnionResults(results, payload, inst, ctx);\n        return Promise.all(results).then((results) => {\n            return handleUnionResults(results, payload, inst, ctx);\n        });\n    };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n    const matches = [];\n    for (let i = 0; i < results.length; i++) {\n        if (results[i].issues.length === 0)\n            matches.push(i);\n    }\n    if (matches.length === 1) {\n        final.value = results[matches[0]].value;\n        return final;\n    }\n    if (matches.length === 0) {\n        // No matches - same as regular union\n        final.issues.push({\n            code: \"invalid_union\",\n            input: final.value,\n            inst,\n            errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n        });\n    }\n    else {\n        // Multiple matches - exclusive union failure\n        final.issues.push({\n            code: \"invalid_union\",\n            input: final.value,\n            inst,\n            errors: [],\n            inclusive: false,\n            matches,\n        });\n    }\n    return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n    $ZodUnion.init(inst, def);\n    def.inclusive = false;\n    const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n    inst._zod.parse = (payload, ctx) => {\n        if (first) {\n            return first(payload, ctx);\n        }\n        let async = false;\n        const results = [];\n        for (const option of def.options) {\n            const result = option._zod.run({\n                value: payload.value,\n                issues: [],\n            }, ctx);\n            if (result instanceof Promise) {\n                results.push(result);\n                async = true;\n            }\n            else {\n                results.push(result);\n            }\n        }\n        if (!async)\n            return handleExclusiveUnionResults(results, payload, inst, ctx);\n        return Promise.all(results).then((results) => {\n            return handleExclusiveUnionResults(results, payload, inst, ctx);\n        });\n    };\n});\n/** Returns the option of `union` whose discriminator claims `value`. */\nexport function getDiscriminatedOption(union, value) {\n    const internals = union._zod;\n    let map = internals.bag.optionsMap;\n    if (!map) {\n        map = new Map();\n        const { options, discriminator } = internals.def;\n        for (const option of options) {\n            // First declaration wins, matching the order the parse path resolves a duplicate in.\n            for (const v of option._zod.propValues?.[discriminator] ?? [])\n                if (!map.has(v))\n                    map.set(v, option);\n        }\n        internals.bag.optionsMap = map;\n    }\n    return map.get(value);\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n    def.inclusive = false;\n    $ZodUnion.init(inst, def);\n    const _super = inst._zod.parse;\n    util.defineLazyInternal(inst, \"propValues\", (zod) => {\n        const propValues = {};\n        for (const option of zod.def.options) {\n            const pv = option._zod.propValues;\n            if (!pv || Object.keys(pv).length === 0)\n                throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n            for (const [k, v] of Object.entries(pv)) {\n                if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n                    util.assignProp(propValues, k, new Set());\n                }\n                for (const val of v) {\n                    propValues[k].add(val);\n                }\n            }\n        }\n        return propValues;\n    });\n    // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map.\n    def.options.forEach((option, i) => {\n        const propShape = propShapes.get(option._zod.def);\n        if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n            throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n        }\n    });\n    const disc = util.cached(() => {\n        const opts = def.options;\n        const map = new Map();\n        for (const o of opts) {\n            const values = o._zod.propValues?.[def.discriminator];\n            if (!values || values.size === 0)\n                throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n            for (const v of values) {\n                if (map.has(v)) {\n                    throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n                }\n                map.set(v, o);\n            }\n        }\n        return map;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!util.isObject(input)) {\n            payload.issues.push({\n                code: \"invalid_type\",\n                expected: \"object\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        const opt = disc.value.get(input?.[def.discriminator]);\n        if (opt) {\n            return opt._zod.run(payload, ctx);\n        }\n        // Fall back to union matching when the fast discriminator path fails:\n        // - explicitly enabled via unionFallback, or\n        // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n        if (def.unionFallback || ctx.direction === \"backward\") {\n            return _super(payload, ctx);\n        }\n        // no matching discriminator\n        payload.issues.push({\n            code: \"invalid_union\",\n            errors: [],\n            note: \"No matching discriminator\",\n            discriminator: def.discriminator,\n            options: Array.from(disc.value.keys()),\n            input,\n            path: [def.discriminator],\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n        const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n        const async = left instanceof Promise || right instanceof Promise;\n        if (async) {\n            return Promise.all([left, right]).then(([left, right]) => {\n                return handleIntersectionResults(payload, left, right);\n            });\n        }\n        return handleIntersectionResults(payload, left, right);\n    };\n});\nexport function mergeValues(a, b) {\n    // const aType = parse.t(a);\n    // const bType = parse.t(b);\n    if (a === b) {\n        return { valid: true, data: a };\n    }\n    if (a instanceof Date && b instanceof Date && +a === +b) {\n        return { valid: true, data: a };\n    }\n    if (util.isPlainObject(a) && util.isPlainObject(b)) {\n        const bKeys = Object.keys(b);\n        const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n        const newObj = { ...a, ...b };\n        if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n            delete newObj.__proto__;\n        for (const key of sharedKeys) {\n            if (key === \"__proto__\")\n                continue;\n            const sharedValue = mergeValues(a[key], b[key]);\n            if (!sharedValue.valid) {\n                return {\n                    valid: false,\n                    mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n                };\n            }\n            newObj[key] = sharedValue.data;\n        }\n        return { valid: true, data: newObj };\n    }\n    if (Array.isArray(a) && Array.isArray(b)) {\n        if (a.length !== b.length) {\n            return { valid: false, mergeErrorPath: [] };\n        }\n        const newArray = [];\n        for (let index = 0; index < a.length; index++) {\n            const itemA = a[index];\n            const itemB = b[index];\n            const sharedValue = mergeValues(itemA, itemB);\n            if (!sharedValue.valid) {\n                return {\n                    valid: false,\n                    mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n                };\n            }\n            newArray.push(sharedValue.data);\n        }\n        return { valid: true, data: newArray };\n    }\n    return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n    // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n    const unrecKeys = new Map();\n    let unrecIssue;\n    const keyIssues = new Map();\n    const collect = (iss, side) => {\n        let keys;\n        if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n            unrecIssue ?? (unrecIssue = iss);\n            keys = iss.keys;\n        }\n        else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n            const k = String(iss.path[0]);\n            if (!keyIssues.has(k))\n                keyIssues.set(k, iss);\n            keys = [k];\n        }\n        else {\n            return false;\n        }\n        for (const k of keys) {\n            if (!unrecKeys.has(k))\n                unrecKeys.set(k, {});\n            unrecKeys.get(k)[side] = true;\n        }\n        return true;\n    };\n    for (const iss of left.issues) {\n        if (!collect(iss, \"l\"))\n            result.issues.push(iss);\n    }\n    for (const iss of right.issues) {\n        if (!collect(iss, \"r\"))\n            result.issues.push(iss);\n    }\n    // Report only keys rejected by BOTH sides\n    const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n    if (bothKeys.length) {\n        const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n        if (aggregated.length)\n            result.issues.push({ ...unrecIssue, keys: aggregated });\n        for (const k of bothKeys) {\n            if (!aggregated.includes(k) && keyIssues.has(k))\n                result.issues.push(keyIssues.get(k));\n        }\n    }\n    const merged = mergeValues(left.value, right.value);\n    if (!merged.valid) {\n        if (util.aborted(result))\n            return result;\n        throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n    }\n    result.value = merged.data;\n    return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const items = def.items;\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!Array.isArray(input)) {\n            payload.issues.push({\n                input,\n                inst,\n                expected: \"tuple\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n        const proms = [];\n        const optinStart = getTupleOptStart(items, \"optin\");\n        const optoutStart = getTupleOptStart(items, \"optout\");\n        if (!def.rest) {\n            if (input.length < optinStart) {\n                payload.issues.push({\n                    code: \"too_small\",\n                    minimum: optinStart,\n                    inclusive: true,\n                    input,\n                    inst,\n                    origin: \"array\",\n                });\n                return payload;\n            }\n            if (input.length > items.length) {\n                payload.issues.push({\n                    code: \"too_big\",\n                    maximum: items.length,\n                    inclusive: true,\n                    input,\n                    inst,\n                    origin: \"array\",\n                });\n            }\n        }\n        // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n        const itemResults = new Array(items.length);\n        for (let i = 0; i < items.length; i++) {\n            const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n            if (r instanceof Promise) {\n                proms.push(r.then((rr) => {\n                    itemResults[i] = rr;\n                }));\n            }\n            else {\n                itemResults[i] = r;\n            }\n        }\n        if (def.rest) {\n            let i = items.length - 1;\n            const rest = input.slice(items.length);\n            for (const el of rest) {\n                i++;\n                const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n                if (result instanceof Promise) {\n                    proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n                }\n                else {\n                    handleTupleResult(result, payload, i);\n                }\n            }\n        }\n        if (proms.length) {\n            return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n        }\n        return handleTupleResults(itemResults, payload, items, input, optoutStart);\n    };\n});\nfunction getTupleOptStart(items, key) {\n    for (let i = items.length - 1; i >= 0; i--) {\n        // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n        const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n        if (!omittable)\n            return i + 1;\n    }\n    return 0;\n}\nfunction handleTupleResult(result, final, index) {\n    if (result.issues.length) {\n        final.issues.push(...util.prefixIssues(index, result.issues));\n    }\n    final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n    // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n    for (let i = 0; i < items.length; i++) {\n        const r = itemResults[i];\n        const isPresent = i < input.length;\n        // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n        if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n            final.value.length = i;\n            break;\n        }\n        if (r.issues.length) {\n            if (!isPresent && i >= optoutStart) {\n                final.value.length = i;\n                break;\n            }\n            final.issues.push(...util.prefixIssues(i, r.issues));\n        }\n        final.value[i] = r.value;\n    }\n    // Drop trailing slots that produced `undefined` for absent input\n    // (the array analog of an absent optional key on an object). The\n    // `i >= input.length` floor is critical: an explicit `undefined`\n    // *inside* the input must be preserved even when the schema is\n    // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n    // explicit undefined value).\n    for (let i = final.value.length - 1; i >= input.length; i--) {\n        if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n            final.value.length = i;\n        }\n        else {\n            break;\n        }\n    }\n    return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!util.isPlainObject(input)) {\n            payload.issues.push({\n                expected: \"record\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        const proms = [];\n        const values = def.keyType._zod.values;\n        if (values && !def.partial) {\n            payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n            const recordKeys = new Set();\n            for (const key of values) {\n                if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n                    recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n                    // A declared __proto__ is stripped but is not an unrecognized key.\n                    if (key === \"__proto__\")\n                        continue;\n                    const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n                    if (keyResult instanceof Promise) {\n                        throw new Error(\"Async schemas not supported in object keys currently\");\n                    }\n                    if (keyResult.issues.length) {\n                        payload.issues.push({\n                            code: \"invalid_key\",\n                            origin: \"record\",\n                            issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n                            input: key,\n                            path: [key],\n                            inst,\n                        });\n                        continue;\n                    }\n                    const outKey = keyResult.value;\n                    if (outKey === \"__proto__\")\n                        continue;\n                    const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n                    if (result instanceof Promise) {\n                        proms.push(result.then((result) => {\n                            if (result.issues.length) {\n                                payload.issues.push(...util.prefixIssues(key, result.issues));\n                            }\n                            payload.value[outKey] = result.value;\n                        }));\n                    }\n                    else {\n                        if (result.issues.length) {\n                            payload.issues.push(...util.prefixIssues(key, result.issues));\n                        }\n                        payload.value[outKey] = result.value;\n                    }\n                }\n            }\n            let unrecognized;\n            for (const key in input) {\n                if (!recordKeys.has(key)) {\n                    if (def.mode === \"loose\") {\n                        // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n                        if (key === \"__proto__\")\n                            continue;\n                        payload.value[key] = input[key];\n                    }\n                    else {\n                        unrecognized = unrecognized ?? [];\n                        unrecognized.push(key);\n                    }\n                }\n            }\n            if (unrecognized && unrecognized.length > 0) {\n                payload.issues.push({\n                    code: \"unrecognized_keys\",\n                    input,\n                    inst,\n                    keys: unrecognized,\n                    continue: true,\n                });\n            }\n        }\n        else {\n            payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n            // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n            let unrecognized;\n            // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n            for (const key of Reflect.ownKeys(input)) {\n                if (key === \"__proto__\")\n                    continue;\n                if (!Object.prototype.propertyIsEnumerable.call(input, key))\n                    continue;\n                let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n                if (keyResult instanceof Promise) {\n                    throw new Error(\"Async schemas not supported in object keys currently\");\n                }\n                // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n                const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n                if (checkNumericKey) {\n                    const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n                    if (retryResult instanceof Promise) {\n                        throw new Error(\"Async schemas not supported in object keys currently\");\n                    }\n                    if (retryResult.issues.length === 0) {\n                        keyResult = retryResult;\n                    }\n                }\n                if (keyResult.issues.length) {\n                    if (def.mode === \"loose\") {\n                        // Pass through unchanged\n                        payload.value[key] = input[key];\n                    }\n                    else if (values) {\n                        unrecognized = unrecognized ?? [];\n                        unrecognized.push(key);\n                    }\n                    else {\n                        // Default \"strict\" behavior: error on invalid key\n                        payload.issues.push({\n                            code: \"invalid_key\",\n                            origin: \"record\",\n                            issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n                            input: key,\n                            path: [key],\n                            inst,\n                        });\n                    }\n                    continue;\n                }\n                // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n                const outKey = keyResult.value;\n                if (outKey === \"__proto__\")\n                    continue;\n                const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n                if (result instanceof Promise) {\n                    proms.push(result.then((result) => {\n                        if (result.issues.length) {\n                            payload.issues.push(...util.prefixIssues(key, result.issues));\n                        }\n                        payload.value[outKey] = result.value;\n                    }));\n                }\n                else {\n                    if (result.issues.length) {\n                        payload.issues.push(...util.prefixIssues(key, result.issues));\n                    }\n                    payload.value[outKey] = result.value;\n                }\n            }\n            if (unrecognized && unrecognized.length > 0) {\n                payload.issues.push({\n                    code: \"unrecognized_keys\",\n                    input,\n                    inst,\n                    keys: unrecognized,\n                    continue: true,\n                });\n            }\n        }\n        if (proms.length) {\n            return Promise.all(proms).then(() => payload);\n        }\n        return payload;\n    };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!(input instanceof Map)) {\n            payload.issues.push({\n                expected: \"map\",\n                code: \"invalid_type\",\n                input,\n                inst,\n            });\n            return payload;\n        }\n        const proms = [];\n        payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n        for (const [key, value] of input) {\n            const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n            const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n            if (keyResult instanceof Promise || valueResult instanceof Promise) {\n                proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n                    handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n                }));\n            }\n            else {\n                handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n            }\n        }\n        if (proms.length)\n            return Promise.all(proms).then(() => payload);\n        return payload;\n    };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n    if (keyResult.issues.length) {\n        if (util.propertyKeyTypes.has(typeof key)) {\n            final.issues.push(...util.prefixIssues(key, keyResult.issues));\n        }\n        else {\n            final.issues.push({\n                code: \"invalid_key\",\n                origin: \"map\",\n                input,\n                inst,\n                issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n            });\n        }\n    }\n    if (valueResult.issues.length) {\n        if (util.propertyKeyTypes.has(typeof key)) {\n            final.issues.push(...util.prefixIssues(key, valueResult.issues));\n        }\n        else {\n            final.issues.push({\n                origin: \"map\",\n                code: \"invalid_element\",\n                input,\n                inst,\n                key: key,\n                issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n            });\n        }\n    }\n    final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const memo = core.globalConfig.memoizer;\n    memo?.attach(inst);\n    inst._zod.parse = (payload, ctx) => {\n        const input = payload.value;\n        if (!(input instanceof Set)) {\n            payload.issues.push({\n                input,\n                inst,\n                expected: \"set\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        const proms = [];\n        payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n        for (const item of input) {\n            const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n            if (result instanceof Promise) {\n                proms.push(result.then((result) => handleSetResult(result, payload)));\n            }\n            else\n                handleSetResult(result, payload);\n        }\n        if (proms.length)\n            return Promise.all(proms).then(() => payload);\n        return payload;\n    };\n});\nfunction handleSetResult(result, final) {\n    if (result.issues.length) {\n        final.issues.push(...result.issues);\n    }\n    final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const values = util.getEnumValues(def.entries);\n    const valuesSet = new Set(values);\n    inst._zod.values = valuesSet;\n    const patternValues = values.filter((k) => util.propertyKeyTypes.has(typeof k));\n    // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n    inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (valuesSet.has(input)) {\n            return payload;\n        }\n        payload.issues.push({\n            code: \"invalid_value\",\n            values,\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const values = new Set(def.values);\n    inst._zod.values = values;\n    // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n    inst._zod.pattern = new RegExp(def.values.length\n        ? `^(${def.values\n            .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n            .join(\"|\")})$`\n        : \"^[^\\\\s\\\\S]$\");\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        if (values.has(input)) {\n            return payload;\n        }\n        payload.issues.push({\n            code: \"invalid_value\",\n            values: def.values,\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        const input = payload.value;\n        // @ts-ignore\n        if (input instanceof File)\n            return payload;\n        payload.issues.push({\n            expected: \"file\",\n            code: \"invalid_type\",\n            input,\n            inst,\n        });\n        return payload;\n    };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.optin = \"optional\";\n    core.globalConfig.memoizer?.guard(inst);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            throw new core.$ZodEncodeError(inst.constructor.name);\n        }\n        const _out = def.transform(payload.value, payload);\n        if (ctx.async) {\n            const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n            return output.then((output) => {\n                payload.value = output;\n                return payload;\n            });\n        }\n        if (_out instanceof Promise) {\n            throw new core.$ZodAsyncError();\n        }\n        payload.value = _out;\n        return payload;\n    };\n});\nfunction handleOptionalResult(payload, result) {\n    // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n    payload.value = result.issues.length ? undefined : result.value;\n    return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n    inst._zod.optout = \"optional\";\n    util.defineLazyInternal(inst, \"values\", (zod) => {\n        const values = zod.def.innerType._zod.values;\n        return values ? new Set([...values, undefined]) : undefined;\n    });\n    util.defineLazyInternal(inst, \"pattern\", (zod) => {\n        const pattern = zod.def.innerType._zod.pattern;\n        return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        if (payload.value === undefined) {\n            // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n            if (def.innerType._zod.optin !== \"defaulted\")\n                return payload;\n            // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n            const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n            if (result instanceof Promise)\n                return result.then((result) => handleOptionalResult(payload, result));\n            return handleOptionalResult(payload, result);\n        }\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n    // Call parent init - inherits optin/optout = \"optional\"\n    $ZodOptional.init(inst, def);\n    // Override values/pattern to NOT add undefined\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n    util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n    // Override parse to just delegate (no undefined handling)\n    inst._zod.parse = (payload, ctx) => {\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n    util.defineLazyInternal(inst, \"pattern\", (zod) => {\n        const pattern = zod.def.innerType._zod.pattern;\n        return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n    });\n    util.defineLazyInternal(inst, \"values\", (zod) => {\n        return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        // Forward direction (decode): allow null to pass through\n        if (payload.value === null)\n            return payload;\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // inst._zod.qin = \"true\";\n    inst._zod.optin = \"defaulted\";\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        // Forward direction (decode): apply defaults for undefined input\n        if (payload.value === undefined) {\n            payload.value = def.defaultValue;\n            /**\n             * $ZodDefault returns the default value immediately in forward direction.\n             * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe.   */\n            return payload;\n        }\n        // Forward direction: continue with default handling\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => handleDefaultResult(result, def));\n        }\n        return handleDefaultResult(result, def);\n    };\n});\nfunction handleDefaultResult(payload, def) {\n    if (payload.value === undefined) {\n        payload.value = def.defaultValue;\n    }\n    return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.optin = \"defaulted\";\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        // Forward direction (decode): apply prefault for undefined input\n        if (payload.value === undefined) {\n            payload.value = def.defaultValue;\n        }\n        return def.innerType._zod.run(payload, ctx);\n    };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"values\", (zod) => {\n        const v = zod.def.innerType._zod.values;\n        return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n    });\n    inst._zod.parse = (payload, ctx) => {\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => handleNonOptionalResult(result, inst));\n        }\n        return handleNonOptionalResult(result, inst);\n    };\n});\nfunction handleNonOptionalResult(payload, inst) {\n    if (!payload.issues.length && payload.value === undefined) {\n        payload.issues.push({\n            code: \"invalid_type\",\n            expected: \"nonoptional\",\n            input: payload.value,\n            inst,\n        });\n    }\n    return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            throw new core.$ZodEncodeError(\"ZodSuccess\");\n        }\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => {\n                payload.value = result.issues.length === 0;\n                return payload;\n            });\n        }\n        payload.value = result.issues.length === 0;\n        return payload;\n    };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n    if (!result.issues.length) {\n        payload.value = result.value;\n        // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n        if (result.memo)\n            payload.memo = true;\n        return payload;\n    }\n    // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n    payload.value = def.catchValue({\n        ...result,\n        value: payload.value,\n        error: {\n            issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n        },\n        input: payload.value,\n    });\n    return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        // Forward direction (decode): apply catch logic\n        const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n        if (result instanceof Promise) {\n            return result.then((result) => handleCatchResult(payload, result, def, ctx));\n        }\n        return handleCatchResult(payload, result, def, ctx);\n    };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _ctx) => {\n        if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n            payload.issues.push({\n                input: payload.value,\n                inst,\n                expected: \"nan\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        return payload;\n    };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n    util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            const right = def.out._zod.run(payload, ctx);\n            if (right instanceof Promise) {\n                return right.then((right) => handlePipeResult(right, def.in, ctx));\n            }\n            return handlePipeResult(right, def.in, ctx);\n        }\n        const left = def.in._zod.run(payload, ctx);\n        if (left instanceof Promise) {\n            return left.then((left) => handlePipeResult(left, def.out, ctx));\n        }\n        return handlePipeResult(left, def.out, ctx);\n    };\n});\nfunction handlePipeResult(left, next, ctx) {\n    // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n    if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n        // prevent further checks\n        left.aborted = true;\n        return left;\n    }\n    return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n    util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n    inst._zod.parse = (payload, ctx) => {\n        const direction = ctx.direction || \"forward\";\n        if (direction === \"forward\") {\n            const left = def.in._zod.run(payload, ctx);\n            if (left instanceof Promise) {\n                return left.then((left) => handleCodecAResult(left, def, ctx));\n            }\n            return handleCodecAResult(left, def, ctx);\n        }\n        else {\n            const right = def.out._zod.run(payload, ctx);\n            if (right instanceof Promise) {\n                return right.then((right) => handleCodecAResult(right, def, ctx));\n            }\n            return handleCodecAResult(right, def, ctx);\n        }\n    };\n});\nfunction handleCodecAResult(result, def, ctx) {\n    if (result.issues.length) {\n        // prevent further checks\n        result.aborted = true;\n        return result;\n    }\n    const direction = ctx.direction || \"forward\";\n    if (direction === \"forward\") {\n        const transformed = def.transform(result.value, result);\n        if (transformed instanceof Promise) {\n            return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n        }\n        return handleCodecTxResult(result, transformed, def.out, ctx);\n    }\n    else {\n        const transformed = def.reverseTransform(result.value, result);\n        if (transformed instanceof Promise) {\n            return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n        }\n        return handleCodecTxResult(result, transformed, def.in, ctx);\n    }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n    // Check if transform added any issues\n    if (left.issues.length) {\n        left.aborted = true;\n        return left;\n    }\n    return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n    $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n    $ZodType.init(inst, def);\n    util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n    util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n    inst._zod.parse = (payload, ctx) => {\n        if (ctx.direction === \"backward\") {\n            return def.innerType._zod.run(payload, ctx);\n        }\n        const result = def.innerType._zod.run(payload, ctx);\n        if (result instanceof Promise) {\n            return result.then(handleReadonlyResult);\n        }\n        return handleReadonlyResult(result);\n    };\n});\nfunction handleReadonlyResult(payload) {\n    // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n    if (!payload.memo)\n        payload.value = Object.freeze(payload.value);\n    return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n    $ZodType.init(inst, def);\n    const regexParts = [];\n    for (const part of def.parts) {\n        if (typeof part === \"object\" && part !== null) {\n            // is Zod schema\n            if (!part._zod.pattern) {\n                // if (!source)\n                throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n            }\n            const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n            if (!source)\n                throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n            const start = source.startsWith(\"^\") ? 1 : 0;\n            const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n            regexParts.push(source.slice(start, end));\n        }\n        else if (part === null || util.primitiveTypes.has(typeof part)) {\n            regexParts.push(util.escapeRegex(`${part}`));\n        }\n        else {\n            throw new Error(`Invalid template literal part: ${part}`);\n        }\n    }\n    inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n    inst._zod.parse = (payload, _ctx) => {\n        if (typeof payload.value !== \"string\") {\n            payload.issues.push({\n                input: payload.value,\n                inst,\n                expected: \"string\",\n                code: \"invalid_type\",\n            });\n            return payload;\n        }\n        inst._zod.pattern.lastIndex = 0;\n        if (!inst._zod.pattern.test(payload.value)) {\n            payload.issues.push({\n                input: payload.value,\n                inst,\n                code: \"invalid_format\",\n                format: def.format ?? \"template_literal\",\n                pattern: inst._zod.pattern.source,\n            });\n            return payload;\n        }\n        return payload;\n    };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n    Object.defineProperty(inst, \"_def\", { value: def });\n    inst._zod.def = def;\n    inst.implement = (func) => {\n        if (typeof func !== \"function\") {\n            throw new Error(\"implement() must be called with a function\");\n        }\n        // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n        return Object.defineProperty(function (...args) {\n            const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n            const result = Reflect.apply(func, this, parsedArgs);\n            if (inst._def.output) {\n                return parse(inst._def.output, result);\n            }\n            return result;\n        }, \"_zod\", { value: inst._zod, enumerable: false });\n    };\n    inst.implementAsync = (func) => {\n        if (typeof func !== \"function\") {\n            throw new Error(\"implementAsync() must be called with a function\");\n        }\n        return Object.defineProperty(async function (...args) {\n            const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n            const result = await Reflect.apply(func, this, parsedArgs);\n            if (inst._def.output) {\n                return await parseAsync(inst._def.output, result);\n            }\n            return result;\n        }, \"_zod\", { value: inst._zod, enumerable: false });\n    };\n    inst._zod.parse = (payload, _ctx) => {\n        if (typeof payload.value !== \"function\") {\n            payload.issues.push({\n                code: \"invalid_type\",\n                expected: \"function\",\n                input: payload.value,\n                inst,\n            });\n            return payload;\n        }\n        // Check if output is a promise type to determine if we should use async implementation\n        const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n        if (hasPromiseOutput) {\n            payload.value = inst.implementAsync(payload.value);\n        }\n        else {\n            payload.value = inst.implement(payload.value);\n        }\n        return payload;\n    };\n    inst.input = (...args) => {\n        const F = inst.constructor;\n        if (Array.isArray(args[0])) {\n            return new F({\n                type: \"function\",\n                input: new $ZodTuple({\n                    type: \"tuple\",\n                    items: args[0],\n                    rest: args[1],\n                }),\n                output: inst._def.output,\n            });\n        }\n        return new F({\n            type: \"function\",\n            input: args[0],\n            output: inst._def.output,\n        });\n    };\n    inst.output = (output) => {\n        const F = inst.constructor;\n        return new F({\n            type: \"function\",\n            input: inst._def.input,\n            output,\n        });\n    };\n    return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, ctx) => {\n        return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n    };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n    $ZodType.init(inst, def);\n    // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n    util.defineLazy(inst._zod, \"innerType\", () => {\n        const d = def;\n        if (!d._cachedInner)\n            d._cachedInner = def.getter();\n        return d._cachedInner;\n    });\n    util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n    util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n    util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n    util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n    inst._zod.parse = (payload, ctx) => {\n        const inner = inst._zod.innerType;\n        return inner._zod.run(payload, ctx);\n    };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n    checks.$ZodCheck.init(inst, def);\n    $ZodType.init(inst, def);\n    inst._zod.parse = (payload, _) => {\n        return payload;\n    };\n    inst._zod.check = (payload) => {\n        const input = payload.value;\n        const r = def.fn(input);\n        if (r instanceof Promise) {\n            return r.then((r) => handleRefineResult(r, payload, input, inst));\n        }\n        handleRefineResult(r, payload, input, inst);\n        return;\n    };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n    if (!result) {\n        const _iss = {\n            code: \"custom\",\n            input,\n            inst, // incorporates params.error into issue reporting\n            path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n            continue: !inst._zod.def.abort,\n            // params: inst._zod.def.params,\n        };\n        if (inst._zod.def.params)\n            _iss.params = inst._zod.def.params;\n        payload.issues.push(util.issue(_iss));\n    }\n}\n","export class $ZodCyclicError extends Error {\n    constructor() {\n        super(`Cannot parse a reference cycle that closes through a transform`);\n        this.name = \"ZodCyclicError\";\n    }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n    return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack) {\n    const cached = recursive.get(inst);\n    if (cached !== undefined)\n        return cached;\n    // Relative to the walk in progress, so not cached.\n    if (stack.has(inst))\n        return true;\n    stack.add(inst);\n    let result = false;\n    const check = (child) => {\n        if (!result && child?._zod && isRecursive(child, stack))\n            result = true;\n    };\n    const def = inst._zod.def;\n    const kind = def.type;\n    switch (kind) {\n        case \"object\": {\n            // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n            for (const key of Reflect.ownKeys(def.shape))\n                check(def.shape[key]);\n            check(def.catchall);\n            break;\n        }\n        case \"array\":\n            check(def.element);\n            break;\n        case \"tuple\":\n            for (const el of def.items)\n                check(el);\n            check(def.rest);\n            break;\n        case \"record\":\n        case \"map\":\n            check(def.keyType);\n            check(def.valueType);\n            break;\n        case \"set\":\n            check(def.valueType);\n            break;\n        case \"union\":\n            for (const el of def.options)\n                check(el);\n            break;\n        case \"intersection\":\n            check(def.left);\n            check(def.right);\n            break;\n        case \"optional\":\n        case \"nullable\":\n        case \"default\":\n        case \"prefault\":\n        case \"catch\":\n        case \"readonly\":\n        case \"nonoptional\":\n        case \"promise\":\n        case \"success\":\n            check(def.innerType);\n            break;\n        case \"pipe\":\n            check(def.in);\n            check(def.out);\n            break;\n        case \"function\":\n            check(def.input);\n            check(def.output);\n            break;\n        // reading `_zod.innerType` resolves the getter once and caches it\n        case \"lazy\":\n            check(inst._zod.innerType);\n            break;\n        // a leaf by choice: `parts` are regex fragments, not data positions\n        case \"template_literal\":\n        // leaves\n        case \"string\":\n        case \"number\":\n        case \"int\":\n        case \"boolean\":\n        case \"bigint\":\n        case \"symbol\":\n        case \"undefined\":\n        case \"null\":\n        case \"void\":\n        case \"never\":\n        case \"any\":\n        case \"unknown\":\n        case \"date\":\n        case \"nan\":\n        case \"enum\":\n        case \"literal\":\n        case \"file\":\n        case \"transform\":\n        case \"custom\":\n            break;\n        default: {\n            // a new built-in kind becomes a compile error here\n            kind;\n            // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code\n            for (const key in def) {\n                const desc = Object.getOwnPropertyDescriptor(def, key);\n                if (!desc || desc.get)\n                    continue;\n                const value = desc.value;\n                if (!value || typeof value !== \"object\")\n                    continue;\n                if (value._zod)\n                    check(value);\n                else if (Array.isArray(value))\n                    for (const el of value)\n                        check(el);\n            }\n        }\n    }\n    stack.delete(inst);\n    recursive.set(inst, result);\n    return result;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n    return isRecursive(inst, new Set());\n}\nfunction bucketFor(state, inst) {\n    let bucket = state.buckets.get(inst);\n    if (!bucket) {\n        bucket = new Map();\n        state.buckets.set(inst, bucket);\n    }\n    return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.\nconst open = [];\nconst memo = {\n    alloc(_inst, payload, empty) {\n        const bucket = handoff;\n        if (!bucket)\n            return empty;\n        handoff = undefined;\n        const entry = { value: empty, issues: null };\n        bucket.set(payload.value, entry);\n        open.push(entry);\n        return empty;\n    },\n    guard(inst) {\n        var _a;\n        (_a = inst._zod).deferred ?? (_a.deferred = []);\n        inst._zod.deferred.push(() => {\n            const base = inst._zod.parse;\n            const wrapped = (payload, ctx) => {\n                // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.\n                if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n                    throw new $ZodCyclicError();\n                return base(payload, ctx);\n            };\n            inst._zod.parse = wrapped;\n            if (inst._zod.run === base)\n                inst._zod.run = wrapped;\n        });\n    },\n    attach(inst) {\n        var _a;\n        let isRecursiveInst;\n        // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes\n        let lastCtx;\n        let lastBucket;\n        // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.\n        (_a = inst._zod).deferred ?? (_a.deferred = []);\n        inst._zod.deferred.push(() => {\n            const base = inst._zod.parse;\n            const wrapped = (payload, ctx) => {\n                if (isRecursiveInst === undefined) {\n                    isRecursiveInst = isRecursive(inst, new Set());\n                    if (!isRecursiveInst) {\n                        // Nothing here can ever fire, so take it back out.\n                        inst._zod.parse = base;\n                        if (inst._zod.run === wrapped)\n                            inst._zod.run = base;\n                        return base(payload, ctx);\n                    }\n                }\n                const input = payload.value;\n                if (input === null || typeof input !== \"object\")\n                    return base(payload, ctx);\n                let state = ctx[STATE];\n                if (!state) {\n                    state = { buckets: new Map(), backEdges: undefined };\n                    ctx[STATE] = state;\n                }\n                let bucket;\n                if (lastCtx === ctx) {\n                    bucket = lastBucket;\n                }\n                else {\n                    bucket = bucketFor(state, inst);\n                    lastCtx = ctx;\n                    lastBucket = bucket;\n                }\n                const hit = bucket.get(input);\n                if (hit) {\n                    payload.value = hit.value;\n                    if (hit.issues) {\n                        if (hit.issues.length)\n                            payload.issues.push(...cloneIssues(hit.issues));\n                    }\n                    else {\n                        // Still being parsed: its own checks cover it, so skip them here.\n                        payload.memo = true;\n                        state.backEdges ?? (state.backEdges = new Set());\n                        state.backEdges.add(hit.value);\n                    }\n                    return payload;\n                }\n                handoff = bucket;\n                const depth = open.length;\n                const result = base(payload, ctx);\n                handoff = undefined;\n                // A container that rejected its input outright allocated nothing.\n                const entry = open.length > depth ? open.pop() : undefined;\n                // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.\n                if (result instanceof Promise) {\n                    return result.then((r) => {\n                        if (entry)\n                            entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n                        return r;\n                    });\n                }\n                if (entry)\n                    entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n                return result;\n            };\n            inst._zod.parse = wrapped;\n            if (inst._zod.run === base)\n                inst._zod.run = wrapped;\n        });\n    },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n    return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n    const backEdges = ctx[STATE]?.backEdges;\n    return backEdges !== undefined && value !== null && typeof value === \"object\" && backEdges.has(value);\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n    const Sizable = {\n        string: { unit: \"characters\", verb: \"to have\" },\n        file: { unit: \"bytes\", verb: \"to have\" },\n        array: { unit: \"items\", verb: \"to have\" },\n        set: { unit: \"items\", verb: \"to have\" },\n        map: { unit: \"entries\", verb: \"to have\" },\n    };\n    function getSizing(origin) {\n        return Sizable[origin] ?? null;\n    }\n    const FormatDictionary = {\n        regex: \"input\",\n        email: \"email address\",\n        url: \"URL\",\n        emoji: \"emoji\",\n        uuid: \"UUID\",\n        uuidv4: \"UUIDv4\",\n        uuidv6: \"UUIDv6\",\n        nanoid: \"nanoid\",\n        guid: \"GUID\",\n        cuid: \"cuid\",\n        cuid2: \"cuid2\",\n        ulid: \"ULID\",\n        xid: \"XID\",\n        ksuid: \"KSUID\",\n        datetime: \"ISO datetime\",\n        date: \"ISO date\",\n        time: \"ISO time\",\n        duration: \"ISO duration\",\n        ipv4: \"IPv4 address\",\n        ipv6: \"IPv6 address\",\n        mac: \"MAC address\",\n        cidrv4: \"IPv4 range\",\n        cidrv6: \"IPv6 range\",\n        base64: \"base64-encoded string\",\n        base64url: \"base64url-encoded string\",\n        json_string: \"JSON string\",\n        e164: \"E.164 number\",\n        credit_card: \"credit card number\",\n        jwt: \"JWT\",\n        template_literal: \"input\",\n    };\n    // type names: missing keys = do not translate (use raw value via ?? fallback)\n    const TypeDictionary = {\n        // Compatibility: \"nan\" -> \"NaN\" for display\n        nan: \"NaN\",\n        // All other type names omitted - they fall back to raw values via ?? operator\n    };\n    function getTypeName(type, input) {\n        if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n            return String(input);\n        }\n        return TypeDictionary[type] ?? type;\n    }\n    return (issue) => {\n        switch (issue.code) {\n            case \"invalid_type\": {\n                const expected = getTypeName(issue.expected);\n                const receivedType = util.parsedType(issue.input);\n                const received = getTypeName(receivedType, issue.input);\n                return `Invalid input: expected ${expected}, received ${received}`;\n            }\n            case \"invalid_value\":\n                if (issue.values.length === 1)\n                    return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n                return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n            case \"too_big\": {\n                const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n                const sizing = getSizing(issue.origin);\n                if (sizing)\n                    return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n                return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n            }\n            case \"too_small\": {\n                const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n                const sizing = getSizing(issue.origin);\n                if (sizing) {\n                    return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n                }\n                return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n            }\n            case \"invalid_format\": {\n                const _issue = issue;\n                if (_issue.format === \"starts_with\") {\n                    return `Invalid string: must start with \"${_issue.prefix}\"`;\n                }\n                if (_issue.format === \"ends_with\")\n                    return `Invalid string: must end with \"${_issue.suffix}\"`;\n                if (_issue.format === \"includes\")\n                    return `Invalid string: must include \"${_issue.includes}\"`;\n                if (_issue.format === \"regex\")\n                    return `Invalid string: must match pattern ${_issue.pattern}`;\n                return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n            }\n            case \"not_multiple_of\":\n                return `Invalid number: must be a multiple of ${issue.divisor}`;\n            case \"unrecognized_keys\":\n                return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n            case \"invalid_key\":\n                return `Invalid key in ${issue.origin}`;\n            case \"invalid_union\":\n                if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n                    const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n                    return `Invalid discriminator value. Expected ${opts}`;\n                }\n                if (issue.inclusive === false) {\n                    return \"Invalid input: more than one option matched\";\n                }\n                return \"Invalid input\";\n            case \"invalid_element\":\n                return `Invalid value in ${issue.origin}`;\n            default:\n                return `Invalid input`;\n        }\n    };\n};\nexport default function () {\n    return {\n        localeError: error(),\n    };\n}\n","var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n    constructor() {\n        this._map = new WeakMap();\n        this._idmap = new Map();\n    }\n    add(schema, ..._meta) {\n        const meta = _meta[0];\n        this._map.set(schema, meta);\n        if (meta && typeof meta === \"object\" && \"id\" in meta) {\n            this._idmap.set(meta.id, schema);\n        }\n        return this;\n    }\n    clear() {\n        this._map = new WeakMap();\n        this._idmap = new Map();\n        return this;\n    }\n    remove(schema) {\n        const meta = this._map.get(schema);\n        if (meta && typeof meta === \"object\" && \"id\" in meta) {\n            this._idmap.delete(meta.id);\n        }\n        this._map.delete(schema);\n        return this;\n    }\n    get(schema) {\n        // return this._map.get(schema) as any;\n        // inherit metadata\n        const p = schema._zod.parent;\n        if (p) {\n            const pm = { ...(this.get(p) ?? {}) };\n            delete pm.id; // do not inherit id\n            const f = { ...pm, ...this._map.get(schema) };\n            return Object.keys(f).length ? f : undefined;\n        }\n        return this._map.get(schema);\n    }\n    has(schema) {\n        return this._map.has(schema);\n    }\n}\n// registries\nexport function registry() {\n    return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n    return new Class({\n        type: \"string\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n    return new Class({\n        type: \"string\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"email\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"guid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        version: \"v4\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        version: \"v6\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"uuid\",\n        check: \"string_format\",\n        abort: false,\n        version: \"v7\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"url\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"emoji\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"nanoid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cuid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cuid2\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ulid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"xid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ksuid\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ipv4\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"ipv6\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"mac\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cidrv4\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"cidrv6\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"base64\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"base64url\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"e164\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"credit_card\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"jwt\",\n        check: \"string_format\",\n        abort: false,\n        ...util.normalizeParams(params),\n    });\n}\nexport const TimePrecision = {\n    Any: null,\n    Minute: -1,\n    Second: 0,\n    Millisecond: 3,\n    Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"datetime\",\n        check: \"string_format\",\n        offset: false,\n        local: false,\n        precision: null,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"date\",\n        check: \"string_format\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"time\",\n        check: \"string_format\",\n        precision: null,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n    return new Class({\n        type: \"string\",\n        format: \"duration\",\n        check: \"string_format\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n    return new Class({\n        type: \"number\",\n        checks: [],\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n    return new Class({\n        type: \"number\",\n        coerce: true,\n        checks: [],\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"safeint\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"float32\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"float64\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"int32\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n    return new Class({\n        type: \"number\",\n        check: \"number_format\",\n        abort: false,\n        format: \"uint32\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n    return new Class({\n        type: \"boolean\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n    return new Class({\n        type: \"boolean\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        check: \"bigint_format\",\n        abort: false,\n        format: \"int64\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n    return new Class({\n        type: \"bigint\",\n        check: \"bigint_format\",\n        abort: false,\n        format: \"uint64\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n    return new Class({\n        type: \"symbol\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n    return new Class({\n        type: \"undefined\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n    return new Class({\n        type: \"null\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n    return new Class({\n        type: \"any\",\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n    return new Class({\n        type: \"unknown\",\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n    return new Class({\n        type: \"never\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n    return new Class({\n        type: \"void\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n    return new Class({\n        type: \"date\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n    return new Class({\n        type: \"date\",\n        coerce: true,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n    return new Class({\n        type: \"nan\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n    return new checks.$ZodCheckLessThan({\n        check: \"less_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: false,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n    return new checks.$ZodCheckLessThan({\n        check: \"less_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: true,\n    });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n    return new checks.$ZodCheckGreaterThan({\n        check: \"greater_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: false,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n    return new checks.$ZodCheckGreaterThan({\n        check: \"greater_than\",\n        ...util.normalizeParams(params),\n        value,\n        inclusive: true,\n    });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n    return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n    return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n    return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n    return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n    return new checks.$ZodCheckMultipleOf({\n        check: \"multiple_of\",\n        ...util.normalizeParams(params),\n        value,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n    return new checks.$ZodCheckMaxSize({\n        check: \"max_size\",\n        ...util.normalizeParams(params),\n        maximum,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n    return new checks.$ZodCheckMinSize({\n        check: \"min_size\",\n        ...util.normalizeParams(params),\n        minimum,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n    return new checks.$ZodCheckSizeEquals({\n        check: \"size_equals\",\n        ...util.normalizeParams(params),\n        size,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n    const ch = new checks.$ZodCheckMaxLength({\n        check: \"max_length\",\n        ...util.normalizeParams(params),\n        maximum,\n    });\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n    return new checks.$ZodCheckMinLength({\n        check: \"min_length\",\n        ...util.normalizeParams(params),\n        minimum,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n    return new checks.$ZodCheckLengthEquals({\n        check: \"length_equals\",\n        ...util.normalizeParams(params),\n        length,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n    return new checks.$ZodCheckRegex({\n        check: \"string_format\",\n        format: \"regex\",\n        ...util.normalizeParams(params),\n        pattern,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n    return new checks.$ZodCheckLowerCase({\n        check: \"string_format\",\n        format: \"lowercase\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n    return new checks.$ZodCheckUpperCase({\n        check: \"string_format\",\n        format: \"uppercase\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n    return new checks.$ZodCheckIncludes({\n        check: \"string_format\",\n        format: \"includes\",\n        ...util.normalizeParams(params),\n        includes,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n    return new checks.$ZodCheckStartsWith({\n        check: \"string_format\",\n        format: \"starts_with\",\n        ...util.normalizeParams(params),\n        prefix,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n    return new checks.$ZodCheckEndsWith({\n        check: \"string_format\",\n        format: \"ends_with\",\n        ...util.normalizeParams(params),\n        suffix,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n    return new checks.$ZodCheckProperty({\n        check: \"property\",\n        property,\n        schema,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape) {\n    return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: \"property\", property, schema }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n    return new checks.$ZodCheckMimeType({\n        check: \"mime_type\",\n        mime: types,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n    return new checks.$ZodCheckOverwrite({\n        check: \"overwrite\",\n        tx,\n    });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n    return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n    return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n    return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n    return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n    return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n    return new Class({\n        type: \"array\",\n        element,\n        // get element() {\n        //   return element;\n        // },\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n    return new Class({\n        type: \"union\",\n        options,\n        ...util.normalizeParams(params),\n    });\n}\nexport function _xor(Class, options, params) {\n    return new Class({\n        type: \"union\",\n        options,\n        inclusive: false,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n    return new Class({\n        type: \"union\",\n        options: options,\n        discriminator,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n    return new Class({\n        type: \"intersection\",\n        left,\n        right,\n    });\n}\n// export function _tuple(\n//   Class: util.SchemaClass<schemas.$ZodTuple>,\n//   items: [],\n//   params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n    const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n    const params = hasRest ? _params : _paramsOrRest;\n    const rest = hasRest ? _paramsOrRest : null;\n    return new Class({\n        type: \"tuple\",\n        items,\n        rest,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n    return new Class({\n        type: \"record\",\n        keyType,\n        valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n    return new Class({\n        type: \"map\",\n        keyType,\n        valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n    return new Class({\n        type: \"set\",\n        valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n    const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n    // if (Array.isArray(values)) {\n    //   for (const value of values) {\n    //     entries[value] = value;\n    //   }\n    // } else {\n    //   Object.assign(entries, values);\n    // }\n    // const entries: util.EnumLike = {};\n    // for (const val of values) {\n    //   entries[val] = val;\n    // }\n    return new Class({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n    return new Class({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n    return new Class({\n        type: \"literal\",\n        values: Array.isArray(value) ? value : [value],\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n    return new Class({\n        type: \"file\",\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n    return new Class({\n        type: \"transform\",\n        transform: fn,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n    return new Class({\n        type: \"optional\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n    return new Class({\n        type: \"nullable\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n    return new Class({\n        type: \"default\",\n        innerType,\n        get defaultValue() {\n            return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n        },\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n    return new Class({\n        type: \"nonoptional\",\n        innerType,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n    return new Class({\n        type: \"success\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n    return new Class({\n        type: \"catch\",\n        innerType,\n        catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n    return new Class({\n        type: \"pipe\",\n        in: in_,\n        out,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n    return new Class({\n        type: \"readonly\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n    return new Class({\n        type: \"template_literal\",\n        parts,\n        ...util.normalizeParams(params),\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n    return new Class({\n        type: \"lazy\",\n        getter,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n    return new Class({\n        type: \"promise\",\n        innerType,\n    });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n    const norm = util.normalizeParams(_params);\n    norm.abort ?? (norm.abort = true); // default to abort:false\n    const schema = new Class({\n        type: \"custom\",\n        check: \"custom\",\n        fn: fn,\n        ...norm,\n    });\n    return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n    const schema = new Class({\n        type: \"custom\",\n        check: \"custom\",\n        fn: fn,\n        ...util.normalizeParams(_params),\n    });\n    return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n    const ch = _check((payload) => {\n        payload.addIssue = (issue) => {\n            if (typeof issue === \"string\") {\n                payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n            }\n            else {\n                // for Zod 3 backwards compatibility\n                const _issue = issue;\n                if (_issue.fatal)\n                    _issue.continue = false;\n                _issue.code ?? (_issue.code = \"custom\");\n                if (!(\"input\" in _issue))\n                    _issue.input = payload.value;\n                _issue.inst ?? (_issue.inst = ch);\n                _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n                payload.issues.push(util.issue(_issue));\n            }\n        };\n        return fn(payload.value, payload);\n    }, params);\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n    const ch = new checks.$ZodCheck({\n        check: \"custom\",\n        ...util.normalizeParams(params),\n    });\n    ch._zod.check = fn;\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n    const ch = new checks.$ZodCheck({ check: \"describe\" });\n    ch._zod.onattach = [\n        (inst) => {\n            const existing = registries.globalRegistry.get(inst) ?? {};\n            registries.globalRegistry.add(inst, { ...existing, description });\n        },\n    ];\n    ch._zod.check = () => { }; // no-op check\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n    const ch = new checks.$ZodCheck({ check: \"meta\" });\n    ch._zod.onattach = [\n        (inst) => {\n            const existing = registries.globalRegistry.get(inst) ?? {};\n            registries.globalRegistry.add(inst, { ...existing, ...metadata });\n        },\n    ];\n    ch._zod.check = () => { }; // no-op check\n    return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n    const params = util.normalizeParams(_params);\n    let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n    let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n    if (params.case !== \"sensitive\") {\n        truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n        falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n    }\n    const truthySet = new Set(truthyArray);\n    const falsySet = new Set(falsyArray);\n    const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n    const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n    const _String = Classes.String ?? schemas.$ZodString;\n    const stringSchema = new _String({ type: \"string\", error: params.error });\n    const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n    const codec = new _Codec({\n        type: \"pipe\",\n        in: stringSchema,\n        out: booleanSchema,\n        transform: ((input, payload) => {\n            let data = input;\n            if (params.case !== \"sensitive\")\n                data = data.toLowerCase();\n            if (truthySet.has(data)) {\n                return true;\n            }\n            else if (falsySet.has(data)) {\n                return false;\n            }\n            else {\n                payload.issues.push({\n                    code: \"invalid_value\",\n                    expected: \"stringbool\",\n                    values: [...truthySet, ...falsySet],\n                    input: payload.value,\n                    inst: codec,\n                    continue: false,\n                });\n                return {};\n            }\n        }),\n        reverseTransform: ((input, _payload) => {\n            if (input === true) {\n                return truthyArray[0] || \"true\";\n            }\n            else {\n                return falsyArray[0] || \"false\";\n            }\n        }),\n        error: params.error,\n    });\n    codec._zod.bag.truthy = truthyArray;\n    codec._zod.bag.falsy = falsyArray;\n    codec._zod.bag.case = params.case ?? \"insensitive\";\n    return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n    const params = util.normalizeParams(_params);\n    const def = {\n        check: \"string_format\",\n        type: \"string\",\n        format,\n        fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n        ...params,\n    };\n    if (fnOrRegex instanceof RegExp) {\n        def.pattern = fnOrRegex;\n    }\n    const inst = new Class(def);\n    return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n    for (const source of sources) {\n        for (const key of Reflect.ownKeys(source)) {\n            if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n                assignProp(target, key, source[key]);\n            }\n        }\n    }\n    return target;\n}\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n//   return {\n//     processor: inputs.processor,\n//     metadataRegistry: inputs.metadata ?? globalRegistry,\n//     target: inputs.target ?? \"draft-2020-12\",\n//     unrepresentable: inputs.unrepresentable ?? \"throw\",\n//   };\n// }\nexport function initializeContext(params) {\n    // Normalize target: convert old non-hyphenated versions to hyphenated versions\n    let target = params?.target ?? \"draft-2020-12\";\n    if (target === \"draft-4\")\n        target = \"draft-04\";\n    if (target === \"draft-7\")\n        target = \"draft-07\";\n    return {\n        processors: params.processors ?? {},\n        metadataRegistry: params?.metadata ?? globalRegistry,\n        target,\n        unrepresentable: params?.unrepresentable ?? \"throw\",\n        override: params?.override ?? (() => { }),\n        io: params?.io ?? \"output\",\n        counter: 0,\n        seen: new Map(),\n        sharedDefsExtractedFor: undefined,\n        sharedEmitDoneFor: undefined,\n        cycles: params?.cycles ?? \"ref\",\n        reused: params?.reused ?? \"inline\",\n        intersections: [],\n        deferred: [],\n        external: params?.external ?? undefined,\n    };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n    const result = typeof ctx.unrepresentable === \"function\"\n        ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n        : ctx.unrepresentable;\n    if (result === \"any\")\n        return false;\n    if (result === undefined || result === \"throw\")\n        throw new Error(message);\n    Object.assign(json, result);\n    return true;\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n    var _a;\n    const def = schema._zod.def;\n    // check for schema in seens\n    const seen = ctx.seen.get(schema);\n    if (seen) {\n        seen.count++;\n        // check if cycle\n        const isCycle = _params.schemaPath.includes(schema);\n        if (isCycle) {\n            seen.cycle = _params.path;\n        }\n        return seen.schema;\n    }\n    // initialize\n    const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n    ctx.seen.set(schema, result);\n    ctx.sharedDefsExtractedFor = undefined;\n    ctx.sharedEmitDoneFor = undefined;\n    // custom method overrides default behavior\n    const overrideSchema = schema._zod.toJSONSchema?.();\n    if (overrideSchema) {\n        result.schema = overrideSchema;\n    }\n    else {\n        const params = {\n            ..._params,\n            schemaPath: [..._params.schemaPath, schema],\n            path: _params.path,\n        };\n        if (schema._zod.processJSONSchema) {\n            schema._zod.processJSONSchema(ctx, result.schema, params);\n        }\n        else {\n            const _json = result.schema;\n            const processor = ctx.processors[def.type];\n            if (!processor) {\n                throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n            }\n            processor(schema, ctx, _json, params);\n        }\n        const parent = schema._zod.parent;\n        if (parent) {\n            // Also set ref if processor didn't (for inheritance)\n            if (!result.ref)\n                result.ref = parent;\n            process(parent, ctx, params);\n            ctx.seen.get(parent).isParent = true;\n        }\n    }\n    // metadata\n    const meta = ctx.metadataRegistry.get(schema);\n    if (meta)\n        assignProps(result.schema, meta);\n    if (ctx.io === \"input\" && isTransforming(schema)) {\n        // examples/defaults only apply to output type of pipe\n        delete result.schema.examples;\n        delete result.schema.default;\n    }\n    // set prefault as default\n    if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n        (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n    delete result.schema._prefault;\n    // pulling fresh from ctx.seen in case it was overwritten\n    const _result = ctx.seen.get(schema);\n    return _result.schema;\n}\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n    return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n    // iterate over seen map;\n    const root = ctx.seen.get(schema);\n    if (!root)\n        throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n    // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once.\n    if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n        return;\n    // Track ids to detect duplicates across different schemas\n    const idToSchema = new Map();\n    for (const entry of ctx.seen.entries()) {\n        const id = ctx.metadataRegistry.get(entry[0])?.id;\n        if (id) {\n            const existing = idToSchema.get(id);\n            if (existing && existing !== entry[0]) {\n                throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n            }\n            idToSchema.set(id, entry[0]);\n        }\n    }\n    // returns a ref to the schema defId will be empty if the ref points to an external schema (or #)\n    const makeURI = (entry) => {\n        // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy\n        // external is configured\n        const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n        if (ctx.external) {\n            const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n            // check if schema is in the external registry\n            const uriGenerator = ctx.external.uri ?? ((id) => id);\n            if (externalId) {\n                return { ref: uriGenerator(externalId) };\n            }\n            // otherwise, add to __shared\n            const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n            entry[1].defId = id; // set defId so it will be reused if needed\n            return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };\n        }\n        const uriPrefix = `#`;\n        const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n        // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n        if (entry[1] === root && !entry[1].schema.id) {\n            return { ref: uriPrefix };\n        }\n        // self-contained schema\n        const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n        return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n    };\n    // stored cached version in `def` property remove all properties, set $ref\n    const extractToDef = (entry) => {\n        // if the schema is already a reference, do not extract it\n        if (entry[1].schema.$ref) {\n            return;\n        }\n        const seen = entry[1];\n        const { ref, defId } = makeURI(entry);\n        seen.def = { ...seen.schema };\n        // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema\n        if (defId)\n            seen.defId = defId;\n        // wipe away all properties except $ref\n        const schema = seen.schema;\n        for (const key in schema) {\n            delete schema[key];\n        }\n        schema.$ref = ref;\n    };\n    // throw on cycles\n    // break cycles\n    if (ctx.cycles === \"throw\") {\n        for (const entry of ctx.seen.entries()) {\n            const seen = entry[1];\n            if (seen.cycle) {\n                throw new Error(\"Cycle detected: \" +\n                    `#/${seen.cycle?.join(\"/\")}/<root>` +\n                    '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n            }\n        }\n    }\n    // extract schemas into $defs\n    for (const entry of ctx.seen.entries()) {\n        const seen = entry[1];\n        // convert root schema to # $ref\n        if (schema === entry[0]) {\n            extractToDef(entry); // this has special handling for the root schema\n            continue;\n        }\n        // extract schemas that are in the external registry\n        if (ctx.external) {\n            const ext = ctx.external.registry.get(entry[0])?.id;\n            if (schema !== entry[0] && ext) {\n                extractToDef(entry);\n                continue;\n            }\n        }\n        // extract schemas with `id` meta\n        const id = ctx.metadataRegistry.get(entry[0])?.id;\n        if (id) {\n            extractToDef(entry);\n            continue;\n        }\n        // break cycles\n        if (seen.cycle) {\n            // any\n            extractToDef(entry);\n            continue;\n        }\n        // extract reused schemas\n        if (seen.count > 1) {\n            if (ctx.reused === \"ref\") {\n                extractToDef(entry);\n                // biome-ignore lint:\n                continue;\n            }\n        }\n    }\n    if (ctx.external)\n        ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** Rewrites `anyOf: [{type: \"a\"}, {type: \"b\"}]` to `type: [\"a\", \"b\"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so \"exactly one\" and \"at least one\" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */\nfunction compactTypeUnion(schema) {\n    const options = schema.anyOf;\n    if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n        return;\n    const types = [];\n    for (const option of options) {\n        if (!option || typeof option !== \"object\")\n            return;\n        // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in.\n        compactTypeUnion(option);\n        const keys = Object.keys(option);\n        if (keys.length !== 1 || keys[0] !== \"type\")\n            return;\n        const type = option.type;\n        for (const member of Array.isArray(type) ? type : [type]) {\n            if (typeof member !== \"string\")\n                return;\n            if (!types.includes(member))\n                types.push(member);\n        }\n    }\n    delete schema.anyOf;\n    // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n    schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */\nfunction undeclaredConstraint(member) {\n    const extra = member.additionalProperties;\n    if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n        return null;\n    return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n    const objects = [];\n    for (const member of members) {\n        // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n        if (typeof member !== \"object\" || member.type !== \"object\")\n            return null;\n        for (const key in member) {\n            if (!FOLDABLE_KEYS.has(key))\n                return null;\n        }\n        objects.push(member);\n    }\n    const properties = {};\n    const required = new Set();\n    for (const object of objects) {\n        for (const key in object.properties) {\n            // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n            if (Object.prototype.hasOwnProperty.call(properties, key))\n                continue;\n            // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down.\n            const parts = [];\n            for (const other of objects) {\n                const part = other.properties?.[key] ?? undeclaredConstraint(other);\n                if (part === null || part === undefined)\n                    continue;\n                if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n                    parts.push(part);\n            }\n            const merged = parts.length === 1\n                ? parts[0]\n                : (foldObjects(parts) ?? { allOf: parts });\n            assignProp(properties, key, merged);\n        }\n        for (const key of object.required ?? [])\n            required.add(key);\n    }\n    const folded = { type: \"object\", properties };\n    if (required.size)\n        folded.required = [...required];\n    // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key.\n    if (objects.every((object) => object.additionalProperties === false)) {\n        folded.additionalProperties = false;\n    }\n    else {\n        const constraints = [];\n        for (const object of objects) {\n            const constraint = undeclaredConstraint(object);\n            if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n                constraints.push(constraint);\n        }\n        if (constraints.length === 1)\n            folded.additionalProperties = constraints[0];\n        else if (constraints.length > 1)\n            folded.additionalProperties = { allOf: constraints };\n    }\n    return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n    const allOf = json.allOf;\n    if (!Array.isArray(allOf) || allOf.length < 2)\n        return;\n    // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them.\n    for (const key of FOLDABLE_KEYS)\n        if (key in json)\n            return;\n    // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out.\n    const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n    let folded = null;\n    if (!unions.length) {\n        folded = foldObjects(allOf);\n    }\n    else {\n        const union = unions[0];\n        const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n        if (Object.keys(union).length !== 1)\n            return;\n        const rest = allOf.filter((m) => m !== union);\n        const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n        if (branches.some((b) => !b))\n            return;\n        folded = { [keyword]: branches };\n    }\n    if (!folded)\n        return;\n    delete json.allOf;\n    assignProps(json, folded);\n}\nexport function finalize(ctx, schema) {\n    const root = ctx.seen.get(schema);\n    if (!root)\n        throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n    // flatten refs - inherit properties from parent schemas\n    const flattenRef = (zodSchema) => {\n        const seen = ctx.seen.get(zodSchema);\n        // already processed\n        if (seen.ref === null)\n            return;\n        const schema = seen.def ?? seen.schema;\n        const _cached = { ...schema };\n        const ref = seen.ref;\n        seen.ref = null; // prevent infinite recursion\n        if (ref) {\n            flattenRef(ref);\n            const refSeen = ctx.seen.get(ref);\n            const refSchema = refSeen.schema;\n            // merge referenced schema into current\n            if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n                // older drafts can't combine $ref with other properties\n                schema.allOf = schema.allOf ?? [];\n                schema.allOf.push(refSchema);\n            }\n            else {\n                assignProps(schema, refSchema);\n            }\n            // restore child's own properties (child wins)\n            assignProps(schema, _cached);\n            const isParentRef = zodSchema._zod.parent === ref;\n            // For parent chain, child is a refinement - remove parent-only properties\n            if (isParentRef) {\n                for (const key in schema) {\n                    if (key === \"$ref\" || key === \"allOf\")\n                        continue;\n                    if (!(key in _cached)) {\n                        delete schema[key];\n                    }\n                }\n            }\n            // When ref was extracted to $defs, remove properties that match the definition\n            if (refSchema.$ref && refSeen.def) {\n                for (const key in schema) {\n                    if (key === \"$ref\" || key === \"allOf\")\n                        continue;\n                    if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n                        delete schema[key];\n                    }\n                }\n            }\n        }\n        // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced\n        const parent = zodSchema._zod.parent;\n        if (parent && parent !== ref) {\n            // Ensure parent is processed first so its def has inherited properties\n            flattenRef(parent);\n            const parentSeen = ctx.seen.get(parent);\n            if (parentSeen?.schema.$ref) {\n                schema.$ref = parentSeen.schema.$ref;\n                // De-duplicate with parent's definition\n                if (parentSeen.def) {\n                    for (const key in schema) {\n                        if (key === \"$ref\" || key === \"allOf\")\n                            continue;\n                        if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n                            delete schema[key];\n                        }\n                    }\n                }\n            }\n        }\n        // execute overrides\n        ctx.override({\n            zodSchema: zodSchema,\n            jsonSchema: schema,\n            path: seen.path ?? [],\n        });\n    };\n    // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion.\n    if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n        for (const entry of [...ctx.seen.entries()].reverse()) {\n            flattenRef(entry[0]);\n        }\n        if (ctx.target !== \"openapi-3.0\") {\n            for (const entry of ctx.seen.entries()) {\n                compactTypeUnion(entry[1].def ?? entry[1].schema);\n            }\n        }\n        for (const rewrite of ctx.deferred)\n            rewrite();\n        // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy.\n        if (ctx.intersections.length) {\n            const carriers = new Map();\n            for (const seen of ctx.seen.values()) {\n                for (const json of [seen.schema, seen.def]) {\n                    const allOf = json?.allOf;\n                    if (!Array.isArray(allOf))\n                        continue;\n                    const existing = carriers.get(allOf);\n                    if (existing)\n                        existing.push(json);\n                    else\n                        carriers.set(allOf, [json]);\n                }\n            }\n            for (const allOf of ctx.intersections) {\n                for (const json of carriers.get(allOf) ?? [])\n                    foldIntersection(json);\n            }\n        }\n    }\n    const result = {};\n    if (ctx.target === \"draft-2020-12\") {\n        result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n    }\n    else if (ctx.target === \"draft-07\") {\n        result.$schema = \"http://json-schema.org/draft-07/schema#\";\n    }\n    else if (ctx.target === \"draft-04\") {\n        result.$schema = \"http://json-schema.org/draft-04/schema#\";\n    }\n    else if (ctx.target === \"openapi-3.0\") {\n        // OpenAPI 3.0 schema objects should not include a $schema property\n    }\n    else {\n        // Arbitrary string values are allowed but won't have a $schema property set\n    }\n    if (ctx.external?.uri) {\n        const id = ctx.external.registry.get(schema)?.id;\n        if (!id)\n            throw new Error(\"Schema is missing an `id` property\");\n        result.$id = ctx.external.uri(id);\n    }\n    // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n    assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n    // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths).\n    const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n    if (rootMetaId !== undefined && result.id === rootMetaId)\n        delete result.id;\n    // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt.\n    const defs = ctx.external?.defs ?? {};\n    if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n        for (const entry of ctx.seen.entries()) {\n            const seen = entry[1];\n            if (seen.def && seen.defId) {\n                if (seen.def.id === seen.defId)\n                    delete seen.def.id;\n                assignProp(defs, seen.defId, seen.def);\n            }\n        }\n    }\n    if (ctx.external)\n        ctx.sharedEmitDoneFor = ctx.external;\n    // set definitions in result\n    if (ctx.external) {\n    }\n    else {\n        if (Object.keys(defs).length > 0) {\n            if (ctx.target === \"draft-2020-12\") {\n                result.$defs = defs;\n            }\n            else {\n                result.definitions = defs;\n            }\n        }\n    }\n    try {\n        // this \"finalizes\" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared\n        const finalized = JSON.parse(JSON.stringify(result));\n        Object.defineProperty(finalized, \"~standard\", {\n            value: {\n                ...schema[\"~standard\"],\n                jsonSchema: {\n                    input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n                    output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n                },\n            },\n            enumerable: false,\n            writable: false,\n        });\n        return finalized;\n    }\n    catch (_err) {\n        throw new Error(\"Error converting schema to JSON.\");\n    }\n}\nfunction isTransforming(_schema, _ctx) {\n    const ctx = _ctx ?? { seen: new Set() };\n    if (ctx.seen.has(_schema))\n        return false;\n    ctx.seen.add(_schema);\n    const def = _schema._zod.def;\n    if (def.type === \"transform\")\n        return true;\n    if (def.type === \"array\")\n        return isTransforming(def.element, ctx);\n    if (def.type === \"set\")\n        return isTransforming(def.valueType, ctx);\n    if (def.type === \"lazy\")\n        return isTransforming(def.getter(), ctx);\n    if (def.type === \"promise\" ||\n        def.type === \"optional\" ||\n        def.type === \"nonoptional\" ||\n        def.type === \"nullable\" ||\n        def.type === \"readonly\" ||\n        def.type === \"default\" ||\n        def.type === \"prefault\" ||\n        def.type === \"catch\") {\n        return isTransforming(def.innerType, ctx);\n    }\n    if (def.type === \"intersection\") {\n        return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n    }\n    if (def.type === \"record\" || def.type === \"map\") {\n        return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n    }\n    if (def.type === \"pipe\") {\n        if (_schema._zod.traits.has(\"$ZodCodec\"))\n            return true;\n        return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n    }\n    if (def.type === \"object\") {\n        for (const key in def.shape) {\n            if (isTransforming(def.shape[key], ctx))\n                return true;\n        }\n        return false;\n    }\n    if (def.type === \"union\") {\n        for (const option of def.options) {\n            if (isTransforming(option, ctx))\n                return true;\n        }\n        return false;\n    }\n    if (def.type === \"tuple\") {\n        for (const item of def.items) {\n            if (isTransforming(item, ctx))\n                return true;\n        }\n        if (def.rest && isTransforming(def.rest, ctx))\n            return true;\n        return false;\n    }\n    return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n    const ctx = initializeContext({ ...params, processors });\n    process(schema, ctx);\n    extractDefs(ctx, schema);\n    return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n    const { libraryOptions, target } = params ?? {};\n    const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n    process(schema, ctx);\n    extractDefs(ctx, schema);\n    return finalize(ctx, schema);\n};\n","import * as regexes from \"./regexes.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, process, } from \"./to-json-schema.js\";\nimport { assignProp, getEnumValues } from \"./util.js\";\nconst formatMap = {\n    guid: \"uuid\",\n    url: \"uri\",\n    datetime: \"date-time\",\n    json_string: \"json-string\",\n    regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n    const json = _json;\n    json.type = \"string\";\n    const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod\n        .bag;\n    if (typeof minimum === \"number\")\n        json.minLength = minimum;\n    if (typeof maximum === \"number\")\n        json.maxLength = maximum;\n    // custom pattern overrides format\n    if (format) {\n        json.format = formatMap[format] ?? format;\n        if (json.format === \"\")\n            delete json.format; // empty format is not valid\n        // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n        if (format === \"time\" || laxFormat) {\n            delete json.format;\n        }\n    }\n    if (contentEncoding)\n        json.contentEncoding = contentEncoding;\n    if (patterns && patterns.size > 0) {\n        const patternList = [...patterns];\n        if (patternList.length === 1)\n            json.pattern = patternList[0].source;\n        else if (patternList.length > 1) {\n            json.allOf = [\n                ...patternList.map((regex) => ({\n                    ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n                        ? { type: \"string\" }\n                        : {}),\n                    pattern: regex.source,\n                })),\n            ];\n        }\n    }\n};\nexport const numberProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n    if (typeof format === \"string\" && format.includes(\"int\"))\n        json.type = \"integer\";\n    else\n        json.type = \"number\";\n    // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n    const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n    const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n    const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n    if (exMin) {\n        if (legacy) {\n            json.minimum = exclusiveMinimum;\n            json.exclusiveMinimum = true;\n        }\n        else {\n            json.exclusiveMinimum = exclusiveMinimum;\n        }\n    }\n    else if (typeof minimum === \"number\") {\n        json.minimum = minimum;\n    }\n    if (exMax) {\n        if (legacy) {\n            json.maximum = exclusiveMaximum;\n            json.exclusiveMaximum = true;\n        }\n        else {\n            json.exclusiveMaximum = exclusiveMaximum;\n        }\n    }\n    else if (typeof maximum === \"number\") {\n        json.maximum = maximum;\n    }\n    if (typeof multipleOf === \"number\") {\n        // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.\n        if (Number.isFinite(multipleOf) && multipleOf !== 0)\n            json.multipleOf = Math.abs(multipleOf);\n        else\n            handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`);\n    }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n    json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n    if (ctx.target === \"openapi-3.0\") {\n        json.type = \"string\";\n        json.nullable = true;\n        json.enum = [null];\n    }\n    else {\n        json.type = \"null\";\n    }\n};\nexport const undefinedProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n    json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n    // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n    // empty schema accepts anything\n};\nexport const dateProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n    const def = schema._zod.def;\n    const values = getEnumValues(def.entries);\n    // an empty enum accepts nothing, same as z.never()\n    if (values.length === 0) {\n        json.not = {};\n        return;\n    }\n    // Number enums can have both string and number values\n    if (values.every((v) => typeof v === \"number\"))\n        json.type = \"number\";\n    if (values.every((v) => typeof v === \"string\"))\n        json.type = \"string\";\n    json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    // a literal with no values accepts nothing, same as z.never()\n    if (def.values.length === 0) {\n        json.not = {};\n        return;\n    }\n    const vals = [];\n    for (const val of def.values) {\n        if (val === undefined) {\n            // a custom schema replaces the whole literal, so there is nothing left to accumulate\n            if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n                return;\n            // otherwise do not add to vals\n        }\n        else if (typeof val === \"bigint\") {\n            if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n                return;\n            vals.push(Number(val));\n        }\n        else {\n            vals.push(val);\n        }\n    }\n    if (vals.length === 0) {\n        // do nothing (an undefined literal was stripped)\n    }\n    else if (vals.length === 1) {\n        const val = vals[0];\n        json.type = val === null ? \"null\" : typeof val;\n        if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n            json.enum = [val];\n        }\n        else {\n            json.const = val;\n        }\n    }\n    else {\n        if (vals.every((v) => typeof v === \"number\"))\n            json.type = \"number\";\n        if (vals.every((v) => typeof v === \"string\"))\n            json.type = \"string\";\n        if (vals.every((v) => typeof v === \"boolean\"))\n            json.type = \"boolean\";\n        if (vals.every((v) => v === null))\n            json.type = \"null\";\n        json.enum = vals;\n    }\n};\nexport const nanProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n    const _json = json;\n    const pattern = schema._zod.pattern;\n    if (!pattern)\n        throw new Error(\"Pattern not found in template literal\");\n    _json.type = \"string\";\n    _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n    const _json = json;\n    const file = {\n        type: \"string\",\n        format: \"binary\",\n        contentEncoding: \"binary\",\n    };\n    const { minimum, maximum, mime } = schema._zod.bag;\n    if (minimum !== undefined)\n        file.minLength = minimum;\n    if (maximum !== undefined)\n        file.maxLength = maximum;\n    if (mime) {\n        if (mime.length === 1) {\n            file.contentMediaType = mime[0];\n            Object.assign(_json, file);\n        }\n        else {\n            Object.assign(_json, file); // shared props at root\n            _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n        }\n    }\n    else {\n        Object.assign(_json, file);\n    }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n    json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n    handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    const { minimum, maximum } = schema._zod.bag;\n    if (typeof minimum === \"number\")\n        json.minItems = minimum;\n    if (typeof maximum === \"number\")\n        json.maxItems = maximum;\n    json.type = \"array\";\n    json.items = process(def.element, ctx, {\n        ...params,\n        path: [...params.path, \"items\"],\n    });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n    const def = schema._zod.def;\n    if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n        return inputOptin(def.out);\n    }\n    if (def.type === \"catch\") {\n        return inputOptin(def.innerType);\n    }\n    return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    const shape = def.shape;\n    // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n    const symbolKeys = Object.getOwnPropertySymbols(shape);\n    if (symbolKeys.length &&\n        handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n        return;\n    }\n    json.type = \"object\";\n    json.properties = {};\n    for (const key in shape) {\n        // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n        assignProp(json.properties, key, process(shape[key], ctx, {\n            ...params,\n            path: [...params.path, \"properties\", key],\n        }));\n    }\n    // required keys\n    const allKeys = new Set(Object.keys(shape));\n    const requiredKeys = new Set([...allKeys].filter((key) => {\n        const field = def.shape[key];\n        if (ctx.io === \"input\") {\n            return inputOptin(field) === undefined;\n        }\n        else {\n            return field._zod.optout === undefined;\n        }\n    }));\n    if (requiredKeys.size > 0) {\n        json.required = Array.from(requiredKeys);\n    }\n    // catchall\n    if (def.catchall?._zod.def.type === \"never\") {\n        // strict\n        json.additionalProperties = false;\n    }\n    else if (!def.catchall) {\n        // regular\n        if (ctx.io === \"output\")\n            json.additionalProperties = false;\n    }\n    else if (def.catchall) {\n        json.additionalProperties = process(def.catchall, ctx, {\n            ...params,\n            path: [...params.path, \"additionalProperties\"],\n        });\n    }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions\n    const isExclusive = def.inclusive === false;\n    const options = def.options.map((x, i) => process(x, ctx, {\n        ...params,\n        path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n    }));\n    if (isExclusive) {\n        json.oneOf = options;\n    }\n    else {\n        json.anyOf = options;\n    }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    const a = process(def.left, ctx, {\n        ...params,\n        path: [...params.path, \"allOf\", 0],\n    });\n    const b = process(def.right, ctx, {\n        ...params,\n        path: [...params.path, \"allOf\", 1],\n    });\n    const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n    const allOf = [\n        ...(isSimpleIntersection(a) ? a.allOf : [a]),\n        ...(isSimpleIntersection(b) ? b.allOf : [b]),\n    ];\n    json.allOf = allOf;\n    // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.\n    ctx.intersections.push(allOf);\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    json.type = \"array\";\n    const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n    const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n    const prefixItems = def.items.map((x, i) => process(x, ctx, {\n        ...params,\n        path: [...params.path, prefixPath, i],\n    }));\n    const rest = def.rest\n        ? process(def.rest, ctx, {\n            ...params,\n            path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n        })\n        : null;\n    let minItems = def.items.length;\n    while (minItems > 0) {\n        const item = def.items[minItems - 1];\n        const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n        if (!optional)\n            break;\n        minItems--;\n    }\n    const maxItems = def.items.length;\n    const isClosed = !def.rest;\n    if (ctx.target === \"draft-2020-12\") {\n        json.prefixItems = prefixItems;\n        if (isClosed) {\n            json.items = false;\n        }\n        else if (rest) {\n            json.items = rest;\n        }\n        if (minItems > 0)\n            json.minItems = minItems;\n        if (isClosed)\n            json.maxItems = maxItems;\n    }\n    else if (ctx.target === \"openapi-3.0\") {\n        json.items = {\n            anyOf: prefixItems,\n        };\n        if (rest) {\n            json.items.anyOf.push(rest);\n        }\n        if (minItems > 0)\n            json.minItems = minItems;\n        if (isClosed)\n            json.maxItems = maxItems;\n    }\n    else {\n        json.items = prefixItems;\n        if (isClosed) {\n            json.additionalItems = false;\n        }\n        else if (rest) {\n            json.additionalItems = rest;\n        }\n        if (minItems > 0)\n            json.minItems = minItems;\n        if (isClosed)\n            json.maxItems = maxItems;\n    }\n    // explicit user-defined length checks take precedence\n    const { minimum, maximum } = schema._zod.bag;\n    if (typeof minimum === \"number\")\n        json.minItems = minimum;\n    if (typeof maximum === \"number\")\n        json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n    // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.\n    if (json.$ref) {\n        // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n        if (visited.has(json))\n            return json;\n        visited.add(json);\n        const def = bySchema.get(json)?.def;\n        if (!def)\n            return json;\n        const inlined = stringifyKeyNames(bySchema, def, visited);\n        return inlined === def ? json : inlined;\n    }\n    for (const keyword of [\"anyOf\", \"oneOf\"]) {\n        const branches = json[keyword];\n        if (!Array.isArray(branches))\n            continue;\n        const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n        // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n        if (mapped.some((branch, i) => branch !== branches[i]))\n            json = { ...json, [keyword]: mapped };\n    }\n    // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric\n    const types = Array.isArray(json.type) ? json.type : [json.type];\n    const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n    // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n    const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n    if (!numericType && !values?.some((v) => typeof v === \"number\"))\n        return json;\n    const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n    if (rest.enum)\n        rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n    else if (typeof rest.const === \"number\")\n        rest.const = String(rest.const);\n    // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n    if (!numericType)\n        return rest;\n    rest.type = \"string\";\n    if (!values)\n        rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n    return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n    // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.\n    const bySchema = new Map();\n    for (const entry of ctx.seen.values()) {\n        if (entry.def && !bySchema.has(entry.schema))\n            bySchema.set(entry.schema, entry);\n    }\n    const rewrites = new Map();\n    for (const record of pendingRecords.get(ctx) ?? []) {\n        const seen = ctx.seen.get(record);\n        const names = (seen?.def ?? seen?.schema)?.propertyNames;\n        if (!names || names === true || rewrites.has(names))\n            continue;\n        const rewritten = stringifyKeyNames(bySchema, names, new Set());\n        if (rewritten !== names)\n            rewrites.set(names, rewritten);\n    }\n    if (!rewrites.size)\n        return;\n    // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together\n    for (const entry of ctx.seen.values()) {\n        for (const carrier of [entry.schema, entry.def]) {\n            const rewritten = carrier && rewrites.get(carrier.propertyNames);\n            if (rewritten)\n                carrier.propertyNames = rewritten;\n        }\n    }\n}\nexport const recordProcessor = (schema, ctx, _json, params) => {\n    const json = _json;\n    const def = schema._zod.def;\n    json.type = \"object\";\n    // For looseRecord with regex patterns, use patternProperties. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n    const keyType = def.keyType;\n    const keyBag = keyType._zod.bag;\n    const patterns = keyBag?.patterns;\n    if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n        // Use patternProperties for looseRecord with regex patterns\n        const valueSchema = process(def.valueType, ctx, {\n            ...params,\n            path: [...params.path, \"patternProperties\", \"*\"],\n        });\n        json.patternProperties = {};\n        for (const pattern of patterns) {\n            assignProp(json.patternProperties, pattern.source, valueSchema);\n        }\n    }\n    else {\n        // Default behavior: use propertyNames + additionalProperties\n        if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n            json.propertyNames = process(def.keyType, ctx, {\n                ...params,\n                path: [...params.path, \"propertyNames\"],\n            });\n            let pending = pendingRecords.get(ctx);\n            if (!pending) {\n                pending = [];\n                pendingRecords.set(ctx, pending);\n                ctx.deferred.push(() => rewriteKeyNames(ctx));\n            }\n            pending.push(schema);\n        }\n        json.additionalProperties = process(def.valueType, ctx, {\n            ...params,\n            path: [...params.path, \"additionalProperties\"],\n        });\n    }\n    // Add required for keys with discrete values (enum, literal, etc.)\n    const keyValues = keyType._zod.values;\n    // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.\n    const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n    if (keyValues && !def.partial && !omittableOnInput) {\n        const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n        if (validKeyValues.length > 0) {\n            json.required = validKeyValues.map(String);\n        }\n    }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    const inner = process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    if (ctx.target === \"openapi-3.0\") {\n        seen.ref = def.innerType;\n        json.nullable = true;\n    }\n    else {\n        json.anyOf = [inner, { type: \"null\" }];\n    }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n    let unrepresentable = false;\n    const serialized = JSON.stringify(value, (_, val) => {\n        if (typeof val !== \"bigint\")\n            return val;\n        unrepresentable = true;\n        return null;\n    });\n    if (!unrepresentable)\n        return JSON.parse(serialized);\n    handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n    return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n    if (value !== UNREPRESENTABLE_DEFAULT)\n        json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    if (ctx.io !== \"input\")\n        return;\n    const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n    if (value !== UNREPRESENTABLE_DEFAULT)\n        json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    let catchValue;\n    try {\n        catchValue = def.catchValue(undefined);\n    }\n    catch {\n        handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n        return;\n    }\n    json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n    const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n    process(innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n    json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n    const def = schema._zod.def;\n    process(def.innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n    const innerType = schema._zod.innerType;\n    process(innerType, ctx, params);\n    const seen = ctx.seen.get(schema);\n    seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n    string: stringProcessor,\n    number: numberProcessor,\n    boolean: booleanProcessor,\n    bigint: bigintProcessor,\n    symbol: symbolProcessor,\n    null: nullProcessor,\n    undefined: undefinedProcessor,\n    void: voidProcessor,\n    never: neverProcessor,\n    any: anyProcessor,\n    unknown: unknownProcessor,\n    date: dateProcessor,\n    enum: enumProcessor,\n    literal: literalProcessor,\n    nan: nanProcessor,\n    template_literal: templateLiteralProcessor,\n    file: fileProcessor,\n    success: successProcessor,\n    custom: customProcessor,\n    function: functionProcessor,\n    transform: transformProcessor,\n    map: mapProcessor,\n    set: setProcessor,\n    array: arrayProcessor,\n    object: objectProcessor,\n    union: unionProcessor,\n    intersection: intersectionProcessor,\n    tuple: tupleProcessor,\n    record: recordProcessor,\n    nullable: nullableProcessor,\n    nonoptional: nonoptionalProcessor,\n    default: defaultProcessor,\n    prefault: prefaultProcessor,\n    catch: catchProcessor,\n    pipe: pipeProcessor,\n    readonly: readonlyProcessor,\n    promise: promiseProcessor,\n    optional: optionalProcessor,\n    lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n    if (\"_idmap\" in input) {\n        // Registry case\n        const registry = input;\n        const ctx = initializeContext({ ...params, processors: allProcessors });\n        const defs = {};\n        // First pass: process all schemas to build the seen map\n        for (const entry of registry._idmap.entries()) {\n            const [_, schema] = entry;\n            process(schema, ctx);\n        }\n        const schemas = {};\n        const external = {\n            registry,\n            uri: params?.uri,\n            defs,\n        };\n        // Update the context with external configuration\n        ctx.external = external;\n        // Second pass: emit each schema\n        for (const entry of registry._idmap.entries()) {\n            const [key, schema] = entry;\n            extractDefs(ctx, schema);\n            assignProp(schemas, key, finalize(ctx, schema));\n        }\n        if (Object.keys(defs).length > 0) {\n            const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n            schemas.__shared = {\n                [defsSegment]: defs,\n            };\n        }\n        return { schemas };\n    }\n    // Single schema case\n    const ctx = initializeContext({ ...params, processors: allProcessors });\n    process(input, ctx);\n    extractDefs(ctx, input);\n    return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n    Object.defineProperty(proto, key, {\n        configurable: true,\n        enumerable: false,\n        get() {\n            const value = make(this);\n            Object.defineProperty(this, key, { value, configurable: true, writable: true });\n            return value;\n        },\n        set(value) {\n            Object.defineProperty(this, key, { value, configurable: true, writable: true });\n        },\n    });\n}\nconst initializer = (inst, issues) => {\n    $ZodError.init(inst, issues);\n    inst.name = \"ZodError\";\n    const proto = Object.getPrototypeOf(inst);\n    if (_installedErrorProtos.has(proto))\n        return;\n    _installedErrorProtos.add(proto);\n    _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n    _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n    _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n        self.issues.push(issue);\n        self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n    });\n    _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n        self.issues.push(...issues);\n        self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n    });\n    Object.defineProperty(proto, \"isEmpty\", {\n        configurable: true,\n        enumerable: false,\n        get() {\n            return this.issues.length === 0;\n        },\n    });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\n    Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\nexport { validate, validateAsync } from \"../core/index.js\";\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present.\nfunction _ensureDefaultLocale() {\n    if (!core.globalConfig.localeError)\n        core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n    if (!core.globalConfig.memoizer)\n        core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n    _ensureDefaultLocale();\n    core.$ZodType.init(inst, def);\n    inst.def = def;\n    inst.type = def.type;\n    return inst;\n}, {\n    check(...chks) {\n        const def = this.def;\n        return this.clone(util.mergeDefs(def, {\n            checks: [\n                ...(def.checks ?? []),\n                ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n            ],\n        }), { parent: true });\n    },\n    with(...chks) {\n        return this.check(...chks);\n    },\n    clone(def, params) {\n        return core.clone(this, def, params);\n    },\n    brand() {\n        return this;\n    },\n    register(reg, meta) {\n        reg.add(this, meta);\n        return this;\n    },\n    refine(check, params) {\n        return this.check(refine(check, params));\n    },\n    superRefine(refinement, params) {\n        return this.check(superRefine(refinement, params));\n    },\n    overwrite(fn) {\n        return this.check(checks.overwrite(fn));\n    },\n    optional() {\n        return optional(this);\n    },\n    exactOptional() {\n        return exactOptional(this);\n    },\n    nullable() {\n        return nullable(this);\n    },\n    nullish() {\n        return optional(nullable(this));\n    },\n    nonoptional(params) {\n        return nonoptional(this, params);\n    },\n    array() {\n        return array(this);\n    },\n    or(arg) {\n        return union([this, arg]);\n    },\n    and(arg) {\n        return intersection(this, arg);\n    },\n    transform(tx) {\n        return pipe(this, transform(tx));\n    },\n    default(d) {\n        return _default(this, d);\n    },\n    prefault(d) {\n        return prefault(this, d);\n    },\n    catch(params) {\n        return _catch(this, params);\n    },\n    pipe(target) {\n        return pipe(this, target);\n    },\n    readonly() {\n        return readonly(this);\n    },\n    describe(description) {\n        const cl = this.clone();\n        core.globalRegistry.add(cl, { description });\n        return cl;\n    },\n    meta(...args) {\n        // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime.\n        if (args.length === 0)\n            return core.globalRegistry.get(this);\n        const cl = this.clone();\n        core.globalRegistry.add(cl, args[0]);\n        return cl;\n    },\n    isOptional() {\n        return this.safeParse(undefined).success;\n    },\n    isNullable() {\n        return this.safeParse(null).success;\n    },\n    apply(fn, ...args) {\n        return args.length === 0 ? fn(this) : fn(this, ...args);\n    },\n    // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n    get \"~standard\"() {\n        return util.hide(this, \"~standard\", {\n            ...core.standardProps(this),\n            jsonSchema: {\n                input: createStandardJSONSchemaMethod(this, \"input\"),\n                output: createStandardJSONSchemaMethod(this, \"output\"),\n            },\n        });\n    },\n    set \"~standard\"(value) {\n        util.own(this, \"~standard\", value);\n    },\n    parse: function _parse(data, params) {\n        return parse.parse(this, data, params, { callee: _parse });\n    },\n    parseAsync: async function _parseAsync(data, params) {\n        return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n    },\n    safeParse(data, params) {\n        return parse.safeParse(this, data, params);\n    },\n    async safeParseAsync(data, params) {\n        return parse.safeParseAsync(this, data, params);\n    },\n    // `spa` is an alias: same function object as `safeParseAsync`, as before.\n    get spa() {\n        return this?.safeParseAsync;\n    },\n    set spa(value) {\n        util.own(this, \"spa\", value);\n    },\n    encode: function _encode(data, params) {\n        return parse.encode(this, data, params, { callee: _encode });\n    },\n    decode: function _decode(data, params) {\n        return parse.decode(this, data, params, { callee: _decode });\n    },\n    encodeAsync: async function _encodeAsync(data, params) {\n        return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n    },\n    decodeAsync: async function _decodeAsync(data, params) {\n        return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n    },\n    safeEncode(data, params) {\n        return parse.safeEncode(this, data, params);\n    },\n    safeDecode(data, params) {\n        return parse.safeDecode(this, data, params);\n    },\n    async safeEncodeAsync(data, params) {\n        return parse.safeEncodeAsync(this, data, params);\n    },\n    async safeDecodeAsync(data, params) {\n        return parse.safeDecodeAsync(this, data, params);\n    },\n    toJSONSchema(params) {\n        return createToJSONSchemaMethod(this, {})(params);\n    },\n    // Reads through to the registry on every access, so it must not cache.\n    get description() {\n        return core.globalRegistry.get(this)?.description;\n    },\n    // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n    get _def() {\n        return this._zod.def;\n    },\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n    core.$ZodString.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n    const bag = inst._zod.bag;\n    inst.format = bag.format ?? null;\n    inst.minLength = bag.minimum ?? null;\n    inst.maxLength = bag.maximum ?? null;\n}, {\n    regex(...args) {\n        return this.check(checks.regex(...args));\n    },\n    includes(...args) {\n        return this.check(checks.includes(...args));\n    },\n    startsWith(...args) {\n        return this.check(checks.startsWith(...args));\n    },\n    endsWith(...args) {\n        return this.check(checks.endsWith(...args));\n    },\n    min(...args) {\n        return this.check(checks.minLength(...args));\n    },\n    max(...args) {\n        return this.check(checks.maxLength(...args));\n    },\n    length(...args) {\n        return this.check(checks.length(...args));\n    },\n    nonempty(...args) {\n        return this.check(checks.minLength(1, ...args));\n    },\n    lowercase(params) {\n        return this.check(checks.lowercase(params));\n    },\n    uppercase(params) {\n        return this.check(checks.uppercase(params));\n    },\n    trim() {\n        return this.check(checks.trim());\n    },\n    normalize(...args) {\n        return this.check(checks.normalize(...args));\n    },\n    toLowerCase() {\n        return this.check(checks.toLowerCase());\n    },\n    toUpperCase() {\n        return this.check(checks.toUpperCase());\n    },\n    slugify() {\n        return this.check(checks.slugify());\n    },\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n    core.$ZodString.init(inst, def);\n    _ZodString.init(inst, def);\n}, {\n    email(params) {\n        return this.check(core._email(ZodEmail, params));\n    },\n    url(params) {\n        return this.check(core._url(ZodURL, params));\n    },\n    jwt(params) {\n        return this.check(core._jwt(ZodJWT, params));\n    },\n    emoji(params) {\n        return this.check(core._emoji(ZodEmoji, params));\n    },\n    guid(params) {\n        return this.check(core._guid(ZodGUID, params));\n    },\n    uuid(params) {\n        return this.check(core._uuid(ZodUUID, params));\n    },\n    uuidv4(params) {\n        return this.check(core._uuidv4(ZodUUID, params));\n    },\n    uuidv6(params) {\n        return this.check(core._uuidv6(ZodUUID, params));\n    },\n    uuidv7(params) {\n        return this.check(core._uuidv7(ZodUUID, params));\n    },\n    nanoid(params) {\n        return this.check(core._nanoid(ZodNanoID, params));\n    },\n    cuid(params) {\n        return this.check(core._cuid(ZodCUID, params));\n    },\n    cuid2(params) {\n        return this.check(core._cuid2(ZodCUID2, params));\n    },\n    ulid(params) {\n        return this.check(core._ulid(ZodULID, params));\n    },\n    base64(params) {\n        return this.check(core._base64(ZodBase64, params));\n    },\n    base64url(params) {\n        return this.check(core._base64url(ZodBase64URL, params));\n    },\n    xid(params) {\n        return this.check(core._xid(ZodXID, params));\n    },\n    ksuid(params) {\n        return this.check(core._ksuid(ZodKSUID, params));\n    },\n    ipv4(params) {\n        return this.check(core._ipv4(ZodIPv4, params));\n    },\n    ipv6(params) {\n        return this.check(core._ipv6(ZodIPv6, params));\n    },\n    cidrv4(params) {\n        return this.check(core._cidrv4(ZodCIDRv4, params));\n    },\n    cidrv6(params) {\n        return this.check(core._cidrv6(ZodCIDRv6, params));\n    },\n    e164(params) {\n        return this.check(core._e164(ZodE164, params));\n    },\n    datetime(params) {\n        return this.check(core._isoDateTime(ZodISODateTime, params));\n    },\n    date(params) {\n        return this.check(core._isoDate(ZodISODate, params));\n    },\n    time(params) {\n        return this.check(core._isoTime(ZodISOTime, params));\n    },\n    duration(params) {\n        return this.check(core._isoDuration(ZodISODuration, params));\n    },\n});\nexport function string(params) {\n    return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n    core.$ZodStringFormat.init(inst, def);\n    _ZodString.init(inst, def);\n});\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n    core.$ZodISODateTime.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n    core.$ZodISODate.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n    core.$ZodISOTime.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n    core.$ZodISODuration.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodEmail.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n    return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodGUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n    return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodUUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n    return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n    return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n    return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n    return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodURL.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n    return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n    return core._url(ZodURL, {\n        protocol: core.regexes.httpProtocol,\n        hostname: core.regexes.domain,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodEmoji.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n    return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodNanoID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n    return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodCUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n    return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodCUID2.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n    return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodULID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n    return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodXID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n    return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodKSUID.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n    return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodIPv4.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n    return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodMAC.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n    return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodIPv6.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n    return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n    core.$ZodCIDRv4.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n    return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n    core.$ZodCIDRv6.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n    return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodBase64.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n    return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodBase64URL.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n    return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodE164.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n    return core._e164(ZodE164, params);\n}\nexport const ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n    core.$ZodCreditCard.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n    return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodJWT.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n    return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n    // ZodStringFormat.init(inst, def);\n    core.$ZodCustomStringFormat.init(inst, def);\n    ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n    return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n    return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n    return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n    const enc = params?.enc ?? \"hex\";\n    const format = `${alg}_${enc}`;\n    const regex = core.regexes[format];\n    if (!regex)\n        throw new Error(`Unrecognized hash format: ${format}`);\n    return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n    core.$ZodNumber.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n    const bag = inst._zod.bag;\n    inst.minValue =\n        Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n    inst.maxValue =\n        Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n    inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n    inst.isFinite = true;\n    inst.format = bag.format ?? null;\n}, {\n    gt(value, params) {\n        return this.check(checks.gt(value, params));\n    },\n    gte(value, params) {\n        return this.check(checks.gte(value, params));\n    },\n    min(value, params) {\n        return this.check(checks.gte(value, params));\n    },\n    lt(value, params) {\n        return this.check(checks.lt(value, params));\n    },\n    lte(value, params) {\n        return this.check(checks.lte(value, params));\n    },\n    max(value, params) {\n        return this.check(checks.lte(value, params));\n    },\n    int(params) {\n        return this.check(int(params));\n    },\n    safe(params) {\n        return this.check(int(params));\n    },\n    positive(params) {\n        return this.check(checks.gt(0, params));\n    },\n    nonnegative(params) {\n        return this.check(checks.gte(0, params));\n    },\n    negative(params) {\n        return this.check(checks.lt(0, params));\n    },\n    nonpositive(params) {\n        return this.check(checks.lte(0, params));\n    },\n    multipleOf(value, params) {\n        return this.check(checks.multipleOf(value, params));\n    },\n    step(value, params) {\n        return this.check(checks.multipleOf(value, params));\n    },\n    finite() {\n        return this;\n    },\n});\nexport function number(params) {\n    return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n    core.$ZodNumberFormat.init(inst, def);\n    ZodNumber.init(inst, def);\n});\nexport function int(params) {\n    return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n    return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n    return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n    return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n    return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n    core.$ZodBoolean.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n    return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n    core.$ZodBigInt.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n    const bag = inst._zod.bag;\n    inst.minValue = bag.minimum ?? null;\n    inst.maxValue = bag.maximum ?? null;\n    inst.format = bag.format ?? null;\n}, {\n    gte(value, params) {\n        return this.check(checks.gte(value, params));\n    },\n    min(value, params) {\n        return this.check(checks.gte(value, params));\n    },\n    gt(value, params) {\n        return this.check(checks.gt(value, params));\n    },\n    lt(value, params) {\n        return this.check(checks.lt(value, params));\n    },\n    lte(value, params) {\n        return this.check(checks.lte(value, params));\n    },\n    max(value, params) {\n        return this.check(checks.lte(value, params));\n    },\n    positive(params) {\n        return this.check(checks.gt(BigInt(0), params));\n    },\n    negative(params) {\n        return this.check(checks.lt(BigInt(0), params));\n    },\n    nonpositive(params) {\n        return this.check(checks.lte(BigInt(0), params));\n    },\n    nonnegative(params) {\n        return this.check(checks.gte(BigInt(0), params));\n    },\n    multipleOf(value, params) {\n        return this.check(checks.multipleOf(value, params));\n    },\n});\nexport function bigint(params) {\n    return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n    core.$ZodBigIntFormat.init(inst, def);\n    ZodBigInt.init(inst, def);\n});\nexport function int64(params) {\n    return core._int64(ZodBigIntFormat, params);\n}\nexport function uint64(params) {\n    return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n    core.$ZodSymbol.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n    return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n    core.$ZodUndefined.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n    return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n    core.$ZodNull.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n    return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n    core.$ZodAny.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n    return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n    core.$ZodUnknown.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n    return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n    core.$ZodNever.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n    return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n    core.$ZodVoid.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n    return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n    core.$ZodDate.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n    inst.min = (value, params) => inst.check(checks.gte(value, params));\n    inst.max = (value, params) => inst.check(checks.lte(value, params));\n    const c = inst._zod.bag;\n    inst.minDate = c.minimum ? new Date(c.minimum) : null;\n    inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n    return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodArray.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n    inst.element = def.element;\n}, {\n    min(n, params) {\n        return this.check(checks.minLength(n, params));\n    },\n    nonempty(params) {\n        return this.check(checks.minLength(1, params));\n    },\n    max(n, params) {\n        return this.check(checks.maxLength(n, params));\n    },\n    length(n, params) {\n        return this.check(checks.length(n, params));\n    },\n    unwrap() {\n        return this.element;\n    },\n});\nexport function array(element, params) {\n    return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n    const shape = schema._zod.def.shape;\n    return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodObjectJIT.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n    util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n    keyof() {\n        return _enum(Object.keys(this._zod.def.shape));\n    },\n    catchall(catchall) {\n        return this.clone({ ...this._zod.def, catchall: catchall });\n    },\n    passthrough() {\n        return this.clone({ ...this._zod.def, catchall: unknown() });\n    },\n    loose() {\n        return this.clone({ ...this._zod.def, catchall: unknown() });\n    },\n    strict() {\n        return this.clone({ ...this._zod.def, catchall: never() });\n    },\n    strip() {\n        return this.clone({ ...this._zod.def, catchall: undefined });\n    },\n    extend(incoming) {\n        return util.extend(this, incoming);\n    },\n    safeExtend(incoming) {\n        return util.safeExtend(this, incoming);\n    },\n    merge(other) {\n        return util.merge(this, other);\n    },\n    pick(mask) {\n        return util.pick(this, mask);\n    },\n    omit(mask) {\n        return util.omit(this, mask);\n    },\n    partial(...args) {\n        return util.partial(ZodOptional, this, args[0]);\n    },\n    exactPartial(...args) {\n        return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n    },\n    required(...args) {\n        return util.required(ZodNonOptional, this, args[0]);\n    },\n});\nexport function object(shape, params) {\n    const def = {\n        type: \"object\",\n        shape: shape ?? {},\n        ...util.normalizeParams(params),\n    };\n    return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n    return new ZodObject({\n        type: \"object\",\n        shape,\n        catchall: never(),\n        ...util.normalizeParams(params),\n    });\n}\n// looseObject\nexport function looseObject(shape, params) {\n    return new ZodObject({\n        type: \"object\",\n        shape,\n        catchall: unknown(),\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n    core.$ZodUnion.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n    inst.options = def.options;\n});\nexport function union(options, params) {\n    return new ZodUnion({\n        type: \"union\",\n        options: options,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n    ZodUnion.init(inst, def);\n    core.$ZodXor.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n    inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n    return new ZodXor({\n        type: \"union\",\n        options: options,\n        inclusive: false,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n    ZodUnion.init(inst, def);\n    core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n    // const [options, params] = args;\n    return new ZodDiscriminatedUnion({\n        type: \"union\",\n        options: options,\n        discriminator,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n    core.$ZodIntersection.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n    return new ZodIntersection({\n        type: \"intersection\",\n        left: left,\n        right: right,\n    });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodTuple.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n}, {\n    rest(rest) {\n        return this.clone({\n            ...this._zod.def,\n            rest: rest,\n        });\n    },\n    partial() {\n        const def = this._zod.def;\n        // a refinement was authored against the full arity; partialing would run it on a shorter array\n        if (def.checks?.length)\n            throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n        return this.clone({\n            ...def,\n            items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n        });\n    },\n});\nexport function tuple(items, _paramsOrRest, _params) {\n    const hasRest = _paramsOrRest instanceof core.$ZodType;\n    const params = hasRest ? _params : _paramsOrRest;\n    const rest = hasRest ? _paramsOrRest : null;\n    return new ZodTuple({\n        type: \"tuple\",\n        items: items,\n        rest,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodRecord.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n    inst.keyType = def.keyType;\n    inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n    // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n    if (!valueType || !valueType._zod) {\n        return new ZodRecord({\n            type: \"record\",\n            keyType: string(),\n            valueType: keyType,\n            ...util.normalizeParams(valueType),\n        });\n    }\n    return new ZodRecord({\n        type: \"record\",\n        keyType,\n        valueType: valueType,\n        ...util.normalizeParams(params),\n    });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n    return new ZodRecord({\n        type: \"record\",\n        keyType,\n        valueType: valueType,\n        ...util.normalizeParams(params),\n        partial: true,\n    });\n}\nexport function looseRecord(keyType, valueType, params) {\n    return new ZodRecord({\n        type: \"record\",\n        keyType,\n        valueType: valueType,\n        mode: \"loose\",\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodMap.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n    inst.keyType = def.keyType;\n    inst.valueType = def.valueType;\n    inst.min = (...args) => inst.check(core._minSize(...args));\n    inst.nonempty = (params) => inst.check(core._minSize(1, params));\n    inst.max = (...args) => inst.check(core._maxSize(...args));\n    inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n    return new ZodMap({\n        type: \"map\",\n        keyType: keyType,\n        valueType: valueType,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodSet.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n    inst.min = (...args) => inst.check(core._minSize(...args));\n    inst.nonempty = (params) => inst.check(core._minSize(1, params));\n    inst.max = (...args) => inst.check(core._maxSize(...args));\n    inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n    return new ZodSet({\n        type: \"set\",\n        valueType: valueType,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n    core.$ZodEnum.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n    inst.enum = def.entries;\n    inst.options = Object.values(def.entries);\n    const keys = new Set(Object.keys(def.entries));\n    inst.extract = (values, params) => {\n        const newEntries = {};\n        for (const value of values) {\n            if (keys.has(value)) {\n                newEntries[value] = def.entries[value];\n            }\n            else\n                throw new Error(`Key ${value} not found in enum`);\n        }\n        return new ZodEnum({\n            ...def,\n            checks: [],\n            ...util.normalizeParams(params),\n            entries: newEntries,\n        });\n    };\n    inst.exclude = (values, params) => {\n        const newEntries = { ...def.entries };\n        for (const value of values) {\n            if (keys.has(value)) {\n                delete newEntries[value];\n            }\n            else\n                throw new Error(`Key ${value} not found in enum`);\n        }\n        return new ZodEnum({\n            ...def,\n            checks: [],\n            ...util.normalizeParams(params),\n            entries: newEntries,\n        });\n    };\n});\nfunction _enum(values, params) {\n    const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n    return new ZodEnum({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n    return new ZodEnum({\n        type: \"enum\",\n        entries,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n    core.$ZodLiteral.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n    inst.values = new Set(def.values);\n    Object.defineProperty(inst, \"value\", {\n        get() {\n            if (def.values.length > 1) {\n                throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n            }\n            return def.values[0];\n        },\n    });\n});\nexport function literal(value, params) {\n    return new ZodLiteral({\n        type: \"literal\",\n        values: Array.isArray(value) ? value : [value],\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n    core.$ZodFile.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n    inst.min = (size, params) => inst.check(core._minSize(size, params));\n    inst.max = (size, params) => inst.check(core._maxSize(size, params));\n    inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n    return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n    _ensureDefaultMemoizer();\n    core.$ZodTransform.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n    inst._zod.parse = (payload, _ctx) => {\n        if (_ctx.direction === \"backward\") {\n            throw new core.$ZodEncodeError(inst.constructor.name);\n        }\n        payload.addIssue = (issue) => {\n            if (typeof issue === \"string\") {\n                payload.issues.push(util.issue(issue, payload.value, def));\n            }\n            else {\n                // for Zod 3 backwards compatibility\n                const _issue = issue;\n                if (_issue.fatal)\n                    _issue.continue = false;\n                _issue.code ?? (_issue.code = \"custom\");\n                if (!(\"input\" in _issue))\n                    _issue.input = payload.value;\n                _issue.inst ?? (_issue.inst = inst);\n                // _issue.continue ??= true;\n                payload.issues.push(util.issue(_issue));\n            }\n        };\n        const output = def.transform(payload.value, payload);\n        if (output instanceof Promise) {\n            return output.then((output) => {\n                payload.value = output;\n                return payload;\n            });\n        }\n        payload.value = output;\n        return payload;\n    };\n});\nexport function transform(fn) {\n    return new ZodTransform({\n        type: \"transform\",\n        transform: fn,\n    });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n    core.$ZodOptional.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n    return new ZodOptional({\n        type: \"optional\",\n        innerType: innerType,\n    });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n    core.$ZodExactOptional.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n    return new ZodExactOptional({\n        type: \"optional\",\n        innerType: innerType,\n    });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n    core.$ZodNullable.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n    return new ZodNullable({\n        type: \"nullable\",\n        innerType: innerType,\n    });\n}\n// nullish\nexport function nullish(innerType) {\n    return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n    core.$ZodDefault.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n    inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n    return new ZodDefault({\n        type: \"default\",\n        innerType: innerType,\n        get defaultValue() {\n            return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n        },\n    });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n    core.$ZodPrefault.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n    return new ZodPrefault({\n        type: \"prefault\",\n        innerType: innerType,\n        get defaultValue() {\n            return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n        },\n    });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n    core.$ZodNonOptional.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n    return new ZodNonOptional({\n        type: \"nonoptional\",\n        innerType: innerType,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n    core.$ZodSuccess.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n    return new ZodSuccess({\n        type: \"success\",\n        innerType: innerType,\n    });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n    core.$ZodCatch.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n    inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n    return new ZodCatch({\n        type: \"catch\",\n        innerType: innerType,\n        catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n    });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n    core.$ZodNaN.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n    return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n    core.$ZodPipe.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n    inst.in = def.in;\n    inst.out = def.out;\n});\nexport function pipe(in_, out) {\n    return new ZodPipe({\n        type: \"pipe\",\n        in: in_,\n        out: out,\n        // ...util.normalizeParams(params),\n    });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n    ZodPipe.init(inst, def);\n    core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n    return new ZodCodec({\n        type: \"pipe\",\n        in: in_,\n        out: out,\n        transform: params.decode,\n        reverseTransform: params.encode,\n    });\n}\nexport function invertCodec(codec) {\n    const def = codec._zod.def;\n    return new ZodCodec({\n        type: \"pipe\",\n        in: def.out,\n        out: def.in,\n        transform: def.reverseTransform,\n        reverseTransform: def.transform,\n    });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n    ZodPipe.init(inst, def);\n    core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n    core.$ZodReadonly.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n    return new ZodReadonly({\n        type: \"readonly\",\n        innerType: innerType,\n    });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n    core.$ZodTemplateLiteral.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n    return new ZodTemplateLiteral({\n        type: \"template_literal\",\n        parts,\n        ...util.normalizeParams(params),\n    });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n    core.$ZodLazy.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n    return new ZodLazy({\n        type: \"lazy\",\n        getter: getter,\n    });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n    core.$ZodPromise.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n    inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n    return new ZodPromise({\n        type: \"promise\",\n        innerType: innerType,\n    });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n    core.$ZodFunction.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n    return new ZodFunction({\n        type: \"function\",\n        input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n        output: params?.output ?? unknown(),\n    });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n    core.$ZodCustom.init(inst, def);\n    ZodType.init(inst, def);\n    inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n    const ch = new core.$ZodCheck({\n        check: \"custom\",\n        // ...util.normalizeParams(params),\n    });\n    ch._zod.check = fn;\n    return ch;\n}\nexport function custom(fn, _params) {\n    return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n    return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n    return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n    const inst = new ZodCustom({\n        type: \"custom\",\n        check: \"custom\",\n        fn: (data) => data instanceof cls,\n        abort: true,\n        ...util.normalizeParams(params),\n    });\n    inst._zod.bag.Class = cls;\n    // Override check to emit invalid_type instead of custom\n    inst._zod.check = (payload) => {\n        if (!(payload.value instanceof cls)) {\n            payload.issues.push({\n                code: \"invalid_type\",\n                expected: cls.name,\n                input: payload.value,\n                inst,\n                path: [...(inst._zod.def.path ?? [])],\n            });\n        }\n    };\n    return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n    Codec: ZodCodec,\n    Boolean: ZodBoolean,\n    String: ZodString,\n}, ...args);\nexport function json(params) {\n    const jsonSchema = lazy(() => {\n        return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n    });\n    return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n    return new ZodPreprocess({\n        type: \"pipe\",\n        in: transform(fn),\n        out: schema,\n    });\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n    return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n    return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n    return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n    return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n    return core._coercedDate(schemas.ZodDate, params);\n}\n","import { z } from \"zod\";\nimport { createHash } from \"node:crypto\";\n//#region src/context-tree.ts\nconst ContextTreeRepositorySchema = z.string().trim().max(140).regex(/^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}\\/[a-zA-Z0-9_][a-zA-Z0-9._-]{0,99}$/).refine((value) => !value.toLowerCase().endsWith(\".git\"), \"Use OWNER/REPO without .git\");\n/** Matches the upstream CLI's project-local treeNameSchema (aliases are case-sensitive). */\nconst ContextTreeAliasSchema = z.string().regex(/^[A-Za-z\\d][A-Za-z\\d._-]{0,99}$/u).refine((value) => !/\\.git$/iu.test(value), \"Alias must not end with .git\");\nconst ContextTreeConnectionSchema = z.object({\n\talias: ContextTreeAliasSchema,\n\trepository: ContextTreeRepositorySchema\n}).strict();\nconst CONTEXT_TREES_MAX = 32;\nconst ContextTreesSchema = z.array(ContextTreeConnectionSchema).max(32).superRefine((connections, context) => {\n\tconst aliases = /* @__PURE__ */ new Set();\n\tconst repositories = /* @__PURE__ */ new Set();\n\tconnections.forEach((connection, index) => {\n\t\tif (aliases.has(connection.alias)) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [index, \"alias\"],\n\t\t\tmessage: \"Aliases must be unique\"\n\t\t});\n\t\tif (repositories.has(connection.repository.toLowerCase())) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [index, \"repository\"],\n\t\t\tmessage: \"Repositories must be unique\"\n\t\t});\n\t\taliases.add(connection.alias);\n\t\trepositories.add(connection.repository.toLowerCase());\n\t});\n});\n/** Array order is presentation only; no tree takes precedence over another. */\nfunction normalizeContextTrees(connections) {\n\treturn connections.map(({ alias, repository }) => ({\n\t\talias,\n\t\trepository: repository.toLowerCase()\n\t})).sort((left, right) => left.alias < right.alias ? -1 : left.alias > right.alias ? 1 : 0);\n}\n//#endregion\n//#region src/runtime-config.ts\nconst RUNTIME_ID_MAX_BYTES = 128;\nconst RUNTIME_INSTRUCTIONS_MAX_BYTES = 24576;\nconst RUNTIME_DEFAULT_MAX_DURATION_MS = 18e5;\nconst RUNTIME_MAX_DURATION_MS = 864e5;\nconst OPENTAG_PLATFORM_INSTRUCTIONS = \"You run inside OpenTag. IM output is never sent automatically.\";\n/** Upper bound on an Agent slug, shared with `AgentNameSchema` so both budgets agree. */\nconst AGENT_SLUG_MAX_LENGTH = 64;\nconst utf8 = new TextEncoder();\nfunction runtimeUtf8Length(value) {\n\treturn utf8.encode(value).byteLength;\n}\n/**\n* The trusted platform instruction layer for one Agent. The prompt is the only channel that\n* reaches an Agent's reasoning, so it is where the Agent learns which `members/<agent-slug>/`\n* directory in the Context Tree is its own. Callers that hash Agent revision identity must hash\n* this exact string.\n*/\nfunction renderPlatformInstructions(input) {\n\treturn `${OPENTAG_PLATFORM_INSTRUCTIONS}\\n\\nOpenTag Agent slug: ${input.agentSlug}`;\n}\nfunction runtimeByteString(maxBytes, message, minimumBytes = 0) {\n\treturn z.string().superRefine((value, context) => {\n\t\tconst bytes = runtimeUtf8Length(value);\n\t\tif (bytes < minimumBytes || bytes > maxBytes) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage\n\t\t});\n\t});\n}\nconst RuntimeModelSchema = runtimeByteString(128, \"Model exceeds the 128-byte limit\", 1);\nconst RuntimeReasoningEffortSchema = runtimeByteString(64, \"Reasoning effort exceeds the 64-byte limit\", 1);\nconst RuntimeInstructionSchema = runtimeByteString(RUNTIME_INSTRUCTIONS_MAX_BYTES, \"Runtime instructions are too large\");\nconst RuntimeInstructionsSchema = z.object({\n\tplatform: RuntimeInstructionSchema,\n\tagent: RuntimeInstructionSchema,\n\tsession: RuntimeInstructionSchema.optional()\n}).strict().superRefine((instructions, context) => {\n\tif (runtimeUtf8Length(instructions.platform) + runtimeUtf8Length(instructions.agent) + runtimeUtf8Length(instructions.session ?? \"\") > 24576) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"Combined instructions exceed the 24 KiB limit\"\n\t});\n});\nconst RuntimeMaxDurationMsSchema = z.number().int().safe().positive().max(RUNTIME_MAX_DURATION_MS);\n//#endregion\n//#region src/agent.ts\nconst AgentNameSchema = z.string().trim().min(1, \"Agent name is required\").max(64, `Agent name must be at most 64 characters`).regex(/^[a-z0-9][a-z0-9-]*$/, \"Agent name must start with a lowercase letter or number and contain only lowercase letters, numbers, and hyphens\");\nconst AgentDisplayNameSchema = z.string().trim().min(1).max(120);\nconst AgentCreationIntentIdSchema = z.string().uuid();\nconst AGENT_RUNTIME_PROVIDERS = [\n\t\"codex\",\n\t\"claude-code\",\n\t\"pi\"\n];\nconst AgentRuntimeProviderSchema = z.enum(AGENT_RUNTIME_PROVIDERS);\nconst ReceiveModeSchema = z.enum([\"all_message\", \"mention_only\"]);\nconst AgentStatusSchema = z.enum([\"active\", \"suspended\"]);\nconst AgentInstructionsSchema = RuntimeInstructionSchema.superRefine((instructions, context) => {\n\tif (!RuntimeInstructionsSchema.safeParse({\n\t\tplatform: renderPlatformInstructions({ agentSlug: \"a\".repeat(64) }),\n\t\tagent: instructions\n\t}).success) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"Platform and Agent instructions exceed the combined 24 KiB limit\"\n\t});\n});\nconst AgentRuntimeConfigSchema = z.object({\n\trevision: z.number().int().safe().positive(),\n\tmodel: RuntimeModelSchema.nullable(),\n\treasoningEffort: RuntimeReasoningEffortSchema.nullable(),\n\tinstructions: AgentInstructionsSchema,\n\tmaxDurationMs: RuntimeMaxDurationMsSchema.nullable(),\n\tcontextTrees: ContextTreesSchema\n}).strict();\nconst CreateAgentRuntimeConfigSchema = z.object({\n\tmodel: RuntimeModelSchema.nullable().optional(),\n\treasoningEffort: RuntimeReasoningEffortSchema.nullable().optional(),\n\tinstructions: AgentInstructionsSchema.optional(),\n\tmaxDurationMs: RuntimeMaxDurationMsSchema.nullable().optional()\n}).strict();\nconst UpdateAgentRuntimeConfigSchema = z.object({\n\tmodel: RuntimeModelSchema.nullable().optional(),\n\treasoningEffort: RuntimeReasoningEffortSchema.nullable().optional(),\n\tinstructions: AgentInstructionsSchema.optional(),\n\tmaxDurationMs: RuntimeMaxDurationMsSchema.nullable().optional()\n}).strict().refine((value) => Object.keys(value).length > 0, { message: \"At least one runtime config field must be updated\" });\nconst AgentIdentitySchema = z.object({\n\tid: z.string().uuid(),\n\tname: AgentNameSchema,\n\tdisplayName: AgentDisplayNameSchema,\n\truntimeProvider: AgentRuntimeProviderSchema,\n\treceiveMode: ReceiveModeSchema,\n\tstatus: AgentStatusSchema,\n\tcreatedAt: z.string().datetime(),\n\tupdatedAt: z.string().datetime()\n}).strict();\nconst AgentSummarySchema = AgentIdentitySchema.extend({\n\tavatarUrl: z.string().url().nullable().optional(),\n\tcreatedBy: z.object({\n\t\tuserId: z.string().uuid(),\n\t\tdisplayName: z.string().min(1)\n\t}).strict(),\n\t/**\n\t* `null` while the Agent has no Computer. An Agent is created before its Computer exists, so the\n\t* binding is a later fact rather than a creation precondition, and a reader that cannot tell\n\t* \"not bound yet\" from \"bound to a machine we could not read\" reports the wrong recovery.\n\t*/\n\tcomputer: z.object({\n\t\tcomputerId: z.string().uuid(),\n\t\tdisplayName: z.string().min(1),\n\t\tplatform: z.enum([\n\t\t\t\"darwin\",\n\t\t\t\"linux\",\n\t\t\t\"win32\"\n\t\t])\n\t}).strict().nullable(),\n\t/**\n\t* Present when the Agent creator does not own the bound Computer. The Agent stays visible; execution\n\t* is rejected until the creator rebinds it to an owned Computer.\n\t*/\n\trequiresComputerRebind: z.boolean().optional()\n}).strict();\nconst RebindAgentComputerRequestSchema = z.object({ computerId: z.string().uuid() }).strict();\nconst AGENT_USAGE_WINDOW_DAYS = 30;\nconst AGENT_USAGE_WINDOW_OPTIONS = [\n\t1,\n\t7,\n\t30,\n\t90\n];\nconst AgentUsageWindowDaysSchema = z.union([\n\tz.literal(AGENT_USAGE_WINDOW_OPTIONS[0]),\n\tz.literal(AGENT_USAGE_WINDOW_OPTIONS[1]),\n\tz.literal(AGENT_USAGE_WINDOW_OPTIONS[2]),\n\tz.literal(AGENT_USAGE_WINDOW_OPTIONS[3])\n]);\nconst AgentListActivitySchema = z.discriminatedUnion(\"state\", [\n\tz.object({ state: z.literal(\"idle\") }).strict(),\n\tz.object({ state: z.literal(\"unknown\") }).strict(),\n\tz.object({\n\t\tstate: z.literal(\"working\"),\n\t\tstartedAt: z.string().datetime()\n\t}).strict()\n]);\nconst AgentDetailSchema = AgentSummarySchema.extend({ activity: AgentListActivitySchema }).strict();\nconst AgentUsageSummarySchema = z.object({\n\twindowDays: z.literal(30),\n\ttasks: z.number().int().safe().nonnegative(),\n\tfailed: z.number().int().safe().nonnegative(),\n\ttokens: z.number().int().safe().nonnegative()\n}).strict();\nconst AgentUsageTokenBreakdownSchema = z.object({\n\tinputTokens: z.number().int().safe().nonnegative(),\n\tcachedInputTokens: z.number().int().safe().nonnegative(),\n\toutputTokens: z.number().int().safe().nonnegative(),\n\ttokens: z.number().int().safe().nonnegative()\n}).strict();\nconst AgentUsageDetailSchema = z.object({\n\twindowDays: AgentUsageWindowDaysSchema,\n\tstartedAt: z.string().datetime(),\n\tendedAt: z.string().datetime(),\n\ttasks: z.number().int().safe().nonnegative(),\n\tmeasuredTasks: z.number().int().safe().nonnegative(),\n\tfailed: z.number().int().safe().nonnegative(),\n\t...AgentUsageTokenBreakdownSchema.shape,\n\tdaily: z.array(z.object({\n\t\tdate: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n\t\ttasks: z.number().int().safe().nonnegative(),\n\t\tmeasuredTasks: z.number().int().safe().nonnegative(),\n\t\t...AgentUsageTokenBreakdownSchema.shape\n\t}).strict())\n}).strict().superRefine((usage, context) => {\n\tconst validateTokenBreakdown = (breakdown, path) => {\n\t\tif (breakdown.tokens !== breakdown.inputTokens + breakdown.outputTokens) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [...path, \"tokens\"],\n\t\t\tmessage: \"Total Tokens must equal input and output Tokens\"\n\t\t});\n\t};\n\tif (usage.failed > usage.tasks) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"failed\"],\n\t\tmessage: \"Failed Tasks cannot exceed Tasks\"\n\t});\n\tif (usage.measuredTasks > usage.tasks) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"measuredTasks\"],\n\t\tmessage: \"Measured Tasks cannot exceed Tasks\"\n\t});\n\tif (new Date(usage.startedAt).getTime() > new Date(usage.endedAt).getTime()) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"startedAt\"],\n\t\tmessage: \"Usage start cannot follow usage end\"\n\t});\n\tvalidateTokenBreakdown(usage, []);\n\tfor (const [index, point] of usage.daily.entries()) {\n\t\tif (point.measuredTasks > point.tasks) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\n\t\t\t\t\"daily\",\n\t\t\t\tindex,\n\t\t\t\t\"measuredTasks\"\n\t\t\t],\n\t\t\tmessage: \"Measured Tasks cannot exceed Tasks\"\n\t\t});\n\t\tif (index > 0 && point.date <= (usage.daily[index - 1]?.date ?? \"\")) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\n\t\t\t\t\"daily\",\n\t\t\t\tindex,\n\t\t\t\t\"date\"\n\t\t\t],\n\t\t\tmessage: \"Daily usage dates must be unique and ordered\"\n\t\t});\n\t\tvalidateTokenBreakdown(point, [\"daily\", index]);\n\t}\n});\nconst AgentListItemSchema = AgentSummarySchema.extend({\n\tactivity: AgentListActivitySchema,\n\tusage: AgentUsageSummarySchema\n}).strict();\nconst AgentAdminConfigSchema = AgentIdentitySchema.extend({\n\tcreatedByUserId: z.string().uuid(),\n\tcomputerId: z.string().uuid().nullable(),\n\trevision: z.number().int().min(1),\n\truntimeConfig: AgentRuntimeConfigSchema\n}).strict();\nconst CreateAgentRequestSchema = z.object({\n\tcreationIntentId: AgentCreationIntentIdSchema.optional(),\n\tname: AgentNameSchema,\n\tdisplayName: AgentDisplayNameSchema,\n\truntimeProvider: AgentRuntimeProviderSchema,\n\t/**\n\t* Optional: the Computer binding is changeable after creation, so requiring it here would state\n\t* a creation-time precondition the product does not have. An Agent created without one exists\n\t* and can be configured; it cannot run until a Computer is bound.\n\t*/\n\tcomputerId: z.string().uuid().optional(),\n\truntimeConfig: CreateAgentRuntimeConfigSchema.optional()\n}).strict();\n/** Read-only reconciliation of one exact pre-Agent creation identity. */\nconst AgentCreationIntentResultSchema = z.discriminatedUnion(\"kind\", [z.object({ kind: z.literal(\"not-found\") }).strict(), z.object({\n\tkind: z.literal(\"found\"),\n\tagentId: z.string().uuid()\n}).strict()]);\nconst UpdateAgentRequestSchema = z.object({\n\texpectedRevision: z.number().int().min(1),\n\tdisplayName: AgentDisplayNameSchema.optional(),\n\treceiveMode: ReceiveModeSchema.optional(),\n\truntimeConfig: UpdateAgentRuntimeConfigSchema.optional()\n}).strict().refine((value) => value.displayName !== void 0 || value.receiveMode !== void 0 || value.runtimeConfig !== void 0, { message: \"At least one Agent field must be updated\" });\nconst ListAgentsResponseSchema = z.object({ agents: z.array(AgentListItemSchema) }).strict();\nconst AGENT_RUNTIME_TEST_FAILURE_CODES = [\n\t\"stale_configuration\",\n\t\"computer_unavailable\",\n\t\"capability_missing\",\n\t\"busy\",\n\t\"timeout\",\n\t\"cancelled\",\n\t\"interaction_or_tool\",\n\t\"provider_start_failed\",\n\t\"provider_failed\"\n];\nconst AgentRuntimeTestFailureCodeSchema = z.enum(AGENT_RUNTIME_TEST_FAILURE_CODES);\nconst AgentRuntimeTestRequestSchema = z.object({\n\texpectedRevision: z.number().int().min(1),\n\texpectedRuntimeConfigRevision: z.number().int().min(1)\n}).strict();\nconst AgentRuntimeTestResponseSchema = z.discriminatedUnion(\"status\", [z.object({ status: z.literal(\"passed\") }).strict(), z.object({\n\tstatus: z.literal(\"failed\"),\n\tcode: AgentRuntimeTestFailureCodeSchema\n}).strict()]);\n//#endregion\n//#region src/semver.ts\n/**\n* Strict SemVer 2.0.0 grammar. Channel targets, Client versions, and release coordinates are all\n* compared through this one module so the Server, the Client updater, and release tooling never\n* drift on what \"newer\" means.\n*/\nconst SEMVER_PATTERN = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$/;\nconst SemVerStringSchema = z.string().regex(SEMVER_PATTERN, \"Must be a strict SemVer 2.0.0 version\");\nfunction parseSemVer(value) {\n\tconst match = SEMVER_PATTERN.exec(value);\n\tif (!match) return void 0;\n\treturn {\n\t\tmajor: Number(match[1]),\n\t\tminor: Number(match[2]),\n\t\tpatch: Number(match[3]),\n\t\tprerelease: match[4] ? match[4].split(\".\") : [],\n\t\tbuild: match[5] ? match[5].split(\".\") : []\n\t};\n}\nfunction isSemVer(value) {\n\treturn SEMVER_PATTERN.test(value);\n}\nfunction requireSemVer(value) {\n\tif (typeof value !== \"string\") return value;\n\tconst parsed = parseSemVer(value);\n\tif (!parsed) throw new Error(`Not a valid SemVer version: ${JSON.stringify(value)}`);\n\treturn parsed;\n}\nfunction compareNumericIdentifier(left, right) {\n\tconst leftNumeric = /^\\d+$/u.test(left);\n\tconst rightNumeric = /^\\d+$/u.test(right);\n\tif (leftNumeric && rightNumeric) return compareNumericStrings(left, right);\n\tif (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;\n\treturn compareStrings(left, right);\n}\nfunction compareNumericStrings(left, right) {\n\tif (left.length !== right.length) return left.length < right.length ? -1 : 1;\n\treturn compareStrings(left, right);\n}\nfunction compareStrings(left, right) {\n\tif (left === right) return 0;\n\treturn left < right ? -1 : 1;\n}\nfunction compareCore(left, right) {\n\tfor (const key of [\n\t\t\"major\",\n\t\t\"minor\",\n\t\t\"patch\"\n\t]) if (left[key] !== right[key]) return left[key] < right[key] ? -1 : 1;\n\treturn 0;\n}\nfunction compareReleasePresence(left, right) {\n\tif (left.length > 0 && right.length > 0) return void 0;\n\tif (left.length === right.length) return 0;\n\treturn left.length === 0 ? 1 : -1;\n}\nfunction comparePrerelease(left, right) {\n\tconst releasePresence = compareReleasePresence(left, right);\n\tif (releasePresence !== void 0) return releasePresence;\n\tconst shared = Math.min(left.length, right.length);\n\tfor (let index = 0; index < shared; index += 1) {\n\t\tconst comparison = compareNumericIdentifier(left[index] ?? \"\", right[index] ?? \"\");\n\t\tif (comparison !== 0) return comparison < 0 ? -1 : 1;\n\t}\n\tif (left.length === right.length) return 0;\n\treturn left.length < right.length ? -1 : 1;\n}\n/**\n* SemVer 2.0.0 precedence (section 11): build metadata is ignored, a prerelease ranks below its\n* release, numeric identifiers rank below alphanumeric ones, and a shorter prerelease set ranks\n* below a longer one when every shared identifier is equal.\n*/\nfunction compareSemVer(leftInput, rightInput) {\n\tconst left = requireSemVer(leftInput);\n\tconst right = requireSemVer(rightInput);\n\tconst core = compareCore(left, right);\n\treturn core === 0 ? comparePrerelease(left.prerelease, right.prerelease) : core;\n}\n//#endregion\n//#region src/computer.ts\nconst ComputerPlatformSchema = z.enum([\n\t\"darwin\",\n\t\"linux\",\n\t\"win32\"\n]);\nconst ComputerKindSchema = z.enum([\"local\", \"cloud\"]);\nconst ComputerConnectionStatusSchema = z.enum([\"online\", \"offline\"]);\nconst ProviderReadinessStatusSchema = z.enum([\n\t\"checking\",\n\t\"install\",\n\t\"sign-in\",\n\t\"ready\",\n\t\"unavailable\"\n]);\nconst ImCliReadinessStatusSchema = z.enum([\n\t\"checking\",\n\t\"install\",\n\t\"ready\",\n\t\"unavailable\"\n]);\nconst IM_CLI_PROVIDERS = [\"feishu\", \"slack\"];\nconst ImCliProviderSchema = z.enum(IM_CLI_PROVIDERS);\nconst INTEGRATION_CREDENTIAL_EXECUTION_STATUSES = [\n\t\"unconfirmed\",\n\t\"checking\",\n\t\"retrying\",\n\t\"ready\",\n\t\"needs_attention\"\n];\nconst IntegrationCredentialExecutionStatusSchema = z.enum(INTEGRATION_CREDENTIAL_EXECUTION_STATUSES);\nconst INTEGRATION_CREDENTIAL_EXECUTION_REASONS = [\n\t\"provider_unreachable\",\n\t\"rate_limited\",\n\t\"credential_rejected\",\n\t\"identity_mismatch\",\n\t\"scope_missing\",\n\t\"upgrade_required\"\n];\nconst IntegrationCredentialExecutionReasonSchema = z.enum(INTEGRATION_CREDENTIAL_EXECUTION_REASONS);\nconst PROVIDER_CLI_VALIDATION_RETRY_REASONS = [\n\t\"validation_busy\",\n\t\"validation_expired\",\n\t\"artifact_changed\"\n];\nconst ProviderCliValidationRetryReasonSchema = z.enum(PROVIDER_CLI_VALIDATION_RETRY_REASONS);\nconst ProviderCliValidationResultReasonSchema = z.enum([...INTEGRATION_CREDENTIAL_EXECUTION_REASONS, ...PROVIDER_CLI_VALIDATION_RETRY_REASONS]);\n/** Allowlisted artifact failure reasons that may leave the machine. */\nconst PROVIDER_CLI_ARTIFACT_PUBLIC_REASONS = [\n\t\"unsupported_platform\",\n\t\"global_bin_unavailable\",\n\t\"integrity_failed\",\n\t\"version_incompatible\"\n];\nconst ProviderCliArtifactPublicReasonSchema = z.enum(PROVIDER_CLI_ARTIFACT_PUBLIC_REASONS);\nconst PROVIDER_CLI_PUBLIC_FAILURE_REASONS = [...INTEGRATION_CREDENTIAL_EXECUTION_REASONS, ...PROVIDER_CLI_ARTIFACT_PUBLIC_REASONS];\nconst ProviderCliPublicFailureReasonSchema = z.enum(PROVIDER_CLI_PUBLIC_FAILURE_REASONS);\nconst PROVIDER_READINESS_V1_HEADER = \"x-opentag-provider-readiness\";\nconst PROVIDER_READINESS_V2_HEADER = \"x-opentag-provider-readiness-v2\";\nconst PROVIDER_CLI_REASON_V2_HEADER = \"x-opentag-provider-cli-reason\";\n/** Independent of readiness v2: old Clients never see Cloud identity shapes. */\nconst CLOUD_IDENTITY_CAPABILITY_HEADER = \"x-opentag-cloud-identity\";\nconst CLOUD_IDENTITY_CAPABILITY_VERSION = \"1\";\nfunction requestsProviderCliReasonV2(value) {\n\treturn headerValueEquals(value, \"2\");\n}\nfunction requestsProviderReadinessV1(value) {\n\treturn headerValueEquals(value, \"1\");\n}\nfunction requestsProviderReadinessV2(value) {\n\treturn headerValueEquals(value, \"2\");\n}\nfunction requestsCloudIdentityV1(value) {\n\treturn headerValueEquals(value, \"1\");\n}\nfunction headerValueEquals(value, expected) {\n\treturn (Array.isArray(value) ? value[0] : value) === expected;\n}\nconst PROVIDER_CLI_ALWAYS_MANUAL_ARTIFACT_REASONS = /* @__PURE__ */ new Set([\n\t\"unsupported_platform\",\n\t\"global_bin_unavailable\",\n\t\"integrity_failed\"\n]);\n/** Map a local diagnostic code onto the public artifact allowlist. Unknown codes stay unpublished. */\nfunction publicProviderCliArtifactReason(code) {\n\tif (code === \"unsupported_platform\" || code === \"global_bin_unavailable\" || code === \"integrity_failed\" || code === \"version_incompatible\") return code;\n}\n/**\n* Manual failures need a user or release change. `version_incompatible` is manual only after a\n* final ensure: an inspection may still be repaired by installing a supported managed artifact.\n*/\nfunction providerCliArtifactFailureIsManual(input) {\n\tif (!input.reason) return false;\n\tif (PROVIDER_CLI_ALWAYS_MANUAL_ARTIFACT_REASONS.has(input.reason)) return true;\n\treturn input.reason === \"version_incompatible\" && input.stage === \"ensure\";\n}\n/** Shared Client/Server/Web/Agent classification for one Provider CLI artifact failure. */\nfunction classifyProviderCliArtifactFailure(input) {\n\tconst publicReason = publicProviderCliArtifactReason(input.reason);\n\tconst manual = providerCliArtifactFailureIsManual({\n\t\treason: input.reason,\n\t\tstage: input.stage\n\t});\n\treturn {\n\t\t...publicReason ? { publicReason } : {},\n\t\tmanual\n\t};\n}\nconst ComputerConnectCodeModeSchema = z.enum([\"create\", \"repair\"]);\n/**\n* Exchange identifies the local installation, not an existing Computer. The Server decides create vs\n* repair only from the one-time code: create always allocates a new Computer, and repair names its\n* target Computer when the code is issued.\n*/\nconst ComputerConnectCodeExchangeRequestSchema = z.object({\n\tcode: z.string().trim().min(16).max(512),\n\tinstallationId: z.string().uuid(),\n\tdisplayName: z.string().trim().min(1).max(255),\n\tplatform: ComputerPlatformSchema,\n\tarch: z.string().trim().min(1).max(64),\n\tclientVersion: z.string().trim().min(1).max(64)\n}).strict();\nconst ComputerConnectCodeExchangeResponseSchema = z.object({\n\t/** Present when this setup code atomically bound an explicit Agent to the connected Computer. */\n\tagentId: z.string().uuid().optional(),\n\t/**\n\t* The exact Runtime of the bound Agent, answered only to Clients that marked themselves with\n\t* {@link clientSupportsComputerRuntimeProvider} support. Unmarked Clients keep the strict legacy\n\t* response shape, and `agentId`-only responses stay parseable for a marked Client talking to an\n\t* older Server.\n\t*/\n\truntimeProvider: AgentRuntimeProviderSchema.optional(),\n\tcomputerId: z.string().uuid(),\n\tinstallationId: z.string().uuid(),\n\tmachineToken: z.string().min(1).max(4096)\n}).strict().superRefine((response, context) => {\n\tif (response.runtimeProvider !== void 0 && response.agentId === void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"runtimeProvider\"],\n\t\tmessage: \"runtimeProvider is only meaningful next to the bound agentId it describes\"\n\t});\n});\n/**\n* The SemVer build-metadata identifier a Client appends to its own version to advertise that it\n* understands the targeted connect exchange `runtimeProvider` field. It never changes precedence\n* (SemVer build metadata is ignored by `compareSemVer`) and it never raises the release floor: the\n* Server answers the field only to Clients that carry this exact marker, so an unmarked legacy\n* Client keeps receiving the response shape its own strict parser knows.\n*/\nconst COMPUTER_RUNTIME_PROVIDER_CAPABILITY = \"opentag-connect-runtime-v1\";\nconst COMPUTER_CLIENT_VERSION_MAX_LENGTH = 64;\n/**\n* Marks a Client version as supporting the targeted connect exchange `runtimeProvider` by appending\n* {@link COMPUTER_RUNTIME_PROVIDER_CAPABILITY} as SemVer build metadata. Existing prerelease and\n* build identifiers are preserved; applying the marker twice is a no-op. Invalid SemVer input and\n* any version whose marked result would exceed the 64-character Client version bound are rejected\n* before a caller could send them over the wire.\n*/\nfunction withComputerRuntimeProviderSupport(version) {\n\tconst parsed = parseSemVer(version);\n\tif (!parsed) throw new TypeError(`Cannot mark an invalid SemVer Client version: ${JSON.stringify(version)}`);\n\tconst result = parsed.build.includes(\"opentag-connect-runtime-v1\") ? version : `${version}${parsed.build.length > 0 ? \".\" : \"+\"}${COMPUTER_RUNTIME_PROVIDER_CAPABILITY}`;\n\tif (result.length > COMPUTER_CLIENT_VERSION_MAX_LENGTH) throw new TypeError(`Marked Client version exceeds ${COMPUTER_CLIENT_VERSION_MAX_LENGTH} characters: ${JSON.stringify(result)}`);\n\treturn result;\n}\n/**\n* Fail-closed recognizer for the {@link COMPUTER_RUNTIME_PROVIDER_CAPABILITY} marker: true only for a\n* strict, at-most-64-character SemVer version whose build metadata carries the exact capability\n* identifier. Invalid or overlong versions, unmarked versions, and unknown or lookalike markers\n* (wrong casing, wrong suffix, the marker smuggled into prerelease position) all answer false.\n*/\nfunction clientSupportsComputerRuntimeProvider(version) {\n\tif (version.length > COMPUTER_CLIENT_VERSION_MAX_LENGTH) return false;\n\treturn parseSemVer(version)?.build.includes(\"opentag-connect-runtime-v1\") ?? false;\n}\n/** Empty body and `{ mode: \"create\" }` both issue a create code. */\nconst AccountComputerConnectCodeCreateRequestSchema = z.object({\n\tmode: z.literal(\"create\").optional(),\n\t/** Optional setup target. The Server embeds it into the opaque code and binds it at redemption. */\n\ttargetAgentId: z.string().uuid().optional()\n}).strict();\n/** Repair is Account-authorized and must name an explicit Computer owned by that Account. */\nconst AccountComputerConnectCodeRepairRequestSchema = z.object({\n\tmode: z.literal(\"repair\"),\n\ttargetComputerId: z.string().uuid(),\n\t/** When supplied, the Agent must already be bound to the repaired Computer. */\n\ttargetAgentId: z.string().uuid().optional()\n}).strict();\n/**\n* The Account-native connect-code request carries no client-selected authority: the issuing Account comes\n* from the access token alone. Repair names its target Computer; create never infers one.\n*/\nconst AccountComputerConnectCodeIssueRequestSchema = z.union([AccountComputerConnectCodeCreateRequestSchema, AccountComputerConnectCodeRepairRequestSchema]);\nconst ComputerConnectCodeIssueResponseSchema = z.object({\n\t/**\n\t* The Server's own handle on the issued code row. Opaque and non-secret: it names the code for the\n\t* pollable status read and is worthless at the exchange, which still requires the code itself.\n\t*/\n\tconnectCodeId: z.string().uuid(),\n\tbootstrapCommand: z.string().min(1),\n\texpiresIn: z.number().int().positive(),\n\tissuedAt: z.string().datetime(),\n\tmode: ComputerConnectCodeModeSchema.optional()\n}).strict();\n/**\n* The lifecycle of one issued connect code as the issuing Account may observe it. `pending` means\n* nobody has redeemed it yet; `redeemed` names the exact Computer that did. `expired` and `revoked`\n* fail closed: the read keeps answering, but it never names a Computer for them.\n*/\nconst ComputerConnectCodeStateSchema = z.enum([\n\t\"pending\",\n\t\"redeemed\",\n\t\"expired\",\n\t\"revoked\"\n]);\n/**\n* The Server-authoritative correlation between a connect code and the Computer that redeemed it.\n* Carries identity and timing evidence only — never the raw code, its hash, or any machine token.\n* `computerId` and `redeemedAt` are present exactly in the `redeemed` state.\n*/\nconst ComputerConnectCodeTerminalStatusFields = {\n\tconnectCodeId: z.string().uuid(),\n\tcomputerId: z.null(),\n\tredeemedAt: z.null()\n};\nconst ComputerConnectCodeStatusSchema = z.discriminatedUnion(\"state\", [\n\tz.object({\n\t\t...ComputerConnectCodeTerminalStatusFields,\n\t\tstate: z.literal(\"pending\")\n\t}).strict(),\n\tz.object({\n\t\t...ComputerConnectCodeTerminalStatusFields,\n\t\tstate: z.literal(\"expired\")\n\t}).strict(),\n\tz.object({\n\t\t...ComputerConnectCodeTerminalStatusFields,\n\t\tstate: z.literal(\"revoked\")\n\t}).strict(),\n\tz.object({\n\t\tconnectCodeId: z.string().uuid(),\n\t\tstate: z.literal(\"redeemed\"),\n\t\tcomputerId: z.string().uuid(),\n\t\tredeemedAt: z.string().datetime()\n\t}).strict()\n]);\nconst ComputerProviderReadinessSchema = z.object({\n\tprovider: AgentRuntimeProviderSchema,\n\tstatus: ProviderReadinessStatusSchema,\n\tobservedAt: z.string().datetime().nullable()\n}).strict();\nconst ComputerProviderReadinessCollectionSchema = z.array(ComputerProviderReadinessSchema).max(AGENT_RUNTIME_PROVIDERS.length).superRefine((observations, context) => {\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const [index, observation] of observations.entries()) {\n\t\tif (seen.has(observation.provider)) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [index, \"provider\"],\n\t\t\tmessage: \"Provider readiness must be unique\"\n\t\t});\n\t\tseen.add(observation.provider);\n\t\tif (index > 0 && AGENT_RUNTIME_PROVIDERS.indexOf(observation.provider) < AGENT_RUNTIME_PROVIDERS.indexOf(observations[index - 1]?.provider ?? \"codex\")) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [index, \"provider\"],\n\t\t\tmessage: \"Provider readiness must use canonical Provider order\"\n\t\t});\n\t}\n});\nconst ComputerImCliReadinessSchema = z.object({\n\tprovider: ImCliProviderSchema,\n\tstatus: ImCliReadinessStatusSchema,\n\tobservedAt: z.string().datetime().nullable(),\n\treason: ProviderCliArtifactPublicReasonSchema.optional()\n}).strict();\nconst ComputerImCliReadinessCollectionSchema = z.array(ComputerImCliReadinessSchema).max(IM_CLI_PROVIDERS.length).superRefine((observations, context) => {\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const [index, observation] of observations.entries()) {\n\t\tif (seen.has(observation.provider)) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [index, \"provider\"],\n\t\t\tmessage: \"IM CLI readiness must be unique\"\n\t\t});\n\t\tseen.add(observation.provider);\n\t\tif (index > 0 && IM_CLI_PROVIDERS.indexOf(observation.provider) < IM_CLI_PROVIDERS.indexOf(observations[index - 1]?.provider ?? \"feishu\")) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [index, \"provider\"],\n\t\t\tmessage: \"IM CLI readiness must use canonical Provider order\"\n\t\t});\n\t}\n});\n/**\n* Local computer preparation vocabulary. A single `connect`/`repair` run reports one Result whose\n* Components mirror the plan the run executed: the Computer itself, the targeted Runtime CLI\n* (`runtime:codex`, `runtime:claude-code`, `runtime:pi`, or `runtime:unconfirmed` when the Server did not name\n* one), and the Provider CLIs (`im-cli:lark`, `im-cli:slack`). Components may carry child Checks\n* (for example the Computer's credential and daemon) with bounded ids of their own.\n*\n* This is local proof rendered from one run only: it is never persisted and never becomes a Server\n* stage. The Server has no counterpart state machine, so the schema enforces internal consistency\n* rather than deriving verdicts: duplicate top-level component ids, counts that do not match the\n* reported components, and `ready` claims that conceal a required or blocking non-ready child Check\n* are all invalid. A non-blocking warning (`blocking: false` only) never overrides `ready`.\n*/\nconst LocalPreparationStatusSchema = z.enum([\n\t\"waiting\",\n\t\"checking\",\n\t\"install_required\",\n\t\"installing\",\n\t\"ready\",\n\t\"needs_attention\",\n\t\"unavailable\",\n\t\"stale\",\n\t\"skipped\"\n]);\nconst LocalPreparationActionSchema = z.object({\n\t/** Shell command the user may run to repair or verify. */\n\tcommand: z.string().trim().min(1).max(16384).optional(),\n\t/** Human-readable step the user should take when no single command captures it. */\n\tinstruction: z.string().trim().min(1).max(512).optional()\n}).strict().refine((action) => action.command !== void 0 || action.instruction !== void 0, { message: \"A local preparation action must provide a command or an instruction\" });\nconst LocalPreparationWarningSchema = z.object({\n\tcode: z.string().trim().min(1).max(64),\n\tmessage: z.string().trim().min(1).max(512).optional(),\n\t/** Warnings never block: `blocking` is fixed false so no warning can override a ready verdict. */\n\tblocking: z.literal(false)\n}).strict();\nconst LocalPreparationCheckFieldsSchema = z.object({\n\tid: z.string().trim().min(1).max(64),\n\tlabel: z.string().trim().min(1).max(200),\n\t/** A required Check must reach `ready` before its Component may claim readiness. */\n\trequired: z.boolean(),\n\tstatus: LocalPreparationStatusSchema,\n\t/** Currently blocking, not merely a gate: a ready Check must be unblocked. */\n\tblocking: z.boolean(),\n\tphase: z.string().trim().min(1).max(64).optional(),\n\tmessage: z.string().trim().min(1).max(512).optional(),\n\tversion: z.string().trim().min(1).max(64).optional(),\n\tobservedAt: z.string().datetime().optional(),\n\tdiagnosticCode: z.string().trim().min(1).max(64).optional(),\n\tnextAction: LocalPreparationActionSchema.optional(),\n\tverifyAction: LocalPreparationActionSchema.optional(),\n\twarnings: z.array(LocalPreparationWarningSchema).optional()\n}).strict();\nconst LocalPreparationCheckSchema = LocalPreparationCheckFieldsSchema.refine((check) => check.status !== \"ready\" || !check.blocking, {\n\tpath: [\"blocking\"],\n\tmessage: \"A ready Check cannot be blocking\"\n});\nconst LocalPreparationComponentSchema = LocalPreparationCheckFieldsSchema.extend({ \n/** Child Checks (for example credential and daemon under the Computer component). */\nchecks: z.array(LocalPreparationCheckSchema).optional() }).strict().refine((component) => component.status !== \"ready\" || !component.blocking, {\n\tpath: [\"blocking\"],\n\tmessage: \"A ready Component cannot be blocking\"\n});\nconst LocalComputerPreparationResultSchema = z.object({\n\t/** Human projection of `localReady`: `ready` exactly when every required Component is. */\n\tstatus: z.enum([\"ready\", \"needs_attention\"]),\n\tcomponents: z.array(LocalPreparationComponentSchema).min(1),\n\treadyCount: z.number().int().nonnegative(),\n\trequiredCount: z.number().int().nonnegative(),\n\tlocalReady: z.boolean()\n}).strict().superRefine((result, context) => {\n\tfor (const issue of assessLocalPreparation(result)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: issue.path,\n\t\tmessage: issue.message\n\t});\n});\n/**\n* The gate Checks of one Component: children that are required or blocking and have not reached\n* `ready` (including deliberate `skipped` states such as a `--no-start` daemon). A Component that\n* reports `ready` while any of them is non-ready would conceal a repair need.\n*/\nfunction concealedGateCheckIds(component) {\n\treturn (component.checks ?? []).flatMap((check) => check.blocking || check.required && check.status !== \"ready\" ? [check.id] : []);\n}\nfunction readyComponentIssue(component, concealed, index) {\n\tif (component.status !== \"ready\" || concealed.length === 0) return void 0;\n\treturn {\n\t\tpath: [\n\t\t\t\"components\",\n\t\t\tindex,\n\t\t\t\"status\"\n\t\t],\n\t\tmessage: `A ready Component cannot conceal non-ready required/blocking Checks: ${concealed.join(\", \")}`\n\t};\n}\nfunction assessLocalPreparation(result) {\n\tconst issues = [];\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst summaries = result.components.map((component, index) => ({\n\t\tcomponent,\n\t\tindex,\n\t\tconcealed: concealedGateCheckIds(component)\n\t}));\n\tfor (const summary of summaries) {\n\t\tconst { component, concealed, index } = summary;\n\t\tif (seen.has(component.id)) issues.push({\n\t\t\tpath: [\n\t\t\t\t\"components\",\n\t\t\t\tindex,\n\t\t\t\t\"id\"\n\t\t\t],\n\t\t\tmessage: \"Component ids must be unique\"\n\t\t});\n\t\tseen.add(component.id);\n\t\tconst readyIssue = readyComponentIssue(component, concealed, index);\n\t\tif (readyIssue) issues.push(readyIssue);\n\t}\n\tconst ready = (summary) => summary.component.status === \"ready\" && !summary.component.blocking && summary.concealed.length === 0;\n\tconst requiredCount = summaries.filter((summary) => summary.component.required).length;\n\tconst readyCount = summaries.filter((summary) => summary.component.required && ready(summary)).length;\n\tconst allRequiredReady = requiredCount === readyCount;\n\tif (requiredCount !== result.requiredCount) issues.push({\n\t\tpath: [\"requiredCount\"],\n\t\tmessage: `requiredCount must match the ${requiredCount} required Component(s)`\n\t});\n\tif (readyCount !== result.readyCount) issues.push({\n\t\tpath: [\"readyCount\"],\n\t\tmessage: `readyCount must match the ${readyCount} ready Component(s)`\n\t});\n\tif (result.localReady !== allRequiredReady) issues.push({\n\t\tpath: [\"localReady\"],\n\t\tmessage: allRequiredReady ? \"localReady must be true when every required Component is ready and unblocked\" : \"localReady must be false while a required Component is not ready or unblocked\"\n\t});\n\tconst expectedStatus = allRequiredReady ? \"ready\" : \"needs_attention\";\n\tif (result.status !== expectedStatus) issues.push({\n\t\tpath: [\"status\"],\n\t\tmessage: `status must be ${expectedStatus} for the reported required Components`\n\t});\n\treturn issues;\n}\n//#endregion\n//#region src/account.ts\n/** Opt-in inventory retains explicitly disconnected Computers; legacy callers see active access only. */\nconst COMPUTER_ACCESS_CAPABILITY_HEADER = \"x-opentag-computer-access\";\nconst CompleteAccountSetupRequestSchema = z.object({ agentId: z.string().uuid() }).strict();\nconst AccountSetupCompletionSchema = z.object({ setupCompletedAt: z.string().datetime() }).strict();\n/** How much of the authenticated Account to reset before onboarding is walked again. */\nconst AccountSetupResetModeSchema = z.enum([\"all\", \"reboard\"]);\nconst AccountSetupResetRequestSchema = z.object({ mode: AccountSetupResetModeSchema }).strict();\n/** Staging-wide visibility for product areas that are not ready for public navigation. */\nconst InternalNavigationVisibilitySchema = z.object({ integrations: z.boolean() }).strict();\nconst AccountComputerSummarySchema = z.object({\n\tcomputerId: z.string().uuid(),\n\t/** Present only for explicitly Cloud-capable callers; absent from legacy Local responses. */\n\tkind: ComputerKindSchema.optional(),\n\tdisplayName: z.string().min(1),\n\tplatform: ComputerPlatformSchema,\n\tconnectionStatus: z.enum([\n\t\t\"online\",\n\t\t\"offline\",\n\t\t\"disconnected\"\n\t]),\n\tproviderReadiness: ComputerProviderReadinessCollectionSchema.optional(),\n\timCliReadiness: ComputerImCliReadinessCollectionSchema.optional(),\n\tconnectedAt: z.string().datetime().nullable(),\n\tlastSeenAt: z.string().datetime().nullable(),\n\tobservedAt: z.string().datetime(),\n\tcreatedAt: z.string().datetime(),\n\tagentIds: z.array(z.string().uuid())\n}).strict();\nconst ListAccountComputersResponseSchema = z.object({ computers: z.array(AccountComputerSummarySchema) }).strict();\n/**\n* Dedicated Cloud Computer ensure body. `kind` is required here without changing the Local list DTO.\n* `connectionStatus` is logical online of the Cloud identity, not daemon heartbeat evidence and not\n* Sandbox allocation or Pi execution readiness.\n*/\nconst AccountCloudComputerEnsureResponseSchema = z.object({\n\tcomputerId: z.string().uuid(),\n\tkind: z.literal(\"cloud\"),\n\tdisplayName: z.string().min(1),\n\tplatform: ComputerPlatformSchema,\n\tconnectionStatus: z.literal(\"online\"),\n\tcreatedAt: z.string().datetime()\n}).strict();\n//#endregion\n//#region src/im-message.ts\nconst ImConversationKindSchema = z.enum([\n\t\"channel\",\n\t\"dm\",\n\t\"group_dm\"\n]);\nconst NormalizedImConversationKindSchema = z.union([ImConversationKindSchema, z.literal(\"unknown\")]);\nconst ImMessageOperationSchema = z.enum([\n\t\"created\",\n\t\"edited\",\n\t\"deleted\"\n]);\nconst ImMessageDirectionSchema = z.enum([\"inbound\", \"outbound\"]);\nconst ImAuthorKindSchema = z.enum([\n\t\"human\",\n\t\"bot\",\n\t\"system\"\n]);\nconst ImAttentionSchema = z.enum([\"direct\", \"ambient\"]);\nconst ProviderInboundContextSchema = z.discriminatedUnion(\"provider\", [z.object({\n\tprovider: z.literal(\"feishu\"),\n\tchatType: z.string().min(1).max(160).optional(),\n\tthreadId: z.string().min(1).max(512).optional(),\n\trootId: z.string().min(1).max(512).optional(),\n\tparentId: z.string().min(1).max(512).optional()\n}).strict(), z.object({\n\tprovider: z.literal(\"slack\"),\n\tchannelType: z.string().min(1).max(160).optional(),\n\tthreadTs: z.string().min(1).max(512).optional()\n}).strict()]);\nconst ImResourceDescriptorSchema = z.object({\n\tproviderResourceKey: z.string().min(1).max(2048),\n\tkind: z.enum([\n\t\t\"image\",\n\t\t\"file\",\n\t\t\"audio\",\n\t\t\"video\"\n\t]),\n\tfilename: z.string().max(512).nullable(),\n\tmediaType: z.string().max(255).nullable(),\n\tsizeBytes: z.number().int().nonnegative().safe().nullable(),\n\tordinal: z.number().int().min(0).max(15).optional(),\n\tavailability: z.enum([\n\t\t\"available\",\n\t\t\"unavailable\",\n\t\t\"too_large\",\n\t\t\"unsupported\"\n\t]).optional()\n}).strict();\nconst ImTextBlockSchema = z.object({\n\ttype: z.literal(\"text\"),\n\ttext: z.string().max(65536)\n}).strict();\nconst ImMentionBlockSchema = z.object({\n\ttype: z.literal(\"mention\"),\n\texternalId: z.string().min(1).max(255),\n\tlabel: z.string().max(512)\n}).strict();\nconst ImLinkBlockSchema = z.object({\n\ttype: z.literal(\"link\"),\n\turl: z.string().url(),\n\tlabel: z.string().max(2048)\n}).strict();\nconst ImCodeBlockSchema = z.object({\n\ttype: z.literal(\"code\"),\n\tlanguage: z.string().max(80).nullable(),\n\ttext: z.string().max(65536)\n}).strict();\nconst ImQuoteBlockSchema = z.object({\n\ttype: z.literal(\"quote\"),\n\ttext: z.string().max(65536)\n}).strict();\nconst ImResourceBlockSchema = z.object({\n\ttype: z.enum([\"image\", \"file\"]),\n\tresourceOrdinal: z.number().int().min(0).max(15),\n\tlabel: z.string().max(512)\n}).strict();\nconst ImUnsupportedBlockSchema = z.object({\n\ttype: z.literal(\"unsupported\"),\n\tproviderType: z.string().min(1).max(160)\n}).strict();\n/**\n* Optional metadata present only on captured OUTBOUND messages (a confirmed send the Server\n* observed through the provider proxy). Inbound rows never carry it, and older stored content\n* simply omits it; both read back unchanged.\n*/\nconst ImOutboundContentMetaSchema = z.object({\n\t/** Native message type the platform reported (Feishu msg_type, Slack message subtype/type). */\n\tmessageType: z.string().min(1).max(160).optional(),\n\t/**\n\t* False when the platform response carried no usable body. The record still proves the send;\n\t* the body is honestly reported as unavailable rather than reconstructed from the request.\n\t*/\n\tcontentAvailable: z.boolean(),\n\t/** `provider` when occurred_at is the platform's send time, `observed` when it is the capture time. */\n\ttimeSource: z.enum([\"provider\", \"observed\"])\n}).strict();\nconst ImContentBlockSchema = z.discriminatedUnion(\"type\", [\n\tImTextBlockSchema,\n\tImMentionBlockSchema,\n\tImLinkBlockSchema,\n\tImCodeBlockSchema,\n\tImQuoteBlockSchema,\n\tImResourceBlockSchema,\n\tImUnsupportedBlockSchema\n]);\nconst ImContentV1Schema = z.object({\n\tversion: z.literal(1),\n\tfallbackText: z.string().max(65536),\n\tblocks: z.array(ImContentBlockSchema).max(512),\n\tresources: z.array(ImResourceDescriptorSchema).max(16).optional(),\n\ttruncated: z.boolean().default(false),\n\toutbound: ImOutboundContentMetaSchema.optional()\n}).strict().superRefine((value, context) => {\n\tif (new TextEncoder().encode(JSON.stringify(value)).byteLength > 262144) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"Canonical IM content exceeds 256 KiB\"\n\t});\n});\nconst ExternalMentionSchema = z.object({\n\texternalId: z.string().min(1).max(255),\n\tdisplayName: z.string().max(512).nullable()\n}).strict();\nconst NormalizedInboundImEventSchema = z.object({\n\tproviderEventId: z.string().min(1).max(512),\n\texternalAppId: z.string().min(1).max(255),\n\texternalTeamId: z.string().min(1).max(255),\n\tproviderContext: ProviderInboundContextSchema,\n\tconversation: z.object({\n\t\texternalId: z.string().min(1).max(512),\n\t\tkind: NormalizedImConversationKindSchema,\n\t\tdisplayName: z.string().max(512).nullable().optional()\n\t}).strict(),\n\tmessage: z.object({\n\t\texternalId: z.string().min(1).max(512),\n\t\trevisionKey: z.string().min(1).max(512),\n\t\toperation: ImMessageOperationSchema,\n\t\tthreadKey: z.string().min(1).max(512).nullable().optional(),\n\t\treplyToExternalId: z.string().min(1).max(512).nullable().optional(),\n\t\tauthor: z.object({\n\t\t\texternalId: z.string().min(1).max(255),\n\t\t\tkind: ImAuthorKindSchema,\n\t\t\tdisplayName: z.string().max(512).nullable().optional(),\n\t\t\tisSelf: z.boolean().optional()\n\t\t}).strict(),\n\t\toccurredAt: z.coerce.date(),\n\t\tcontent: ImContentV1Schema,\n\t\tresources: z.array(ImResourceDescriptorSchema).max(16)\n\t}).strict(),\n\tmentions: z.array(ExternalMentionSchema).max(256)\n}).strict();\n//#endregion\n//#region src/sandbox.ts\nconst SandboxLifecycleSchema = z.enum([\n\t\"unallocated\",\n\t\"preparing\",\n\t\"ready\",\n\t\"releasing\"\n]);\nconst AccountSandboxEnsureScopeSchema = {\n\timBindingId: z.string().uuid(),\n\tchannelId: z.string().min(1).max(512),\n\tconversationKind: ImConversationKindSchema\n};\n/**\n* Account-owned Sandbox ensure input. Session identity is derived from an existing owned IM binding\n* plus channel/thread scope; `internal` Sessions are out of scope. `threadKey` is required for\n* thread Sessions and forbidden for channel Sessions.\n*/\nconst AccountSandboxEnsureRequestSchema = z.discriminatedUnion(\"kind\", [z.object({\n\t...AccountSandboxEnsureScopeSchema,\n\tkind: z.literal(\"channel\")\n}).strict(), z.object({\n\t...AccountSandboxEnsureScopeSchema,\n\tkind: z.literal(\"thread\"),\n\tthreadKey: z.string().min(1).max(512)\n}).strict()]);\n/**\n* Durable Sandbox identity as an Account may read it. Resource fields are null while unallocated;\n* a later phase may still report a resource name/UID until removal is verified. This is not\n* evidence that compute is allocated or that Pi can execute.\n*/\nconst AccountSandboxResponseSchema = z.object({\n\tsandboxId: z.string().uuid(),\n\tsessionId: z.string().uuid(),\n\tcomputerId: z.string().uuid(),\n\tstorageUri: z.string().min(1).max(2048),\n\tlifecycle: SandboxLifecycleSchema,\n\tenvironmentGeneration: z.number().int().nonnegative(),\n\tcurrentResourceName: z.string().min(1).max(1024).nullable(),\n\tcurrentResourceUid: z.string().min(1).max(128).nullable(),\n\tcurrentOperationName: z.string().min(1).max(1024).nullable(),\n\tcreatedAt: z.string().datetime(),\n\tupdatedAt: z.string().datetime()\n}).strict();\n//#endregion\n//#region src/session.ts\nconst SessionKindSchema = z.enum([\n\t\"channel\",\n\t\"thread\",\n\t\"internal\"\n]);\nconst SessionSchema = z.object({\n\tid: z.string().uuid(),\n\timBindingId: z.string().uuid(),\n\tchannelId: z.string().min(1).max(512),\n\tconversationKind: z.enum([\n\t\t\"channel\",\n\t\t\"dm\",\n\t\t\"group_dm\"\n\t]),\n\tkind: SessionKindSchema,\n\tthreadKey: z.string().min(1).max(512).nullable(),\n\tcreatedBySessionId: z.string().uuid().nullable(),\n\truntimeModel: RuntimeModelSchema.nullable(),\n\truntimeReasoningEffort: RuntimeReasoningEffortSchema.nullable(),\n\truntimeMaxDurationMs: RuntimeMaxDurationMsSchema.nullable(),\n\tendedAt: z.string().datetime().nullable(),\n\trevision: z.number().int().min(1),\n\tcreatedAt: z.string().datetime()\n}).strict();\nconst SessionPlacementSchema = z.object({\n\tsessionId: z.string().uuid(),\n\tcomputerId: z.string().uuid(),\n\tgeneration: z.number().int().min(1),\n\tupdatedAt: z.string().datetime()\n}).strict();\n//#endregion\n//#region src/cloud-product.ts\n/** Deployment configuration, not evidence that an Instance is already running. */\nconst CloudAvailabilitySchema = z.object({\n\tenabled: z.boolean(),\n\tavailable: z.boolean(),\n\treason: z.enum([\n\t\t\"disabled\",\n\t\t\"execution_unavailable\",\n\t\t\"model_unavailable\"\n\t]).nullable(),\n\tobservedAt: z.string().datetime()\n}).strict();\n/**\n* Upper bound on the Router-offered model list the Server relays. The Server-side catalog applies\n* the same bound before caching, so a response larger than this can never be published.\n*/\nconst CLOUD_MODEL_OPTIONS_MAX_MODELS = 256;\n/**\n* The Cloud model choices the account surface offers, sourced ONLY from the deployment Router's\n* authenticated model list (`GET {upstreamBaseUrl}/models`): the Router already applies tenant\n* permissions and the priced registry, and no Server-side static list restricts or extends it.\n* The default an Agent without an explicit model executes with is the FIRST Router model. The\n* shape is coherent by construction: `available: false` always pairs with an empty list and a\n* null default, and an available list is non-empty with the default as its first entry.\n*/\nconst CloudModelOptionsSchema = z.object({\n\tavailable: z.boolean(),\n\tmodels: z.array(RuntimeModelSchema).max(256),\n\tdefaultModel: RuntimeModelSchema.nullable()\n}).strict().superRefine((value, context) => {\n\tif (!value.available) {\n\t\tif (value.models.length !== 0 || value.defaultModel !== null) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"An unavailable Cloud model list carries no models and no default\"\n\t\t});\n\t\treturn;\n\t}\n\tif (value.models.length === 0 || value.defaultModel !== value.models[0]) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"An available Cloud model list is non-empty and defaults to its first model\"\n\t});\n});\nconst CloudSessionSummarySchema = z.object({\n\tsessionId: z.string().uuid(),\n\tsandboxId: z.string().uuid(),\n\tkind: SessionKindSchema,\n\tlifecycle: SandboxLifecycleSchema,\n\tenvironmentGeneration: z.number().int().nonnegative().safe(),\n\trunnerConnected: z.boolean(),\n\trunnerReady: z.boolean(),\n\ttaskState: z.enum([\n\t\t\"idle\",\n\t\t\"queued\",\n\t\t\"running\",\n\t\t\"unknown\"\n\t]),\n\tlastErrorCode: z.string().max(128).nullable(),\n\tlastErrorAt: z.string().datetime().nullable(),\n\tupdatedAt: z.string().datetime(),\n\tcanRelease: z.boolean(),\n\tcanDiscard: z.boolean()\n}).strict();\nconst AgentCloudOverviewSchema = z.object({\n\tagentId: z.string().uuid(),\n\tobservedAt: z.string().datetime(),\n\tcapacity: z.object({\n\t\taccountUsed: z.number().int().nonnegative().safe(),\n\t\taccountLimit: z.number().int().positive().safe()\n\t}).strict(),\n\tcounts: z.object({\n\t\tallocated: z.number().int().nonnegative().safe(),\n\t\tqueued: z.number().int().nonnegative().safe(),\n\t\trunning: z.number().int().nonnegative().safe(),\n\t\tattention: z.number().int().nonnegative().safe()\n\t}).strict(),\n\tsessions: z.array(CloudSessionSummarySchema).max(100),\n\tnextCursor: z.string().uuid().nullable()\n}).strict();\nconst AgentCloudOverviewQuerySchema = z.object({\n\tcursor: z.string().uuid().optional(),\n\tsessionId: z.string().uuid().optional(),\n\tlimit: z.coerce.number().int().min(1).max(100).default(20)\n}).strict().refine((value) => !value.cursor || !value.sessionId, { message: \"A Session filter cannot be combined with a cursor\" });\n//#endregion\n//#region src/im-binding.ts\nconst ImProviderSchema = z.enum([\"feishu\", \"slack\"]);\nconst ImBindingStateSchema = z.enum([\n\t\"provisioning\",\n\t\"active\",\n\t\"reauthorization_required\",\n\t\"error\",\n\t\"disabled\"\n]);\nconst FEISHU_REQUIRED_TENANT_SCOPES = [\n\t\"im:message\",\n\t\"im:message:send_as_bot\",\n\t\"im:message.group_at_msg:readonly\",\n\t\"im:message.group_msg\",\n\t\"im:message.p2p_msg:readonly\",\n\t\"im:chat.members:read\",\n\t\"im:chat:readonly\",\n\t\"im:message:readonly\",\n\t\"im:message.reactions:read\",\n\t\"im:message.reactions:write_only\",\n\t\"im:resource\",\n\t\"contact:user.id:readonly\",\n\t\"docx:document:create\",\n\t\"docx:document:readonly\",\n\t\"docx:document:write_only\",\n\t\"docs:document.media:upload\",\n\t\"docs:document.media:download\",\n\t\"docs:permission.member:create\",\n\t\"docs:permission.member:retrieve\",\n\t\"docs:permission.member:update\",\n\t\"drive:drive.metadata:readonly\",\n\t\"drive:file:upload\",\n\t\"drive:file:download\",\n\t\"space:document:delete\",\n\t\"space:folder:create\",\n\t\"wiki:wiki\",\n\t\"sheets:spreadsheet:create\",\n\t\"sheets:spreadsheet:read\",\n\t\"sheets:spreadsheet:write_only\",\n\t\"sheets:spreadsheet.meta:read\",\n\t\"base:app:create\",\n\t\"base:app:read\",\n\t\"base:app:update\",\n\t\"base:table:create\",\n\t\"base:table:read\",\n\t\"base:table:update\",\n\t\"base:table:delete\",\n\t\"base:field:create\",\n\t\"base:field:read\",\n\t\"base:field:update\",\n\t\"base:field:delete\",\n\t\"base:record:create\",\n\t\"base:record:read\",\n\t\"base:record:retrieve\",\n\t\"base:record:update\",\n\t\"base:record:delete\",\n\t\"base:view:read\",\n\t\"base:view:write_only\",\n\t\"calendar:calendar:create\",\n\t\"calendar:calendar:read\",\n\t\"calendar:calendar:update\",\n\t\"calendar:calendar:delete\",\n\t\"calendar:calendar.event:create\",\n\t\"calendar:calendar.event:read\",\n\t\"calendar:calendar.event:update\",\n\t\"calendar:calendar.event:delete\",\n\t\"calendar:calendar.event:reply\",\n\t\"calendar:calendar.free_busy:read\",\n\t\"task:task:read\",\n\t\"task:task:write\",\n\t\"task:tasklist:read\",\n\t\"task:tasklist:write\",\n\t\"task:comment:read\",\n\t\"task:comment:write\",\n\t\"task:attachment:read\",\n\t\"task:attachment:write\"\n];\nfunction hasRequiredFeishuTenantScopes(scopes) {\n\tconst granted = new Set(scopes);\n\treturn FEISHU_REQUIRED_TENANT_SCOPES.every((scope) => granted.has(scope));\n}\nconst REQUIRED_TENANT_SCOPE_SET = new Set(FEISHU_REQUIRED_TENANT_SCOPES);\nconst SLACK_REQUIRED_BOT_SCOPES = [\n\t\"app_mentions:read\",\n\t\"channels:history\",\n\t\"channels:join\",\n\t\"channels:read\",\n\t\"chat:write\",\n\t\"files:read\",\n\t\"files:write\",\n\t\"groups:history\",\n\t\"groups:read\",\n\t\"im:history\",\n\t\"im:read\",\n\t\"im:write\",\n\t\"mpim:history\",\n\t\"mpim:read\",\n\t\"reactions:read\",\n\t\"reactions:write\",\n\t\"team:read\",\n\t\"users:read\"\n];\nconst SLACK_SUBSCRIBED_BOT_EVENTS = [\n\t\"app_mention\",\n\t\"app_uninstalled\",\n\t\"message.channels\",\n\t\"message.groups\",\n\t\"message.im\",\n\t\"message.mpim\",\n\t\"tokens_revoked\"\n];\nfunction hasRequiredSlackBotScopes(scopes) {\n\tconst granted = new Set(scopes);\n\treturn SLACK_REQUIRED_BOT_SCOPES.every((scope) => granted.has(scope));\n}\nconst ImBindingIdentitySchema = z.discriminatedUnion(\"provider\", [z.object({\n\tprovider: z.literal(\"feishu\"),\n\tappId: z.string().min(1).max(255),\n\tteamId: z.string().min(1).max(255).nullable(),\n\tbotOpenId: z.string().min(1).max(255),\n\tteamBrand: z.string().max(255).nullable()\n}).strict(), z.object({\n\tprovider: z.literal(\"slack\"),\n\tappId: z.string().min(1).max(255),\n\tteamId: z.string().min(1).max(255),\n\tenterpriseId: z.string().min(1).max(255).nullable(),\n\tbotUserId: z.string().min(1).max(255),\n\tappIdEvidence: z.literal(\"configured\")\n}).strict()]);\nconst ImBindingSummarySchema = z.object({\n\tid: z.string().uuid(),\n\tagentId: z.string().uuid(),\n\tprovider: ImProviderSchema,\n\tbindingState: ImBindingStateSchema,\n\tbot: z.object({\n\t\tdisplayName: z.string().max(255).nullable(),\n\t\tavatarUrl: z.string().url().nullable()\n\t}).strict(),\n\treceiveMode: ReceiveModeSchema,\n\tlastInboundAt: z.string().datetime().nullable(),\n\tlastValidatedAt: z.string().datetime().nullable(),\n\tlastRuntimeObservationAt: z.string().datetime().nullable()\n}).strict();\nconst ProviderCliHandoffPhaseSchema = z.enum([\n\t\"preparing_cli\",\n\t\"checking_credentials\",\n\t\"needs_attention\"\n]);\nconst ProviderCliHandoffProgressSchema = z.object({\n\tphase: ProviderCliHandoffPhaseSchema,\n\treason: ProviderCliPublicFailureReasonSchema.optional()\n}).strict();\n/**\n* The machine-readable identity a cross-Provider messaging start fails with: unbind this exact current binding,\n* then bind any Provider. Mirrors the `messaging-unbind-required` Agent setup blocker.\n*/\nconst ImBindingUnbindRequiredDetailSchema = z.object({\n\tcurrentProvider: ImProviderSchema,\n\tcurrentBindingId: z.string().uuid(),\n\trequestedProvider: ImProviderSchema\n}).strict().superRefine((detail, context) => {\n\tif (detail.currentProvider === detail.requestedProvider) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"requestedProvider\"],\n\t\tmessage: \"Unbind is required only when the requested Provider differs from the current Provider\"\n\t});\n});\n/**\n* The messaging state a caller observed when it decided on a mutation. Commands carrying one are fenced\n* against the exact current binding: unbound means no configured binding may exist, bound names the exact\n* binding identity and credential generation. Keep in parity with AgentSetupExpectedMessagingStateSchema.\n*/\nconst ImBindingMessagingExpectationSchema = z.discriminatedUnion(\"kind\", [z.object({ kind: z.literal(\"unbound\") }).strict(), z.object({\n\tkind: z.literal(\"bound\"),\n\tprovider: ImProviderSchema,\n\tbindingId: z.string().uuid(),\n\tcredentialGeneration: z.number().int().positive()\n}).strict()]);\n/** Fixed surfaces a Slack OAuth round trip may return to. Keep in parity with AGENT_SETUP_RETURN_SURFACES. */\nconst SLACK_OAUTH_RETURN_SURFACES = [\"agent-setup\", \"agent-messaging-settings\"];\nconst SlackOAuthReturnSurfaceSchema = z.enum(SLACK_OAUTH_RETURN_SURFACES);\nconst ImBindingHandoffStatusSchema = z.union([\n\tz.object({\n\t\tbindingState: z.literal(\"active\"),\n\t\thandoffReady: z.literal(true)\n\t}).strict(),\n\tz.object({\n\t\tbindingState: z.literal(\"active\"),\n\t\thandoffReady: z.literal(false),\n\t\tproviderCli: ProviderCliHandoffProgressSchema.optional()\n\t}).strict(),\n\tz.object({\n\t\tbindingState: z.enum([\n\t\t\t\"provisioning\",\n\t\t\t\"reauthorization_required\",\n\t\t\t\"error\",\n\t\t\t\"disabled\"\n\t\t]),\n\t\thandoffReady: z.literal(false)\n\t}).strict()\n]);\nconst ImBindingAdminDetailSchema = ImBindingSummarySchema.extend({\n\tidentity: ImBindingIdentitySchema,\n\tcredentialGeneration: z.number().int().min(1),\n\tgrantedCapabilities: z.array(z.string().min(1).max(160)).max(128),\n\treauthorizationRequired: z.boolean(),\n\tlastErrorCode: z.string().min(1).max(120).nullable()\n}).strict();\nconst FeishuSetupIntentSchema = z.enum([\n\t\"create\",\n\t\"reauthorize\",\n\t\"replace\"\n]);\nconst FeishuSetupStateSchema = z.enum([\n\t\"awaiting_user\",\n\t\"pending_activation\",\n\t\"validating\",\n\t\"succeeded\",\n\t\"failed\",\n\t\"expired\",\n\t\"canceled\"\n]);\n/**\n* Why a durable authorization candidate is not activated yet. `checking` means no completed\n* observation is available — a check is in flight or the candidate was just saved. The remaining\n* reasons are the bounded classification of one completed upstream observation, never a guess at\n* an approval event.\n*/\nconst FEISHU_SETUP_ACTIVATION_REASONS = [\n\t\"checking\",\n\t\"permissions_pending\",\n\t\"app_unavailable\",\n\t\"runtime_unavailable\",\n\t\"temporary_failure\"\n];\nconst FeishuSetupActivationReasonSchema = z.enum(FEISHU_SETUP_ACTIVATION_REASONS);\nconst FeishuSetupActivationSchema = z.object({\n\tappId: z.string().min(1).max(255),\n\treason: FeishuSetupActivationReasonSchema,\n\t/** Only members of the canonical required tenant scope list; the app secret is never exposed. */\n\tmissingScopes: z.array(z.string().min(1).max(160)).max(FEISHU_REQUIRED_TENANT_SCOPES.length).refine((scopes) => scopes.every((scope) => REQUIRED_TENANT_SCOPE_SET.has(scope)) && new Set(scopes).size === scopes.length, { message: \"missingScopes must be unique canonical required tenant scopes\" }),\n\tlastCheckedAt: z.string().datetime().nullable(),\n\tnextCheckAt: z.string().datetime()\n}).strict();\nconst FeishuSetupAttemptSchema = z.object({\n\tid: z.string().uuid(),\n\tagentId: z.string().uuid(),\n\tintent: FeishuSetupIntentSchema,\n\tstate: FeishuSetupStateSchema,\n\tqrUrl: z.string().url().nullable(),\n\texpiresAt: z.string().datetime(),\n\terrorCode: z.string().min(1).max(120).nullable(),\n\tcompletedAt: z.string().datetime().nullable(),\n\tcreatedAt: z.string().datetime(),\n\t/** Present for a durable `pending_activation`/`validating` candidate; absent for legacy QR attempts. */\n\tactivation: FeishuSetupActivationSchema.optional()\n}).strict().superRefine((attempt, context) => {\n\tif (attempt.state === \"pending_activation\" && !attempt.activation) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"activation\"],\n\t\tmessage: \"A saved candidate requires activation details\"\n\t});\n\tif (attempt.activation && (attempt.qrUrl !== null || ![\"pending_activation\", \"validating\"].includes(attempt.state))) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"activation\"],\n\t\tmessage: \"Activation details belong only to an open candidate without a QR\"\n\t});\n});\nconst CreateFeishuSetupAttemptRequestSchema = z.object({\n\tintent: FeishuSetupIntentSchema.default(\"create\"),\n\texpectedMessaging: ImBindingMessagingExpectationSchema.optional()\n}).strict().superRefine((request, context) => {\n\tif (request.intent === \"create\" && request.expectedMessaging?.kind === \"bound\") context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"expectedMessaging\"],\n\t\tmessage: \"Feishu create requires the Agent to be unbound\"\n\t});\n});\n/** Names the exact current binding the Account asked to unbind, fencing the mutation against a stale view. */\nconst UnbindAgentMessagingRequestSchema = z.object({\n\tprovider: ImProviderSchema,\n\tbindingId: z.string().uuid()\n}).strict();\nconst SlackConfigurationIntentSchema = z.enum([\"create\", \"reauthorize\"]);\nconst SlackIdentityClosureSchema = z.object({\n\tstatus: z.enum([\"pending\", \"verified\"]),\n\tverifiedAt: z.string().datetime().nullable()\n}).strict();\nconst SlackConfigurationResultSchema = z.object({\n\timBindingId: z.string().uuid(),\n\tagentId: z.string().uuid(),\n\tappId: z.string().min(1).max(255),\n\tteamId: z.string().min(1).max(255),\n\tbotUserId: z.string().min(1).max(255),\n\tcredentialGeneration: z.number().int().min(1),\n\tbindingState: z.literal(\"active\"),\n\tidentityClosure: SlackIdentityClosureSchema\n}).strict();\nconst StartSlackOAuthRequestSchema = z.object({\n\tintent: SlackConfigurationIntentSchema,\n\treturnSurface: SlackOAuthReturnSurfaceSchema.optional(),\n\texpectedMessaging: ImBindingMessagingExpectationSchema.optional()\n}).strict().superRefine((request, context) => {\n\tif (request.intent === \"create\" && request.expectedMessaging?.kind === \"bound\") context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"expectedMessaging\"],\n\t\tmessage: \"Slack create requires the Agent to be unbound\"\n\t});\n\tif (request.intent === \"reauthorize\" && request.expectedMessaging !== void 0 && (request.expectedMessaging.kind !== \"bound\" || request.expectedMessaging.provider !== \"slack\")) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"expectedMessaging\"],\n\t\tmessage: \"Slack reauthorization requires the exact current Slack binding\"\n\t});\n});\nconst StartSlackOAuthResponseSchema = z.object({\n\tauthorizationUrl: z.string().url(),\n\texpiresAt: z.string().datetime()\n}).strict();\nconst ImBindingCredentialStatusSchema = z.enum([\"valid\", \"invalid\"]);\nconst ImBindingDiagnosticsSchema = z.object({\n\timBindingId: z.string().uuid(),\n\tprovider: ImProviderSchema,\n\tready: z.boolean(),\n\tagentRuntimeReadiness: z.enum([\n\t\t\"checking\",\n\t\t\"install\",\n\t\t\"sign-in\",\n\t\t\"ready\",\n\t\t\"unavailable\"\n\t]),\n\tproviderCliReadiness: z.enum([\n\t\t\"checking\",\n\t\t\"install\",\n\t\t\"ready\",\n\t\t\"unavailable\",\n\t\t\"not_applicable\"\n\t]),\n\tproviderCliReason: ProviderCliArtifactPublicReasonSchema.optional(),\n\tcredentialExecutionReadiness: IntegrationCredentialExecutionStatusSchema,\n\tcredentialExecutionReason: IntegrationCredentialExecutionReasonSchema.optional(),\n\tcredentialGeneration: z.number().int().min(0),\n\tcredentialStatus: ImBindingCredentialStatusSchema,\n\trequiredCapabilities: z.array(z.string().min(1).max(160)).max(128),\n\tgrantedCapabilities: z.array(z.string().min(1).max(160)).max(128),\n\tmissingCapabilities: z.array(z.string().min(1).max(160)).max(128),\n\treauthorizationRequired: z.boolean(),\n\tslackAppId: z.object({\n\t\tvalue: z.string().min(1).max(255),\n\t\tevidence: z.literal(\"configured\"),\n\t\tingressMatchRequired: z.literal(true)\n\t}).strict().nullable(),\n\tslackIdentityClosure: SlackIdentityClosureSchema.nullable(),\n\tconnection: z.object({\n\t\tstate: z.enum([\"connected\", \"disconnected\"]),\n\t\tobservedAt: z.string().datetime()\n\t}).nullable(),\n\tlastInboundAt: z.string().datetime().nullable(),\n\tlastValidatedAt: z.string().datetime().nullable(),\n\tlastRuntimeObservationAt: z.string().datetime().nullable(),\n\tlastErrorCode: z.string().min(1).max(120).nullable()\n}).strict();\nconst SlackBindingActivationSchema = z.object({\n\tintent: SlackConfigurationIntentSchema,\n\tagentId: z.string().uuid(),\n\tappId: z.string().min(1).max(255),\n\tteamId: z.string().min(1).max(255),\n\tenterpriseId: z.string().min(1).max(255).optional(),\n\tbotUserId: z.string().min(1).max(255),\n\tgrantedBotScopes: z.array(z.string().min(1).max(160)).max(128),\n\tbotAccessToken: z.string().min(1),\n\tsigningSecret: z.string().min(1),\n\tinstalledAt: z.coerce.date(),\n\tprofile: ImBindingSummarySchema.shape.bot.optional()\n}).strict();\n//#endregion\n//#region src/agent-setup.ts\nconst AGENT_SETUP_STAGES = [\n\t\"needs-computer\",\n\t\"needs-runtime\",\n\t\"needs-provider-clis\",\n\t\"needs-messaging\",\n\t\"ready\"\n];\nconst AgentSetupStageSchema = z.enum(AGENT_SETUP_STAGES);\n/**\n* The IM CLI Providers that must be freshly ready on the setup Computer before a not-configured\n* Messaging state may advance. The order is canonical: Server snapshots, component projections, and\n* consumers must never reorder or subset this set on their own.\n*/\nconst AGENT_SETUP_REQUIRED_IM_CLI_PROVIDERS = [\"feishu\", \"slack\"];\nconst AgentSetupComputerIdentityShape = {\n\tcomputerId: z.string().uuid(),\n\tdisplayName: z.string().min(1),\n\tplatform: ComputerPlatformSchema\n};\nconst AgentSetupComputerStateSchema = z.discriminatedUnion(\"kind\", [\n\tz.object({ kind: z.literal(\"not-bound\") }).strict(),\n\tz.object({\n\t\tkind: z.literal(\"observation-failed\"),\n\t\t...AgentSetupComputerIdentityShape\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"requires-rebind\"),\n\t\t...AgentSetupComputerIdentityShape\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"bound\"),\n\t\t...AgentSetupComputerIdentityShape,\n\t\tconnectionStatus: ComputerConnectionStatusSchema,\n\t\timCliReadiness: ComputerImCliReadinessCollectionSchema,\n\t\tlastSeenAt: z.string().datetime().nullable(),\n\t\tobservedAt: z.string().datetime()\n\t}).strict(),\n\tz.object({\n\t\t/**\n\t\t* The Account's logical Cloud Computer. The identity is bound and managed by the platform;\n\t\t* it carries no connection status, no heartbeat, and no local IM CLI reports, because none\n\t\t* of those exist for a Computer that is not a machine.\n\t\t*/\n\t\tkind: z.literal(\"cloud\"),\n\t\t...AgentSetupComputerIdentityShape,\n\t\t/** When the Server read the managed identity; never a connectivity observation. */\n\t\tobservedAt: z.string().datetime()\n\t}).strict()\n]);\nconst AgentSetupRuntimeUnavailableReasonSchema = z.enum([\n\t\"computer-not-bound\",\n\t\"computer-observation-failed\",\n\t\"computer-rebind-required\",\n\t\"computer-offline\"\n]);\nconst AgentSetupRuntimeStateSchema = z.discriminatedUnion(\"kind\", [\n\tz.object({\n\t\tkind: z.literal(\"observation-failed\"),\n\t\tprovider: AgentSummarySchema.shape.runtimeProvider\n\t}).strict(),\n\tz.object({\n\t\t/** No fresh readiness report exists for the exact runtime Provider on the online Computer. */\n\t\tkind: z.literal(\"waiting\"),\n\t\tprovider: AgentSummarySchema.shape.runtimeProvider\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"unavailable\"),\n\t\tprovider: AgentSummarySchema.shape.runtimeProvider,\n\t\treason: AgentSetupRuntimeUnavailableReasonSchema\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"observed\"),\n\t\tprovider: AgentSummarySchema.shape.runtimeProvider,\n\t\tstatus: ProviderReadinessStatusSchema,\n\t\t/** An observed report always carries its observation time; a ready report cannot lack evidence. */\n\t\tobservedAt: z.string().datetime()\n\t}).strict(),\n\tz.object({\n\t\t/**\n\t\t* The runtime leg of a Cloud-bound Agent. The platform runs the exact runtime Provider, so\n\t\t* readiness is the deployment's Cloud execution configuration — never a Runner session probe\n\t\t* and never a claim that an environment was validated. `available` means the platform can\n\t\t* start an environment for the first real task, not that one is already running.\n\t\t*/\n\t\tkind: z.literal(\"cloud-managed\"),\n\t\tprovider: AgentSummarySchema.shape.runtimeProvider,\n\t\tavailability: CloudAvailabilitySchema\n\t}).strict()\n]);\n/**\n* The local-preparation component vocabulary. Existing wire statuses are reused verbatim wherever a\n* report exists; `waiting` is the only new word and means \"no fresh report yet\", never a fabricated\n* checking state.\n*/\nconst AGENT_SETUP_COMPUTER_COMPONENT_STATUSES = [\n\t\"not-bound\",\n\t\"requires-rebind\",\n\t\"observation-failed\",\n\t\"offline\",\n\t\"online\"\n];\nconst AGENT_SETUP_RUNTIME_COMPONENT_STATUSES = [\n\t\"observation-failed\",\n\t\"waiting\",\n\t\"checking\",\n\t\"install\",\n\t\"sign-in\",\n\t\"ready\",\n\t\"unavailable\"\n];\nconst AGENT_SETUP_IM_CLI_COMPONENT_STATUSES = [\n\t\"waiting\",\n\t\"checking\",\n\t\"install\",\n\t\"ready\",\n\t\"unavailable\"\n];\n/**\n* The managed Cloud service leg of a Cloud-bound Agent, projected from the deployment's Cloud\n* availability at the observed instant. `available` is a configuration fact — the platform can\n* start an execution environment for a real task — never a claim that one was already started\n* or validated.\n*/\nconst AGENT_SETUP_CLOUD_COMPONENT_STATUSES = [\n\t\"available\",\n\t\"execution-unavailable\",\n\t\"model-unavailable\",\n\t\"disabled\"\n];\nconst AgentSetupComputerComponentStatusSchema = z.enum(AGENT_SETUP_COMPUTER_COMPONENT_STATUSES);\nconst AgentSetupRuntimeComponentStatusSchema = z.enum(AGENT_SETUP_RUNTIME_COMPONENT_STATUSES);\nconst AgentSetupImCliComponentStatusSchema = z.enum(AGENT_SETUP_IM_CLI_COMPONENT_STATUSES);\nconst AgentSetupCloudComponentStatusSchema = z.enum(AGENT_SETUP_CLOUD_COMPONENT_STATUSES);\nconst AgentSetupComputerComponentSchema = z.object({\n\tkind: z.literal(\"computer\"),\n\tstatus: AgentSetupComputerComponentStatusSchema,\n\t/** Whether this leg currently blocks the setup cursor. */\n\tblocking: z.boolean(),\n\tcomputerId: z.string().uuid().nullable(),\n\tdisplayName: z.string().min(1).nullable(),\n\tplatform: ComputerPlatformSchema.nullable(),\n\tobservedAt: z.string().datetime().nullable()\n}).strict();\nconst AgentSetupRuntimeComponentSchema = z.object({\n\tkind: z.literal(\"runtime\"),\n\tstatus: AgentSetupRuntimeComponentStatusSchema,\n\tblocking: z.boolean(),\n\tprovider: AgentSummarySchema.shape.runtimeProvider,\n\tobservedAt: z.string().datetime().nullable()\n}).strict();\nconst AgentSetupImCliComponentSchema = z.object({\n\tkind: z.literal(\"im-cli\"),\n\tstatus: AgentSetupImCliComponentStatusSchema,\n\tblocking: z.boolean(),\n\tprovider: ImCliProviderSchema,\n\tobservedAt: z.string().datetime().nullable()\n}).strict();\nconst AgentSetupCloudComponentSchema = z.object({\n\tkind: z.literal(\"cloud\"),\n\tstatus: AgentSetupCloudComponentStatusSchema,\n\t/** Whether the managed service currently blocks the setup cursor. */\n\tblocking: z.boolean(),\n\tcomputerId: z.string().uuid(),\n\tdisplayName: z.string().min(1),\n\tplatform: ComputerPlatformSchema,\n\t/** When the Server read the Cloud identity and configuration; not a machine heartbeat. */\n\tobservedAt: z.string().datetime()\n}).strict();\n/**\n* The canonical component projection of one setup snapshot: the exact Computer, the Agent's exact\n* Runtime, then one entry per required IM CLI Provider in canonical order. A Cloud-bound Agent has\n* a single managed-service component instead: there is no machine to connect and no local CLI to\n* prepare. Schema validation, the Server projection, and in-memory adapters derive rows through\n* the same helper so no consumer guesses at identity, status, or blocking on its own.\n*/\nconst AgentSetupComponentSchema = z.discriminatedUnion(\"kind\", [\n\tAgentSetupComputerComponentSchema,\n\tAgentSetupRuntimeComponentSchema,\n\tAgentSetupImCliComponentSchema,\n\tAgentSetupCloudComponentSchema\n]);\nfunction computerComponentStatus(computer) {\n\tif (computer.kind === \"bound\") return computer.connectionStatus;\n\treturn computer.kind;\n}\nfunction runtimeComponentStatus(runtime) {\n\tif (runtime.kind === \"observed\") return runtime.status;\n\tif (runtime.kind === \"cloud-managed\") return \"unavailable\";\n\treturn runtime.kind;\n}\n/** The Cloud component's status is the deployment availability reason, or `available`. */\nfunction cloudComponentStatus(runtime) {\n\tif (runtime.kind !== \"cloud-managed\") return \"disabled\";\n\tif (runtime.availability.available) return \"available\";\n\tswitch (runtime.availability.reason) {\n\t\tcase \"execution_unavailable\": return \"execution-unavailable\";\n\t\tcase \"model_unavailable\": return \"model-unavailable\";\n\t\tdefault: return \"disabled\";\n\t}\n}\n/**\n* Projects the canonical component rows for one observed instant. Blocking follows the setup cursor:\n* the Computer leg blocks until it is bound and online, the Runtime leg blocks once the Computer is\n* usable but the exact runtime report is not freshly ready, and each required IM CLI leg blocks only\n* while Messaging is not-configured and the other two legs are ready. A known Messaging state\n* (authorizing, waiting-handoff, blocked, ready) never makes an unselected CLI a continuing blocker.\n*/\nfunction projectAgentSetupComponents(input) {\n\tconst { computer, runtime, messaging } = input;\n\tif (computer.kind === \"cloud\") {\n\t\tconst status = cloudComponentStatus(runtime);\n\t\treturn [{\n\t\t\tkind: \"cloud\",\n\t\t\tstatus,\n\t\t\tblocking: status !== \"available\",\n\t\t\tcomputerId: computer.computerId,\n\t\t\tdisplayName: computer.displayName,\n\t\t\tplatform: computer.platform,\n\t\t\tobservedAt: computer.observedAt\n\t\t}];\n\t}\n\tconst computerReady = computer.kind === \"bound\" && computer.connectionStatus === \"online\";\n\tconst runtimeReady = runtime.kind === \"observed\" && runtime.status === \"ready\";\n\tconst cliEntries = computer.kind === \"bound\" ? computer.imCliReadiness : [];\n\tconst cliEntryByProvider = new Map(cliEntries.map((entry) => [entry.provider, entry]));\n\treturn [\n\t\t{\n\t\t\tkind: \"computer\",\n\t\t\tstatus: computerComponentStatus(computer),\n\t\t\tblocking: !computerReady,\n\t\t\tcomputerId: computer.kind === \"not-bound\" ? null : computer.computerId,\n\t\t\tdisplayName: computer.kind === \"not-bound\" ? null : computer.displayName,\n\t\t\tplatform: computer.kind === \"not-bound\" ? null : computer.platform,\n\t\t\tobservedAt: computer.kind === \"bound\" ? computer.observedAt : null\n\t\t},\n\t\t{\n\t\t\tkind: \"runtime\",\n\t\t\tstatus: runtimeComponentStatus(runtime),\n\t\t\tblocking: computerReady && !runtimeReady,\n\t\t\tprovider: runtime.provider,\n\t\t\tobservedAt: runtime.kind === \"observed\" ? runtime.observedAt : null\n\t\t},\n\t\t...input.requiredImCliProviders.map((provider) => {\n\t\t\tconst entry = cliEntryByProvider.get(provider);\n\t\t\tconst status = cliReportStatus(entry);\n\t\t\tconst ready = status === \"ready\";\n\t\t\treturn {\n\t\t\t\tkind: \"im-cli\",\n\t\t\t\tprovider,\n\t\t\t\tstatus,\n\t\t\t\tobservedAt: entry?.observedAt ?? null,\n\t\t\t\tblocking: messaging.kind === \"not-configured\" && computerReady && runtimeReady && !ready\n\t\t\t};\n\t\t})\n\t];\n}\nconst AGENT_SETUP_MESSAGING_BLOCKER_CODES = [\n\t\"authorization-failed\",\n\t\"reauthorization-required\",\n\t\"provider-error\",\n\t\"unbind-required\"\n];\nconst AgentSetupMessagingBlockerCodeSchema = z.enum(AGENT_SETUP_MESSAGING_BLOCKER_CODES);\nconst AgentSetupMessagingStateSchema = z.union([\n\tz.object({ kind: z.literal(\"not-configured\") }).strict(),\n\tz.object({ kind: z.literal(\"observation-failed\") }).strict(),\n\tz.object({\n\t\tkind: z.literal(\"authorizing\"),\n\t\tprovider: z.literal(\"feishu\"),\n\t\tattemptId: z.string().uuid(),\n\t\tqrUrl: z.string().url().nullable(),\n\t\texpiresAt: z.string().datetime(),\n\t\t/**\n\t\t* Present when the setup attempt holds a durable candidate and no longer needs the page to\n\t\t* stay open: the same `authorizing` kind carries the bounded waiting observation. Legacy QR\n\t\t* attempts omit it.\n\t\t*/\n\t\tactivation: FeishuSetupActivationSchema.optional()\n\t}).strict().refine((value) => !value.activation || value.qrUrl === null, { message: \"A saved authorization has no QR\" }),\n\tz.object({\n\t\tkind: z.literal(\"authorizing\"),\n\t\tprovider: z.literal(\"slack\"),\n\t\texpiresAt: z.string().datetime()\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"waiting-handoff\"),\n\t\tprovider: ImProviderSchema,\n\t\tbindingId: z.string().uuid(),\n\t\tcredentialGeneration: z.number().int().positive(),\n\t\tprogress: ProviderCliHandoffProgressSchema.optional()\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"blocked\"),\n\t\tprovider: ImProviderSchema,\n\t\tbindingId: z.string().uuid().optional(),\n\t\tcredentialGeneration: z.number().int().nonnegative().optional(),\n\t\tcode: AgentSetupMessagingBlockerCodeSchema,\n\t\terrorCode: z.string().min(1).max(120).nullable()\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"ready\"),\n\t\tprovider: ImProviderSchema,\n\t\tbindingId: z.string().uuid(),\n\t\tcredentialGeneration: z.number().int().positive()\n\t}).strict()\n]);\nconst AGENT_SETUP_ACTION_KINDS = [\n\t\"refresh\",\n\t\"bind-computer\",\n\t\"repair-computer\",\n\t\"start-messaging\",\n\t\"cancel-messaging-attempt\",\n\t\"reauthorize-messaging\",\n\t\"replace-messaging\",\n\t\"unbind-messaging\"\n];\nconst AgentSetupActionSchema = z.discriminatedUnion(\"kind\", [\n\tz.object({ kind: z.literal(\"refresh\") }).strict(),\n\tz.object({ kind: z.literal(\"bind-computer\") }).strict(),\n\tz.object({\n\t\tkind: z.literal(\"repair-computer\"),\n\t\tcomputerId: z.string().uuid()\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"start-messaging\"),\n\t\tprovider: ImProviderSchema\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"cancel-messaging-attempt\"),\n\t\tprovider: z.literal(\"feishu\"),\n\t\tattemptId: z.string().uuid()\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"reauthorize-messaging\"),\n\t\tprovider: ImProviderSchema,\n\t\tbindingId: z.string().uuid(),\n\t\tcredentialGeneration: z.number().int().positive()\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"replace-messaging\"),\n\t\tprovider: z.literal(\"feishu\"),\n\t\tbindingId: z.string().uuid(),\n\t\tcredentialGeneration: z.number().int().positive()\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"unbind-messaging\"),\n\t\tprovider: ImProviderSchema,\n\t\tbindingId: z.string().uuid()\n\t}).strict()\n]);\nconst AGENT_SETUP_BLOCKER_CODES = [\n\t\"computer-not-bound\",\n\t\"computer-rebind-required\",\n\t\"computer-offline\",\n\t\"runtime-not-ready\",\n\t\"provider-cli-not-ready\",\n\t\"cloud-service-unavailable\",\n\t\"messaging-not-configured\",\n\t\"messaging-not-ready\",\n\t\"messaging-unbind-required\",\n\t\"resource-observation-failed\"\n];\nconst AgentSetupBlockerSchema = z.discriminatedUnion(\"code\", [\n\tz.object({ code: z.literal(\"computer-not-bound\") }).strict(),\n\tz.object({ code: z.literal(\"computer-rebind-required\") }).strict(),\n\tz.object({\n\t\tcode: z.literal(\"computer-offline\"),\n\t\tcomputerId: z.string().uuid()\n\t}).strict(),\n\tz.object({\n\t\tcode: z.literal(\"runtime-not-ready\"),\n\t\tprovider: AgentSummarySchema.shape.runtimeProvider,\n\t\tstatus: z.enum([\n\t\t\t\"checking\",\n\t\t\t\"install\",\n\t\t\t\"sign-in\",\n\t\t\t\"unavailable\",\n\t\t\t\"waiting\"\n\t\t])\n\t}).strict(),\n\tz.object({\n\t\tcode: z.literal(\"provider-cli-not-ready\"),\n\t\tprovider: ImCliProviderSchema,\n\t\tstatus: z.enum([\n\t\t\t\"waiting\",\n\t\t\t\"checking\",\n\t\t\t\"install\",\n\t\t\t\"unavailable\"\n\t\t])\n\t}).strict(),\n\tz.object({\n\t\t/**\n\t\t* The managed Cloud execution service cannot start an environment right now. The reason\n\t\t* is the deployment configuration fact, never an inferred runtime or machine failure.\n\t\t*/\n\t\tcode: z.literal(\"cloud-service-unavailable\"),\n\t\treason: z.enum([\n\t\t\t\"disabled\",\n\t\t\t\"execution-unavailable\",\n\t\t\t\"model-unavailable\"\n\t\t])\n\t}).strict(),\n\tz.object({ code: z.literal(\"messaging-not-configured\") }).strict(),\n\tz.object({\n\t\tcode: z.literal(\"messaging-not-ready\"),\n\t\tprovider: ImProviderSchema,\n\t\tbindingId: z.string().uuid().optional(),\n\t\tstate: z.enum([\n\t\t\t\"authorizing\",\n\t\t\t\"waiting-handoff\",\n\t\t\t\"blocked\"\n\t\t])\n\t}).strict(),\n\tz.object({\n\t\tcode: z.literal(\"messaging-unbind-required\"),\n\t\tcurrentProvider: ImProviderSchema,\n\t\tcurrentBindingId: z.string().uuid(),\n\t\trequestedProvider: ImProviderSchema\n\t}).strict(),\n\tz.object({\n\t\tcode: z.literal(\"resource-observation-failed\"),\n\t\tresource: z.enum([\n\t\t\t\"agent\",\n\t\t\t\"computer\",\n\t\t\t\"runtime\",\n\t\t\t\"messaging\"\n\t\t])\n\t}).strict()\n]).superRefine((blocker, context) => {\n\tif (blocker.code === \"messaging-unbind-required\" && blocker.currentProvider === blocker.requestedProvider) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"requestedProvider\"],\n\t\tmessage: \"Unbind is required only when the requested Provider differs from the current Provider\"\n\t});\n});\nconst AgentSetupSnapshotBaseSchema = z.object({\n\tagent: AgentSummarySchema,\n\tstage: AgentSetupStageSchema,\n\tcomputer: AgentSetupComputerStateSchema,\n\truntime: AgentSetupRuntimeStateSchema,\n\tmessaging: AgentSetupMessagingStateSchema,\n\t/** Canonical required IM CLI Providers in canonical order; the current policy requires both. */\n\trequiredImCliProviders: z.array(ImCliProviderSchema).max(AGENT_SETUP_REQUIRED_IM_CLI_PROVIDERS.length),\n\t/** Canonical local-preparation components: the exact Computer, Runtime, then each required IM CLI. */\n\tcomponents: z.array(AgentSetupComponentSchema).max(4),\n\tblockers: z.array(AgentSetupBlockerSchema).max(16),\n\tactions: z.array(AgentSetupActionSchema).max(16),\n\tobservedAt: z.string().datetime()\n}).strict();\nfunction validateSetupComputer(snapshot, addIssue) {\n\tconst agentComputer = snapshot.agent.computer;\n\tif (snapshot.computer.kind === \"not-bound\") {\n\t\tif (agentComputer !== null) addIssue([\"computer\"], \"A not-bound setup Computer must match the Agent\");\n\t\tif (snapshot.agent.requiresComputerRebind === true) addIssue([\"computer\"], \"A Computer that requires rebind must retain its identity\");\n\t\treturn;\n\t}\n\tif (agentComputer === null || agentComputer.computerId !== snapshot.computer.computerId || agentComputer.displayName !== snapshot.computer.displayName || agentComputer.platform !== snapshot.computer.platform) addIssue([\"computer\"], \"The setup Computer must match the exact Agent binding\");\n\tif (snapshot.computer.kind === \"observation-failed\") return;\n\tif (snapshot.computer.kind === \"requires-rebind\" && snapshot.agent.requiresComputerRebind !== true) addIssue([\"computer\"], \"A requires-rebind setup Computer must be marked on the Agent\");\n\tif (snapshot.computer.kind === \"bound\" && snapshot.agent.requiresComputerRebind === true) addIssue([\"computer\"], \"A Computer that requires rebind is not a usable bound Computer\");\n\tif (snapshot.computer.kind === \"cloud\" && snapshot.agent.requiresComputerRebind === true) addIssue([\"computer\"], \"A Computer that requires rebind is not a usable Cloud Computer\");\n}\nfunction expectedRuntimeUnavailableReason(computer) {\n\tif (computer.kind === \"not-bound\") return \"computer-not-bound\";\n\tif (computer.kind === \"observation-failed\") return \"computer-observation-failed\";\n\tif (computer.kind === \"requires-rebind\") return \"computer-rebind-required\";\n\tif (computer.kind === \"cloud\") return void 0;\n\tif (computer.connectionStatus === \"offline\") return \"computer-offline\";\n}\nfunction validateSetupRuntime(snapshot, addIssue) {\n\tif (snapshot.runtime.provider !== snapshot.agent.runtimeProvider) addIssue([\"runtime\", \"provider\"], \"Runtime readiness must describe the Agent's exact Provider\");\n\tif (snapshot.computer.kind === \"cloud\") {\n\t\tif (snapshot.runtime.kind !== \"cloud-managed\") addIssue([\"runtime\"], \"A Cloud Computer's runtime readiness is the managed Cloud service, not a local report\");\n\t\treturn;\n\t}\n\tif (snapshot.runtime.kind === \"cloud-managed\") {\n\t\taddIssue([\"runtime\"], \"A Local Computer's runtime readiness must come from its own observations\");\n\t\treturn;\n\t}\n\tconst unavailableReason = expectedRuntimeUnavailableReason(snapshot.computer);\n\tif (unavailableReason === void 0) {\n\t\tif (snapshot.runtime.kind !== \"observed\" && snapshot.runtime.kind !== \"waiting\" && snapshot.runtime.kind !== \"observation-failed\") addIssue([\"runtime\"], \"An online bound Computer must expose an observed, waiting, or observation-failed runtime readiness\");\n\t\treturn;\n\t}\n\tif (snapshot.runtime.kind !== \"unavailable\" || snapshot.runtime.reason !== unavailableReason) addIssue([\"runtime\"], \"Runtime state must preserve why the exact Computer cannot be observed\");\n}\nfunction setupCliReadiness(snapshot) {\n\treturn snapshot.computer.kind === \"bound\" ? snapshot.computer.imCliReadiness : [];\n}\n/**\n* The effective IM CLI status one Computer report row carries. Only an `unavailable` row — the\n* offline connection fence — is legitimate without an observation time: a ready/checking/install\n* report with no `observedAt` is evidence-less and must read as waiting, never as a real\n* observation. Freshness itself stays source-authoritative.\n*/\nfunction cliReportStatus(entry) {\n\tif (!entry) return \"waiting\";\n\tif (entry.observedAt === null && entry.status !== \"unavailable\") return \"waiting\";\n\treturn entry.status;\n}\n/** Serializes JSON-shaped data with object keys sorted, so parsed and authored objects compare equal. */\nfunction stableSerialize(value) {\n\tif (Array.isArray(value)) return `[${value.map(stableSerialize).join(\",\")}]`;\n\tif (value !== null && typeof value === \"object\") {\n\t\tconst record = value;\n\t\treturn `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableSerialize(record[key])}`).join(\",\")}}`;\n\t}\n\treturn JSON.stringify(value);\n}\nfunction requiredCliReady(snapshot, provider) {\n\treturn cliReportStatus(setupCliReadiness(snapshot).find((readiness) => readiness.provider === provider)) === \"ready\";\n}\n/** The Provider CLI blockers canonical for the given facts: one per required CLI that is not ready. */\nfunction failingProviderCliBlockers(snapshot) {\n\treturn snapshot.requiredImCliProviders.flatMap((provider) => {\n\t\tconst status = cliReportStatus(setupCliReadiness(snapshot).find((readiness) => readiness.provider === provider));\n\t\treturn status === \"ready\" ? [] : [{\n\t\t\tcode: \"provider-cli-not-ready\",\n\t\t\tprovider,\n\t\t\tstatus\n\t\t}];\n\t});\n}\nfunction deriveSetupStage(snapshot) {\n\tconst cloudManaged = snapshot.computer.kind === \"cloud\";\n\tif (!(cloudManaged || snapshot.computer.kind === \"bound\" && snapshot.computer.connectionStatus === \"online\")) return \"needs-computer\";\n\tif (!(cloudManaged ? snapshot.runtime.kind === \"cloud-managed\" && snapshot.runtime.availability.available : snapshot.runtime.kind === \"observed\" && snapshot.runtime.status === \"ready\")) return \"needs-runtime\";\n\tif (snapshot.messaging.kind === \"ready\") return \"ready\";\n\tif (snapshot.messaging.kind !== \"not-configured\") return \"needs-messaging\";\n\tif (cloudManaged) return \"needs-messaging\";\n\treturn snapshot.requiredImCliProviders.every((provider) => requiredCliReady(snapshot, provider)) ? \"needs-messaging\" : \"needs-provider-clis\";\n}\nfunction hasObservationBlocker(snapshot, resource) {\n\treturn snapshot.blockers.some((blocker) => blocker.code === \"resource-observation-failed\" && blocker.resource === resource);\n}\nfunction validateSetupStage(snapshot, addIssue) {\n\tif (snapshot.stage !== deriveSetupStage(snapshot)) addIssue([\"stage\"], \"Stage must be derived from Computer, runtime, and Messaging facts in canonical order\");\n\tconst blockerCodes = new Set(snapshot.blockers.map((blocker) => blocker.code));\n\tif (snapshot.stage === \"ready\" && snapshot.blockers.length > 0) {\n\t\taddIssue([\"blockers\"], \"A ready Agent setup cannot retain blockers\");\n\t\treturn;\n\t}\n\tconst providerCliBlockers = snapshot.blockers.filter((blocker) => blocker.code === \"provider-cli-not-ready\");\n\tif (snapshot.stage === \"needs-provider-clis\") {\n\t\tconst expected = failingProviderCliBlockers(snapshot);\n\t\tif (stableSerialize(providerCliBlockers) !== stableSerialize(expected)) addIssue([\"blockers\"], \"A needs-provider-clis setup must block exactly the required IM CLIs that are not freshly ready\");\n\t\treturn;\n\t}\n\tif (providerCliBlockers.length > 0) addIssue([\"blockers\"], \"Provider CLI blockers apply only while the setup waits on required IM CLI readiness\");\n\tif (snapshot.stage === \"needs-runtime\" && !blockerCodes.has(\"runtime-not-ready\") && !blockerCodes.has(\"cloud-service-unavailable\") && !hasObservationBlocker(snapshot, \"runtime\")) addIssue([\"blockers\"], \"A needs-runtime setup must name its runtime blocker\");\n\tconst hasMessagingBlocker = blockerCodes.has(\"messaging-not-configured\") || blockerCodes.has(\"messaging-not-ready\");\n\tif (snapshot.stage === \"needs-messaging\" && !hasMessagingBlocker && !hasObservationBlocker(snapshot, \"messaging\")) addIssue([\"blockers\"], \"A needs-messaging setup must name its Messaging blocker\");\n\tconst hasComputerBlocker = blockerCodes.has(\"computer-not-bound\") || blockerCodes.has(\"computer-rebind-required\") || blockerCodes.has(\"computer-offline\");\n\tif (snapshot.stage === \"needs-computer\" && !hasComputerBlocker && !hasObservationBlocker(snapshot, \"computer\")) addIssue([\"blockers\"], \"A needs-computer setup must name its Computer blocker\");\n}\nfunction readCurrentBinding(messaging) {\n\tif (messaging.kind === \"waiting-handoff\" || messaging.kind === \"ready\") return {\n\t\tprovider: messaging.provider,\n\t\tbindingId: messaging.bindingId,\n\t\tcredentialGeneration: messaging.credentialGeneration\n\t};\n\tif (messaging.kind === \"blocked\" && messaging.bindingId && messaging.credentialGeneration !== void 0) return {\n\t\tprovider: messaging.provider,\n\t\tbindingId: messaging.bindingId,\n\t\tcredentialGeneration: messaging.credentialGeneration\n\t};\n}\nfunction isInitialFeishuRetry(messaging, action) {\n\treturn action.kind === \"start-messaging\" && action.provider === \"feishu\" && messaging.kind === \"blocked\" && messaging.provider === \"feishu\" && messaging.code === \"authorization-failed\" && messaging.bindingId !== void 0 && messaging.credentialGeneration === 0;\n}\nfunction validateSetupAction(snapshot, action, index, addIssue) {\n\tif (action.kind === \"start-messaging\" && snapshot.messaging.kind !== \"not-configured\" && !isInitialFeishuRetry(snapshot.messaging, action)) addIssue([\"actions\", index], \"Start requires not-configured state or an unactivated same-Provider authorization retry\");\n\tif (action.kind === \"start-messaging\" && (snapshot.stage !== \"needs-messaging\" || failingProviderCliBlockers(snapshot).length > 0)) addIssue([\"actions\", index], \"A Provider can be started only after the required IM CLI preparation gate has passed\");\n\tif (action.kind === \"cancel-messaging-attempt\") {\n\t\tif (!(snapshot.messaging.kind === \"authorizing\" && snapshot.messaging.provider === \"feishu\" && snapshot.messaging.attemptId === action.attemptId)) addIssue([\"actions\", index], \"Cancel must name the current Feishu setup attempt\");\n\t}\n\tif (action.kind !== \"reauthorize-messaging\" && action.kind !== \"replace-messaging\" && action.kind !== \"unbind-messaging\") return;\n\tconst currentBinding = readCurrentBinding(snapshot.messaging);\n\tif (currentBinding?.provider !== action.provider || currentBinding.bindingId !== action.bindingId) addIssue([\"actions\", index], \"Binding actions must name the current Provider and binding identity\");\n\tif (action.kind !== \"unbind-messaging\" && currentBinding?.credentialGeneration !== action.credentialGeneration) addIssue([\"actions\", index], \"Binding authorization actions must name the current credential generation\");\n}\nfunction validateSetupActions(snapshot, addIssue) {\n\tconst actionKeys = /* @__PURE__ */ new Set();\n\tfor (const [index, action] of snapshot.actions.entries()) {\n\t\tconst actionKey = JSON.stringify(action);\n\t\tif (actionKeys.has(actionKey)) addIssue([\"actions\", index], \"Permitted actions must be unique\");\n\t\tactionKeys.add(actionKey);\n\t\tvalidateSetupAction(snapshot, action, index, addIssue);\n\t}\n}\nfunction validateCloudBlocker(snapshot, blocker, index, addIssue) {\n\tif (snapshot.computer.kind !== \"cloud\" || snapshot.runtime.kind !== \"cloud-managed\" || snapshot.runtime.availability.available) addIssue([\"blockers\", index], \"A Cloud service blocker requires an unavailable Cloud-managed runtime\");\n\telse if (blocker.reason !== cloudComponentStatus(snapshot.runtime)) addIssue([\"blockers\", index], \"A Cloud service blocker must carry the availability's exact reason\");\n}\nfunction validateSetupBlockers(snapshot, addIssue) {\n\tconst currentBinding = readCurrentBinding(snapshot.messaging);\n\tfor (const [index, blocker] of snapshot.blockers.entries()) {\n\t\tif (blocker.code === \"cloud-service-unavailable\") {\n\t\t\tvalidateCloudBlocker(snapshot, blocker, index, addIssue);\n\t\t\tcontinue;\n\t\t}\n\t\tif (blocker.code !== \"messaging-unbind-required\") continue;\n\t\tif (currentBinding?.provider !== blocker.currentProvider || currentBinding.bindingId !== blocker.currentBindingId) addIssue([\"blockers\", index], \"An unbind-required blocker must name the current binding\");\n\t}\n}\nfunction validateSetupRequiredProviders(snapshot, addIssue) {\n\tconst { requiredImCliProviders } = snapshot;\n\tif (snapshot.computer.kind === \"cloud\") {\n\t\tif (requiredImCliProviders.length !== 0) addIssue([\"requiredImCliProviders\"], \"A Cloud setup requires no local IM CLI Providers\");\n\t\treturn;\n\t}\n\tconst canonical = AGENT_SETUP_REQUIRED_IM_CLI_PROVIDERS;\n\tif (requiredImCliProviders.length !== canonical.length || requiredImCliProviders.some((provider, index) => provider !== canonical[index])) addIssue([\"requiredImCliProviders\"], \"Required IM CLI Providers must be exactly the canonical set in canonical order, without duplicates\");\n}\nfunction validateSetupComponents(snapshot, addIssue) {\n\tconst expected = projectAgentSetupComponents({\n\t\tcomputer: snapshot.computer,\n\t\truntime: snapshot.runtime,\n\t\tmessaging: snapshot.messaging,\n\t\trequiredImCliProviders: snapshot.requiredImCliProviders\n\t});\n\tif (stableSerialize(snapshot.components) !== stableSerialize(expected)) addIssue([\"components\"], \"Components must project the exact Computer, runtime Provider, and required IM CLI readiness in canonical order\");\n}\nconst AgentSetupSnapshotSchema = AgentSetupSnapshotBaseSchema.superRefine((snapshot, context) => {\n\tconst addIssue = (path, message) => context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath,\n\t\tmessage\n\t});\n\tvalidateSetupComputer(snapshot, addIssue);\n\tvalidateSetupRuntime(snapshot, addIssue);\n\tvalidateSetupRequiredProviders(snapshot, addIssue);\n\tvalidateSetupComponents(snapshot, addIssue);\n\tvalidateSetupStage(snapshot, addIssue);\n\tvalidateSetupActions(snapshot, addIssue);\n\tvalidateSetupBlockers(snapshot, addIssue);\n});\nconst AGENT_SETUP_RETURN_SURFACES = [\"agent-setup\", \"agent-messaging-settings\"];\nconst AgentSetupReturnSurfaceSchema = z.enum(AGENT_SETUP_RETURN_SURFACES);\nconst AgentSetupExpectedMessagingStateSchema = z.discriminatedUnion(\"kind\", [z.object({ kind: z.literal(\"unbound\") }).strict(), z.object({\n\tkind: z.literal(\"bound\"),\n\tprovider: ImProviderSchema,\n\tbindingId: z.string().uuid(),\n\tcredentialGeneration: z.number().int().positive()\n}).strict()]);\nconst AgentSetupSlackOAuthContextSchema = z.object({\n\tagentId: z.string().uuid(),\n\tintent: SlackConfigurationIntentSchema,\n\treturnSurface: AgentSetupReturnSurfaceSchema,\n\texpectedMessaging: AgentSetupExpectedMessagingStateSchema\n}).strict().superRefine((oauth, context) => {\n\tif (oauth.intent === \"create\" && oauth.expectedMessaging.kind !== \"unbound\") context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"expectedMessaging\"],\n\t\tmessage: \"Slack create requires the Agent to remain unbound\"\n\t});\n\tif (oauth.intent === \"reauthorize\" && (oauth.expectedMessaging.kind !== \"bound\" || oauth.expectedMessaging.provider !== \"slack\")) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"expectedMessaging\"],\n\t\tmessage: \"Slack reauthorization requires the exact current Slack binding\"\n\t});\n});\nconst AGENT_CREATION_RECOVERY_ACTIONS = [\n\t\"check-result\",\n\t\"retry\",\n\t\"discard\"\n];\nconst AgentCreationRecoveryActionSchema = z.enum(AGENT_CREATION_RECOVERY_ACTIONS);\n//#endregion\n//#region src/auth.ts\nconst TokenResponseFields = {\n\taccessToken: z.string().min(1),\n\trefreshToken: z.string().min(1),\n\ttokenType: z.literal(\"Bearer\"),\n\texpiresIn: z.number().int().positive()\n};\nconst ConnectCodeExchangeRequestSchema = z.object({\n\tcode: z.string().trim().min(16).max(512),\n\texpectedUserId: z.string().uuid().optional()\n}).strict();\nconst ConnectCodeExchangeResponseSchema = z.object(TokenResponseFields).strict();\nconst ConnectCodeIssueResponseSchema = z.object({\n\tbootstrapCommand: z.string().min(1),\n\texpiresIn: z.number().int().positive(),\n\tissuedAt: z.string().datetime()\n}).strict();\nconst ConnectCodeIssueRequestSchema = z.object({}).strict();\nconst RefreshTokenRequestSchema = z.object({ refreshToken: z.string().min(1).max(4096) }).strict();\nconst RefreshTokenResponseSchema = z.object(TokenResponseFields).strict();\nconst AuthIdentityProviderSchema = z.enum([\n\t\"google\",\n\t\"github\",\n\t\"oidc\"\n]);\nconst UserDisplayNameSchema = z.string().trim().min(1).max(255);\nconst UserProfileSchema = z.object({\n\tid: z.string().uuid(),\n\temail: z.string().email(),\n\tdisplayName: UserDisplayNameSchema\n}).strict();\nconst UpdateUserProfileRequestSchema = z.object({ displayName: UserDisplayNameSchema }).strict();\n/**\n* Authentication proves Account identity only. `setupCompletedAt` is durable Account state from\n* `users.setup_completed_at`; it is never derived from Agents, Workspaces, or grants.\n*/\nconst MeResponseSchema = z.object({\n\tuser: UserProfileSchema,\n\tsetupCompletedAt: z.string().datetime().nullable()\n}).strict();\n/** Minimal session presence for the public website; never includes Account identity or credentials. */\nconst BrowserSessionStatusResponseSchema = z.object({ authenticated: z.boolean() }).strict();\n/**\n* Password bounds, shared so one number governs both sides of the check.\n*\n* The server configures Better Auth from these same constants. Stating them only in the schema would let the library\n* keep its own defaults underneath, and a password accepted here but refused there — or the reverse — is a rejection\n* with no message that fits it.\n*\n* The floor is twelve rather than the library's eight because this credential is not backed by a second factor and,\n* unlike the redirect providers, is verified entirely by the server that stores it.\n*/\nconst PASSWORD_MIN_LENGTH = 12;\n/** Bounded because the hash cost is paid on the server, so an unbounded password is an unbounded amount of work. */\nconst PASSWORD_MAX_LENGTH = 128;\n/** Not `.trim()`: leading and trailing spaces are part of a password, and silently removing them changes the secret. */\nconst PasswordSchema = z.string().min(12).max(128);\nconst EmailAddressSchema = z.string().trim().toLowerCase().email().max(320);\nconst EmailSignUpRequestSchema = z.object({\n\temail: EmailAddressSchema,\n\tpassword: PasswordSchema,\n\tdisplayName: UserDisplayNameSchema\n}).strict();\nconst EmailSignInRequestSchema = z.object({\n\temail: EmailAddressSchema,\n\tpassword: z.string().min(1).max(128)\n}).strict();\n/**\n* `password` is a form rather than a link, so it is the one provider with no `startUrl`.\n*\n* A caller that renders providers by following `startUrl` must therefore special-case it rather than filtering it out,\n* which is why it is listed here at all instead of being reported through a separate field.\n*/\nconst AuthProvidersResponseSchema = z.object({ providers: z.array(z.object({\n\tid: z.enum([\n\t\t\"google\",\n\t\t\"dev\",\n\t\t\"password\"\n\t]),\n\tenabled: z.boolean(),\n\tstartUrl: z.string().min(1).nullable()\n}).strict()) }).strict();\n//#endregion\n//#region src/channel-name.ts\n/**\n* Release channel names. Kept free of Node.js imports so browser bundles and protocol schemas can\n* reference channels without pulling in `node:os`/`node:path`.\n*/\nconst ChannelNameSchema = z.enum([\n\t\"dev\",\n\t\"staging\",\n\t\"prod\"\n]);\n//#endregion\n//#region src/runner-workspace.ts\n/** Latest-state persistence, negotiated independently of delivery and credential transport. */\nconst RUNNER_WORKSPACE_VERSION = 1;\nconst RUNNER_WORKSPACE_PATH = \"/api/v1/sandbox-runner/workspace\";\nconst RUNNER_WORKSPACE_ARCHIVE_MAX_BYTES = 134217728;\nconst RUNNER_WORKSPACE_TIMEOUT_MS = 12e4;\n/** GCS generations are opaque decimal strings; conversion to Number loses precision. */\nconst RunnerWorkspaceObjectSchema = z.object({\n\tgeneration: z.string().regex(/^[1-9][0-9]{0,29}$/),\n\tmetageneration: z.string().regex(/^[1-9][0-9]{0,29}$/),\n\townerGeneration: z.number().int().positive().safe(),\n\tsaved: z.boolean(),\n\tsealed: z.boolean(),\n\tbytes: z.number().int().nonnegative().max(RUNNER_WORKSPACE_ARCHIVE_MAX_BYTES),\n\tsha256: z.string().regex(/^[a-f0-9]{64}$/),\n\tmd5: z.string().regex(/^[A-Za-z0-9+/]{22}==$/)\n}).strict();\n/** Stop all workspace writers, save the latest complete state, and remain sealed until release. */\nconst RunnerWorkspaceSealFrameSchema = z.object({\n\ttype: z.literal(\"workspace:seal\"),\n\trequestId: z.string().uuid()\n}).strict();\nconst RunnerWorkspaceSealResultFrameSchema = z.object({\n\ttype: z.literal(\"workspace:seal:result\"),\n\trequestId: z.string().uuid(),\n\tok: z.boolean(),\n\tcode: z.enum([\"workspace_save_failed\", \"workspace_not_restored\"]).optional()\n}).strict();\n//#endregion\n//#region src/mcp-gateway.ts\n/**\n* MCP gateway contract — the runtime half of the MCP feature.\n*\n* The management plane (`./mcp.ts`) lets an Account register MCP Servers and authorize them per\n* Agent. This module describes how a running Agent actually *reaches* those Servers: the OpenTag\n* Server publishes one inbound Streamable HTTP MCP endpoint, a provider CLI mounts it like any\n* other remote MCP Server, and the gateway aggregates every Server that Agent has bound.\n*\n* Two properties shape everything here:\n*\n* - **No upstream credential ever leaves the Server.** The gateway resolves the Agent's own\n*   authorization row and builds the outbound headers itself, so the Agent's machine never holds a\n*   decrypted upstream secret.\n* - **The Agent's credential is execution-scoped.** The bearer the provider CLI presents resolves to\n*   one live execution and nothing else; it is worthless the moment that execution ends, so a token\n*   read out of a config file by a prompt-injected Agent buys no lasting access.\n*\n* Nothing in this module carries a secret: the token itself travels in its own runtime frame\n* (`./runtime-credentials.ts`), never in a schema defined here.\n*/\n/** The single fixed inbound route. A caller cannot select another target. */\nconst MCP_GATEWAY_PATH = \"/api/v1/mcp\";\n/**\n* The name the gateway registers itself under in a provider's MCP configuration.\n*\n* Constrained by Claude Code's permission-rule grammar, `/^mcp__[\\w-]+(?:__(?:[\\w.-]+|\\*))?$/`: the\n* server half admits only word characters and hyphens. A bare `mcp__<server>` rule matches every\n* tool of that server, which is why the aggregated tool list need not be known at launch time.\n*/\nconst MCP_GATEWAY_SERVER_NAME = \"opentag-mcp\";\n/** The permission-rule entry that authorizes every aggregated tool. */\nconst MCP_GATEWAY_ALLOWED_TOOL_RULE = `mcp__${MCP_GATEWAY_SERVER_NAME}`;\nconst RUNTIME_MCP_SERVICE = \"mcp\";\n/**\n* The one scope this service grants. Listing and calling are not separable: a client that can see a\n* tool can call it, and a client that cannot see one has no name to call.\n*/\nconst RuntimeMcpServiceScopeSchema = z.enum([\"mcp:tools\"]);\n/**\n* The composed tool name bound.\n*\n* An upstream tool name is already bounded at 128 bytes and a Server name at 64, so a naive\n* `<server>__<tool>` reaches 194 — past what several MCP clients accept. Names that would exceed\n* this are shortened deterministically; see {@link composeGatewayToolName}.\n*/\nconst MCP_GATEWAY_TOOL_NAME_MAX_BYTES = 128;\n/** Total tools the gateway will publish for one Agent, across every Server it has bound. */\nconst MCP_GATEWAY_MAX_TOOLS = 400;\n/** Inbound JSON-RPC request bound. */\nconst MCP_GATEWAY_REQUEST_MAX_BYTES = 1048576;\n/** The separator between the Server name and the upstream tool name. */\nconst MCP_GATEWAY_NAME_SEPARATOR = \"__\";\n/** Hex characters of the disambiguating digest appended to a shortened name. */\nconst DIGEST_LENGTH = 6;\n/**\n* Compose the model-facing name for one upstream tool.\n*\n* The plain form is `<serverName>__<toolName>`, which is what a model sees and what reads back\n* unambiguously to a human. When that exceeds {@link MCP_GATEWAY_TOOL_NAME_MAX_BYTES} the tool half\n* is truncated and a short digest of the *full* pair is appended, so two long tool names sharing a\n* prefix still land on distinct composed names.\n*\n* The result is a pure function of its inputs, which is what lets the gateway stay stateless: it\n* never stores a name map, it recomputes composed names over the Agent's stored tool snapshots and\n* matches the one the caller asked for.\n*/\nfunction composeGatewayToolName(serverName, toolName) {\n\tconst plain = `${serverName}__${toolName}`;\n\tif (runtimeUtf8Length(plain) <= 128) return plain;\n\tconst digest = shortDigest(`${serverName}\\u0000${toolName}`);\n\tconst prefix = `${serverName}__`;\n\tconst budget = 128 - (runtimeUtf8Length(prefix) + DIGEST_LENGTH + 1);\n\treturn `${prefix}${budget > 0 ? truncateToBytes(toolName, budget) : \"\"}-${digest}`;\n}\n/**\n* Truncate to a byte budget without splitting a UTF-8 code point.\n*\n* `String.prototype.slice` counts UTF-16 code units, so a budget expressed in bytes cannot be\n* applied directly: one emoji is two code units and four bytes. Characters are appended while the\n* running byte count fits, which also keeps a surrogate pair whole because iteration yields code\n* points rather than code units.\n*/\nfunction truncateToBytes(value, maxBytes) {\n\tlet bytes = 0;\n\tlet result = \"\";\n\tfor (const character of value) {\n\t\tconst size = runtimeUtf8Length(character);\n\t\tif (bytes + size > maxBytes) break;\n\t\tbytes += size;\n\t\tresult += character;\n\t}\n\treturn result;\n}\n/**\n* A short digest over the full name pair.\n*\n* FNV-1a rather than SHA-256: this module is browser-safe and must not reach for `node:crypto`, and\n* the digest is a disambiguator among at most {@link MCP_GATEWAY_MAX_TOOLS} names of one Account —\n* not a security boundary. A collision would make one tool unaddressable, which the gateway detects\n* when two snapshot entries compose to the same name.\n*/\nfunction shortDigest(value) {\n\tlet hash = 2166136261;\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\thash ^= value.charCodeAt(index);\n\t\thash = Math.imul(hash, 16777619) >>> 0;\n\t}\n\treturn hash.toString(16).padStart(8, \"0\").slice(0, DIGEST_LENGTH);\n}\n/**\n* Why the gateway refused, as a bounded code.\n*\n* These describe the *gateway*, not an upstream Server. An upstream failure is reported to the model\n* as a tool result with `isError: true`, because a model reads and recovers from that, while a\n* transport error ends its turn.\n*\n* The list is exactly what the gateway produces. Codes for conditions it can describe but never\n* reaches — an ambiguous tool name, an oversized result, a catalogue outage — were declared and\n* mapped to statuses before anything raised them, which made the contract describe a larger surface\n* than the implementation has.\n*/\nconst MCP_GATEWAY_ERROR_CODES = [\n\t\"unauthenticated\",\n\t\"execution_unknown\",\n\t\"execution_closed\",\n\t\"scope_denied\",\n\t\"timeout\"\n];\nconst McpGatewayErrorCodeSchema = z.enum(MCP_GATEWAY_ERROR_CODES);\n//#endregion\n//#region src/web-tools.ts\n/**\n* Tavily web tools v1 wire authority (OpenTag side).\n*\n* Chain: Pi extension → trusted Runner/Client gateway (local Unix socket where supported; the\n* native Cloud sandbox uses the verified dedicated sandbox-exec duplex pipe, never a mounted\n* parent socket) → OpenTag Server (`POST /api/v1/runtime/web/search|fetch`, authenticated by a Local\n* machine token or a Cloud execution bearer, execution-fenced) → existing Router\n* (`POST /v1/web/search|fetch`, one deployment-wide Bearer key held only by the Server). Every object here is strict: unknown fields are rejected at each\n* hop and never forwarded. Nothing in this module carries a supplier key or the deployment's Router\n* web-only key — those never cross the OpenTag wire.\n*/\nconst WEB_TOOLS_PROTOCOL_VERSION = 1;\n/** Fixed Server routes the trusted Runner calls. Callers cannot select another target. */\nconst RUNTIME_WEB_SEARCH_PATH = \"/api/v1/runtime/web/search\";\nconst RUNTIME_WEB_FETCH_PATH = \"/api/v1/runtime/web/fetch\";\n/** Fixed trusted-gateway paths the Pi extension calls on the per-execution Unix socket. */\nconst WEB_GATEWAY_SEARCH_PATH = \"/web/search\";\nconst WEB_GATEWAY_FETCH_PATH = \"/web/fetch\";\n/**\n* Remaining end-to-end budget header. Reconstructed by each trusted hop from its own clock,\n* never forwarded verbatim, and never part of the semantic request digest.\n*/\nconst WEB_TIMEOUT_HEADER = \"x-web-timeout-ms\";\nconst WEB_REQUEST_MAX_BYTES = 16384;\nconst WEB_SEARCH_QUERY_MAX_CODEPOINTS = 400;\nconst WEB_SEARCH_LIMIT_DEFAULT = 5;\nconst WEB_SEARCH_LIMIT_MAX = 10;\nconst WEB_SEARCH_DOMAINS_MAX = 10;\nconst WEB_DOMAIN_MAX_BYTES = 253;\n/** Router accepts 1..64 characters (English names such as `portuguese` are valid). */\nconst WEB_LANGUAGE_MAX_CODEPOINTS = 64;\nconst WEB_PUBLISHED_AT_MAX_BYTES = 128;\nconst WEB_FETCH_URLS_MAX = 3;\nconst WEB_URL_MAX_BYTES = 4096;\nconst WEB_SEARCH_TIMEOUT_CAP_MS = 15e3;\nconst WEB_FETCH_TIMEOUT_CAP_MS = 45e3;\n/** Server↔Router and Runner↔Server serialized response bounds. */\nconst WEB_SEARCH_RESPONSE_MAX_BYTES = 1048576;\nconst WEB_FETCH_RESPONSE_MAX_BYTES = 3145728;\n/** Model-facing budgets enforced by the Pi extension. */\nconst WEB_TOOL_PREVIEW_PAGE_MAX_BYTES = 12288;\nconst WEB_TOOL_RESULT_MAX_BYTES = 49152;\n/** Per-page stored extracted-content bound (matches the Router response bound). */\nconst WEB_PAGE_BODY_MAX_BYTES = 1048576;\n/**\n* Idempotency namespace: the Server derives `opentag.web.v1:<executionId>:<toolCallId>`, which\n* is stable across retransmits of one logical tool call, printable ASCII, and ≤ 200 bytes.\n*/\nconst WEB_IDEMPOTENCY_NAMESPACE = \"opentag.web.v1\";\nconst WEB_IDEMPOTENCY_KEY_MAX_BYTES = 200;\nconst WebToolDepthSchema = z.enum([\"basic\", \"advanced\"]);\nconst WebToolTimeRangeSchema = z.enum([\n\t\"day\",\n\t\"week\",\n\t\"month\",\n\t\"year\"\n]);\nconst isoDateTime$1 = z.string().datetime({ offset: true });\nconst uuid = z.string().uuid();\nconst protocolVersion = z.literal(1);\n/** Router rejects raw control characters (and space) before URL parsing; WHATWG strips them. */\nconst RAW_URL_CONTROL_RE = /[\\u0000-\\u0020\\u007f]/;\n/** Public dotted DNS name, at least two labels, 253-byte bound (mirrors the Router grammar). */\nconst ASCII_DOMAIN_RE = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;\nconst NUMERIC_HOST_RE = /^[0-9.]+$/;\nconst HEX_LABEL_RE = /^0x[0-9a-f]+$/;\n/** ES2024 `String.prototype.isWellFormed` without depending on the newer lib target. */\nfunction isWellFormedUnicode(value) {\n\tfor (let index = 0; index < value.length; index += 1) {\n\t\tconst code = value.charCodeAt(index);\n\t\tif (code >= 55296 && code <= 56319) {\n\t\t\tconst next = value.charCodeAt(index + 1);\n\t\t\tif (!(next >= 56320 && next <= 57343)) return false;\n\t\t\tindex += 1;\n\t\t} else if (code >= 56320 && code <= 57343) return false;\n\t}\n\treturn true;\n}\n/** Well-known non-public DNS suffixes (RFC 2606/6762 plus common intranet TLDs). */\nconst INTERNAL_HOST_SUFFIXES = /* @__PURE__ */ new Set([\n\t\"localhost\",\n\t\"local\",\n\t\"internal\",\n\t\"lan\",\n\t\"corp\",\n\t\"home\",\n\t\"intranet\",\n\t\"test\",\n\t\"example\",\n\t\"invalid\",\n\t\"localdomain\"\n]);\n/**\n* Static public-target check: http/https only, no embedded credentials, and a literal IP host\n* must be a public address. The raw string is checked for control characters before WHATWG URL\n* parsing (which silently strips them), and un-UTF-8-encodable strings are rejected instead of\n* being substituted. Hostname destinations are not resolved here — this is not DNS-rebinding\n* protection; the Router re-checks its own host policy. Rejects loopback, private, link-local,\n* CGNAT, multicast, documentation, and other reserved literal ranges for both IPv4 and IPv6\n* (including IPv4-mapped IPv6).\n*/\nfunction parseWebTargetUrl(raw) {\n\tif (raw.length === 0 || runtimeUtf8Length(raw) > 4096) return void 0;\n\tif (!isWellFormedUnicode(raw) || RAW_URL_CONTROL_RE.test(raw)) return void 0;\n\tlet url;\n\ttry {\n\t\turl = new URL(raw);\n\t} catch {\n\t\treturn;\n\t}\n\tif (url.protocol !== \"http:\" && url.protocol !== \"https:\") return void 0;\n\tif (url.username || url.password) return void 0;\n\tconst hostname = url.hostname;\n\tif (!hostname) return void 0;\n\tconst literal = decodeLiteralIp(hostname);\n\tif (literal) return isPublicLiteralAddress(literal) ? url : void 0;\n\treturn isPublicDnsHostname(hostname) ? url : void 0;\n}\n/** Public dotted DNS name for a URL target; a trailing dot or single label is not accepted. */\nfunction isPublicDnsHostname(hostname) {\n\tif (hostname.endsWith(\".\")) return false;\n\tif (runtimeUtf8Length(hostname) > 253) return false;\n\tif (NUMERIC_HOST_RE.test(hostname)) return false;\n\tfor (const label of hostname.split(\".\")) if (HEX_LABEL_RE.test(label)) return false;\n\tif (!ASCII_DOMAIN_RE.test(hostname)) return false;\n\tconst suffix = hostname.slice(hostname.lastIndexOf(\".\") + 1);\n\treturn !INTERNAL_HOST_SUFFIXES.has(suffix);\n}\n/** Documented normalization for fetch dedup/result matching: lowercase scheme+host, drop the default port and the fragment. */\nfunction normalizeWebTargetUrl(raw) {\n\tconst url = parseWebTargetUrl(raw);\n\tif (!url) return void 0;\n\turl.hash = \"\";\n\tif (url.protocol === \"http:\" && url.port === \"80\" || url.protocol === \"https:\" && url.port === \"443\") url.port = \"\";\n\treturn url.toString();\n}\n/** Fixed-length tuple from already-validated values; the defaults never trigger. */\nfunction toIpv4(values) {\n\tconst [a = -1, b = -1, c = -1, d = -1] = values;\n\treturn [\n\t\ta,\n\t\tb,\n\t\tc,\n\t\td\n\t];\n}\nfunction toIpv6(values) {\n\tconst [a = -1, b = -1, c = -1, d = -1, e = -1, f = -1, g = -1, h = -1] = values;\n\treturn [\n\t\ta,\n\t\tb,\n\t\tc,\n\t\td,\n\t\te,\n\t\tf,\n\t\tg,\n\t\th\n\t];\n}\nfunction decodeLiteralIp(hostname) {\n\tconst v4 = parseIpv4(hostname);\n\tif (v4) return {\n\t\tversion: 4,\n\t\tparts: v4\n\t};\n\tconst unbracketed = hostname.startsWith(\"[\") && hostname.endsWith(\"]\") ? hostname.slice(1, -1) : hostname;\n\tif (!unbracketed.includes(\":\")) return void 0;\n\tconst v6 = parseIpv6(unbracketed);\n\treturn v6 ? {\n\t\tversion: 6,\n\t\tgroups: v6\n\t} : void 0;\n}\nfunction parseIpv4(hostname) {\n\tif (!/^[0-9.]+$/.test(hostname)) return void 0;\n\tconst parts = hostname.split(\".\");\n\tif (parts.length !== 4) return void 0;\n\tconst values = [];\n\tfor (const part of parts) {\n\t\tconst value = Number(part);\n\t\tif (!Number.isInteger(value) || value < 0 || value > 255 || String(value) !== part) return void 0;\n\t\tvalues.push(value);\n\t}\n\treturn toIpv4(values);\n}\nfunction parseIpv6(hostname) {\n\tif (hostname.length === 0 || hostname.includes(\"%\")) return void 0;\n\treturn parseIpv6Groups(hostname);\n}\nfunction parseIpv6Groups(address) {\n\tconst halves = address.split(\"::\");\n\tif (halves.length > 2) return void 0;\n\tconst head = parseIpv6Half(halves[0] ?? \"\");\n\tconst tail = halves.length === 2 ? parseIpv6Half(halves[1] ?? \"\") : void 0;\n\tif (!head || halves.length === 2 && !tail) return void 0;\n\tif (halves.length === 1) return head.length === 8 ? toIpv6(head) : void 0;\n\tconst missing = 8 - head.length - (tail?.length ?? 0);\n\tif (missing < 1) return void 0;\n\treturn toIpv6([\n\t\t...head,\n\t\t...Array(missing).fill(0),\n\t\t...tail ?? []\n\t]);\n}\nfunction parseIpv6Half(half) {\n\tif (half === \"\") return [];\n\tconst groups = half.split(\":\");\n\tconst values = [];\n\tfor (const [index, group] of groups.entries()) {\n\t\tif (group.includes(\".\")) {\n\t\t\tif (index !== groups.length - 1) return void 0;\n\t\t\tconst v4 = parseIpv4(group);\n\t\t\tif (!v4) return void 0;\n\t\t\tvalues.push(v4[0] << 8 | v4[1], v4[2] << 8 | v4[3]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!/^[0-9a-fA-F]{1,4}$/.test(group)) return void 0;\n\t\tvalues.push(Number.parseInt(group, 16));\n\t}\n\treturn values;\n}\nfunction isPublicLiteralAddress(literal) {\n\tif (literal.version === 4) return isPublicIpv4(literal.parts);\n\tconst groups = literal.groups;\n\tif (isIpv4MappedGroups(groups)) {\n\t\tconst g6 = groups[6];\n\t\tconst g7 = groups[7];\n\t\treturn isPublicIpv4(toIpv4([\n\t\t\tg6 >> 8,\n\t\t\tg6 & 255,\n\t\t\tg7 >> 8,\n\t\t\tg7 & 255\n\t\t]));\n\t}\n\treturn !isReservedIpv6(groups);\n}\n/** IPv4-mapped and IPv4-compatible IPv6 inherit the IPv4 rules. */\nfunction isIpv4MappedGroups([g0, g1, g2, g3, g4, g5]) {\n\treturn g0 === 0 && g1 === 0 && g2 === 0 && g3 === 0 && g4 === 0 && (g5 === 65535 || g5 === 0);\n}\nfunction isReservedIpv6(groups) {\n\tconst [first] = groups;\n\tif (groups.every((group) => group === 0)) return true;\n\tif (groups[7] === 1 && groups.slice(0, 7).every((group) => group === 0)) return true;\n\tif ((first & 65472) === 65152) return true;\n\tif ((first & 65024) === 64512) return true;\n\tif ((first & 65280) === 65280) return true;\n\treturn isReservedIpv6Assignment(groups);\n}\nfunction isReservedIpv6Assignment(groups) {\n\tconst [first, second, third, fourth] = groups;\n\tif (first === 100 && second === 65435 && third === 1) return true;\n\tif (first === 256 && second === 0 && third === 0 && fourth === 0) return true;\n\tif (first === 8194) return true;\n\tif (first === 16383 && (second & 61440) === 0) return true;\n\tif (first !== 8193) return false;\n\tif (second === 3512) return true;\n\treturn isReservedProtocolAssignment(groups);\n}\n/** 2001::/23 IETF protocol assignments, minus the publicly assigned exceptions. */\nfunction isReservedProtocolAssignment(groups) {\n\tconst [, second, third] = groups;\n\tif ((second & 65024) !== 0) return false;\n\treturn !(second === 1 && third === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 && groups[6] === 0 && (groups[7] === 1 || groups[7] === 2) || second === 3 || second === 4 && third === 274 || (second & 65520) === 32 || (second & 65520) === 48);\n}\nfunction isPublicIpv4(parts) {\n\treturn !isNonPublicIpv4(parts) && !isReservedIpv4(parts);\n}\nfunction isNonPublicIpv4([a, b]) {\n\tif (a === 0) return true;\n\tif (a === 10) return true;\n\tif (a === 127) return true;\n\tif (a === 169 && b === 254) return true;\n\tif (a === 172 && b >= 16 && b <= 31) return true;\n\tif (a === 192 && b === 168) return true;\n\tif (a === 100 && b >= 64 && b <= 127) return true;\n\treturn a >= 224;\n}\nfunction isReservedIpv4([a, b, c, d]) {\n\tif (a === 192 && b === 0 && c === 0) return d !== 9 && d !== 10;\n\tif (a === 192 && b === 0 && c === 2) return true;\n\tif (a === 198 && (b === 18 || b === 19)) return true;\n\tif (a === 198 && b === 51 && c === 100) return true;\n\treturn a === 203 && b === 0 && c === 113;\n}\n/**\n* Public domain entry for search scoping: a plain host name, never a URL, wildcard, or\n* credential. Mirrors the Router grammar: lowercase, IDNA, trailing dots stripped, at least two\n* labels, 253-byte bound. Literal IP hosts and internal-style single labels are not accepted.\n*/\nfunction parseWebDomain(raw) {\n\tconst lowered = normalizeWebDomainInput(raw);\n\tif (!lowered) return void 0;\n\tlet url;\n\ttry {\n\t\turl = new URL(`https://${lowered}`);\n\t} catch {\n\t\treturn;\n\t}\n\tif (url.port || url.username || url.password) return void 0;\n\tconst host = url.hostname;\n\tif (!host || decodeLiteralIp(host)) return void 0;\n\tif (runtimeUtf8Length(host) > 253 || !ASCII_DOMAIN_RE.test(host)) return void 0;\n\treturn host;\n}\n/** Lowercase/IDNA input normalization shared by domain validation, mirroring the Router. */\nfunction normalizeWebDomainInput(raw) {\n\tif (raw.length === 0 || runtimeUtf8Length(raw) > 253) return void 0;\n\tif (!isWellFormedUnicode(raw)) return void 0;\n\tconst lowered = raw.toLowerCase();\n\tif (lowered !== raw.trim().toLowerCase()) return void 0;\n\tif (lowered.includes(\"*\") || lowered.includes(\"@\")) return void 0;\n\tif (/[/:?#\\\\%]/.test(lowered)) return void 0;\n\tconst stripped = lowered.replace(/\\.+$/, \"\");\n\treturn stripped.length > 0 ? stripped : void 0;\n}\nconst querySchema = z.string().min(1).superRefine((value, context) => {\n\tif (!isWellFormedUnicode(value)) {\n\t\tcontext.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"The query must be valid Unicode\"\n\t\t});\n\t\treturn;\n\t}\n\tif ([...value].length > 400) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"The query exceeds the 400-codepoint limit\"\n\t});\n});\nconst domainSchema = runtimeByteString(253, \"A domain exceeds the 253-byte limit\", 1).superRefine((value, context) => {\n\tif (!parseWebDomain(value)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"A domain must be a public host name\"\n\t});\n});\nconst languageSchema = z.string().superRefine((value, context) => {\n\tif (!isWellFormedUnicode(value)) {\n\t\tcontext.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"The language must be valid Unicode\"\n\t\t});\n\t\treturn;\n\t}\n\tif ([...value].length < 1 || [...value].length > 64) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"The language must be 1..64 characters\"\n\t});\n\tif (/[\\u0000-\\u001f\\u007f-\\u009f]/.test(value)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"The language must not contain control characters\"\n\t});\n});\nconst targetUrlSchema = runtimeByteString(WEB_URL_MAX_BYTES, \"A URL exceeds the 4 KiB limit\", 1).superRefine((value, context) => {\n\tif (!parseWebTargetUrl(value)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"A URL must be a public http(s) target without credentials or a non-public literal address\"\n\t});\n});\n/** Business parameters shared by every hop; unknown fields are rejected. */\nconst WebSearchParamsSchema = z.object({\n\tquery: querySchema,\n\tlimit: z.number().int().min(1).max(10).default(5),\n\tdomains: z.array(domainSchema).min(1).max(10).optional(),\n\ttimeRange: WebToolTimeRangeSchema.optional(),\n\tlanguage: languageSchema.optional(),\n\tdepth: WebToolDepthSchema.default(\"basic\")\n}).strict();\nconst WebFetchParamsSchema = z.object({\n\turls: z.array(targetUrlSchema).min(1).max(3),\n\tdepth: WebToolDepthSchema.default(\"basic\")\n}).strict();\n/** Extension → trusted gateway. The gateway injects the execution identity itself. */\nconst WebGatewaySearchRequestSchema = z.object({\n\tprotocolVersion,\n\ttoolCallId: uuid\n}).extend(WebSearchParamsSchema.shape).strict();\nconst WebGatewayFetchRequestSchema = z.object({\n\tprotocolVersion,\n\ttoolCallId: uuid\n}).extend(WebFetchParamsSchema.shape).strict();\n/** Trusted Runner → Server. Identity fields are fence-checked, never trusted as claims. */\nconst WebSearchExecutionRequestSchema = z.object({\n\tprotocolVersion,\n\texecutionId: uuid,\n\ttoolCallId: uuid\n}).extend(WebSearchParamsSchema.shape).strict();\nconst WebFetchExecutionRequestSchema = z.object({\n\tprotocolVersion,\n\texecutionId: uuid,\n\ttoolCallId: uuid\n}).extend(WebFetchParamsSchema.shape).strict();\n/** Server → Router business payload: parameters only — no identity, Account, or timeout fields. */\nconst RouterWebSearchRequestSchema = WebSearchParamsSchema;\nconst RouterWebFetchRequestSchema = WebFetchParamsSchema;\nconst WebSearchResultItemSchema = z.object({\n\tsourceId: runtimeByteString(128, \"A source id exceeds the 128-byte limit\", 1),\n\ttitle: runtimeByteString(2048, \"A result title exceeds the 2 KiB limit\"),\n\turl: runtimeByteString(WEB_URL_MAX_BYTES, \"A result URL exceeds the 4 KiB limit\", 1),\n\tsnippet: runtimeByteString(8192, \"A result snippet exceeds the 8 KiB limit\"),\n\tpublishedAt: runtimeByteString(128, \"A published timestamp exceeds the 128-byte limit\").optional()\n}).strict();\nconst WebSearchResultSchema = z.object({\n\trequestId: runtimeByteString(128, \"The request id exceeds the 128-byte limit\", 1),\n\tstatus: z.literal(\"ok\"),\n\tretrievedAt: isoDateTime$1,\n\teffectiveDepth: WebToolDepthSchema,\n\tresults: z.array(WebSearchResultItemSchema).max(25)\n}).strict();\n/**\n* Wire fetch item. `artifactPath`/`artifactSaved`/`sha256` are extension-local additions made\n* only after a verified file write; they are never part of the Server/Router payload.\n*/\nconst WebFetchItemSuccessSchema = z.object({\n\tstatus: z.enum([\"ok\", \"partial\"]),\n\turl: runtimeByteString(WEB_URL_MAX_BYTES, \"A fetch URL exceeds the 4 KiB limit\", 1),\n\tfinalUrl: runtimeByteString(WEB_URL_MAX_BYTES, \"A final URL exceeds the 4 KiB limit\").nullable(),\n\tcontentKind: z.literal(\"extracted\"),\n\tcompleteness: z.literal(\"unknown\"),\n\tcontent: runtimeByteString(WEB_PAGE_BODY_MAX_BYTES, \"A page body exceeds the 1 MiB limit\"),\n\tsourceFetchedAt: runtimeByteString(64, \"A source fetch timestamp exceeds the 64-byte limit\").nullable(),\n\tpreviewTruncated: z.boolean(),\n\tartifactTruncated: z.boolean(),\n\tupstreamTruncated: z.boolean().nullable()\n}).strict();\nconst WebFetchItemFailureSchema = z.object({\n\tstatus: z.literal(\"failed\"),\n\turl: runtimeByteString(WEB_URL_MAX_BYTES, \"A fetch URL exceeds the 4 KiB limit\", 1),\n\tcode: runtimeByteString(64, \"A failure code exceeds the 64-byte limit\", 1),\n\tretryable: z.boolean()\n}).strict();\nconst WebFetchItemSchema = z.union([WebFetchItemSuccessSchema, WebFetchItemFailureSchema]);\nconst WebFetchResultSchema = z.object({\n\trequestId: runtimeByteString(128, \"The request id exceeds the 128-byte limit\", 1),\n\tstatus: z.enum([\n\t\t\"ok\",\n\t\t\"partial\",\n\t\t\"failed\"\n\t]),\n\tretrievedAt: isoDateTime$1,\n\teffectiveDepth: WebToolDepthSchema,\n\tresults: z.array(WebFetchItemSchema).max(3)\n}).strict();\nconst WEB_TOOL_ERROR_CODES = [\n\t\"invalid_request\",\n\t\"unauthenticated\",\n\t\"web_disabled\",\n\t\"execution_unknown\",\n\t\"execution_closed\",\n\t\"credential_scope_denied\",\n\t\"idempotency_conflict\",\n\t\"insufficient_credit\",\n\t\"request_in_progress\",\n\t\"request_uncertain\",\n\t\"rate_limited\",\n\t\"timeout\",\n\t\"aborted\",\n\t\"upstream_unavailable\",\n\t\"upstream_error\",\n\t\"provider_protocol_error\",\n\t\"response_too_large\",\n\t\"result_unavailable\",\n\t\"unknown\"\n];\nconst WebToolErrorCodeSchema = z.enum(WEB_TOOL_ERROR_CODES);\n/** Bounded, redacted error envelope on every hop; upstream bodies are never echoed. */\nconst WebToolErrorEnvelopeSchema = z.object({ error: z.object({\n\tcode: WebToolErrorCodeSchema,\n\tmessage: runtimeByteString(512, \"The error message exceeds the 512-byte limit\", 1),\n\tretryable: z.boolean().optional()\n}).strict() }).strict();\n/** Existing Router GatewayError envelope (OpenAI-style), parsed defensively and never re-echoed. */\nconst RouterGatewayErrorSchema = z.object({ error: z.object({\n\tmessage: runtimeByteString(1024, \"The Router error message exceeds the 1 KiB limit\"),\n\ttype: runtimeByteString(128, \"The Router error type exceeds the 128-byte limit\"),\n\tparam: runtimeByteString(256, \"The Router error parameter exceeds the 256-byte limit\").nullish(),\n\tcode: runtimeByteString(128, \"The Router error code exceeds the 128-byte limit\").nullish(),\n\trequest_id: runtimeByteString(128, \"The Router request id exceeds the 128-byte limit\").optional()\n}).passthrough() }).passthrough();\n/** Stable derived Idempotency-Key for one logical tool call; retransmits reuse it verbatim. */\nfunction deriveWebIdempotencyKey(input) {\n\tconst key = `${WEB_IDEMPOTENCY_NAMESPACE}:${input.executionId}:${input.toolCallId}`;\n\tif (runtimeUtf8Length(key) > 200 || !/^[\\x20-\\x7e]+$/.test(key)) throw new Error(\"The derived web idempotency key violates the Router bounds\");\n\treturn key;\n}\n/**\n* Remaining-budget rule shared by every hop: an absent budget means the operation's hard cap,\n* a finite positive budget is capped, and an explicitly invalid budget (0, negative, NaN,\n* Infinity, non-integer) fails closed to zero so it can never restart a full cap.\n*/\nfunction capWebTimeoutMs(operation, requestedMs) {\n\tconst cap = operation === \"search\" ? WEB_SEARCH_TIMEOUT_CAP_MS : WEB_FETCH_TIMEOUT_CAP_MS;\n\tif (requestedMs === void 0) return cap;\n\tif (!Number.isSafeInteger(requestedMs) || requestedMs < 1) return 0;\n\treturn Math.min(requestedMs, cap);\n}\n/**\n* Strict header parse: at most seven ASCII digits and a positive value. `undefined` means the\n* header was absent; a malformed header also returns `undefined` so the caller rejects it as\n* invalid_request instead of turning it into a fresh full budget.\n*/\nfunction parseWebTimeoutHeader(raw, operation) {\n\tif (raw === void 0) return void 0;\n\tif (!/^[0-9]{1,7}$/.test(raw)) return void 0;\n\tconst value = Number(raw);\n\tif (!Number.isSafeInteger(value) || value < 1) return void 0;\n\treturn capWebTimeoutMs(operation, value);\n}\nconst RUNTIME_WEB_SERVICE = \"web\";\nconst RuntimeWebServiceScopeSchema = z.enum([\"web:search\", \"web:fetch\"]);\n/** The scope each fixed route requires. */\nfunction webServiceScopeForOperation(operation) {\n\treturn operation === \"search\" ? \"web:search\" : \"web:fetch\";\n}\n//#endregion\n//#region src/execution-services.ts\n/**\n* Platform services a Client may opt into when it opens an execution.\n*\n* This module exists so no single service owns the union. The two schemas below started inside\n* `web-tools.ts`, which was correct while `web` was the only service; adding `mcp` there would have\n* parked the MCP contract permanently inside the Tavily module and made every future service\n* import from it.\n*\n* A grant is a pure authorization statement — the service and its exact scopes. It carries no\n* secret: a service whose runtime needs a credential hands it over through its own frame in\n* `./runtime-credentials.ts`, which is the invariant every other secret in that protocol already\n* follows.\n*/\n/** Services a Client may request at execution open. Each is gated by its own negotiated capability. */\nconst RuntimeExecutionServiceRequestSchema = z.enum([\"web\", \"mcp\"]);\nconst RuntimeWebExecutionServiceSchema = z.object({\n\tservice: z.literal(\"web\"),\n\tscopes: z.array(RuntimeWebServiceScopeSchema).min(1).max(2)\n}).strict();\nconst RuntimeMcpExecutionServiceSchema = z.object({\n\tservice: z.literal(\"mcp\"),\n\tscopes: z.array(RuntimeMcpServiceScopeSchema).min(1).max(1)\n}).strict();\n/**\n* One service grant attached to an opened execution.\n*\n* Discriminated on `service` rather than flattened, so each service states its own scope vocabulary\n* and a reader that narrows on `service === \"web\"` cannot silently accept an `mcp` grant's scopes.\n*/\nconst RuntimeExecutionServiceSchema = z.discriminatedUnion(\"service\", [RuntimeWebExecutionServiceSchema, RuntimeMcpExecutionServiceSchema]);\n//#endregion\n//#region src/github-integration.ts\n/**\n* GitHub integration contract: repository bindings, connection status, and the nonsecret OAuth flow\n* context persisted on a connection row.\n*\n* One OpenTag Account holds at most one current connection per (GitHub host, GitHub App) pair, and the\n* connection carries the bounded repository/Agent binding configuration. These schemas are the source\n* of truth for that JSON: they are strict (unknown fields are rejected), browser-compatible, and they\n* never carry secrets — credential ciphertext, key IDs, OAuth state hashes, and session-bound values\n* live only on the server.\n*\n* Numeric boundaries: GitHub numeric IDs and row version counters cross JSON boundaries as decimal\n* strings (never JS numbers, which lose precision past 2^53) and stay inside the signed PostgreSQL\n* bigint range.\n*/\nconst GITHUB_REPOSITORY_BINDINGS_SCHEMA_VERSION = 1;\nconst GITHUB_REPOSITORY_BINDINGS_MAX_REPOSITORIES = 100;\nconst GITHUB_REPOSITORY_BINDINGS_MAX_AGENT_SCOPES = 1e3;\nconst GITHUB_REPOSITORY_BINDINGS_MAX_BYTES = 262144;\n/** Largest signed PostgreSQL bigint; decimal ID and version strings must stay within it. */\nconst PG_BIGINT_MAX = 9223372036854775807n;\n/**\n* UUIDs compare case-insensitively at the PostgreSQL boundary, so the contract normalizes them to\n* lowercase. Uniqueness rules (binding IDs, Agent/repository/role grants) then cannot be bypassed by\n* letter-case aliases of the same UUID.\n*/\nconst UuidSchema$2 = z.string().uuid().transform((value) => value.toLowerCase());\nfunction fitsPgBigInt(value) {\n\ttry {\n\t\treturn BigInt(value) <= PG_BIGINT_MAX;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** A positive GitHub numeric ID (user/installation/repository/App) as a decimal string. */\nconst GitHubDecimalIdSchema = z.string().regex(/^[1-9][0-9]{0,18}$/, \"A GitHub numeric ID is a positive decimal string\").refine(fitsPgBigInt, { message: \"A GitHub numeric ID must fit the signed PostgreSQL bigint range\" });\n/** A nonnegative row version counter (authorization version / credential generation) as a decimal string. */\nconst GitHubVersionStringSchema = z.string().regex(/^(0|[1-9][0-9]{0,18})$/, \"A row version is a nonnegative decimal string\").refine(fitsPgBigInt, { message: \"A row version must fit the signed PostgreSQL bigint range\" });\nconst GitHubConnectionStateSchema = z.enum([\n\t\"pending\",\n\t\"active\",\n\t\"reauthorization_required\",\n\t\"revoked\",\n\t\"superseded\"\n]);\n/**\n* Every controlled failure the GitHub connection/management services report. The Account HTTP error\n* envelope accepts exactly these codes, so a management failure always reaches the UI as a bounded\n* code instead of collapsing into a generic 500. The set is also the base allowlist for the\n* `lastErrorCode` persisted on a connection row; upstream classifications the worker records add a\n* few explicit entries beside it.\n*/\nconst GITHUB_CONNECTION_ERROR_CODES = {\n\tADMISSION_PROOF_INVALID: \"GITHUB_ADMISSION_PROOF_INVALID\",\n\tADMISSION_PROOF_STALE: \"GITHUB_ADMISSION_PROOF_STALE\",\n\tAGENT_OWNERSHIP_INVALID: \"GITHUB_AGENT_OWNERSHIP_INVALID\",\n\tAUTHORIZATION_VERSION_CONFLICT: \"GITHUB_AUTHORIZATION_VERSION_CONFLICT\",\n\tCONNECTION_CONFLICT: \"GITHUB_CONNECTION_CONFLICT\",\n\tCONNECTION_NOT_FOUND: \"GITHUB_CONNECTION_NOT_FOUND\",\n\tCONNECTION_STATE_INVALID: \"GITHUB_CONNECTION_STATE_INVALID\",\n\tCREDENTIAL_INPUT_INVALID: \"GITHUB_CREDENTIAL_INPUT_INVALID\",\n\tIDENTITY_MISMATCH: \"GITHUB_IDENTITY_MISMATCH\",\n\tINPUT_INVALID: \"GITHUB_INPUT_INVALID\",\n\tOAUTH_FLOW_EXPIRED: \"GITHUB_OAUTH_FLOW_EXPIRED\",\n\tOAUTH_FLOW_INVALID: \"GITHUB_OAUTH_FLOW_INVALID\",\n\tOAUTH_SESSION_MISMATCH: \"GITHUB_OAUTH_SESSION_MISMATCH\",\n\tINTEGRATION_UNAVAILABLE: \"GITHUB_INTEGRATION_UNAVAILABLE\",\n\tUPSTREAM_UNAVAILABLE: \"GITHUB_UPSTREAM_UNAVAILABLE\",\n\tUPSTREAM_ERROR: \"GITHUB_UPSTREAM_ERROR\",\n\tRATE_LIMITED: \"GITHUB_RATE_LIMITED\",\n\tTOKEN_LIFETIME_UNSUPPORTED: \"GITHUB_TOKEN_LIFETIME_UNSUPPORTED\",\n\tADMISSION_INSTALLATION_MISSING: \"GITHUB_ADMISSION_INSTALLATION_MISSING\",\n\tADMISSION_REPOSITORY_MISSING: \"GITHUB_ADMISSION_REPOSITORY_MISSING\",\n\tADMISSION_PERMISSION_INSUFFICIENT: \"GITHUB_ADMISSION_PERMISSION_INSUFFICIENT\",\n\tAPP_IDENTITY_MISMATCH: \"GITHUB_APP_IDENTITY_MISMATCH\",\n\tOAUTH_DENIED: \"GITHUB_OAUTH_DENIED\",\n\t/** A task delegation names an IM binding that is not a current binding of the connection's Account. */\n\tDELEGATED_IM_BINDING_INVALID: \"GITHUB_DELEGATED_IM_BINDING_INVALID\"\n};\nconst GIT_REF_FORBIDDEN_CHARACTERS = /[\\u0000-\\u0020~^:?*[\\\\\\u007f]/;\n/**\n* Full git-check-ref-format validation for a qualified ref — not a prefix check. Rejects empty\n* components, dot-leading components, `.lock` suffixes, `..`, `//`, `@{`, a lone `@`, control\n* characters, and every other byte Git forbids in a refname.\n*/\nfunction isValidGitRefName(ref) {\n\tif (ref.length === 0 || ref.length > 255) return false;\n\tif (GIT_REF_FORBIDDEN_CHARACTERS.test(ref)) return false;\n\tif (ref.startsWith(\"/\") || ref.endsWith(\"/\") || ref.endsWith(\".\")) return false;\n\tif (ref.includes(\"..\") || ref.includes(\"//\") || ref.includes(\"@{\")) return false;\n\tif (ref === \"@\") return false;\n\treturn ref.split(\"/\").every((component) => component.length > 0 && !component.startsWith(\".\") && !component.endsWith(\".lock\"));\n}\n/** A Context Tree branch is always a fully qualified branch ref such as `refs/heads/master`. */\nconst GitBranchRefSchema = z.string().min(1).max(255).refine((ref) => ref.startsWith(\"refs/heads/\") && isValidGitRefName(ref), { message: \"A Tree branch must be a fully qualified valid Git branch ref (refs/heads/<branch>)\" });\nconst GITHUB_AGENT_SCOPE_MAX_DELEGATED_IM_SENDERS = 100;\nconst GITHUB_AGENT_SCOPE_MAX_DELEGATED_SESSION_AGENTS = 100;\n/**\n* A provider-stable messaging identity (the provider's `author_external_id`, for example a Feishu\n* open_id or a Slack member ID) as the owner typed it into the delegation list. The bounded safe\n* shape keeps only the identifier itself: no display names, no conversation IDs, no free text.\n* An identifier outside this shape simply cannot be delegated — the runtime comparison is exact.\n*/\nconst GitHubDelegatedImSenderIdSchema = z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9_.:@+-]{0,254}$/, \"A messaging sender identity starts alphanumeric and uses only letters, digits, or _ . : @ + -\");\n/** One delegated messaging identity: the exact Account-owned IM binding plus the provider sender ID. */\nconst GitHubDelegatedImSenderSchema = z.object({\n\tbindingId: UuidSchema$2,\n\tsenderId: GitHubDelegatedImSenderIdSchema\n}).strict();\n/**\n* The owner's explicit task delegation for one Agent scope. There is deliberately no wildcard: an\n* omitted delegation, or one whose lists are both empty, denies every GitHub execution for the\n* scope. Messaging entries name the exact Account-owned IM binding and provider sender identity\n* the owner trusts; `sessionAgents` names the exact collaborating Agents whose sessions may pass a\n* task down. Duplicates are rejected so a list cannot silently grow aliases.\n*/\nconst GitHubAgentScopeTaskDelegationSchema = z.object({\n\timSenders: z.array(GitHubDelegatedImSenderSchema).max(100),\n\tsessionAgents: z.array(UuidSchema$2).max(100)\n}).strict().superRefine((delegation, context) => {\n\tconst senders = /* @__PURE__ */ new Set();\n\tdelegation.imSenders.forEach((sender, index) => {\n\t\tconst pair = `${sender.bindingId}/${sender.senderId}`;\n\t\tif (senders.has(pair)) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"imSenders\", index],\n\t\t\tmessage: \"A delegated messaging identity appears at most once\"\n\t\t});\n\t\tsenders.add(pair);\n\t});\n\tconst agents = /* @__PURE__ */ new Set();\n\tdelegation.sessionAgents.forEach((agentId, index) => {\n\t\tif (agents.has(agentId)) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"sessionAgents\", index],\n\t\t\tmessage: \"A delegated session Agent appears at most once\"\n\t\t});\n\t\tagents.add(agentId);\n\t});\n});\n/**\n* The single resolution rule for owner task delegation: a scope allows execution only when its\n* explicit delegation lists contain the candidate's exact IM sender or the exact source Agent.\n* A missing delegation, an omitted candidate identity, and an empty list all deny. Only the\n* runtime supplies the candidate, and it must resolve both values from trusted persisted facts.\n*/\nfunction githubAgentScopeAllowsTaskDelegation(scope, candidate) {\n\tconst delegation = scope.taskDelegation;\n\tif (!delegation) return false;\n\tconst sender = candidate.imSender;\n\tif (sender !== void 0 && delegation.imSenders.some((entry) => entry.bindingId === sender.bindingId.toLowerCase() && entry.senderId === sender.senderId)) return true;\n\tconst sourceAgentId = candidate.sourceAgentId?.toLowerCase();\n\treturn sourceAgentId !== void 0 && delegation.sessionAgents.includes(sourceAgentId);\n}\nconst GitHubRepositoryRoleSchema = z.enum([\"code\", \"context_tree\"]);\nconst GitHubRepositoryAccessSchema = z.enum([\"read\", \"write\"]);\nconst GitHubRepositoryPublishModeSchema = z.enum([\"direct\", \"pull_request\"]);\n/**\n* One Agent's use of one bound repository.\n*\n* Read representation: a read-only scope is exactly `{ access: \"read\" }` with **no** `publish`\n* property — never `publish: null` and never a placeholder mode — so a read scope can never request\n* a write publish mode. `access: \"write\"` always names an explicit `publish` mode. `branch` exists\n* exactly for the `context_tree` role: it is required there (a Tree publishes to one branch) and\n* rejected for `code` scopes.\n*\n* `taskDelegation` is optional and defaults to absent, which preserves every binding configuration\n* written before delegation existed — and denies GitHub execution for that scope just as an empty\n* delegation does. It is never defaulted to a permissive value.\n*/\nconst GitHubAgentScopeSchema = z.object({\n\tagentId: UuidSchema$2,\n\trole: GitHubRepositoryRoleSchema,\n\taccess: GitHubRepositoryAccessSchema,\n\tpublish: GitHubRepositoryPublishModeSchema.optional(),\n\tbranch: GitBranchRefSchema.optional(),\n\ttaskDelegation: GitHubAgentScopeTaskDelegationSchema.optional()\n}).strict().superRefine((scope, context) => {\n\tif (scope.access === \"read\" && scope.publish !== void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"publish\"],\n\t\tmessage: \"A read scope cannot request a write publish mode\"\n\t});\n\tif (scope.access === \"write\" && scope.publish === void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"publish\"],\n\t\tmessage: \"A write scope requires an explicit publish mode\"\n\t});\n\tif (scope.role === \"context_tree\" && scope.branch === void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"branch\"],\n\t\tmessage: \"A context_tree scope requires its Tree branch\"\n\t});\n\tif (scope.role === \"code\" && scope.branch !== void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"branch\"],\n\t\tmessage: \"A code scope does not take a Tree branch\"\n\t});\n});\n/** Display-only repository name (`owner/repository`); routing uses the stable numeric IDs. */\nconst GitHubRepositoryFullNameSchema = z.string().min(3).max(255).regex(/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/, \"A repository display name has the owner/repository shape\");\nconst GitHubRepositoryBindingSchema = z.object({\n\t/** Stable client-assigned ID for this binding; unique across the connection's bindings. */\n\tbindingId: UuidSchema$2,\n\tinstallationId: GitHubDecimalIdSchema,\n\trepositoryId: GitHubDecimalIdSchema,\n\tfullNameDisplay: GitHubRepositoryFullNameSchema,\n\tagentScopes: z.array(GitHubAgentScopeSchema).min(1)\n}).strict();\n/**\n* The bounded binding configuration persisted on a connection row: at most 100 repositories, at most\n* 1000 Agent scopes in total, and at most 256 KiB of UTF-8 JSON. Violations fail validation; nothing\n* is silently truncated.\n*/\nconst GitHubRepositoryBindingsSchema = z.array(GitHubRepositoryBindingSchema).max(100).superRefine((bindings, context) => {\n\tconst bindingIds = /* @__PURE__ */ new Set();\n\tconst repositoryPairs = /* @__PURE__ */ new Set();\n\tconst grantedRoles = /* @__PURE__ */ new Set();\n\tlet agentScopeCount = 0;\n\tbindings.forEach((binding, bindingIndex) => {\n\t\tif (bindingIds.has(binding.bindingId)) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [bindingIndex, \"bindingId\"],\n\t\t\tmessage: \"Binding IDs are unique and stable within a connection\"\n\t\t});\n\t\tbindingIds.add(binding.bindingId);\n\t\tconst repositoryPair = `${binding.installationId}/${binding.repositoryId}`;\n\t\tif (repositoryPairs.has(repositoryPair)) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [bindingIndex, \"repositoryId\"],\n\t\t\tmessage: \"One installation/repository pair appears at most once\"\n\t\t});\n\t\trepositoryPairs.add(repositoryPair);\n\t\tbinding.agentScopes.forEach((scope, scopeIndex) => {\n\t\t\tagentScopeCount += 1;\n\t\t\tconst grantedRole = `${scope.agentId}/${binding.repositoryId}/${scope.role}`;\n\t\t\tif (grantedRoles.has(grantedRole)) context.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [\n\t\t\t\t\tbindingIndex,\n\t\t\t\t\t\"agentScopes\",\n\t\t\t\t\tscopeIndex,\n\t\t\t\t\t\"role\"\n\t\t\t\t],\n\t\t\t\tmessage: \"The same Agent/repo/role grant is not duplicated\"\n\t\t\t});\n\t\t\tgrantedRoles.add(grantedRole);\n\t\t});\n\t});\n\tif (agentScopeCount > 1e3) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [],\n\t\tmessage: `A connection holds at most ${GITHUB_REPOSITORY_BINDINGS_MAX_AGENT_SCOPES} Agent scopes`\n\t});\n\tif (new TextEncoder().encode(JSON.stringify(bindings)).length > 262144) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [],\n\t\tmessage: `Repository bindings must fit ${GITHUB_REPOSITORY_BINDINGS_MAX_BYTES} UTF-8 bytes`\n\t});\n});\n/**\n* The canonical serialized form of a binding configuration: schema-normalized (key order, defaults)\n* JSON. Internal callers bind admission proofs to a hash of this exact string.\n*/\nfunction canonicalizeGitHubRepositoryBindings(bindings) {\n\treturn JSON.stringify(GitHubRepositoryBindingsSchema.parse(bindings));\n}\n/** Fixed surfaces a GitHub OAuth round trip may return to. */\nconst GITHUB_OAUTH_RETURN_SURFACES = [\"account-integrations\", \"agent-integrations\"];\nconst GitHubOAuthReturnSurfaceSchema = z.enum(GITHUB_OAUTH_RETURN_SURFACES);\nconst GitHubOAuthFlowIntentSchema = z.enum([\n\t\"create\",\n\t\"reauthorize\",\n\t\"replace\"\n]);\nconst GitHubOAuthFlowPhaseSchema = z.enum([\"awaiting_callback\", \"claimed\"]);\n/** A hex SHA-256 binding of an OAuth flow to the Account login session that started it. */\nconst GitHubLoginSessionHashSchema = z.string().regex(/^[0-9a-f]{64}$/, \"A session hash is hex SHA-256\");\n/**\n* `agentId` deep-links an `agent-integrations` round trip back to the exact Agent that started it;\n* it is rejected on the account surface and required on the Agent surface.\n*/\nconst agentReturnRefinement = (value, context) => {\n\tif (value.returnSurface === \"account-integrations\" && value.agentId !== null) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"agentId\"],\n\t\tmessage: \"Only an agent-integrations flow names its return Agent\"\n\t});\n\tif (value.returnSurface === \"agent-integrations\" && value.agentId === null) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"agentId\"],\n\t\tmessage: \"An agent-integrations flow requires its return Agent\"\n\t});\n};\n/**\n* The nonsecret OAuth flow context persisted on the connection row. One connection carries at most\n* one in-flight authorization; beginning a new flow explicitly voids the previous one. Secret\n* material (the PKCE verifier) never appears here — it lives only in the separate encrypted slot.\n*\n* `agentId` is the exact Agent an `agent-integrations` round trip returns to; it is null on the\n* account surface and defaults to null so contexts persisted before the deep link existed still\n* parse. It is never caller-substituted afterwards: the callback redirect reads it only from this\n* verified context.\n*/\nconst GitHubOAuthContextSchema = z.object({\n\tflowId: UuidSchema$2,\n\tintent: GitHubOAuthFlowIntentSchema,\n\tphase: GitHubOAuthFlowPhaseSchema,\n\tloginSessionHash: GitHubLoginSessionHashSchema,\n\treturnSurface: GitHubOAuthReturnSurfaceSchema,\n\tagentId: UuidSchema$2.nullable().default(null),\n\texpiresAt: z.string().datetime(),\n\tclaimedAt: z.string().datetime().nullable()\n}).strict().superRefine((flow, context) => {\n\tif (flow.phase === \"claimed\" !== (flow.claimedAt !== null)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"claimedAt\"],\n\t\tmessage: \"A claimed flow records its claim time; an awaiting flow has none\"\n\t});\n\tagentReturnRefinement(flow, context);\n});\n/**\n* The nonsecret status of a connection as returned to the owning Account: identity, state, binding\n* configuration, version counters, and maintenance metadata. It never contains credential ciphertext,\n* key IDs, OAuth state/session hashes, or refresh claim internals.\n*/\nconst GitHubConnectionStatusSchema = z.object({\n\tid: UuidSchema$2,\n\taccountId: UuidSchema$2,\n\tgithubHost: z.string().min(1).max(255),\n\tappId: GitHubDecimalIdSchema,\n\tgithubUserId: GitHubDecimalIdSchema.nullable(),\n\tgithubLogin: z.string().min(1).max(100).nullable(),\n\tstatus: GitHubConnectionStateSchema,\n\tbindingsSchemaVersion: z.number().int().min(1),\n\tbindings: GitHubRepositoryBindingsSchema,\n\tauthorizationVersion: GitHubVersionStringSchema,\n\tcredentialGeneration: GitHubVersionStringSchema,\n\taccessExpiresAt: z.string().datetime().nullable(),\n\trefreshExpiresAt: z.string().datetime().nullable(),\n\trecheckRequired: z.boolean(),\n\tnextRecheckAt: z.string().datetime().nullable(),\n\tlastVerifiedAt: z.string().datetime().nullable(),\n\tlastErrorCode: z.string().min(1).max(120).nullable(),\n\tcreatedAt: z.string().datetime(),\n\tupdatedAt: z.string().datetime()\n}).strict();\n/**\n* The first integration stage supports github.com only; the column and DTOs stay host-namespaced so\n* a future GitHub Enterprise stage can widen this literal without a data migration.\n*/\nconst CreateGitHubConnectionRequestSchema = z.object({\n\tgithubHost: z.literal(\"github.com\").default(\"github.com\"),\n\tappId: GitHubDecimalIdSchema,\n\treturnSurface: GitHubOAuthReturnSurfaceSchema.default(\"account-integrations\"),\n\tagentId: UuidSchema$2.nullable().default(null)\n}).strict().superRefine(agentReturnRefinement);\nconst BeginGitHubAuthorizationRequestSchema = z.object({\n\tintent: z.enum([\"reauthorize\", \"replace\"]),\n\treturnSurface: GitHubOAuthReturnSurfaceSchema.default(\"account-integrations\"),\n\tagentId: UuidSchema$2.nullable().default(null)\n}).strict().superRefine(agentReturnRefinement);\n/** A bindings update is fenced against the exact authorization version the caller observed. */\nconst UpdateGitHubConnectionBindingsRequestSchema = z.object({\n\texpectedAuthorizationVersion: GitHubVersionStringSchema,\n\tbindings: GitHubRepositoryBindingsSchema\n}).strict();\n//#endregion\n//#region src/context-tree-operation.ts\nconst ContextTreeOperationRequestSchema = z.object({\n\talias: ContextTreeAliasSchema,\n\toperationId: z.string().uuid(),\n\texpectedRevision: z.number().int().positive(),\n\texpectedRuntimeConfigRevision: z.number().int().positive(),\n\taction: z.enum([\n\t\t\"connect\",\n\t\t\"create\",\n\t\t\"disconnect\"\n\t]),\n\trepository: ContextTreeRepositorySchema.nullable()\n}).strict().refine((input) => input.action === \"disconnect\" ? input.repository === null : input.repository !== null);\nconst ContextTreeOperationResponseSchema = z.discriminatedUnion(\"status\", [z.object({\n\tstatus: z.literal(\"completed\"),\n\trepository: ContextTreeRepositorySchema.nullable()\n}).strict(), z.object({\n\tstatus: z.literal(\"failed\"),\n\tcode: z.enum([\n\t\t\"alias_conflict\",\n\t\t\"repository_conflict\",\n\t\t\"tree_limit_reached\",\n\t\t\"stale_configuration\",\n\t\t\"computer_unavailable\",\n\t\t\"capability_missing\",\n\t\t\"busy\",\n\t\t\"pause_required\",\n\t\t\"authentication_required\",\n\t\t\"permission_denied\",\n\t\t\"repository_exists\",\n\t\t\"invalid_tree\",\n\t\t\"publication_uncertain\",\n\t\t\"failed\"\n\t])\n}).strict()]);\nconst ContextTreeOperationFrameSchema = z.object({\n\ttype: z.literal(\"context-tree:operation\"),\n\trequestId: z.string().uuid(),\n\tagentId: z.string().uuid(),\n\tcomputerId: z.string().uuid(),\n\trequireStopped: z.boolean(),\n\tinput: ContextTreeOperationRequestSchema\n}).strict();\nconst ContextTreeOperationResultFrameSchema = z.object({\n\ttype: z.literal(\"context-tree:operation:result\"),\n\trequestId: z.string().uuid(),\n\tresult: ContextTreeOperationResponseSchema\n}).strict();\n//#endregion\n//#region src/mcp.ts\n/**\n* MCP (Model Context Protocol) management contract.\n*\n* This module is the management plane: Server definitions, per-Agent bindings, and per-Agent\n* authorization (Bearer key or OAuth). The runtime half — how a running Agent actually reaches those\n* Servers — is `./mcp-gateway.ts`, and no credential defined here is ever delivered to a Provider:\n* the gateway resolves an Agent's authorization on the Server and calls upstream itself. See\n* `docs/design/mcp-server-integration.md`.\n*\n* Every schema here is strict and browser-compatible. None of them ever carries secrets: no\n* credential ciphertext or key IDs, no OAuth state/PKCE material, no bearer key values, and no\n* access or refresh tokens. A caller learns only whether a credential exists.\n*\n* Authorization is scoped strictly per Agent. One Server may be authorized differently for two\n* Agents of the same Account — Agent A with a bearer key, Agent B with OAuth — and there is no\n* Account-level fallback.\n*/\nconst UuidSchema$1 = z.string().uuid();\nconst MCPServerNameSchema = z.string().trim().min(1).max(64).regex(/^[a-z0-9][a-z0-9-]*$/, \"Server name must start with a lowercase letter or number and contain only lowercase letters, numbers, and hyphens\");\n/**\n* The human-readable description an operator writes over the probed one.\n*\n* Bounded to 1024 bytes by the datastore as well; the plan's byte bound is enforced server-side.\n* This is an override, not the only source: the Server's own `serverInfo.description` arrives with a\n* probe and is reported separately, so a definition with no override still shows the peer's words.\n*/\nconst MCPServerDescriptionSchema = z.string().trim().min(1).max(1024);\n/**\n* The three authorization kinds. `none` is a real authorization row, not an absence: an anonymous\n* Server still has exactly one row per bound Agent, with no credential.\n*/\nconst MCP_AUTH_KINDS = [\n\t\"none\",\n\t\"bearer\",\n\t\"oauth\"\n];\nconst MCPAuthKindSchema = z.enum(MCP_AUTH_KINDS);\nconst MCPAuthorizationStatusSchema = z.enum([\n\t\"pending\",\n\t\"active\",\n\t\"expired\",\n\t\"revoked\",\n\t\"error\"\n]);\nconst MCPProbeStateSchema = z.enum([\n\t\"pending\",\n\t\"succeeded\",\n\t\"failed\"\n]);\n/**\n* The protocol era of the resolved origin, cached per authorization row because an Agent-level URL\n* override makes the origin differ per Agent. `modern` is the stateless per-request model;\n* `legacy` is the `initialize` handshake of 2025-03-26 through 2025-11-25; `null` means unknown and\n* forces a fresh downgrade detection.\n*/\nconst MCPProtocolEraSchema = z.enum([\"modern\", \"legacy\"]);\nconst MCPClientRegistrationSourceSchema = z.enum([\n\t\"preregistered\",\n\t\"cimd\",\n\t\"dcr\"\n]);\n/**\n* RFC 9110 field-name token characters, lowercase only. The set excludes the empty string, so a field\n* name can never be blank, and it excludes every control character, so CR/LF injection into an\n* outbound request is impossible by construction.\n*/\nconst HTTP_FIELD_NAME_PATTERN = /^[!#$%&'*+\\-.^_`|~0-9a-z]+$/;\n/**\n* A header name the Server always controls and a caller may never set: these either belong to the\n* transport (content negotiation, framing) or to the MCP request metadata the client must author.\n*/\nconst MCP_RESERVED_HEADER_NAMES = [\n\t\"host\",\n\t\"content-length\",\n\t\"connection\",\n\t\"transfer-encoding\",\n\t\"content-type\",\n\t\"accept\",\n\t\"keep-alive\",\n\t\"upgrade\",\n\t\"expect\",\n\t\"te\",\n\t\"trailer\",\n\t\"proxy-authorization\",\n\t\"proxy-connection\"\n];\nconst MCP_MAX_EXTRA_HEADERS = 16;\nconst MCP_MAX_EXTRA_HEADER_VALUE_BYTES = 4096;\nconst MCP_MAX_EXTRA_HEADERS_BYTES = 8192;\nconst MCPAuthHeaderNameSchema = z.string().trim().min(1).max(64).transform((value) => value.toLowerCase()).refine((value) => HTTP_FIELD_NAME_PATTERN.test(value), { message: \"The authorization header must be a valid lowercase HTTP field name\" });\nfunction isReservedHeaderName(name) {\n\tconst lower = name.toLowerCase();\n\tif (lower.startsWith(\"mcp-\")) return true;\n\treturn MCP_RESERVED_HEADER_NAMES.includes(lower);\n}\n/**\n* Normalize extra headers to the stored form: names lowercased, values untouched. Comparison is\n* case-insensitive throughout, so `X-Workspace-Id` and `x-workspace-id` can never be stored as two\n* different headers and a rename cannot smuggle a duplicate past the reserved-name check.\n*/\nfunction normalizeExtraHeaders(value) {\n\tconst normalized = {};\n\tfor (const [rawName, rawValue] of Object.entries(value)) normalized[rawName.trim().toLowerCase()] = rawValue;\n\treturn normalized;\n}\n/** A custom authorization header name: an RFC 9110 token that is neither reserved nor transport-owned. */\nconst MCPCustomAuthHeaderSchema = MCPAuthHeaderNameSchema.refine((value) => !isReservedHeaderName(value), { message: \"The authorization header may not be a reserved or transport-owned header\" });\n/**\n* The prefixed form of the authorization value. An empty string is a legitimate value and means the\n* stored secret is sent verbatim (for example `X-API-Key: <key>`), which is why clearing the\n* override is a separate, explicit action rather than an empty one.\n*/\nconst MCPAuthSchemeSchema = z.string().max(64).refine((value) => !/[\\r\\n]/.test(value), { message: \"The authorization scheme may not contain CR or LF\" });\nconst ExtraHeaderKeySchema = z.string().trim().min(1).max(64).transform((value) => value.toLowerCase()).refine((value) => HTTP_FIELD_NAME_PATTERN.test(value), { message: \"An extra header name must be a valid lowercase HTTP field name\" }).refine((value) => !isReservedHeaderName(value), { message: \"An extra header may not be a reserved or transport-owned header\" });\n/**\n* Whether a string contains a control character.\n*\n* Checked in code rather than with a regex: an escape-form character class is what the linter forbids,\n* and writing the literal bytes is worse. Every control character is refused, not only CR and LF — a\n* NUL reaches undici as an invalid header value and surfaced to the user as an unreachable endpoint,\n* an error about the Server for a header this deployment would not send.\n*/\nfunction hasControlCharacter(value) {\n\tfor (const character of value) {\n\t\tconst codePoint = character.codePointAt(0) ?? 0;\n\t\tif (codePoint < 32 || codePoint === 127) return true;\n\t}\n\treturn false;\n}\nconst ExtraHeaderValueSchema = z.string().max(MCP_MAX_EXTRA_HEADER_VALUE_BYTES).refine((value) => !hasControlCharacter(value), { message: \"An extra header value may not contain control characters\" });\n/**\n* Additional static headers sent alongside the authorization header for every kind. They are not\n* credentials, so they apply to `none` as well. Names are compared case-insensitively and stored\n* lowercased; a name that collides with the effective authorization header is rejected.\n*/\nconst MCPExtraHeadersSchema = z.record(ExtraHeaderKeySchema, ExtraHeaderValueSchema).superRefine((headers, context) => {\n\tconst entries = Object.entries(headers);\n\tif (entries.length > 16) {\n\t\tcontext.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: `At most 16 extra headers are allowed`\n\t\t});\n\t\treturn;\n\t}\n\tif (entries.length === 0) return;\n\tconst normalized = {};\n\tfor (const [name, value] of entries) normalized[name.toLowerCase()] = value;\n\tif (BufferByteLength(JSON.stringify(normalized)) > 8192) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: `The extra headers must serialize to at most ${MCP_MAX_EXTRA_HEADERS_BYTES} bytes`\n\t});\n});\n/** UTF-8 byte length without depending on the Node `Buffer` global, so the browser build works. */\nfunction BufferByteLength(value) {\n\treturn new TextEncoder().encode(value).byteLength;\n}\n/**\n* An outbound MCP endpoint. Scheme, host shape, and reachability rules are enforced by the server's\n* single outbound URL policy (`MCP_URL_BLOCKED`); this schema only bounds the parsed shape so the\n* client and server agree on what a URL field may contain.\n*/\nconst MCPServerUrlSchema = z.string().trim().min(1).max(2048).refine((value) => {\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn (url.protocol === \"https:\" || url.protocol === \"http:\") && !url.username && !url.password && !url.hash && url.hostname.length > 0;\n\t} catch {\n\t\treturn false;\n\t}\n}, \"Must be an HTTP(S) URL without credentials or fragment\");\n/**\n* Per-tool bounds on one `tools/list` entry, in UTF-8 bytes. The probe skips a tool that violates\n* any of them and reports the snapshot as truncated; {@link MCPToolSnapshotSchema} refuses the same\n* tool on read, so a stored snapshot can never hold what a probe would not have stored.\n*\n* The description and schema bounds are sized for real hosted Servers: Linear and Notion ship tool\n* descriptions of several KiB and input schemas past 8 KiB, and a bound that fails them buys\n* nothing over one that fits them, because the list-level caps below still bound the whole\n* snapshot.\n*/\nconst MCP_TOOL_NAME_MAX_BYTES = 128;\nconst MCP_TOOL_DESCRIPTION_MAX_BYTES = 16384;\nconst MCP_TOOL_INPUT_SCHEMA_MAX_BYTES = 65536;\n/**\n* Bound a string in UTF-8 bytes rather than `z.string().max()`'s UTF-16 code units, so the schema\n* agrees with the probe on multi-byte text instead of admitting up to three times its bound.\n*/\nfunction utf8Bounded(schema, maxBytes, what) {\n\treturn schema.refine((value) => BufferByteLength(value) <= maxBytes, { message: `The ${what} must be at most ${maxBytes} bytes` });\n}\n/**\n* The UTF-8 byte length of a value's JSON serialization, or undefined when it has none: a circular\n* structure or a BigInt makes `JSON.stringify` throw, and a value that cannot be serialized cannot\n* be stored or sent to a Provider either, so \"no length\" is the honest answer rather than a crash.\n*/\nfunction serializedUtf8Bytes(value) {\n\ttry {\n\t\tconst text = JSON.stringify(value);\n\t\treturn text === void 0 ? void 0 : BufferByteLength(text);\n\t} catch {\n\t\treturn;\n\t}\n}\n/**\n* The input schema is opaque JSON — the shape is the Server's, never this module's — so it is\n* bounded by serialized size alone, as the probe bounds it. A null (or absent) schema is a tool that\n* takes no arguments and is always within bound.\n*/\nconst MCPToolInputSchemaSchema = z.unknown().refine((value) => {\n\tif (value === null || value === void 0) return true;\n\tconst bytes = serializedUtf8Bytes(value);\n\treturn bytes !== void 0 && bytes <= 65536;\n}, { message: `The tool input schema must serialize to at most ${MCP_TOOL_INPUT_SCHEMA_MAX_BYTES} bytes` });\n/**\n* One `tools/list` entry snapshot. Bounded exactly as the probe bounds it, on every field: this\n* schema is what the gateway parses a stored snapshot back through, so a row written by an older\n* bound, or damaged out of band, cannot put an oversized tool into a live catalogue.\n*/\nconst MCPToolSnapshotSchema = z.object({\n\tname: utf8Bounded(z.string().min(1), 128, \"tool name\"),\n\tdescription: utf8Bounded(z.string(), MCP_TOOL_DESCRIPTION_MAX_BYTES, \"tool description\").nullable(),\n\tinputSchema: MCPToolInputSchemaSchema.nullable()\n}).strict();\n/**\n* List-level caps on the whole snapshot. They are deliberately not the product of the per-tool\n* bounds and the tool count: a Server whose every tool is near the per-tool bounds stops at the byte\n* cap long before the count cap, and the snapshot is reported as truncated, exactly as when a tool\n* was skipped. The Account bound is the sum of every stored snapshot, so 256 such snapshots fill it.\n*/\nconst MCP_PROBE_MAX_TOOLS = 200;\nconst MCP_PROBE_MAX_TOOLS_BYTES = 262144;\nconst MCP_ACCOUNT_TOOL_SNAPSHOT_MAX_BYTES = 67108864;\n/**\n* `defaultAuthKind` is a prefill for a newly created authorization and the trigger for creating a\n* `none` row when binding such a Server. It is never a statement of what the Server requires, and\n* it never constrains the kind an Agent actually writes.\n*/\nconst MCPServerSchema = z.object({\n\tid: UuidSchema$1,\n\tname: MCPServerNameSchema,\n\tdescription: MCPServerDescriptionSchema.nullable(),\n\turl: z.string().min(1),\n\tdefaultAuthKind: MCPAuthKindSchema,\n\tauthHeader: z.string().min(1),\n\tauthScheme: z.string(),\n\textraHeaders: z.record(z.string(), z.string()),\n\trevision: z.number().int().min(1),\n\tboundAgentCount: z.number().int().min(0),\n\tauthorizedAgentCount: z.number().int().min(0),\n\tlastProbedAt: z.string().datetime().nullable(),\n\tcreatedAt: z.string().datetime(),\n\tupdatedAt: z.string().datetime()\n}).strict();\nconst ListMCPServersResponseSchema = z.object({ servers: z.array(MCPServerSchema) }).strict();\n/** The Agent-level overrides. Each is independent; `null` means inherit the shared definition. */\nconst MCPBindingOverridesSchema = z.object({\n\turlOverride: z.string().min(1).nullable(),\n\tauthHeaderOverride: z.string().min(1).nullable(),\n\tauthSchemeOverride: z.string().nullable(),\n\textraHeadersOverride: z.record(z.string(), z.string()).nullable()\n}).strict();\n/** The effective configuration one Agent actually uses: definition values with its overrides applied. */\nconst MCPEffectiveConfigSchema = z.object({\n\turl: z.string().min(1),\n\tauthHeader: z.string().min(1),\n\tauthScheme: z.string(),\n\textraHeaders: z.record(z.string(), z.string())\n}).strict();\n/** Which effective fields came from an Agent override rather than the shared definition. */\nconst MCPOverrideSourcesSchema = z.object({\n\turl: z.boolean(),\n\tauthHeader: z.boolean(),\n\tauthScheme: z.boolean(),\n\textraHeaders: z.boolean()\n}).strict();\n/**\n* The authorization as a caller may read it. There is no credential field of any kind — not even a\n* mask — only `hasCredential`, so a leaked response can never carry key material.\n*/\nconst MCPAuthorizationSummarySchema = z.object({\n\tkind: MCPAuthKindSchema,\n\tstatus: MCPAuthorizationStatusSchema,\n\thasCredential: z.boolean(),\n\tscopes: z.array(z.string()).nullable(),\n\taccessTokenExpiresAt: z.string().datetime().nullable(),\n\tauthorizationServer: z.string().nullable(),\n\tprobeState: MCPProbeStateSchema,\n\tprobedAt: z.string().datetime().nullable(),\n\tprobeError: z.string().nullable(),\n\ttoolsCount: z.number().int().min(0).nullable(),\n\ttoolsTruncated: z.boolean(),\n\tfailureCode: z.string().nullable(),\n\trevision: z.number().int().min(1)\n}).strict();\n/**\n* The Server's own description of itself, out of the `serverInfo` a probe recorded.\n*\n* Derived on read rather than stored as its own column: `serverInfo` is already persisted verbatim,\n* so extracting this is a pure function of data that is already there, and a second column could\n* only drift from it. Returns null for any shape that is not the specification's `Implementation`,\n* because `serverInfo` is untrusted JSON from a peer.\n*/\nfunction probedServerDescription(serverInfo) {\n\tif (typeof serverInfo !== \"object\" || serverInfo === null || Array.isArray(serverInfo)) return null;\n\tconst description = serverInfo.description;\n\tif (typeof description !== \"string\") return null;\n\tconst trimmed = description.trim();\n\treturn trimmed.length === 0 ? null : trimmed.slice(0, 1024);\n}\n/** The snapshot one Agent's own credential produced, plus the era that produced it. */\nconst MCPProbeSnapshotSchema = z.object({\n\tprotocolEra: MCPProtocolEraSchema.nullable(),\n\tprotocolVersion: z.string().nullable(),\n\tserverInfo: z.unknown().nullable(),\n\tcapabilities: z.unknown().nullable(),\n\tinstructions: z.string().max(4096).nullable(),\n\ttools: z.array(MCPToolSnapshotSchema).nullable()\n}).strict();\n/**\n* One Agent's view of one Server: where it mounted, whether it is enabled, the effective\n* configuration, and that Agent's own authorization. `enabled` and the authorization status are\n* independent — a disabled binding keeps its credential and needs no reauthorization.\n*/\nconst MCPAgentServerSchema = z.object({\n\tmcpServerId: UuidSchema$1,\n\tname: MCPServerNameSchema,\n\tdescription: MCPServerDescriptionSchema.nullable(),\n\t/**\n\t* What this Agent's own probe heard the Server say about itself, shown when `description` is\n\t* null. Per Agent rather than per definition because the probe runs with this Agent's\n\t* credential, and two credentials can reach two different origins.\n\t*/\n\tdiscoveredDescription: z.string().max(1024).nullable(),\n\tenabled: z.boolean(),\n\teffective: MCPEffectiveConfigSchema,\n\toverridden: MCPOverrideSourcesSchema,\n\tauthorization: MCPAuthorizationSummarySchema.nullable(),\n\tsnapshot: MCPProbeSnapshotSchema.nullable(),\n\tcreatedAt: z.string().datetime(),\n\tupdatedAt: z.string().datetime()\n}).strict();\nconst ListAgentMCPServersResponseSchema = z.object({ servers: z.array(MCPAgentServerSchema) }).strict();\n/** One row of the Server detail's Agent matrix. */\nconst MCPServerAgentSchema = z.object({\n\tagentId: UuidSchema$1,\n\tagentName: MCPServerNameSchema,\n\tagentDisplayName: AgentDisplayNameSchema,\n\tenabled: z.boolean(),\n\teffective: MCPEffectiveConfigSchema,\n\toverridden: MCPOverrideSourcesSchema,\n\tprotocolEra: MCPProtocolEraSchema.nullable(),\n\tprotocolVersion: z.string().nullable(),\n\tauthorization: MCPAuthorizationSummarySchema.nullable()\n}).strict();\nconst MCPServerDetailSchema = z.object({\n\tserver: MCPServerSchema,\n\tagents: z.array(MCPServerAgentSchema)\n}).strict();\n/** An Account Server that this Agent has not mounted, for the \"add existing Server\" chooser. */\nconst MCPAvailableServerSchema = z.object({\n\tid: UuidSchema$1,\n\tname: MCPServerNameSchema,\n\tdescription: MCPServerDescriptionSchema.nullable(),\n\tboundAgentCount: z.number().int().min(0)\n}).strict();\nconst ListAvailableMCPServersResponseSchema = z.object({ servers: z.array(MCPAvailableServerSchema) }).strict();\n/**\n* Definition create/update input. `authHeader`, `authScheme`, and `extraHeaders` only matter for a\n* bearer authorization; they are still stored on the definition so two Agents can override them\n* independently.\n*\n* `description` is absent on create on purpose: a definition's description is what a probe\n* discovered, and there is nothing to probe until the definition exists. Creation writes NULL and\n* the first successful probe fills it in; `update` is where an operator replaces it.\n*/\nconst CreateMCPServerRequestSchema = z.object({\n\tname: MCPServerNameSchema,\n\turl: MCPServerUrlSchema,\n\tdefaultAuthKind: MCPAuthKindSchema.default(\"oauth\"),\n\tauthHeader: MCPCustomAuthHeaderSchema.optional(),\n\tauthScheme: MCPAuthSchemeSchema.optional(),\n\textraHeaders: MCPExtraHeadersSchema.optional()\n}).strict().superRefine((value, context) => {\n\tif (value.extraHeaders && value.authHeader && value.authHeader in value.extraHeaders) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"extraHeaders\"],\n\t\tmessage: \"An extra header may not repeat the authorization header name\"\n\t});\n});\nconst UpdateMCPServerRequestSchema = z.object({\n\tdescription: MCPServerDescriptionSchema.nullable().optional(),\n\turl: MCPServerUrlSchema.optional(),\n\tdefaultAuthKind: MCPAuthKindSchema.optional(),\n\tauthHeader: MCPCustomAuthHeaderSchema.optional(),\n\tauthScheme: MCPAuthSchemeSchema.optional(),\n\textraHeaders: MCPExtraHeadersSchema.optional(),\n\tclearExtraHeaders: z.boolean().optional(),\n\texpectedRevision: z.number().int().min(1)\n}).strict().superRefine((value, context) => {\n\tif (value.extraHeaders !== void 0 && value.clearExtraHeaders === true) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"extraHeaders\"],\n\t\tmessage: \"Setting extra headers and clearing them are mutually exclusive\"\n\t});\n});\nconst AttachMCPServerRequestSchema = z.object({\n\tmcpServerId: UuidSchema$1,\n\tenabled: z.boolean().default(true)\n}).strict();\n/**\n* The binding update: the single enable/disable layer (target 4) plus this Agent's overrides.\n*\n* Every field follows the same three-state contract: omitted leaves the stored value alone,\n* a value writes an override, and the matching `clearX` flag removes the override so the shared\n* definition applies again. A cleared field is never spelled as an empty value, because an empty\n* `authScheme` is a legitimate override meaning \"send the stored secret verbatim\".\n*\n* `extraHeaders` has one extra action the other three do not: `emptyExtraHeaders` writes `{}`,\n* meaning this Agent sends no extra headers at all, which is distinct from inheriting the\n* definition's set.\n*/\nconst UpdateMCPBindingRequestSchema = z.object({\n\tenabled: z.boolean().optional(),\n\turl: MCPServerUrlSchema.optional(),\n\tclearUrl: z.boolean().optional(),\n\tauthHeader: MCPCustomAuthHeaderSchema.optional(),\n\tclearAuthHeader: z.boolean().optional(),\n\tauthScheme: MCPAuthSchemeSchema.optional(),\n\tclearAuthScheme: z.boolean().optional(),\n\textraHeaders: MCPExtraHeadersSchema.optional(),\n\tclearExtraHeaders: z.boolean().optional(),\n\temptyExtraHeaders: z.boolean().optional(),\n\texpectedRevision: z.number().int().min(1).optional()\n}).strict().superRefine((value, context) => {\n\tfor (const [set, clear] of [\n\t\t[\"url\", \"clearUrl\"],\n\t\t[\"authHeader\", \"clearAuthHeader\"],\n\t\t[\"authScheme\", \"clearAuthScheme\"]\n\t]) if (value[set] !== void 0 && value[clear] === true) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [clear],\n\t\tmessage: \"Set and clear are mutually exclusive\"\n\t});\n\tif ([\n\t\tvalue.extraHeaders !== void 0,\n\t\tvalue.clearExtraHeaders === true,\n\t\tvalue.emptyExtraHeaders === true\n\t].filter(Boolean).length > 1) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"extraHeaders\"],\n\t\tmessage: \"Setting, clearing, and emptying extra headers are mutually exclusive\"\n\t});\n});\n/**\n* Writes a bearer credential (or declares `none`) for exactly this Agent, upserting the one row for\n* this (Server, Agent) pair. Changing kind replaces the credential in the same row.\n*/\nconst SetMCPAuthorizationRequestSchema = z.object({\n\tkind: z.enum([\"none\", \"bearer\"]),\n\tbearerKey: z.string().min(1).max(4096).optional()\n}).strict().superRefine((value, context) => {\n\tif (value.kind === \"bearer\" && value.bearerKey === void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"bearerKey\"],\n\t\tmessage: \"A bearer authorization requires its key\"\n\t});\n\tif (value.kind === \"none\" && value.bearerKey !== void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"bearerKey\"],\n\t\tmessage: \"An anonymous authorization carries no key\"\n\t});\n});\nconst StartMCPOAuthRequestSchema = z.object({ scopes: z.array(z.string().min(1).max(255)).max(64).optional() }).strict();\nconst StartMCPOAuthResponseSchema = z.object({\n\tauthorizationUrl: z.string().url().max(8192),\n\texpiresAt: z.string().datetime()\n}).strict();\nconst MCPProbeResponseSchema = z.object({\n\tprobeState: MCPProbeStateSchema,\n\tprobeError: z.string().nullable(),\n\ttoolsCount: z.number().int().min(0).nullable(),\n\ttoolsTruncated: z.boolean(),\n\tprotocolEra: MCPProtocolEraSchema.nullable(),\n\tprotocolVersion: z.string().nullable()\n}).strict();\n/** The OAuth callback's fixed return surface, mirroring the GitHub/Slack outcome parameters. */\nconst MCP_OAUTH_OUTCOME_PARAM = \"mcp_oauth\";\nconst MCP_OAUTH_ERROR_PARAM = \"mcp_oauth_error\";\nconst MCP_OAUTH_SERVER_PARAM = \"server\";\nconst MCP_OAUTH_OUTCOME_SUCCESS = \"success\";\nconst MCP_OAUTH_OUTCOME_ERROR = \"error\";\nconst MCPOAuthOutcomeSearchSchema = z.object({\n\t[MCP_OAUTH_OUTCOME_PARAM]: z.enum([MCP_OAUTH_OUTCOME_SUCCESS, MCP_OAUTH_OUTCOME_ERROR]),\n\t[MCP_OAUTH_ERROR_PARAM]: z.string().min(1).max(120).optional(),\n\t[MCP_OAUTH_SERVER_PARAM]: UuidSchema$1.optional()\n}).strict();\n/**\n* Bounded public error codes. `MCP_AUTHORIZATION_REQUIRED`, `MCP_AUTHORIZATION_SCOPE_REQUIRED`, and\n* `MCP_REFRESH_OUTCOME_UNKNOWN` are internal verdicts: they appear on a row's `failure_code` and in\n* UI copy, never as the primary code of a management-plane HTTP response.\n*/\nconst MCP_ERROR_CODES = {\n\tSERVER_NOT_FOUND: \"MCP_SERVER_NOT_FOUND\",\n\tSERVER_NAME_CONFLICT: \"MCP_SERVER_NAME_CONFLICT\",\n\tSERVER_FORBIDDEN: \"MCP_SERVER_FORBIDDEN\",\n\tSERVER_REVISION_CONFLICT: \"MCP_SERVER_REVISION_CONFLICT\",\n\tSERVER_IN_USE: \"MCP_SERVER_IN_USE\",\n\tSERVER_URL_INVALID: \"MCP_SERVER_URL_INVALID\",\n\tURL_BLOCKED: \"MCP_URL_BLOCKED\",\n\tBINDING_NOT_FOUND: \"MCP_BINDING_NOT_FOUND\",\n\tBINDING_CONFLICT: \"MCP_BINDING_CONFLICT\",\n\tAUTHORIZATION_NOT_FOUND: \"MCP_AUTHORIZATION_NOT_FOUND\",\n\tAUTHORIZATION_REQUIRED: \"MCP_AUTHORIZATION_REQUIRED\",\n\tAUTHORIZATION_SCOPE_REQUIRED: \"MCP_AUTHORIZATION_SCOPE_REQUIRED\",\n\tAUTHORIZATION_KIND_INVALID: \"MCP_AUTHORIZATION_KIND_INVALID\",\n\tCREDENTIAL_INPUT_INVALID: \"MCP_CREDENTIAL_INPUT_INVALID\",\n\tAUTH_HEADER_INVALID: \"MCP_AUTH_HEADER_INVALID\",\n\tOAUTH_FLOW_INVALID: \"MCP_OAUTH_FLOW_INVALID\",\n\tOAUTH_FLOW_EXPIRED: \"MCP_OAUTH_FLOW_EXPIRED\",\n\tOAUTH_DENIED: \"MCP_OAUTH_DENIED\",\n\tOAUTH_FAILED: \"MCP_OAUTH_FAILED\",\n\tREGISTRATION_UNSUPPORTED: \"MCP_REGISTRATION_UNSUPPORTED\",\n\tREGISTRATION_FAILED: \"MCP_REGISTRATION_FAILED\",\n\tTRANSPORT_UNSUPPORTED: \"MCP_TRANSPORT_UNSUPPORTED\",\n\tPROTOCOL_UNSUPPORTED: \"MCP_PROTOCOL_UNSUPPORTED\",\n\tUPSTREAM_UNAVAILABLE: \"MCP_UPSTREAM_UNAVAILABLE\",\n\tUPSTREAM_ERROR: \"MCP_UPSTREAM_ERROR\",\n\tPROBE_FAILED: \"MCP_PROBE_FAILED\",\n\tREFRESH_OUTCOME_UNKNOWN: \"MCP_REFRESH_OUTCOME_UNKNOWN\"\n};\n/** The `category` / `statusCode` mapping every MCP failure uses; see the design document. */\nconst MCP_ERROR_CODE_METADATA = {\n\t[MCP_ERROR_CODES.SERVER_NOT_FOUND]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 404\n\t},\n\t[MCP_ERROR_CODES.BINDING_NOT_FOUND]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 404\n\t},\n\t[MCP_ERROR_CODES.AUTHORIZATION_NOT_FOUND]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 404\n\t},\n\t[MCP_ERROR_CODES.SERVER_FORBIDDEN]: {\n\t\tcategory: \"credential\",\n\t\tstatusCode: 403\n\t},\n\t[MCP_ERROR_CODES.SERVER_NAME_CONFLICT]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 409\n\t},\n\t[MCP_ERROR_CODES.BINDING_CONFLICT]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 409\n\t},\n\t[MCP_ERROR_CODES.SERVER_REVISION_CONFLICT]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 409\n\t},\n\t[MCP_ERROR_CODES.SERVER_IN_USE]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 409\n\t},\n\t[MCP_ERROR_CODES.SERVER_URL_INVALID]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 400\n\t},\n\t[MCP_ERROR_CODES.URL_BLOCKED]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 400\n\t},\n\t[MCP_ERROR_CODES.AUTH_HEADER_INVALID]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 400\n\t},\n\t[MCP_ERROR_CODES.CREDENTIAL_INPUT_INVALID]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 400\n\t},\n\t[MCP_ERROR_CODES.AUTHORIZATION_KIND_INVALID]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 400\n\t},\n\t[MCP_ERROR_CODES.AUTHORIZATION_REQUIRED]: {\n\t\tcategory: \"credential\",\n\t\tstatusCode: 401\n\t},\n\t[MCP_ERROR_CODES.AUTHORIZATION_SCOPE_REQUIRED]: {\n\t\tcategory: \"credential\",\n\t\tstatusCode: 403\n\t},\n\t[MCP_ERROR_CODES.OAUTH_FLOW_INVALID]: {\n\t\tcategory: \"credential\",\n\t\tstatusCode: 400\n\t},\n\t[MCP_ERROR_CODES.OAUTH_FLOW_EXPIRED]: {\n\t\tcategory: \"credential\",\n\t\tstatusCode: 410\n\t},\n\t[MCP_ERROR_CODES.OAUTH_DENIED]: {\n\t\tcategory: \"credential\",\n\t\tstatusCode: 502\n\t},\n\t[MCP_ERROR_CODES.OAUTH_FAILED]: {\n\t\tcategory: \"credential\",\n\t\tstatusCode: 502\n\t},\n\t[MCP_ERROR_CODES.REGISTRATION_UNSUPPORTED]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 422\n\t},\n\t[MCP_ERROR_CODES.REGISTRATION_FAILED]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 502\n\t},\n\t[MCP_ERROR_CODES.TRANSPORT_UNSUPPORTED]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 422\n\t},\n\t[MCP_ERROR_CODES.PROTOCOL_UNSUPPORTED]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 400\n\t},\n\t[MCP_ERROR_CODES.UPSTREAM_UNAVAILABLE]: {\n\t\tcategory: \"transient\",\n\t\tstatusCode: 503\n\t},\n\t[MCP_ERROR_CODES.UPSTREAM_ERROR]: {\n\t\tcategory: \"transient\",\n\t\tstatusCode: 502\n\t},\n\t[MCP_ERROR_CODES.PROBE_FAILED]: {\n\t\tcategory: \"transient\",\n\t\tstatusCode: 502\n\t},\n\t[MCP_ERROR_CODES.REFRESH_OUTCOME_UNKNOWN]: {\n\t\tcategory: \"transient\",\n\t\tstatusCode: 502\n\t}\n};\n/** The protocol versions this client speaks, newest first. */\nconst MCP_MODERN_PROTOCOL_VERSION = \"2026-07-28\";\nconst MCP_LEGACY_PROTOCOL_VERSIONS = [\n\t\"2025-11-25\",\n\t\"2025-06-18\",\n\t\"2025-03-26\"\n];\nconst MCP_SUPPORTED_PROTOCOL_VERSIONS = [MCP_MODERN_PROTOCOL_VERSION, ...MCP_LEGACY_PROTOCOL_VERSIONS];\n//#endregion\n//#region src/skill-manifest-scalar.ts\nconst YAML_NON_STRING_PATTERNS = [\n\t[\"null\", /^(?:~|null)$/i],\n\t[\"boolean\", /^(?:true|false|yes|no|on|off|y|n)$/i],\n\t[\"number\", /^[-+]?(?:0x[0-9a-f_]+|0o[0-7_]+|0b[01_]+|[0-9][0-9_]*)$/i],\n\t[\"number\", /^[-+]?(?:[0-9][0-9_]*(?:\\.[0-9_]*)?(?:e[-+]?[0-9]+)?|\\.[0-9_]+(?:e[-+]?[0-9]+)?|\\.inf|\\.nan)$/i],\n\t[\"date\", /^\\d{4}-\\d{2}-\\d{2}(?:[Tt ]\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:[ \\t]*(?:Z|[-+]\\d{1,2}(?::?\\d{2})?))?)?$/]\n];\n/** The non-string type a plain scalar resolves to, or `null` when YAML would keep it a string. */\nfunction resolveYamlNonStringType(value) {\n\tfor (const [type, pattern] of YAML_NON_STRING_PATTERNS) if (pattern.test(value)) return type;\n\treturn null;\n}\n//#endregion\n//#region src/skill-manifest.ts\n/**\n* `SKILL.md` manifest parsing for the Agent Skills contract.\n*\n* A Skill manifest is YAML frontmatter with two fields this platform reads: `name` and\n* `description`. Everything else is advisory metadata a real Skill may carry (`license`,\n* `metadata`, `allowed-tools`), so it is skipped rather than validated. Keeping the parser in its own\n* module keeps `skill.ts` under the file-size ratchet; `skill.ts` re-exports this surface, so the\n* public `@opentag/shared` exports are unchanged.\n*\n* The platform deliberately carries no YAML dependency: a bounded hand-written parser is smaller and\n* has no transitive supply chain. The two fields must be scalars, so the parser classifies the value\n* by YAML's structural rules — a flow indicator, a block indicator, a mapping key, or a quoted scalar\n* — rather than by enumerating the collection shapes it has seen. Anything it cannot represent\n* faithfully is a typed rejection with a specific reason, which the Server surfaces as\n* `SKILL_MANIFEST_INVALID`.\n*/\nconst SKILL_MANIFEST_MAX_BYTES = 262144;\nconst SKILL_DESCRIPTION_MAX_LENGTH = 1024;\n/** A Skill name: lowercase alphanumerics joined by single hyphens, 1–64 characters. */\nconst SkillNameSchema = z.string().regex(/^(?=.{1,64}$)[a-z0-9]+(-[a-z0-9]+)*$/, \"Skill name must be 1 to 64 characters of lowercase letters, numbers, and single hyphens, and may not start or end with a hyphen\");\n/**\n* Names the platform already owns, so an Agent can never shadow them with an uploaded Skill.\n*\n* These mirror `CONTEXT_TREE_PACKAGED_SKILL_DIRECTORIES` and `RUNNER_TOOL_SKILL_DIRECTORIES` in\n* `packages/client/src/runner/skills.ts`. `@opentag/shared` may not depend on the Client package, so\n* the values are copied here deliberately; the Client lane adds a parity test that fails when the\n* two lists drift.\n*/\nconst SKILL_RESERVED_NAMES = Object.freeze([\n\t\"context-tree-connect\",\n\t\"context-tree-create\",\n\t\"context-tree-publish\",\n\t\"context-tree-read\",\n\t\"context-tree-setup\",\n\t\"context-tree-write\",\n\t\"git\",\n\t\"gh\",\n\t\"lark-cli\",\n\t\"slack\"\n]);\nfunction isReservedSkillName(name) {\n\treturn SKILL_RESERVED_NAMES.includes(name);\n}\n/**\n* The two fields the platform understands in a `SKILL.md` frontmatter block. Unknown top-level keys\n* are ignored because real Skills carry advisory metadata (`license`, `allowed-tools`, …) that the\n* platform neither stores nor validates.\n*\n* The description is trimmed, because a `>`/`|` block scalar carries its chomping-derived trailing\n* newline into the parsed value and the description is stored and shown as one line.\n*/\nconst SkillManifestSchema = z.object({\n\tname: SkillNameSchema,\n\tdescription: z.string().trim().min(1).max(SKILL_DESCRIPTION_MAX_LENGTH)\n});\nfunction utf8Length(value) {\n\treturn new TextEncoder().encode(value).length;\n}\n/** A frontmatter fence: `---` at column zero, ignoring trailing whitespace. */\nfunction isFrontmatterDelimiter(line) {\n\treturn line.trimEnd() === \"---\";\n}\nfunction extractFrontmatter(lines) {\n\tif (!isFrontmatterDelimiter(lines[0] ?? \"\")) return {\n\t\tok: false,\n\t\treason: \"Skill manifest is missing its frontmatter\"\n\t};\n\tfor (let index = 1; index < lines.length; index += 1) if (isFrontmatterDelimiter(lines[index] ?? \"\")) return {\n\t\tok: true,\n\t\tlines: lines.slice(1, index)\n\t};\n\treturn {\n\t\tok: false,\n\t\treason: \"Skill manifest frontmatter is unterminated\"\n\t};\n}\nconst DOUBLE_QUOTE_ESCAPES = {\n\tn: \"\\n\",\n\tr: \"\\r\",\n\tt: \"\t\",\n\t\"\\\\\": \"\\\\\",\n\t\"\\\"\": \"\\\"\"\n};\nfunction unescapeDoubleQuoted(value) {\n\tlet result = \"\";\n\tlet index = 0;\n\twhile (index < value.length) {\n\t\tconst character = value[index] ?? \"\";\n\t\tif (character !== \"\\\\\") {\n\t\t\tresult += character;\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst replacement = DOUBLE_QUOTE_ESCAPES[value[index + 1] ?? \"\"];\n\t\tif (replacement === void 0) return null;\n\t\tresult += replacement;\n\t\tindex += 2;\n\t}\n\treturn result;\n}\nfunction nonStringRejection(key, type) {\n\treturn {\n\t\tok: false,\n\t\treason: `Skill manifest ${key} must be a string, not a ${type}`\n\t};\n}\nfunction parseBlockIndicator(raw) {\n\tconst first = raw[0];\n\tif (first !== \"|\" && first !== \">\") return null;\n\tconst style = first === \"|\" ? \"literal\" : \"folded\";\n\tconst rest = raw.slice(1);\n\tif (rest === \"\") return {\n\t\tstyle,\n\t\tchomp: \"clip\"\n\t};\n\tif (rest === \"-\") return {\n\t\tstyle,\n\t\tchomp: \"strip\"\n\t};\n\tif (rest === \"+\") return {\n\t\tstyle,\n\t\tchomp: \"keep\"\n\t};\n\treturn null;\n}\nfunction collectBlockLines(lines, startIndex) {\n\tconst collected = [];\n\tlet index = startIndex;\n\twhile (index < lines.length) {\n\t\tconst line = lines[index] ?? \"\";\n\t\tif (line.trim().length === 0) {\n\t\t\tcollected.push(\"\");\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!/^[ \\t]/.test(line)) break;\n\t\tcollected.push(line);\n\t\tindex += 1;\n\t}\n\treturn {\n\t\tlines: collected,\n\t\tnextIndex: index\n\t};\n}\nfunction stripBlockIndent(lines) {\n\tlet indent = null;\n\tfor (const line of lines) {\n\t\tif (line.trim().length === 0) continue;\n\t\tconst width = /^[ \\t]*/.exec(line)?.[0].length ?? 0;\n\t\tindent = indent === null ? width : Math.min(indent, width);\n\t}\n\tconst base = indent ?? 0;\n\treturn lines.map((line) => line.trim().length === 0 ? \"\" : line.slice(base));\n}\nfunction countTrailingBlankLines(lines) {\n\tlet count = 0;\n\tfor (let index = lines.length - 1; index >= 0; index -= 1) {\n\t\tif ((lines[index] ?? \"\").length !== 0) break;\n\t\tcount += 1;\n\t}\n\treturn count;\n}\nfunction foldLines(lines) {\n\tlet result = \"\";\n\tlet blankRun = 0;\n\tlet started = false;\n\tfor (const line of lines) {\n\t\tif (line.length === 0) {\n\t\t\tblankRun += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (started) result += blankRun > 0 ? \"\\n\".repeat(blankRun) : \" \";\n\t\tresult += line;\n\t\tstarted = true;\n\t\tblankRun = 0;\n\t}\n\treturn result;\n}\nfunction applyChomp(body, chomp, trailingBlankLines) {\n\tif (chomp === \"strip\") return body;\n\tif (chomp === \"keep\") return `${body}${\"\\n\".repeat(1 + trailingBlankLines)}`;\n\treturn body.length === 0 ? \"\" : `${body}\\n`;\n}\nfunction renderBlockScalar(rawLines, style, chomp) {\n\tconst lines = stripBlockIndent(rawLines);\n\tconst trailingBlankLines = countTrailingBlankLines(lines);\n\tconst core = trailingBlankLines === 0 ? lines : lines.slice(0, lines.length - trailingBlankLines);\n\treturn applyChomp(style === \"literal\" ? core.join(\"\\n\") : foldLines(core), chomp, trailingBlankLines);\n}\n/** A YAML block-sequence item at any indentation, e.g. `- read` or `  - read`. */\nfunction isSequenceLine(line) {\n\treturn /^[ \\t]*-(\\s|$)/.test(line);\n}\nfunction firstNonBlankLine(lines, startIndex) {\n\tfor (let index = startIndex; index < lines.length; index += 1) {\n\t\tconst line = lines[index] ?? \"\";\n\t\tif (line.trim().length > 0) return line;\n\t}\n}\n/**\n* Skip a value the platform does not read.\n*\n* Every following blank, indented, or list line belongs to the preceding key, whatever it contains.\n* Nested maps (`metadata:`) and block sequences (`allowed-tools:`) under an unknown key are therefore\n* ignored instead of being treated as malformed frontmatter — real `SKILL.md` files use both.\n*/\nfunction collectIgnoredValueLines(lines, startIndex) {\n\tlet index = startIndex;\n\twhile (index < lines.length) {\n\t\tconst line = lines[index] ?? \"\";\n\t\tif (!(line.trim().length === 0 || /^[ \\t]/.test(line) || isSequenceLine(line))) break;\n\t\tindex += 1;\n\t}\n\treturn index;\n}\n/** A YAML inline comment begins at whitespace followed by `#`; a plain scalar may not contain one. */\nfunction hasInlineComment(line) {\n\treturn /[ \\t]#/.test(line);\n}\n/**\n* The characters YAML forbids a plain scalar from starting with. `|` and `>` only reach this check on\n* the continuation path, because a key-line `|`/`>` is a block scalar.\n*/\nconst PLAIN_START_INDICATORS = /* @__PURE__ */ new Set([\n\t\"[\",\n\t\"{\",\n\t\"]\",\n\t\"}\",\n\t\",\",\n\t\"#\",\n\t\"&\",\n\t\"*\",\n\t\"!\",\n\t\"|\",\n\t\">\",\n\t\"%\",\n\t\"@\",\n\t\"`\"\n]);\nfunction startsWithPlainScalarIndicator(line) {\n\tconst first = line[0];\n\tif (first !== void 0 && PLAIN_START_INDICATORS.has(first)) return true;\n\treturn /^[-?:](\\s|$)/.test(line);\n}\n/**\n* The index of the first `:` that ends a mapping key — one followed by whitespace or the end of the\n* line — or -1 when the line has none. A colon inside a URL or a time (`http://x`, `12:30`) is not\n* one.\n*/\nfunction mappingColonIndex(line) {\n\tfor (let index = 0; index < line.length; index += 1) {\n\t\tif (line[index] !== \":\") continue;\n\t\tconst next = line[index + 1];\n\t\tif (next === void 0 || /\\s/.test(next)) return index;\n\t}\n\treturn -1;\n}\nfunction collectionRejection(key) {\n\treturn {\n\t\tok: false,\n\t\treason: `Skill manifest ${key} must be a string, not a list or map`\n\t};\n}\n/**\n* A plain scalar on the key line cannot contain `: `; a strict YAML parser reads it as a mapping key.\n* The reason names the fix, quoting the value, while still containing the collection phrase.\n*/\nfunction quoteRejection(key) {\n\treturn {\n\t\tok: false,\n\t\treason: `Skill manifest ${key} must be a string, not a list or map; quote a value that contains \": \"`\n\t};\n}\nfunction quotedRejection(key) {\n\treturn {\n\t\tok: false,\n\t\treason: `Skill manifest ${key} must be one complete quoted string`\n\t};\n}\n/** Unquote a double-quoted run only when its closing `\"` is the last character and is unescaped. */\nfunction unquoteCompleteDoubleQuoted(folded) {\n\tlet escaped = false;\n\tfor (let index = 1; index < folded.length; index += 1) {\n\t\tconst character = folded[index];\n\t\tif (escaped) {\n\t\t\tescaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"\\\\\") {\n\t\t\tescaped = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character !== \"\\\"\") continue;\n\t\treturn index === folded.length - 1 ? unescapeDoubleQuoted(folded.slice(1, -1)) : null;\n\t}\n\treturn null;\n}\n/** Unquote a single-quoted run only when its closing `'` is the last character and is not a `''`. */\nfunction unquoteCompleteSingleQuoted(folded) {\n\tfor (let index = 1; index < folded.length; index += 1) {\n\t\tif (folded[index] !== \"'\") continue;\n\t\tif (folded[index + 1] === \"'\") {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\treturn index === folded.length - 1 ? folded.slice(1, -1).replaceAll(\"''\", \"'\") : null;\n\t}\n\treturn null;\n}\n/** Unquote a folded run only when it is one complete quoted scalar; otherwise `null`. */\nfunction unquoteFoldedScalar(folded) {\n\tif (folded.length < 2) return null;\n\tif (folded[0] === \"\\\"\") return unquoteCompleteDoubleQuoted(folded);\n\tif (folded[0] === \"'\") return unquoteCompleteSingleQuoted(folded);\n\treturn null;\n}\n/**\n* A quoted scalar, which may start on the key line or on the first continuation line and may span\n* lines. Fold the lines like `>` and require exactly one complete quoted scalar; trailing text, a\n* mapping key after the quote, and an unterminated quote are all rejected.\n*/\nfunction readQuotedScalar(valueLines, key, nextIndex) {\n\tconst unquoted = unquoteFoldedScalar(foldLines(valueLines));\n\tif (unquoted !== null) return {\n\t\tok: true,\n\t\tvalue: unquoted,\n\t\tnextIndex\n\t};\n\tif (mappingColonIndex(firstNonBlankLine(valueLines, 0) ?? \"\") > 0) return collectionRejection(key);\n\treturn quotedRejection(key);\n}\nfunction inlineCommentRejection(key) {\n\treturn {\n\t\tok: false,\n\t\treason: `Skill manifest has an inline comment on the ${key} value`\n\t};\n}\nfunction isQuotedStart(line) {\n\treturn line.startsWith(\"\\\"\") || line.startsWith(\"'\");\n}\n/**\n* YAML's plain-scalar START rule on the effective first value line. A key-line value containing `: `\n* is not a collection but is still invalid YAML, so it gets the \"quote the value\" reason.\n*/\nfunction checkEffectivePlainLine(effective, key, fromKeyLine) {\n\tif (effective === void 0) return null;\n\tif (startsWithPlainScalarIndicator(effective)) return collectionRejection(key);\n\tif (mappingColonIndex(effective) > 0) return fromKeyLine ? quoteRejection(key) : collectionRejection(key);\n\tif (hasInlineComment(effective)) return inlineCommentRejection(key);\n\treturn null;\n}\n/** Every other line of a plain scalar must avoid a mapping colon (`: ` or a trailing `:`) and ` #`. */\nfunction checkPlainContinuationLines(valueLines, effective, key) {\n\tfor (const line of valueLines) {\n\t\tif (line.length === 0 || line === effective) continue;\n\t\tif (mappingColonIndex(line) >= 0) return quoteRejection(key);\n\t\tif (hasInlineComment(line)) return inlineCommentRejection(key);\n\t}\n\treturn null;\n}\n/**\n* A plain scalar, optionally continued on following indented lines. The effective first value line is\n* the key-line value when there is one, otherwise the first non-blank continuation; YAML's\n* plain-scalar start rule applies to it, every line must avoid `: ` and a trailing `:`, and the whole\n* folded value must not resolve to a non-string YAML type.\n*/\nfunction readPlainScalar(lines, index, key, rawValue) {\n\tconst collected = collectBlockLines(lines, index + 1);\n\tconst continuation = stripBlockIndent(collected.lines);\n\tconst valueLines = rawValue.length > 0 ? [rawValue, ...continuation] : continuation;\n\tconst effective = firstNonBlankLine(valueLines, 0);\n\tif (effective !== void 0 && isQuotedStart(effective)) return readQuotedScalar(valueLines, key, collected.nextIndex);\n\tconst effectiveRejection = checkEffectivePlainLine(effective, key, rawValue.length > 0);\n\tif (effectiveRejection) return effectiveRejection;\n\tconst continuationRejection = checkPlainContinuationLines(valueLines, effective, key);\n\tif (continuationRejection) return continuationRejection;\n\tconst folded = foldLines(valueLines).trim();\n\tconst nonStringType = resolveYamlNonStringType(folded);\n\tif (nonStringType !== null) return nonStringRejection(key, nonStringType);\n\treturn {\n\t\tok: true,\n\t\tvalue: folded,\n\t\tnextIndex: collected.nextIndex\n\t};\n}\nfunction readManifestFieldValue(lines, index, key, rawValue) {\n\tif (rawValue.startsWith(\"|\") || rawValue.startsWith(\">\")) {\n\t\tconst block = parseBlockIndicator(rawValue);\n\t\tif (!block) return {\n\t\t\tok: false,\n\t\t\treason: `Skill manifest has an unsupported block scalar for ${key}`\n\t\t};\n\t\tconst collected = collectBlockLines(lines, index + 1);\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: renderBlockScalar(collected.lines, block.style, block.chomp),\n\t\t\tnextIndex: collected.nextIndex\n\t\t};\n\t}\n\treturn readPlainScalar(lines, index, key, rawValue);\n}\nfunction readFrontmatterEntry(lines, index) {\n\tconst line = lines[index] ?? \"\";\n\tif (/^[ \\t]/.test(line)) return {\n\t\tok: false,\n\t\treason: \"Skill manifest frontmatter has an indented line with no preceding key\"\n\t};\n\tconst match = /^([A-Za-z0-9_.-]+)\\s*:(.*)$/.exec(line);\n\tif (!match) return {\n\t\tok: false,\n\t\treason: \"Skill manifest frontmatter has a line that is not a top-level key\"\n\t};\n\tconst key = match[1] ?? \"\";\n\tconst rawValue = (match[2] ?? \"\").trim();\n\tif (key !== \"name\" && key !== \"description\") return {\n\t\tok: true,\n\t\tkey,\n\t\tvalue: \"\",\n\t\tnextIndex: collectIgnoredValueLines(lines, index + 1)\n\t};\n\tconst field = readManifestFieldValue(lines, index, key, rawValue);\n\tif (!field.ok) return field;\n\treturn {\n\t\tok: true,\n\t\tkey,\n\t\tvalue: field.value,\n\t\tnextIndex: field.nextIndex\n\t};\n}\nfunction parseFrontmatterEntries(lines) {\n\tconst entries = /* @__PURE__ */ new Map();\n\tlet index = 0;\n\twhile (index < lines.length) {\n\t\tconst line = lines[index] ?? \"\";\n\t\tif (line.trim().length === 0 || line.startsWith(\"#\")) {\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst entry = readFrontmatterEntry(lines, index);\n\t\tif (!entry.ok) return entry;\n\t\tindex = entry.nextIndex;\n\t\tif (entry.key !== \"name\" && entry.key !== \"description\") continue;\n\t\tif (entries.has(entry.key)) return {\n\t\t\tok: false,\n\t\t\treason: `Skill manifest has a duplicate ${entry.key} field`\n\t\t};\n\t\tentries.set(entry.key, entry.value);\n\t}\n\treturn {\n\t\tok: true,\n\t\tentries\n\t};\n}\n/**\n* Parse the `SKILL.md` frontmatter into a manifest, never throwing.\n*\n* Only `name` and `description` are read, and both must be strings: a quoted scalar (on the key line\n* or on a continuation line), a `>`/`|` block scalar, or a plain scalar (single- or multi-line, folded\n* like `>`). A value that is structurally a collection — a flow list/map or a block\n* sequence/mapping — is rejected with a specific reason, because folding it into a string would accept\n* a `SKILL.md` the reference validator rejects. Unknown top-level keys are ignored together with their\n* value, including nested maps and block sequences, because real `SKILL.md` files carry `metadata` and\n* `allowed-tools`. A plain `name`/`description` may not carry an inline comment, and neither key may\n* repeat.\n*/\nfunction parseSkillManifest(markdown) {\n\tif (utf8Length(markdown) > 262144) return {\n\t\tok: false,\n\t\treason: `Skill manifest exceeds ${SKILL_MANIFEST_MAX_BYTES} bytes`\n\t};\n\tconst frontmatter = extractFrontmatter(markdown.replace(/^\\uFEFF/, \"\").split(/\\r\\n|\\r|\\n/));\n\tif (!frontmatter.ok) return frontmatter;\n\tconst parsed = parseFrontmatterEntries(frontmatter.lines);\n\tif (!parsed.ok) return parsed;\n\tconst name = parsed.entries.get(\"name\");\n\tif (name === void 0) return {\n\t\tok: false,\n\t\treason: \"Skill manifest is missing the name field\"\n\t};\n\tconst description = parsed.entries.get(\"description\");\n\tif (description === void 0) return {\n\t\tok: false,\n\t\treason: \"Skill manifest is missing the description field\"\n\t};\n\tconst result = SkillManifestSchema.safeParse({\n\t\tname,\n\t\tdescription\n\t});\n\tif (!result.success) return {\n\t\tok: false,\n\t\treason: result.error.issues[0]?.message ?? \"Skill manifest is invalid\"\n\t};\n\treturn {\n\t\tok: true,\n\t\tmanifest: result.data\n\t};\n}\n//#endregion\n//#region src/skill.ts\n/**\n* Agent Skills contract.\n*\n* A Skill is a directory containing a `SKILL.md` manifest plus supporting files, uploaded to the\n* platform, stored as one archive object, owned by exactly one Agent, and materialized into that\n* Agent's workspace at runtime. This module is the shared contract only: the Server, Client/CLI and\n* Web lanes build on these schemas, constants, and parsing rules. See\n* `docs/design/agent-skills.md`. Manifest parsing lives in `./skill-manifest.ts`, which this module\n* re-exports.\n*\n* Like every module under `src/` that the browser entrypoint re-exports, this one is\n* browser-compatible: it imports nothing from the Node standard library and never uses the Node\n* byte-array global. Byte lengths are measured with `TextEncoder`, as `mcp.ts` does.\n*/\nconst SKILL_ARCHIVE_MAX_BYTES = 16777216;\nconst SKILL_UNPACKED_MAX_BYTES = 67108864;\nconst SKILL_MAX_ENTRIES = 1e3;\nconst SKILL_MAX_PATH_BYTES = 256;\nconst SKILL_MAX_PER_AGENT = 64;\nconst SKILL_MAX_LISTED_FILES = 500;\nconst SKILL_MANIFEST_FILE = \"SKILL.md\";\n/**\n* The marker the Client writes inside every platform-managed skill directory. Sync only ever\n* rewrites directories that carry it, so a Skill an Agent authors locally, and every Context Tree\n* skill, is left alone.\n*/\nconst SKILL_MARKER_FILE = \".opentag-skill.json\";\nconst SkillIdSchema = z.string().uuid();\nconst SkillSourceSchema = z.enum([\n\t\"web_upload\",\n\t\"cli_upload\",\n\t\"agent_upload\"\n]);\nconst SkillArchiveFormatSchema = z.enum([\"tar.gz\", \"zip\"]);\nconst SkillStorageStatusSchema = z.enum([\"available\", \"unavailable\"]);\n/** Lowercase hex SHA-256 of the stored archive. */\nconst SkillArchiveSha256Schema = z.string().regex(/^[0-9a-f]{64}$/);\nconst SkillFileEntrySchema = z.object({\n\tpath: z.string().min(1).max(256),\n\tbytes: z.number().int().min(0)\n}).strict();\nconst SkillSchema = z.object({\n\tid: SkillIdSchema,\n\tagentId: SkillIdSchema,\n\tname: SkillNameSchema,\n\tdescription: z.string().min(1).max(SKILL_DESCRIPTION_MAX_LENGTH),\n\tenabled: z.boolean(),\n\tsource: SkillSourceSchema,\n\tarchiveSha256: SkillArchiveSha256Schema,\n\tarchiveBytes: z.number().int().min(1).max(SKILL_ARCHIVE_MAX_BYTES),\n\tfileCount: z.number().int().min(1).max(SKILL_MAX_ENTRIES),\n\trevision: z.number().int().min(1),\n\tcreatedAt: z.string().datetime(),\n\tupdatedAt: z.string().datetime()\n}).strict();\nconst SkillDetailSchema = SkillSchema.extend({\n\tfiles: z.array(SkillFileEntrySchema).max(500),\n\tfilesTruncated: z.boolean()\n});\nconst ListAgentSkillsResponseSchema = z.object({\n\tskills: z.array(SkillSchema),\n\tstorage: SkillStorageStatusSchema\n}).strict();\nconst UpdateSkillRequestSchema = z.object({ enabled: z.boolean() }).strict();\n/** One enabled Skill as a Computer needs it to fetch and verify a bundle. */\nconst RuntimeSkillManifestEntrySchema = z.object({\n\tid: SkillIdSchema,\n\tname: SkillNameSchema,\n\tarchiveSha256: SkillArchiveSha256Schema,\n\tarchiveBytes: z.number().int().min(1).max(SKILL_ARCHIVE_MAX_BYTES)\n}).strict();\nconst RuntimeSkillManifestSchema = z.object({ skills: z.array(RuntimeSkillManifestEntrySchema).max(64) }).strict();\n/** The content of `SKILL_MARKER_FILE` written inside every platform-managed skill directory. */\nconst SkillInstallMarkerSchema = z.object({\n\tskillId: SkillIdSchema,\n\tarchiveSha256: SkillArchiveSha256Schema\n}).strict();\nconst SKILL_SHA256_HEADER = \"x-opentag-skill-sha256\";\nconst SKILL_FORMAT_HEADER = \"x-opentag-skill-format\";\nconst SKILL_REPLACE_HEADER = \"x-opentag-skill-replace\";\nconst SKILL_UPLOAD_CONTENT_TYPE = \"application/octet-stream\";\nconst SKILL_ERROR_CODES = {\n\tNOT_FOUND: \"SKILL_NOT_FOUND\",\n\tNAME_CONFLICT: \"SKILL_NAME_CONFLICT\",\n\tREVISION_CONFLICT: \"SKILL_REVISION_CONFLICT\",\n\tLIMIT_REACHED: \"SKILL_LIMIT_REACHED\",\n\tNAME_RESERVED: \"SKILL_NAME_RESERVED\",\n\tMANIFEST_INVALID: \"SKILL_MANIFEST_INVALID\",\n\tARCHIVE_INVALID: \"SKILL_ARCHIVE_INVALID\",\n\tHASH_MISMATCH: \"SKILL_HASH_MISMATCH\",\n\tARCHIVE_TOO_LARGE: \"SKILL_ARCHIVE_TOO_LARGE\",\n\tSTORAGE_UNAVAILABLE: \"SKILL_STORAGE_UNAVAILABLE\"\n};\nconst SKILL_ERROR_CODE_METADATA = {\n\t[SKILL_ERROR_CODES.NOT_FOUND]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 404\n\t},\n\t[SKILL_ERROR_CODES.NAME_CONFLICT]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 409\n\t},\n\t[SKILL_ERROR_CODES.REVISION_CONFLICT]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 409\n\t},\n\t[SKILL_ERROR_CODES.LIMIT_REACHED]: {\n\t\tcategory: \"deterministic\",\n\t\tstatusCode: 409\n\t},\n\t[SKILL_ERROR_CODES.NAME_RESERVED]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 400\n\t},\n\t[SKILL_ERROR_CODES.MANIFEST_INVALID]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 400\n\t},\n\t[SKILL_ERROR_CODES.ARCHIVE_INVALID]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 400\n\t},\n\t[SKILL_ERROR_CODES.HASH_MISMATCH]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 400\n\t},\n\t[SKILL_ERROR_CODES.ARCHIVE_TOO_LARGE]: {\n\t\tcategory: \"validation\",\n\t\tstatusCode: 413\n\t},\n\t[SKILL_ERROR_CODES.STORAGE_UNAVAILABLE]: {\n\t\tcategory: \"transient\",\n\t\tstatusCode: 503\n\t}\n};\n//#endregion\n//#region src/errors.ts\nconst ErrorCategorySchema = z.enum([\n\t\"credential\",\n\t\"deterministic\",\n\t\"validation\",\n\t\"transient\",\n\t\"rate_limit\"\n]);\nconst ErrorCodeSchema = z.enum([\n\t\"AUTH_CODE_CONSUMED\",\n\t\"AUTH_CODE_EXPIRED\",\n\t\"AUTH_DEV_USER_UNAVAILABLE\",\n\t\"AUTH_DEV_USER_UNAVAILABLE\",\n\t\"AUTH_INVALID_CODE\",\n\t\"AUTH_INVALID_TOKEN\",\n\t\"AUTH_OAUTH_FAILED\",\n\t\"AUTH_PROVIDER_DISABLED\",\n\t\"AUTH_IDENTITY_CONFLICT\",\n\t\"AUTH_EMAIL_CONFLICT\",\n\t\"AUTH_USER_SUSPENDED\",\n\t\"AUTH_USER_MISMATCH\",\n\t\"ACCOUNT_SETUP_AGENT_NOT_FOUND\",\n\t\"ACCOUNT_SETUP_NOT_READY\",\n\t\"AGENT_COMPUTER_NOT_BOUND\",\n\t\"AGENT_FORBIDDEN\",\n\t\"AGENT_CREATION_INTENT_CONFLICT\",\n\t\"AGENT_NAME_CONFLICT\",\n\t\"AGENT_LIFECYCLE_CONFLICT\",\n\t\"AGENT_REVISION_CONFLICT\",\n\t\"AGENT_REBIND_BLOCKED\",\n\t\"ONBOARDING_RESET_OWNERSHIP_INCONSISTENT\",\n\t\"ONBOARDING_RESET_UNVERIFIED\",\n\t\"IM_BINDING_CONFIGURATION_CONFLICT\",\n\t\"IM_BINDING_FORBIDDEN\",\n\t\"IM_BINDING_GENERATION_STALE\",\n\t\"IM_BINDING_NOT_FOUND\",\n\t\"IM_BINDING_PROVIDER_IMMUTABLE\",\n\t\"IM_BINDING_SCOPE_REAUTH_REQUIRED\",\n\t\"IM_BINDING_TEMPORARILY_UNAVAILABLE\",\n\t\"IM_BINDING_UNBIND_REQUIRED\",\n\t\"FEISHU_APP_ALREADY_BOUND\",\n\t\"FEISHU_BINDING_IDENTITY_MISMATCH\",\n\t\"FEISHU_UPSTREAM_UNAVAILABLE\",\n\t\"SLACK_APP_TEAM_ALREADY_BOUND\",\n\t\"SLACK_AUTH_IDENTITY_INCOMPLETE\",\n\t\"SLACK_AUTH_INVALID\",\n\t\"SLACK_BINDING_IDENTITY_MISMATCH\",\n\t\"SLACK_CONFIGURATION_CONFLICT\",\n\t\"SLACK_OAUTH_FAILED\",\n\t\"SLACK_SCOPE_REAUTH_REQUIRED\",\n\t\"SLACK_UPSTREAM_UNAVAILABLE\",\n\t\"GITHUB_ADMISSION_PROOF_INVALID\",\n\t\"GITHUB_ADMISSION_PROOF_STALE\",\n\t\"GITHUB_AGENT_OWNERSHIP_INVALID\",\n\t\"GITHUB_AUTHORIZATION_VERSION_CONFLICT\",\n\t\"GITHUB_CONNECTION_CONFLICT\",\n\t\"GITHUB_CONNECTION_NOT_FOUND\",\n\t\"GITHUB_CONNECTION_STATE_INVALID\",\n\t\"GITHUB_CREDENTIAL_INPUT_INVALID\",\n\t\"GITHUB_IDENTITY_MISMATCH\",\n\t\"GITHUB_INPUT_INVALID\",\n\t\"GITHUB_OAUTH_FLOW_EXPIRED\",\n\t\"GITHUB_OAUTH_FLOW_INVALID\",\n\t\"GITHUB_OAUTH_SESSION_MISMATCH\",\n\t\"GITHUB_INTEGRATION_UNAVAILABLE\",\n\t\"GITHUB_UPSTREAM_UNAVAILABLE\",\n\t\"GITHUB_UPSTREAM_ERROR\",\n\t\"GITHUB_RATE_LIMITED\",\n\t\"GITHUB_TOKEN_LIFETIME_UNSUPPORTED\",\n\t\"GITHUB_ADMISSION_INSTALLATION_MISSING\",\n\t\"GITHUB_ADMISSION_REPOSITORY_MISSING\",\n\t\"GITHUB_ADMISSION_PERMISSION_INSUFFICIENT\",\n\t\"GITHUB_APP_IDENTITY_MISMATCH\",\n\t\"GITHUB_OAUTH_DENIED\",\n\t\"GITHUB_DELEGATED_IM_BINDING_INVALID\",\n\t...Object.values(MCP_ERROR_CODES),\n\t...Object.values(SKILL_ERROR_CODES),\n\t\"CLIENT_VERSION_UNSUPPORTED\",\n\t\"COMPUTER_IDENTITY_CONFLICT\",\n\t\"COMPUTER_IN_USE\",\n\t\"COMPUTER_NOT_DELETABLE\",\n\t\"COMPUTER_NOT_DISCONNECTABLE\",\n\t\"COMPUTER_NOT_FOUND\",\n\t\"COMPUTER_NOT_REGISTERED\",\n\t\"PROTOCOL_CAPABILITY_UNSUPPORTED\",\n\t\"PROTOCOL_ERROR\",\n\t\"PROTOCOL_VERSION_UNSUPPORTED\",\n\t\"RUNTIME_AUTH_TIMEOUT\",\n\t\"RUNTIME_REGISTER_TIMEOUT\",\n\t\"SESSION_CURSOR_INVALID\",\n\t\"SESSION_PROOF_INVALID\",\n\t\"TASK_NOT_QUEUED\",\n\t\"SANDBOX_RUNNER_CONFLICT\",\n\t\"CLOUD_CAPACITY_EXCEEDED\",\n\t\"CLOUD_MODEL_NOT_ALLOWED\",\n\t\"CLOUD_MODEL_UNAVAILABLE\",\n\t\"INTERNAL_ERROR\",\n\t\"RATE_LIMITED\",\n\t\"RESOURCE_NOT_FOUND\",\n\t\"SERVICE_UNAVAILABLE\",\n\t\"VALIDATION_ERROR\"\n]);\nconst ValidationIssueSchema = z.object({\n\tpath: z.array(z.union([z.string(), z.number()])),\n\tcode: z.string().min(1),\n\tmessage: z.string().min(1)\n}).strict();\nconst ErrorDetailSchema = z.object({\n\tcode: ErrorCodeSchema,\n\tcategory: ErrorCategorySchema,\n\tmessage: z.string().min(1),\n\trequestId: z.string().min(1).optional(),\n\tretryAfterSeconds: z.number().int().positive().optional(),\n\tissues: z.array(ValidationIssueSchema).optional(),\n\tunbindRequired: ImBindingUnbindRequiredDetailSchema.optional()\n}).strict().superRefine((detail, context) => {\n\tif (detail.unbindRequired && detail.code !== \"IM_BINDING_UNBIND_REQUIRED\") context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"unbindRequired\"],\n\t\tmessage: \"Only an unbind-required failure carries the unbind identity\"\n\t});\n});\nconst ErrorEnvelopeSchema = z.object({ error: ErrorDetailSchema }).strict();\n//#endregion\n//#region src/runtime-protocol.ts\nconst RUNTIME_PROTOCOL_V1 = 1;\nconst RUNTIME_PROTOCOL_V2 = 2;\nconst RUNTIME_PROTOCOL_VERSION = 2;\nconst RUNTIME_SUPPORTED_PROTOCOL_VERSIONS = {\n\tmin: 2,\n\tmax: 2\n};\nconst RUNTIME_PROVIDER_READINESS_V1 = 1;\nconst RUNTIME_PROVIDER_READINESS_V2 = 2;\n/** Frozen v1 wire vocabulary. Pi must never appear under version 1. */\nconst RUNTIME_PROVIDER_READINESS_V1_PROVIDERS = [\"codex\", \"claude-code\"];\n/** Explicit v2 wire vocabulary. Opt-in only; never derived into v1. */\nconst RUNTIME_PROVIDER_READINESS_V2_PROVIDERS = [\n\t\"codex\",\n\t\"claude-code\",\n\t\"pi\"\n];\nconst RUNTIME_V0_CAPABILITIES = {\n\tsessionReconcile: 1,\n\timDelivery: 1,\n\tturnReport: 1,\n\tagentTrace: 1,\n\timCredentialGrant: 1\n};\nconst RUNTIME_CAPABILITY = {\n\tcontextTreeSettings: \"runtime.contextTreeSettings\",\n\tagentRuntimeTest: \"runtime.agentRuntimeTest\",\n\tagentTrace: \"runtime.agentTrace\",\n\tchannelTarget: \"runtime.channelTarget\",\n\timDelivery: \"runtime.imDelivery\",\n\timSteer: \"runtime.imSteer\",\n\timCredentialGrant: \"runtime.imCredentialGrant\",\n\tproviderCliPrewarm: \"runtime.providerCliPrewarm\",\n\tproviderCliReconcile: \"runtime.providerCliReconcile\",\n\tproviderProxy: \"runtime.providerProxy\",\n\truntimeCredential: \"runtime.runtimeCredential\",\n\tsessionCollaboration: \"runtime.sessionCollaboration\",\n\tsessionReconcile: \"runtime.sessionReconcile\",\n\tturnReport: \"runtime.turnReport\",\n\twebTools: \"runtime.webTools\",\n\tmcpGateway: \"runtime.mcpGateway\"\n};\nconst RUNTIME_SERVER_CAPABILITY_OFFERS = {\n\t[RUNTIME_CAPABILITY.contextTreeSettings]: {\n\t\tmin: 1,\n\t\tmax: 1\n\t},\n\t[RUNTIME_CAPABILITY.agentRuntimeTest]: {\n\t\tmin: 1,\n\t\tmax: 1\n\t},\n\t[RUNTIME_CAPABILITY.agentTrace]: {\n\t\tmin: 1,\n\t\tmax: 1\n\t},\n\t[RUNTIME_CAPABILITY.channelTarget]: {\n\t\tmin: 1,\n\t\tmax: 1\n\t},\n\t[RUNTIME_CAPABILITY.imDelivery]: {\n\t\tmin: 1,\n\t\tmax: 2\n\t},\n\t[RUNTIME_CAPABILITY.imSteer]: {\n\t\tmin: 1,\n\t\tmax: 2\n\t},\n\t[RUNTIME_CAPABILITY.imCredentialGrant]: {\n\t\tmin: 1,\n\t\tmax: 2\n\t},\n\t[RUNTIME_CAPABILITY.providerCliPrewarm]: {\n\t\tmin: 1,\n\t\tmax: 1\n\t},\n\t[RUNTIME_CAPABILITY.providerCliReconcile]: {\n\t\tmin: 1,\n\t\tmax: 2\n\t},\n\t[RUNTIME_CAPABILITY.providerProxy]: {\n\t\tmin: 1,\n\t\tmax: 1\n\t},\n\t[RUNTIME_CAPABILITY.runtimeCredential]: {\n\t\tmin: 1,\n\t\tmax: 1\n\t},\n\t[RUNTIME_CAPABILITY.sessionCollaboration]: {\n\t\tmin: 2,\n\t\tmax: 2\n\t},\n\t[RUNTIME_CAPABILITY.sessionReconcile]: {\n\t\tmin: 1,\n\t\tmax: 1\n\t},\n\t[RUNTIME_CAPABILITY.turnReport]: {\n\t\tmin: 1,\n\t\tmax: 2\n\t},\n\t[RUNTIME_CAPABILITY.webTools]: {\n\t\tmin: 1,\n\t\tmax: 1\n\t},\n\t[RUNTIME_CAPABILITY.mcpGateway]: {\n\t\tmin: 1,\n\t\tmax: 1\n\t}\n};\nconst RUNTIME_CLIENT_CAPABILITY_OFFERS = RUNTIME_SERVER_CAPABILITY_OFFERS;\nconst RUNTIME_REQUIRED_CLIENT_CAPABILITIES = [RUNTIME_CAPABILITY.contextTreeSettings];\nconst RUNTIME_REQUIRED_SERVER_CAPABILITIES = [RUNTIME_CAPABILITY.contextTreeSettings];\nconst RUNTIME_MAX_FRAME_BYTES = 65536;\nconst RUNTIME_HEARTBEAT_INTERVAL_MIN_MS = 10;\nconst RUNTIME_HEARTBEAT_INTERVAL_MAX_MS = 3e5;\nconst RUNTIME_HEARTBEAT_TIMEOUT_MIN_MS = 100;\nconst RUNTIME_HEARTBEAT_TIMEOUT_MAX_MS = 9e5;\nconst RUNTIME_CLIENT_CAPABILITY_TTL_MS = 6e4;\nconst RUNTIME_PROVIDER_CLI_ARTIFACT_TTL_MS = 3e5;\nconst RUNTIME_PROVIDER_CLI_CREDENTIAL_TTL_MS = 12e4;\nconst RUNTIME_PROVIDER_CLI_VALIDATION_GRANT_TTL_MS = 15e3;\nconst RUNTIME_PROVIDER_CLI_VALIDATION_TIMEOUT_MS = 1e4;\nconst RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES = 1048576;\nconst RUNTIME_PROVIDER_CLI_REQUIREMENT_OPERATION = 1;\nconst RUNTIME_PROVIDER_CLI_VALIDATION_MAX_RETRIES = 3;\nconst RUNTIME_AGENT_RUNTIME_TEST_TIMEOUT_MS = 18e4;\nconst RUNTIME_AGENT_RUNTIME_TEST_CLEANUP_MS = 5e3;\nconst RUNTIME_AGENT_RUNTIME_TEST_TTL_MS = 185e3;\nconst RUNTIME_AGENT_RUNTIME_TEST_MAX_PENDING = 32;\nconst RuntimeRequestIdSchema = z.string().uuid();\nconst RuntimeConnectionIdSchema = z.string().uuid();\nconst RuntimeFrameEnvelopeSchema = z.object({\n\ttype: z.string().min(1).max(128),\n\trequestId: RuntimeRequestIdSchema.optional(),\n\tprotocolVersion: z.number().int().safe().optional(),\n\tconnectionId: RuntimeConnectionIdSchema.optional(),\n\tcritical: z.boolean().optional()\n}).passthrough();\nconst RuntimeHeartbeatIntervalMsSchema = z.number().int().min(10).max(RUNTIME_HEARTBEAT_INTERVAL_MAX_MS);\nconst RuntimeHeartbeatTimeoutMsSchema = z.number().int().min(100).max(RUNTIME_HEARTBEAT_TIMEOUT_MAX_MS);\nconst RuntimeProtocolRangeSchema = z.object({\n\tmin: z.number().int().safe().positive(),\n\tmax: z.number().int().safe().positive()\n}).strict().superRefine((range, context) => {\n\tif (range.min > range.max) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"min\"],\n\t\tmessage: \"Protocol range minimum exceeds maximum\"\n\t});\n});\nconst RuntimeCapabilityRangeSchema = z.object({\n\tmin: z.number().int().safe().positive(),\n\tmax: z.number().int().safe().positive()\n}).strict().superRefine((range, context) => {\n\tif (range.min > range.max) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"min\"],\n\t\tmessage: \"Capability range minimum exceeds maximum\"\n\t});\n});\nconst RuntimeCapabilityNameSchema = z.string().min(1).max(128).regex(/^[a-z][A-Za-z0-9]*(?:\\.[a-z][A-Za-z0-9]*)+$/, \"Capability names must be namespaced identifiers\");\nconst RuntimeCapabilityOffersSchema = z.record(RuntimeCapabilityNameSchema, RuntimeCapabilityRangeSchema);\nconst RuntimeRequiredCapabilitiesSchema = z.array(RuntimeCapabilityNameSchema).max(128).superRefine((capabilities, context) => {\n\tif (new Set(capabilities).size !== capabilities.length) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"Required capabilities must be unique\"\n\t});\n});\nconst RuntimeNegotiatedCapabilitiesSchema = z.record(RuntimeCapabilityNameSchema, z.number().int().safe().positive());\nconst RuntimeCapabilitiesSchema = z.object({\n\tsessionReconcile: z.literal(1),\n\timDelivery: z.literal(1),\n\tturnReport: z.literal(1),\n\tagentTrace: z.literal(1),\n\timCredentialGrant: z.literal(1)\n}).strict();\nconst RuntimeClientCapabilitiesSchema = z.object({ imCredentialGrant: z.union([z.literal(0), z.literal(1)]) }).strict();\nconst RuntimeProviderReadinessObservationSchema = z.object({\n\tprovider: AgentRuntimeProviderSchema,\n\tstatus: ProviderReadinessStatusSchema\n}).strict();\nconst RuntimeProviderReadinessCollectionSchema = z.array(RuntimeProviderReadinessObservationSchema).max(AGENT_RUNTIME_PROVIDERS.length).superRefine(validateCanonicalProviders);\nconst RuntimeImCliReadinessObservationSchema = z.object({\n\tprovider: ImCliProviderSchema,\n\tstatus: ImCliReadinessStatusSchema\n}).strict();\nconst RuntimeImCliReadinessCollectionSchema = z.array(RuntimeImCliReadinessObservationSchema).max(IM_CLI_PROVIDERS.length).superRefine((observations, context) => validateCanonicalIds(observations.map((observation) => observation.provider), IM_CLI_PROVIDERS, \"IM CLI readiness\", context));\nconst RuntimeProviderReadinessV1ProviderSchema = z.enum(RUNTIME_PROVIDER_READINESS_V1_PROVIDERS);\nconst RuntimeProviderReadinessV2ProviderSchema = z.enum(RUNTIME_PROVIDER_READINESS_V2_PROVIDERS);\nconst RuntimeProviderReadinessNegotiationV1Schema = z.object({\n\tversion: z.literal(1),\n\tproviders: z.array(RuntimeProviderReadinessV1ProviderSchema).max(RUNTIME_PROVIDER_READINESS_V1_PROVIDERS.length)\n}).strict().superRefine((negotiation, context) => validateCanonicalProviderIds(negotiation.providers, context, RUNTIME_PROVIDER_READINESS_V1_PROVIDERS));\nconst RuntimeProviderReadinessNegotiationV2Schema = z.object({\n\tversion: z.literal(2),\n\tproviders: z.array(RuntimeProviderReadinessV2ProviderSchema).max(RUNTIME_PROVIDER_READINESS_V2_PROVIDERS.length)\n}).strict().superRefine((negotiation, context) => validateCanonicalProviderIds(negotiation.providers, context, RUNTIME_PROVIDER_READINESS_V2_PROVIDERS));\nconst RuntimeProviderReadinessNegotiationSchema = z.discriminatedUnion(\"version\", [RuntimeProviderReadinessNegotiationV1Schema, RuntimeProviderReadinessNegotiationV2Schema]);\nconst heartbeatPolicyShape = {\n\theartbeatIntervalMs: RuntimeHeartbeatIntervalMsSchema,\n\theartbeatTimeoutMs: RuntimeHeartbeatTimeoutMsSchema\n};\nfunction validateHeartbeatPolicy(frame, context) {\n\tif (frame.heartbeatTimeoutMs < frame.heartbeatIntervalMs * 2) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"heartbeatTimeoutMs\"],\n\t\tmessage: \"Heartbeat timeout must be at least twice the interval\"\n\t});\n}\nconst ServerWelcomeV1FrameSchema = z.object({\n\ttype: z.literal(\"server:welcome\"),\n\tprotocolVersion: z.literal(1),\n\tcapabilities: RuntimeCapabilitiesSchema,\n\t...heartbeatPolicyShape,\n\tproviderReadiness: RuntimeProviderReadinessNegotiationSchema.optional()\n}).strict().superRefine(validateHeartbeatPolicy);\nconst ServerWelcomeV2FrameSchema = z.object({\n\ttype: z.literal(\"server:welcome\"),\n\tprotocolVersion: z.literal(2),\n\tsupportedProtocolVersions: RuntimeProtocolRangeSchema,\n\tsupportedCapabilities: RuntimeCapabilityOffersSchema,\n\trequiredClientCapabilities: RuntimeRequiredCapabilitiesSchema,\n\t...heartbeatPolicyShape,\n\tproviderReadiness: RuntimeProviderReadinessNegotiationSchema.optional()\n}).passthrough().superRefine((frame, context) => {\n\tvalidateHeartbeatPolicy(frame, context);\n\tif (frame.supportedProtocolVersions.min > 2 || frame.supportedProtocolVersions.max < 2) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"supportedProtocolVersions\"],\n\t\tmessage: \"The selected protocol is outside the Server-supported range\"\n\t});\n});\nconst ServerWelcomeFrameSchema = z.union([ServerWelcomeV1FrameSchema, ServerWelcomeV2FrameSchema]);\nconst AuthV1FrameSchema = z.object({\n\ttype: z.literal(\"auth\"),\n\trequestId: RuntimeRequestIdSchema,\n\tprotocolVersion: z.literal(1),\n\tmachineToken: z.string().min(1).max(4096)\n}).strict();\nconst AuthV2FrameSchema = z.object({\n\ttype: z.literal(\"auth\"),\n\trequestId: RuntimeRequestIdSchema,\n\tprotocolVersion: z.literal(2),\n\tsupportedProtocolVersions: RuntimeProtocolRangeSchema,\n\tmachineToken: z.string().min(1).max(4096)\n}).strict().superRefine((frame, context) => {\n\tif (frame.supportedProtocolVersions.min > 2 || frame.supportedProtocolVersions.max < 2) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"supportedProtocolVersions\"],\n\t\tmessage: \"The bootstrap protocol is outside the Client-supported range\"\n\t});\n});\nconst AuthFrameSchema = z.union([AuthV1FrameSchema, AuthV2FrameSchema]);\nconst AuthResultFrameSchema = z.object({\n\ttype: z.literal(\"auth:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tok: z.boolean(),\n\tcomputerId: z.string().uuid().optional(),\n\tinstallationId: z.string().uuid().optional(),\n\terrorCode: ErrorCodeSchema.optional()\n}).strict().superRefine((frame, context) => {\n\tif (frame.ok && (!frame.computerId || !frame.installationId)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"A successful auth result requires the Computer identity\"\n\t});\n\tif (!frame.ok && !frame.errorCode) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"A failed auth result requires an error code\"\n\t});\n});\nconst computerRegistrationShape = {\n\ttype: z.literal(\"computer:register\"),\n\trequestId: RuntimeRequestIdSchema,\n\tinstallationId: z.string().uuid(),\n\tinstanceId: z.string().uuid(),\n\tdisplayName: z.string().trim().min(1).max(255),\n\tplatform: ComputerPlatformSchema,\n\tarch: z.string().trim().min(1).max(64),\n\tclientVersion: z.string().trim().min(1).max(64),\n\tcapabilities: RuntimeClientCapabilitiesSchema.default({ imCredentialGrant: 0 }),\n\tproviderReadiness: RuntimeProviderReadinessCollectionSchema.optional(),\n\timCliReadiness: RuntimeImCliReadinessCollectionSchema.optional()\n};\nconst ComputerRegisterV1FrameSchema = z.object(computerRegistrationShape).strict();\nconst ComputerRegisterV2FrameSchema = z.object({\n\t...computerRegistrationShape,\n\tprotocolVersion: z.literal(2),\n\tsupportedCapabilities: RuntimeCapabilityOffersSchema,\n\trequiredServerCapabilities: RuntimeRequiredCapabilitiesSchema\n}).strict();\nconst ComputerRegisterFrameSchema = z.union([ComputerRegisterV1FrameSchema, ComputerRegisterV2FrameSchema]);\nconst computerRegisterResultShape = {\n\ttype: z.literal(\"computer:register:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tok: z.boolean(),\n\terrorCode: ErrorCodeSchema.optional()\n};\nconst ComputerRegisterResultV1FrameSchema = z.object(computerRegisterResultShape).strict().superRefine(validateFailedResult);\nconst ComputerRegisterResultV2FrameSchema = z.object({\n\t...computerRegisterResultShape,\n\tprotocolVersion: z.literal(2),\n\tconnectionId: RuntimeConnectionIdSchema.optional(),\n\tnegotiatedCapabilities: RuntimeNegotiatedCapabilitiesSchema.optional()\n}).strict().superRefine((frame, context) => {\n\tvalidateFailedResult(frame, context);\n\tif (frame.ok && (!frame.connectionId || !frame.negotiatedCapabilities)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"A successful v2 registration requires negotiated fencing state\"\n\t});\n\tif (!frame.ok && (frame.connectionId || frame.negotiatedCapabilities)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"A failed v2 registration forbids negotiated fencing state\"\n\t});\n});\nconst ComputerRegisterResultFrameSchema = z.union([ComputerRegisterResultV1FrameSchema, ComputerRegisterResultV2FrameSchema]);\nconst heartbeatShape = {\n\ttype: z.literal(\"heartbeat\"),\n\trequestId: RuntimeRequestIdSchema,\n\tinstallationId: z.string().uuid(),\n\tinstanceId: z.string().uuid(),\n\tcapabilities: RuntimeClientCapabilitiesSchema.default({ imCredentialGrant: 0 }),\n\tproviderReadiness: RuntimeProviderReadinessCollectionSchema.optional(),\n\timCliReadiness: RuntimeImCliReadinessCollectionSchema.optional()\n};\nconst HeartbeatV1FrameSchema = z.object(heartbeatShape).strict();\nconst HeartbeatV2FrameSchema = z.object({\n\t...heartbeatShape,\n\tprotocolVersion: z.literal(2),\n\tconnectionId: RuntimeConnectionIdSchema\n}).strict();\nconst HeartbeatFrameSchema = z.union([HeartbeatV1FrameSchema, HeartbeatV2FrameSchema]);\nconst heartbeatResultShape = {\n\ttype: z.literal(\"heartbeat:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tok: z.boolean(),\n\tserverTime: z.string().datetime(),\n\terrorCode: ErrorCodeSchema.optional()\n};\n/**\n* The exact channel latest target the Server currently advertises. Sent only on v2 heartbeat results\n* when the `runtime.channelTarget` capability was negotiated, so older Clients never see a field\n* their strict schemas would reject.\n*/\nconst RuntimeChannelTargetSchema = z.object({\n\tchannel: ChannelNameSchema,\n\tversion: SemVerStringSchema\n}).strict();\nconst HeartbeatResultV1FrameSchema = z.object(heartbeatResultShape).strict().superRefine(validateFailedResult);\nconst HeartbeatResultV2FrameSchema = z.object({\n\t...heartbeatResultShape,\n\tprotocolVersion: z.literal(2),\n\tconnectionId: RuntimeConnectionIdSchema,\n\tchannelTarget: RuntimeChannelTargetSchema.optional()\n}).strict().superRefine(validateFailedResult);\nconst HeartbeatResultFrameSchema = z.union([HeartbeatResultV1FrameSchema, HeartbeatResultV2FrameSchema]);\nconst RuntimeErrorFrameSchema = z.object({\n\ttype: z.literal(\"error\"),\n\trequestId: RuntimeRequestIdSchema.optional(),\n\tcode: ErrorCodeSchema,\n\tmessage: z.string().min(1).max(512)\n}).strict();\nconst ClientRuntimeFrameSchema = z.union([\n\tAuthFrameSchema,\n\tComputerRegisterFrameSchema,\n\tHeartbeatFrameSchema,\n\tRuntimeErrorFrameSchema\n]);\nconst ServerRuntimeFrameSchema = z.union([\n\tServerWelcomeFrameSchema,\n\tAuthResultFrameSchema,\n\tComputerRegisterResultFrameSchema,\n\tHeartbeatResultFrameSchema,\n\tRuntimeErrorFrameSchema\n]);\nfunction advertisedProviderReadiness(version, admitted) {\n\tif (version === 2) {\n\t\tconst providers = RUNTIME_PROVIDER_READINESS_V2_PROVIDERS.filter((provider) => admitted.includes(provider));\n\t\treturn providers.length === 0 ? void 0 : {\n\t\t\tversion: 2,\n\t\t\tproviders\n\t\t};\n\t}\n\tconst providers = RUNTIME_PROVIDER_READINESS_V1_PROVIDERS.filter((provider) => admitted.includes(provider));\n\treturn providers.length === 0 ? void 0 : {\n\t\tversion: 1,\n\t\tproviders\n\t};\n}\nfunction negotiateProviderReadinessFromHeaders(headers, admitted) {\n\tif (requestsProviderReadinessV2(headers[\"x-opentag-provider-readiness-v2\"])) return advertisedProviderReadiness(2, admitted);\n\tif (requestsProviderReadinessV1(headers[\"x-opentag-provider-readiness\"])) return advertisedProviderReadiness(1, admitted);\n}\nfunction negotiateRuntimeCapabilities(local, remote) {\n\tconst negotiated = {};\n\tfor (const name of Object.keys(local).sort()) {\n\t\tconst localRange = local[name];\n\t\tconst remoteRange = remote[name];\n\t\tif (!localRange || !remoteRange) continue;\n\t\tconst minimum = Math.max(localRange.min, remoteRange.min);\n\t\tconst maximum = Math.min(localRange.max, remoteRange.max);\n\t\tif (minimum <= maximum) negotiated[name] = maximum;\n\t}\n\treturn negotiated;\n}\nfunction missingRuntimeCapabilities(required, negotiated) {\n\treturn required.filter((name) => negotiated[name] === void 0);\n}\nfunction runtimeNegotiatedCapabilitiesEqual(left, right) {\n\tconst leftEntries = Object.entries(left).sort(([leftName], [rightName]) => leftName.localeCompare(rightName));\n\tconst rightEntries = Object.entries(right).sort(([leftName], [rightName]) => leftName.localeCompare(rightName));\n\treturn JSON.stringify(leftEntries) === JSON.stringify(rightEntries);\n}\nfunction runtimeFrameByteLength(serializedFrame) {\n\treturn new TextEncoder().encode(serializedFrame).byteLength;\n}\nfunction validateFailedResult(frame, context) {\n\tif (!frame.ok && !frame.errorCode) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"A failed result requires an error code\"\n\t});\n}\nfunction validateCanonicalProviders(observations, context) {\n\tvalidateCanonicalIds(observations.map((observation) => observation.provider), AGENT_RUNTIME_PROVIDERS, \"Provider readiness\", context);\n}\nfunction validateCanonicalProviderIds(providers, context, canonical = AGENT_RUNTIME_PROVIDERS) {\n\tvalidateCanonicalIds(providers, canonical, \"Provider readiness\", context);\n}\nfunction validateCanonicalIds(providers, canonical, label, context) {\n\tconst seen = /* @__PURE__ */ new Set();\n\tfor (const [index, provider] of providers.entries()) {\n\t\tif (seen.has(provider)) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [index],\n\t\t\tmessage: `${label} must be unique`\n\t\t});\n\t\tseen.add(provider);\n\t\tconst previousProvider = providers[index - 1];\n\t\tif (previousProvider !== void 0 && canonical.indexOf(provider) < canonical.indexOf(previousProvider)) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [index],\n\t\t\tmessage: `${label} must use canonical Provider order`\n\t\t});\n\t}\n}\n//#endregion\n//#region src/turn-outgoing-reply.ts\nconst RUNTIME_OUTGOING_REPLY_MAX_COUNT = 16;\nconst RUNTIME_OUTGOING_REPLY_TEXT_MAX_BYTES = 8192;\nconst RUNTIME_OUTGOING_REPLY_RAW_MAX_BYTES = 8192;\nconst RUNTIME_OUTGOING_REPLY_SNAPSHOT_MAX_BYTES = 32768;\nconst outgoingId = runtimeByteString(512, \"Provider reference exceeds the 512-byte limit\", 1);\nconst TurnOutgoingReplyUnavailableReasonSchema = z.enum([\n\t\"content_read_failed\",\n\t\"content_truncated\",\n\t\"out_of_scope\",\n\t\"omitted\"\n]);\nconst TurnOutgoingReplyMsgTypeSchema = z.enum([\n\t\"text\",\n\t\"post\",\n\t\"image\",\n\t\"file\",\n\t\"audio\",\n\t\"video\",\n\t\"media\",\n\t\"interactive\",\n\t\"sticker\",\n\t\"share_chat\",\n\t\"share_user\",\n\t\"unknown\"\n]);\nconst TurnOutgoingReplyContentSchema = z.object({\n\tmsgType: TurnOutgoingReplyMsgTypeSchema,\n\ttext: runtimeByteString(RUNTIME_OUTGOING_REPLY_TEXT_MAX_BYTES, \"Outgoing reply text exceeds the 8 KiB limit\").optional(),\n\tpost: z.unknown().optional(),\n\tfilename: runtimeByteString(512, \"Outgoing reply filename exceeds the 512-byte limit\", 1).optional(),\n\tfileKey: runtimeByteString(512, \"Outgoing reply file key exceeds the 512-byte limit\", 1).optional(),\n\timageKey: runtimeByteString(512, \"Outgoing reply image key exceeds the 512-byte limit\", 1).optional(),\n\traw: runtimeByteString(RUNTIME_OUTGOING_REPLY_RAW_MAX_BYTES, \"Outgoing reply raw payload exceeds the 8 KiB limit\").optional(),\n\tunavailable: TurnOutgoingReplyUnavailableReasonSchema.optional()\n}).strict();\nconst TurnOutgoingReplySchema = z.object({\n\tprovider: z.literal(\"feishu\"),\n\tteamBrand: z.enum([\"feishu\", \"lark\"]),\n\tmessageId: outgoingId,\n\tchatId: outgoingId,\n\tthreadId: outgoingId.optional(),\n\trootId: outgoingId.optional(),\n\tparentId: outgoingId.optional(),\n\tcreateTime: runtimeByteString(64, \"Outgoing reply create time exceeds the 64-byte limit\", 1).optional(),\n\tcontent: TurnOutgoingReplyContentSchema\n}).strict();\nconst TurnOutgoingReplySnapshotSchema = z.object({\n\tstatus: z.enum([\n\t\t\"complete\",\n\t\t\"incomplete\",\n\t\t\"unavailable\"\n\t]),\n\treplies: z.array(TurnOutgoingReplySchema).max(16),\n\tomittedCount: z.number().int().safe().nonnegative().optional(),\n\truntimeSummaryTruncated: z.boolean().optional()\n}).strict().superRefine((snapshot, context) => {\n\tif (runtimeUtf8Length(JSON.stringify(snapshot)) > 32768) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"Outgoing reply snapshot exceeds the 32 KiB limit\"\n\t});\n});\n//#endregion\n//#region src/runtime-domain.ts\nconst RUNTIME_DIRECT_TEXT_MAX_BYTES = 16384;\nconst RUNTIME_FINAL_TEXT_MAX_BYTES = 49152;\nconst RUNTIME_TRACE_EVENT_MAX_BYTES = 16384;\nconst RUNTIME_TRACE_BATCH_MAX_EVENTS = 64;\nconst RUNTIME_IM_HISTORY_MAX_BYTES = 40960;\nconst RUNTIME_IM_RESOURCE_MAX_COUNT = 16;\nconst RUNTIME_MVP_RETAINED_REPORT_LIMIT = 65;\nconst opaqueIdPattern = /^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$/;\nconst relativePathPattern = /^(?![A-Za-z]:)(?!\\/)(?!.*(?:^|\\/)\\.\\.(?:\\/|$))[^\\\\\\0]+$/;\nconst RuntimeOpaqueIdSchema = z.string().min(1).max(128).regex(opaqueIdPattern, \"Runtime IDs must be opaque, path-safe ASCII identifiers\");\nconst RuntimeSequenceSchema = z.number().int().safe().nonnegative();\nconst RuntimeSha256Schema = z.string().regex(/^[a-f0-9]{64}$/, \"Expected a lowercase SHA-256 digest\");\nconst RuntimeDurableWorkKindSchema = z.enum([\"session-message\", \"turn-report\"]);\nconst RuntimeDurableWorkStatusSchema = z.enum([\n\t\"accepted\",\n\t\"running\",\n\t\"succeeded\",\n\t\"retryable\",\n\t\"failed\",\n\t\"dead-letter\"\n]);\nconst RuntimeDurableFailureSchema = z.object({\n\tcategory: z.string().min(1).max(64),\n\tcode: z.string().min(1).max(128),\n\tmessage: z.string().min(1).max(2048),\n\tphase: z.string().min(1).max(64),\n\trequestId: z.string().min(1).max(128),\n\tretryability: z.enum([\"retryable\", \"terminal\"])\n}).strict();\nconst RuntimeDurableWorkRecordSchema = z.object({\n\tattempts: RuntimeSequenceSchema,\n\tacceptedAt: RuntimeSequenceSchema,\n\tkey: RuntimeOpaqueIdSchema,\n\tkind: RuntimeDurableWorkKindSchema,\n\tlastError: RuntimeDurableFailureSchema.optional(),\n\tnextAttemptAt: RuntimeSequenceSchema.optional(),\n\tpayload: z.unknown(),\n\tstatus: RuntimeDurableWorkStatusSchema,\n\tupdatedAt: RuntimeSequenceSchema\n}).strict();\nconst RuntimeDurableWorkListResponseSchema = z.object({\n\titems: z.array(RuntimeDurableWorkRecordSchema).max(1024),\n\tnextCursor: z.string().min(1).max(1024).optional()\n}).strict();\nconst RuntimeRevisionSchema = z.object({\n\tsequence: RuntimeSequenceSchema,\n\tid: RuntimeOpaqueIdSchema\n}).strict();\nconst RuntimeUsageSchema = z.object({\n\tinputTokens: RuntimeSequenceSchema.optional(),\n\tcachedInputTokens: RuntimeSequenceSchema.optional(),\n\toutputTokens: RuntimeSequenceSchema.optional()\n}).strict();\nconst EffectiveRuntimeSnapshotSchema = z.object({\n\tcontextTrees: ContextTreesSchema,\n\trevision: z.object({\n\t\tagent: RuntimeRevisionSchema,\n\t\tsession: RuntimeRevisionSchema\n\t}).strict(),\n\tagentId: RuntimeOpaqueIdSchema,\n\tprovider: AgentRuntimeProviderSchema,\n\tmodel: RuntimeModelSchema.optional(),\n\treasoningEffort: RuntimeReasoningEffortSchema.optional(),\n\tinstructions: RuntimeInstructionsSchema,\n\texecution: z.object({\n\t\tapprovalPolicy: z.literal(\"never\"),\n\t\tnetworkAccess: z.boolean()\n\t}).strict(),\n\tworkspace: z.object({\n\t\tworkspaceId: RuntimeOpaqueIdSchema,\n\t\tmode: z.literal(\"empty_on_create\"),\n\t\tsharing: z.literal(\"agent\")\n\t}).strict(),\n\tbudget: z.object({ maxDurationMs: RuntimeMaxDurationMsSchema.optional() }).strict().optional()\n}).strict();\nconst InputRejectReasonSchema = z.enum([\n\t\"invalid_input\",\n\t\"target_mismatch\",\n\t\"session_not_ready\",\n\t\"stale_generation\",\n\t\"stale_configuration\",\n\t\"agent_configuration_busy\",\n\t\"input_conflict\",\n\t\"session_binding_conflict\",\n\t\"session_recovery_required\",\n\t\"turn_expired\",\n\t\"session_busy\",\n\t\"agent_busy\",\n\t\"client_busy\",\n\t\"provider_unavailable\",\n\t\"configuration_unsupported\"\n]);\nconst TurnFailureReasonSchema = z.enum([\n\t\"workspace_failed\",\n\t\"configuration_conflict\",\n\t\"credential_unavailable\",\n\t\"sandbox_unavailable\",\n\t\"provider_start_failed\",\n\t\"session_resume_failed\",\n\t\"provider_protocol_error\",\n\t\"provider_failed\",\n\t\"provider_empty_result\",\n\t\"output_too_large\",\n\t\"provider_teardown_failed\",\n\t\"turn_state_unknown\",\n\t\"turn_timeout\",\n\t\"client_shutdown\"\n]);\nconst SessionReconcileRequestSchema = z.object({\n\ttype: z.literal(\"session:reconcile\"),\n\trequestId: RuntimeRequestIdSchema,\n\tinstallationId: z.string().uuid(),\n\tsessionId: RuntimeOpaqueIdSchema,\n\tagentId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: RuntimeSequenceSchema,\n\tsessionKind: z.literal(\"internal\").optional(),\n\tcreatorSessionId: z.string().uuid().optional(),\n\tsessionCliProof: z.object({\n\t\tproofId: z.string().uuid(),\n\t\ttoken: runtimeByteString(4096, \"Session CLI proof exceeds the 4 KiB limit\", 32)\n\t}).strict().optional(),\n\tdesired: z.enum([\"ready\", \"stopped\"]),\n\truntime: EffectiveRuntimeSnapshotSchema.optional()\n}).strict().superRefine((frame, context) => {\n\tif (frame.desired === \"ready\" && !frame.runtime) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"runtime\"],\n\t\tmessage: \"A ready reconcile requires a runtime snapshot\"\n\t});\n\tif (frame.desired === \"stopped\" && frame.runtime) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"runtime\"],\n\t\tmessage: \"A stopped reconcile forbids a runtime snapshot\"\n\t});\n\tif (frame.runtime && frame.runtime.agentId !== frame.agentId) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"runtime\", \"agentId\"],\n\t\tmessage: \"Agent identity does not match\"\n\t});\n\tif (frame.sessionKind === \"internal\" && !frame.creatorSessionId) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"creatorSessionId\"],\n\t\tmessage: \"An internal Session requires its creator\"\n\t});\n\tif (frame.sessionKind !== \"internal\" && frame.creatorSessionId) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"creatorSessionId\"],\n\t\tmessage: \"A visible Session forbids a creator\"\n\t});\n\tif (frame.desired === \"stopped\" && frame.sessionCliProof) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"sessionCliProof\"],\n\t\tmessage: \"A stopped reconcile forbids a Session CLI proof\"\n\t});\n});\nconst ReconcileTurnSchema = z.object({\n\tturnId: RuntimeOpaqueIdSchema,\n\tdeliveryId: RuntimeOpaqueIdSchema\n}).strict();\nconst RuntimeImResourceReferenceSchema = z.object({\n\timMessageId: RuntimeOpaqueIdSchema,\n\tordinal: z.number().int().min(0).max(15),\n\tkind: z.enum([\n\t\t\"image\",\n\t\t\"file\",\n\t\t\"audio\",\n\t\t\"video\"\n\t]),\n\tfilename: runtimeByteString(512, \"Resource filename exceeds the 512-byte limit\", 1).optional(),\n\tmediaType: runtimeByteString(255, \"Resource media type exceeds the 255-byte limit\", 1).optional(),\n\tsizeBytes: z.number().int().safe().nonnegative().optional(),\n\tavailability: z.enum([\n\t\t\"available\",\n\t\t\"unavailable\",\n\t\t\"too_large\",\n\t\t\"unsupported\"\n\t])\n}).strict();\nconst RuntimeProviderExternalIdSchema = runtimeByteString(512, \"Provider reference exceeds the 512-byte limit\", 1);\nconst RuntimeProviderMessageRefSchema = z.discriminatedUnion(\"provider\", [z.object({\n\tprovider: z.literal(\"feishu\"),\n\tteamBrand: z.enum([\"feishu\", \"lark\"]),\n\tappId: RuntimeProviderExternalIdSchema,\n\tbotOpenId: RuntimeProviderExternalIdSchema,\n\tchatId: RuntimeProviderExternalIdSchema,\n\tchatType: runtimeByteString(160, \"Feishu chat type exceeds the 160-byte limit\", 1).optional(),\n\tmessageId: RuntimeProviderExternalIdSchema,\n\tthreadId: RuntimeProviderExternalIdSchema.optional(),\n\trootId: RuntimeProviderExternalIdSchema.optional(),\n\tparentId: RuntimeProviderExternalIdSchema.optional()\n}).strict(), z.object({\n\tprovider: z.literal(\"slack\"),\n\tappId: RuntimeProviderExternalIdSchema,\n\tteamId: RuntimeProviderExternalIdSchema,\n\tenterpriseId: RuntimeProviderExternalIdSchema.optional(),\n\tbotUserId: RuntimeProviderExternalIdSchema,\n\tchannelId: RuntimeProviderExternalIdSchema,\n\tchannelType: runtimeByteString(160, \"Slack channel type exceeds the 160-byte limit\", 1).optional(),\n\tmessageTs: RuntimeProviderExternalIdSchema,\n\tthreadTs: RuntimeProviderExternalIdSchema.optional(),\n\tauthorUserId: RuntimeProviderExternalIdSchema.optional()\n}).strict()]);\nconst RuntimeImHistoryItemSchema = z.object({\n\timMessageId: RuntimeOpaqueIdSchema,\n\toccurredAt: z.string().datetime({ offset: true }),\n\ttext: runtimeByteString(RUNTIME_DIRECT_TEXT_MAX_BYTES, \"History item exceeds the 16 KiB limit\"),\n\tproviderRef: RuntimeProviderMessageRefSchema\n}).strict();\nconst RuntimeImDeliveryContentSchema = z.object({\n\tkind: z.literal(\"text\"),\n\ttext: runtimeByteString(RUNTIME_DIRECT_TEXT_MAX_BYTES, \"Direct text exceeds the 16 KiB limit\", 1),\n\tproviderRef: RuntimeProviderMessageRefSchema,\n\thistory: z.array(RuntimeImHistoryItemSchema).max(100).optional(),\n\thistoryTruncated: z.boolean().optional(),\n\tresources: z.array(RuntimeImResourceReferenceSchema).max(16).optional()\n}).strict().superRefine((content, context) => {\n\tif (runtimeUtf8Length(JSON.stringify(content.history ?? [])) > 40960) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"history\"],\n\t\tmessage: \"IM history exceeds 40 KiB\"\n\t});\n});\nconst RetainedTurnReportClaimSchema = z.object({\n\tdispatchRequestId: RuntimeRequestIdSchema,\n\tdeliveryId: RuntimeOpaqueIdSchema,\n\tinputHash: RuntimeSha256Schema,\n\tturnId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: RuntimeSequenceSchema,\n\tresultHash: RuntimeSha256Schema\n}).strict();\nconst SessionReconcileResultSchema = z.object({\n\ttype: z.literal(\"session:reconcile:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tsessionId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: RuntimeSequenceSchema,\n\tstatus: z.enum([\n\t\t\"ready\",\n\t\t\"stopped\",\n\t\t\"running\",\n\t\t\"reporting\",\n\t\t\"busy\",\n\t\t\"recovery_required\",\n\t\t\"rejected\"\n\t]),\n\treason: runtimeByteString(256, \"Reconcile reason exceeds the 256-byte limit\", 1).optional(),\n\tturn: ReconcileTurnSchema.optional(),\n\tretainedReports: z.array(RetainedTurnReportClaimSchema).max(65).optional()\n}).strict().superRefine((frame, context) => {\n\tif ((frame.status === \"running\" || frame.status === \"reporting\" || frame.status === \"recovery_required\") !== Boolean(frame.turn)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"turn\"],\n\t\tmessage: \"The reconcile status and turn fields do not match\"\n\t});\n\tif ((frame.status === \"ready\" || frame.status === \"stopped\") && frame.reason) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"reason\"],\n\t\tmessage: \"Successful reconcile results cannot include a reason\"\n\t});\n\tif (frame.status === \"rejected\" && frame.retainedReports) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"retainedReports\"],\n\t\tmessage: \"Rejected reconciliation cannot establish retained Turn Report claims\"\n\t});\n\tif (frame.retainedReports) {\n\t\tif (new Set(frame.retainedReports.map((claim) => claim.turnId)).size !== frame.retainedReports.length) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"retainedReports\"],\n\t\t\tmessage: \"Retained Turn Report claims must have unique Turn IDs\"\n\t\t});\n\t\tif (new Set(frame.retainedReports.map((claim) => claim.deliveryId)).size !== frame.retainedReports.length) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"retainedReports\"],\n\t\t\tmessage: \"Retained Turn Report claims must have unique delivery IDs\"\n\t\t});\n\t\tif (frame.retainedReports.some((claim) => claim.placementGeneration > frame.placementGeneration)) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"retainedReports\"],\n\t\t\tmessage: \"Retained Turn Report claims cannot be from a future placement generation\"\n\t\t});\n\t}\n});\nconst DirectImMessageDeliveryRequestSchema = z.object({\n\ttype: z.literal(\"im:deliver\"),\n\trequestId: RuntimeRequestIdSchema,\n\tdeliveryId: RuntimeOpaqueIdSchema,\n\timMessageId: RuntimeOpaqueIdSchema,\n\tsessionId: RuntimeOpaqueIdSchema,\n\tagentId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: RuntimeSequenceSchema,\n\tattention: z.enum([\"direct\", \"ambient\"]),\n\treplyRole: z.literal(\"observer\").optional(),\n\tcontent: RuntimeImDeliveryContentSchema,\n\truntime: EffectiveRuntimeSnapshotSchema,\n\tdeadlineAt: z.string().datetime({ offset: true }).optional()\n}).strict().superRefine((frame, context) => {\n\tif (frame.runtime.agentId !== frame.agentId) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"runtime\", \"agentId\"],\n\t\tmessage: \"Agent identity does not match\"\n\t});\n});\nconst RuntimeImSteerRequestSchema = z.object({\n\ttype: z.literal(\"im:steer\"),\n\trequestId: RuntimeRequestIdSchema,\n\tdeliveryId: RuntimeOpaqueIdSchema,\n\timMessageId: RuntimeOpaqueIdSchema,\n\tsessionId: RuntimeOpaqueIdSchema,\n\tagentId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: RuntimeSequenceSchema,\n\trootDeliveryId: RuntimeOpaqueIdSchema,\n\texpectedTurnId: RuntimeOpaqueIdSchema,\n\tattention: z.enum([\"direct\", \"ambient\"]),\n\treplyRole: z.literal(\"observer\").optional(),\n\tcontent: RuntimeImDeliveryContentSchema,\n\tdeadlineAt: z.string().datetime({ offset: true }).optional()\n}).strict();\nconst RuntimeImCredentialGrantRequestSchema = z.object({\n\ttype: z.literal(\"im:credential\"),\n\trequestId: RuntimeRequestIdSchema,\n\tsessionId: RuntimeOpaqueIdSchema,\n\tagentId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: RuntimeSequenceSchema\n}).strict();\nconst RuntimeImCredentialGrantSchema = z.discriminatedUnion(\"provider\", [z.object({\n\tprovider: z.literal(\"feishu\"),\n\tappId: runtimeByteString(512, \"Feishu App ID exceeds the 512-byte limit\", 1),\n\tappSecret: runtimeByteString(4096, \"Feishu App secret exceeds the 4 KiB limit\", 1),\n\tteamBrand: z.enum([\"feishu\", \"lark\"])\n}).strict(), z.object({\n\tprovider: z.literal(\"slack\"),\n\tbotAccessToken: runtimeByteString(4096, \"Slack Bot token exceeds the 4 KiB limit\", 1)\n}).strict()]);\nconst RuntimeImOutboxContextSchema = z.discriminatedUnion(\"provider\", [z.object({\n\tprovider: z.literal(\"feishu\"),\n\tsessionKind: z.enum([\"channel\", \"thread\"]),\n\tchatId: RuntimeProviderExternalIdSchema,\n\tthreadId: RuntimeProviderExternalIdSchema.optional()\n}).strict(), z.object({\n\tprovider: z.literal(\"slack\"),\n\tsessionKind: z.enum([\"channel\", \"thread\"]),\n\tchannelId: RuntimeProviderExternalIdSchema,\n\tthreadTs: RuntimeProviderExternalIdSchema.optional()\n}).strict()]).superRefine((context, refinement) => {\n\tconst threadReference = context.provider === \"feishu\" ? context.threadId : context.threadTs;\n\tif (context.sessionKind === \"thread\" !== Boolean(threadReference)) refinement.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [context.provider === \"feishu\" ? \"threadId\" : \"threadTs\"],\n\t\tmessage: `${context.provider === \"feishu\" ? \"Feishu\" : \"Slack\"} thread outbox context must match the Session kind`\n\t});\n});\nconst RuntimeImCredentialGrantResultSchema = z.discriminatedUnion(\"status\", [z.object({\n\ttype: z.literal(\"im:credential:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tstatus: z.literal(\"succeeded\"),\n\tcredentialGeneration: z.number().int().safe().positive(),\n\tgrant: RuntimeImCredentialGrantSchema,\n\toutboxContext: RuntimeImOutboxContextSchema.optional()\n}).strict(), z.object({\n\ttype: z.literal(\"im:credential:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tstatus: z.literal(\"rejected\"),\n\tcode: z.enum([\n\t\t\"binding_inactive\",\n\t\t\"credential_stale\",\n\t\t\"provider_cli_unready\",\n\t\t\"placement_stale\",\n\t\t\"agent_mismatch\"\n\t])\n}).strict()]).superRefine((result, context) => {\n\tif (result.status === \"succeeded\" && result.outboxContext && result.outboxContext.provider !== result.grant.provider) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"outboxContext\", \"provider\"],\n\t\tmessage: \"The outbox context provider must match the credential grant provider\"\n\t});\n});\nconst ImMessageDeliveryResultBaseSchema = z.object({\n\ttype: z.literal(\"im:deliver:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tdeliveryId: RuntimeOpaqueIdSchema,\n\tsessionId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: RuntimeSequenceSchema\n});\nconst ImMessageDeliveryResultSchema = z.discriminatedUnion(\"status\", [\n\tImMessageDeliveryResultBaseSchema.extend({\n\t\tstatus: z.literal(\"accepted\"),\n\t\tturnId: RuntimeOpaqueIdSchema\n\t}).strict(),\n\tImMessageDeliveryResultBaseSchema.extend({\n\t\tstatus: z.literal(\"absorbed\"),\n\t\trootDeliveryId: RuntimeOpaqueIdSchema,\n\t\tturnId: RuntimeOpaqueIdSchema\n\t}).strict(),\n\tImMessageDeliveryResultBaseSchema.extend({\n\t\tstatus: z.literal(\"rejected\"),\n\t\treason: InputRejectReasonSchema\n\t}).strict()\n]);\nconst RuntimeImSteerResultBaseSchema = z.object({\n\ttype: z.literal(\"im:steer:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tdeliveryId: RuntimeOpaqueIdSchema,\n\tsessionId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: RuntimeSequenceSchema,\n\trootDeliveryId: RuntimeOpaqueIdSchema,\n\texpectedTurnId: RuntimeOpaqueIdSchema\n});\nconst RuntimeImSteerResultSchema = z.discriminatedUnion(\"status\", [\n\tRuntimeImSteerResultBaseSchema.extend({ status: z.literal(\"steered\") }).strict(),\n\tRuntimeImSteerResultBaseSchema.extend({\n\t\tstatus: z.literal(\"retry\"),\n\t\treason: z.literal(\"turn_starting\")\n\t}).strict(),\n\tRuntimeImSteerResultBaseSchema.extend({\n\t\tstatus: z.literal(\"deferred\"),\n\t\treason: z.enum([\n\t\t\t\"turn_not_running\",\n\t\t\t\"steer_unsupported\",\n\t\t\t\"steer_state_unknown\"\n\t\t])\n\t}).strict(),\n\tRuntimeImSteerResultBaseSchema.extend({\n\t\tstatus: z.literal(\"rejected\"),\n\t\treason: z.enum([\n\t\t\t\"invalid_input\",\n\t\t\t\"input_conflict\",\n\t\t\t\"target_mismatch\",\n\t\t\t\"stale_generation\"\n\t\t])\n\t}).strict()\n]);\nconst InternalSessionRuntimeOverridesSchema = z.object({\n\tmodel: RuntimeModelSchema.optional(),\n\treasoningEffort: RuntimeReasoningEffortSchema.optional(),\n\tmaxDurationMs: RuntimeMaxDurationMsSchema.optional()\n}).strict();\nconst SessionMessageContentSchema = z.object({\n\tkind: z.literal(\"text\"),\n\ttext: runtimeByteString(RUNTIME_DIRECT_TEXT_MAX_BYTES, \"Session message text exceeds the 16 KiB limit\", 1)\n}).strict();\nconst SessionMessageDeliveryRequestSchema = z.object({\n\ttype: z.literal(\"session:message:deliver\"),\n\trequestId: RuntimeRequestIdSchema,\n\tmessageId: z.string().uuid(),\n\tsourceSessionId: z.string().uuid(),\n\ttargetSessionId: z.string().uuid(),\n\tagentId: z.string().uuid(),\n\tplacementGeneration: RuntimeSequenceSchema,\n\tcontent: SessionMessageContentSchema,\n\truntime: EffectiveRuntimeSnapshotSchema\n}).strict().superRefine((frame, context) => {\n\tif (frame.runtime.agentId !== frame.agentId) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"runtime\", \"agentId\"],\n\t\tmessage: \"Agent identity does not match\"\n\t});\n});\nconst SessionMessageDeliveryResultSchema = z.object({\n\ttype: z.literal(\"session:message:deliver:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tmessageId: z.string().uuid(),\n\ttargetSessionId: z.string().uuid(),\n\tplacementGeneration: RuntimeSequenceSchema,\n\tstatus: z.enum([\"accepted\", \"rejected\"]),\n\treason: InputRejectReasonSchema.optional()\n}).strict().superRefine((frame, context) => {\n\tif (frame.status === \"accepted\" && frame.reason) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"reason\"],\n\t\tmessage: \"Accepted deliveries forbid a reason\"\n\t});\n\tif (frame.status === \"rejected\" && !frame.reason) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"reason\"],\n\t\tmessage: \"Rejected deliveries require a reason\"\n\t});\n});\nconst TraceEventBaseSchema = z.object({\n\tsequence: z.number().int().safe().positive(),\n\tat: z.string().datetime({ offset: true })\n});\nconst AgentTraceEventSchema = z.discriminatedUnion(\"kind\", [\n\tTraceEventBaseSchema.extend({ kind: z.literal(\"turn_started\") }).strict(),\n\tTraceEventBaseSchema.extend({\n\t\tkind: z.literal(\"item_completed\"),\n\t\titemType: z.enum([\n\t\t\t\"agent_message\",\n\t\t\t\"command\",\n\t\t\t\"file_change\",\n\t\t\t\"tool\",\n\t\t\t\"other\"\n\t\t]),\n\t\tstatus: z.enum([\"completed\", \"failed\"]),\n\t\tpath: runtimeByteString(512, \"Trace path exceeds the 512-byte limit\", 1).regex(relativePathPattern).optional(),\n\t\tpreview: runtimeByteString(2048, \"Trace preview exceeds the 2 KiB limit\").optional()\n\t}).strict(),\n\tTraceEventBaseSchema.extend({\n\t\tkind: z.literal(\"usage_updated\"),\n\t\tusage: RuntimeUsageSchema\n\t}).strict(),\n\tTraceEventBaseSchema.extend({\n\t\tkind: z.literal(\"warning\"),\n\t\tcode: RuntimeOpaqueIdSchema,\n\t\tmessage: runtimeByteString(2048, \"Trace warning exceeds the 2 KiB limit\", 1)\n\t}).strict(),\n\tTraceEventBaseSchema.extend({\n\t\tkind: z.literal(\"turn_completed\"),\n\t\toutcome: z.enum([\n\t\t\t\"completed\",\n\t\t\t\"failed\",\n\t\t\t\"cancelled\",\n\t\t\t\"unknown\"\n\t\t])\n\t}).strict()\n]).superRefine((event, context) => {\n\tif (runtimeUtf8Length(JSON.stringify(event)) > 16384) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"Trace event exceeds the 16 KiB limit\"\n\t});\n});\nconst AgentTraceBatchSchema = z.object({\n\ttype: z.literal(\"agent:trace\"),\n\tbatchId: RuntimeOpaqueIdSchema,\n\tsessionId: RuntimeOpaqueIdSchema,\n\tturnId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: RuntimeSequenceSchema,\n\tevents: z.array(AgentTraceEventSchema).min(1).max(64)\n}).strict().superRefine((batch, context) => {\n\tfor (let index = 1; index < batch.events.length; index += 1) {\n\t\tconst previous = batch.events[index - 1];\n\t\tconst current = batch.events[index];\n\t\tif (previous && current && current.sequence <= previous.sequence) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\n\t\t\t\t\"events\",\n\t\t\t\tindex,\n\t\t\t\t\"sequence\"\n\t\t\t],\n\t\t\tmessage: \"Trace sequences must increase\"\n\t\t});\n\t}\n});\nconst TurnReportRequestSchema = z.object({\n\ttype: z.literal(\"turn:report\"),\n\trequestId: RuntimeRequestIdSchema,\n\tdeliveryId: RuntimeOpaqueIdSchema,\n\tturnId: RuntimeOpaqueIdSchema,\n\tsessionId: RuntimeOpaqueIdSchema,\n\tagentId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: RuntimeSequenceSchema,\n\toutcome: z.enum([\n\t\t\"completed\",\n\t\t\"failed\",\n\t\t\"cancelled\",\n\t\t\"unknown\"\n\t]),\n\texecutionEffects: z.enum([\n\t\t\"not_started\",\n\t\t\"may_have_occurred\",\n\t\t\"completed\"\n\t]),\n\tfinalText: runtimeByteString(RUNTIME_FINAL_TEXT_MAX_BYTES, \"Final text exceeds the 48 KiB limit\", 1).optional(),\n\terrorReason: TurnFailureReasonSchema.optional(),\n\tusage: RuntimeUsageSchema.optional(),\n\ttraceSummary: z.object({\n\t\tlastSequence: RuntimeSequenceSchema,\n\t\tdroppedEvents: RuntimeSequenceSchema\n\t}).strict(),\n\toutgoingReplies: TurnOutgoingReplySnapshotSchema.optional(),\n\tresultHash: RuntimeSha256Schema\n}).strict().superRefine((frame, context) => {\n\tif (frame.outcome === \"completed\" && frame.errorReason) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"errorReason\"],\n\t\tmessage: \"Completed reports cannot include an error\"\n\t});\n\tif (frame.outcome !== \"completed\" && !frame.errorReason) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"errorReason\"],\n\t\tmessage: \"Non-completed reports require an error\"\n\t});\n\tif (frame.resultHash !== computeTurnResultHash(frame)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"resultHash\"],\n\t\tmessage: \"Turn result hash does not match the report\"\n\t});\n});\nconst TurnReportResultSchema = z.object({\n\ttype: z.literal(\"turn:report:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tturnId: RuntimeOpaqueIdSchema,\n\tstatus: z.enum([\n\t\t\"recorded\",\n\t\t\"already_recorded\",\n\t\t\"conflict\",\n\t\t\"stale_generation\",\n\t\t\"unsupported_capability\"\n\t]),\n\tresultHash: RuntimeSha256Schema\n}).strict();\nconst AgentRuntimeTestRequestFrameSchema = z.object({\n\ttype: z.literal(\"agent-runtime:test\"),\n\trequestId: RuntimeRequestIdSchema,\n\tcomputerId: z.string().uuid(),\n\tprovider: AgentRuntimeProviderSchema,\n\tmodel: RuntimeModelSchema.optional(),\n\treasoningEffort: RuntimeReasoningEffortSchema.optional()\n}).strict();\nconst AgentRuntimeTestCancelFrameSchema = z.object({\n\ttype: z.literal(\"agent-runtime:test:cancel\"),\n\trequestId: RuntimeRequestIdSchema\n}).strict();\nconst AgentRuntimeTestResultFrameSchema = z.object({\n\ttype: z.literal(\"agent-runtime:test:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\tstatus: z.enum([\"passed\", \"failed\"]),\n\tcode: AgentRuntimeTestFailureCodeSchema.optional()\n}).strict().superRefine((frame, context) => {\n\tif (frame.status === \"passed\" && frame.code !== void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"code\"],\n\t\tmessage: \"A passed Agent Runtime test forbids a failure code\"\n\t});\n\tif (frame.status === \"failed\" && frame.code === void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"code\"],\n\t\tmessage: \"A failed Agent Runtime test requires a failure code\"\n\t});\n});\nconst ProviderCliExpectedIdentitySchema = z.discriminatedUnion(\"provider\", [z.object({\n\tprovider: z.literal(\"feishu\"),\n\tappId: z.string().min(1).max(255),\n\tbotOpenId: z.string().min(1).max(255),\n\tteamBrand: z.enum([\"feishu\", \"lark\"])\n}).strict(), z.object({\n\tprovider: z.literal(\"slack\"),\n\tteamId: z.string().min(1).max(255),\n\tbotUserId: z.string().min(1).max(255),\n\tbotId: z.string().min(1).max(255)\n}).strict()]);\nconst providerCliFenceShape = {\n\trequestId: RuntimeRequestIdSchema,\n\tprovider: ImCliProviderSchema,\n\tagentId: z.string().uuid(),\n\tintegrationId: z.string().uuid(),\n\tcredentialGeneration: z.number().int().safe().positive()\n};\nconst ProviderCliPrewarmFrameSchema = z.object({\n\ttype: z.literal(\"provider-cli:prewarm\"),\n\trequestId: RuntimeRequestIdSchema,\n\t/**\n\t* Registration only needs a fresh observation after the foreground `connect` command has\n\t* already repaired the machine. Reusing an already-connected Computer has no foreground\n\t* owner, so the daemon must run the same idempotent ensure before it reports readiness.\n\t* Missing means `inspect` for rolling compatibility with older Servers.\n\t*/\n\tmode: z.enum([\"inspect\", \"ensure\"]).optional(),\n\t/** Selected Agent Runtime to probe immediately for a Server-owned ensure operation. */\n\truntimeProvider: AgentRuntimeProviderSchema.optional(),\n\tproviders: z.array(ImCliProviderSchema).min(1).max(IM_CLI_PROVIDERS.length).superRefine((providers, context) => {\n\t\tconst seen = /* @__PURE__ */ new Set();\n\t\tfor (const [index, provider] of providers.entries()) {\n\t\t\tif (seen.has(provider)) context.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [index],\n\t\t\t\tmessage: \"IM CLI prewarm providers must be unique\"\n\t\t\t});\n\t\t\tseen.add(provider);\n\t\t\tconst previous = providers[index - 1];\n\t\t\tif (previous !== void 0 && IM_CLI_PROVIDERS.indexOf(provider) < IM_CLI_PROVIDERS.indexOf(previous)) context.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [index],\n\t\t\t\tmessage: \"IM CLI prewarm providers must use canonical Provider order\"\n\t\t\t});\n\t\t}\n\t})\n}).strict();\n/**\n* Terminal result for one Server-owned preparation operation. The request fence lets the Server\n* reject a result from an older click/rebind while heartbeats continue to report general daemon\n* health independently.\n*/\nconst ProviderCliPrewarmResultFrameSchema = z.object({\n\ttype: z.literal(\"provider-cli:prewarm:result\"),\n\trequestId: RuntimeRequestIdSchema,\n\truntime: z.object({\n\t\tprovider: AgentRuntimeProviderSchema,\n\t\tstatus: ProviderReadinessStatusSchema.exclude([\"checking\"])\n\t}).strict(),\n\tproviders: z.array(z.object({\n\t\tprovider: ImCliProviderSchema,\n\t\tstatus: ImCliReadinessStatusSchema.exclude([\"checking\"])\n\t}).strict()).min(1).max(IM_CLI_PROVIDERS.length).superRefine((observations, context) => {\n\t\tconst providers = observations.map((observation) => observation.provider);\n\t\tif (new Set(providers).size !== providers.length) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tmessage: \"Preparation result providers must be unique\"\n\t\t});\n\t\tfor (const [index, provider] of providers.entries()) {\n\t\t\tconst previous = providers[index - 1];\n\t\t\tif (previous !== void 0 && IM_CLI_PROVIDERS.indexOf(provider) < IM_CLI_PROVIDERS.indexOf(previous)) context.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tpath: [index, \"provider\"],\n\t\t\t\tmessage: \"Preparation result providers must use canonical Provider order\"\n\t\t\t});\n\t\t}\n\t})\n}).strict();\nconst ProviderCliRequirementFrameSchema = z.object({\n\ttype: z.literal(\"provider-cli:requirement\"),\n\toperation: z.literal(1),\n\t...providerCliFenceShape,\n\texpectedIdentity: ProviderCliExpectedIdentitySchema\n}).strict().superRefine((frame, context) => {\n\tif (frame.expectedIdentity.provider !== frame.provider) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"expectedIdentity\", \"provider\"],\n\t\tmessage: \"The expected identity provider must match the requirement provider\"\n\t});\n});\nconst ProviderCliArtifactStatusFrameSchema = z.object({\n\ttype: z.literal(\"provider-cli:artifact:status\"),\n\t...providerCliFenceShape,\n\tstatus: z.enum([\n\t\t\"checking\",\n\t\t\"ready\",\n\t\t\"unavailable\"\n\t]),\n\treason: ProviderCliArtifactPublicReasonSchema.optional()\n}).strict().superRefine((frame, context) => {\n\tif (frame.status !== \"unavailable\" && frame.reason !== void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"reason\"],\n\t\tmessage: \"An artifact reason is only valid on unavailable\"\n\t});\n});\nconst IntegrationCliValidationGrantMaterialSchema = z.discriminatedUnion(\"provider\", [z.object({\n\tprovider: z.literal(\"feishu\"),\n\tappId: runtimeByteString(512, \"Feishu App ID exceeds the 512-byte limit\", 1),\n\tappSecret: runtimeByteString(4096, \"Feishu App secret exceeds the 4 KiB limit\", 1),\n\tteamBrand: z.enum([\"feishu\", \"lark\"])\n}).strict(), z.object({\n\tprovider: z.literal(\"slack\"),\n\tbotAccessToken: runtimeByteString(4096, \"Slack Bot token exceeds the 4 KiB limit\", 1)\n}).strict()]);\nconst ProviderCliValidationGrantFrameSchema = z.object({\n\ttype: z.literal(\"provider-cli:validation:grant\"),\n\t...providerCliFenceShape,\n\trequirementRequestId: RuntimeRequestIdSchema,\n\texpiresAt: z.string().datetime({ offset: true }),\n\texpectedIdentity: ProviderCliExpectedIdentitySchema,\n\tgrant: IntegrationCliValidationGrantMaterialSchema\n}).strict().superRefine((frame, context) => {\n\tif (frame.expectedIdentity.provider !== frame.provider) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"expectedIdentity\", \"provider\"],\n\t\tmessage: \"The expected identity provider must match the grant provider\"\n\t});\n\tif (frame.grant.provider !== frame.provider) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"grant\", \"provider\"],\n\t\tmessage: \"The grant provider must match the frame provider\"\n\t});\n});\nconst ProviderCliValidationRunFrameSchema = z.object({\n\ttype: z.literal(\"provider-cli:validation:run\"),\n\t...providerCliFenceShape,\n\trequirementRequestId: RuntimeRequestIdSchema,\n\texpiresAt: z.string().datetime({ offset: true }),\n\texpectedIdentity: ProviderCliExpectedIdentitySchema,\n\tvalidationRunId: z.string().uuid()\n}).strict().superRefine((frame, context) => {\n\tif (frame.expectedIdentity.provider !== frame.provider) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"expectedIdentity\", \"provider\"],\n\t\tmessage: \"The expected identity provider must match the run provider\"\n\t});\n});\nconst ProviderCliCancelFrameSchema = z.object({\n\ttype: z.literal(\"provider-cli:cancel\"),\n\trequestId: RuntimeRequestIdSchema,\n\trequirementRequestId: RuntimeRequestIdSchema,\n\tprovider: ImCliProviderSchema,\n\tagentId: z.string().uuid(),\n\tintegrationId: z.string().uuid(),\n\tcredentialGeneration: z.number().int().safe().positive()\n}).strict();\nconst ProviderCliValidationResultFrameSchema = z.object({\n\ttype: z.literal(\"provider-cli:validation:result\"),\n\t...providerCliFenceShape,\n\tstatus: z.enum([\n\t\t\"retrying\",\n\t\t\"ready\",\n\t\t\"needs_attention\"\n\t]),\n\treason: ProviderCliValidationResultReasonSchema.optional()\n}).strict().superRefine((frame, context) => {\n\tif (frame.status === \"ready\" && frame.reason !== void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"reason\"],\n\t\tmessage: \"A ready credential execution result forbids a reason\"\n\t});\n\tif (frame.status === \"retrying\" && frame.reason === void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"reason\"],\n\t\tmessage: \"A retrying credential execution result requires a reason\"\n\t});\n\tif (frame.status === \"retrying\" && frame.reason !== void 0 && frame.reason !== \"provider_unreachable\" && frame.reason !== \"rate_limited\" && frame.reason !== \"validation_busy\" && frame.reason !== \"validation_expired\" && frame.reason !== \"artifact_changed\") context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"reason\"],\n\t\tmessage: \"A retrying credential execution result requires a retryable reason\"\n\t});\n\tif (frame.status === \"needs_attention\" && (frame.reason === \"validation_busy\" || frame.reason === \"validation_expired\" || frame.reason === \"artifact_changed\")) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"reason\"],\n\t\tmessage: \"A terminal credential execution result forbids internal retry reasons\"\n\t});\n});\nconst ServerRuntimeBusinessFrameSchema = z.discriminatedUnion(\"type\", [\n\tContextTreeOperationFrameSchema,\n\tSessionReconcileRequestSchema,\n\tDirectImMessageDeliveryRequestSchema,\n\tRuntimeImSteerRequestSchema,\n\tSessionMessageDeliveryRequestSchema,\n\tTurnReportResultSchema,\n\tRuntimeImCredentialGrantResultSchema,\n\tAgentRuntimeTestRequestFrameSchema,\n\tAgentRuntimeTestCancelFrameSchema,\n\tProviderCliPrewarmFrameSchema,\n\tProviderCliRequirementFrameSchema,\n\tProviderCliValidationGrantFrameSchema,\n\tProviderCliValidationRunFrameSchema,\n\tProviderCliCancelFrameSchema\n]);\nconst ClientRuntimeBusinessFrameSchema = z.discriminatedUnion(\"type\", [\n\tContextTreeOperationResultFrameSchema,\n\tSessionReconcileResultSchema,\n\tImMessageDeliveryResultSchema,\n\tRuntimeImSteerResultSchema,\n\tSessionMessageDeliveryResultSchema,\n\tAgentTraceBatchSchema,\n\tTurnReportRequestSchema,\n\tRuntimeImCredentialGrantRequestSchema,\n\tProviderCliArtifactStatusFrameSchema,\n\tProviderCliPrewarmResultFrameSchema,\n\tProviderCliValidationResultFrameSchema\n]);\nfunction runtimeUsageTotalTokens(provider, usage) {\n\tconst cachedInputTokens = {\n\t\tcodex: 0,\n\t\t\"claude-code\": usage.cachedInputTokens ?? 0,\n\t\tpi: usage.cachedInputTokens ?? 0\n\t};\n\tconst total = (usage.inputTokens ?? 0) + cachedInputTokens[provider] + (usage.outputTokens ?? 0);\n\tif (!Number.isSafeInteger(total)) throw new Error(\"Runtime usage token total exceeds the safe integer range\");\n\treturn total;\n}\nfunction computeRuntimeSnapshotHashes(input) {\n\tconst snapshot = EffectiveRuntimeSnapshotSchema.parse(input);\n\tconst agentConfigHash = hashTuple([\n\t\t1,\n\t\tsnapshot.agentId,\n\t\tsnapshot.provider,\n\t\tsnapshot.revision.agent.sequence,\n\t\tsnapshot.revision.agent.id,\n\t\tsnapshot.instructions.platform,\n\t\tsnapshot.instructions.agent,\n\t\tsnapshot.workspace.workspaceId,\n\t\tsnapshot.workspace.mode,\n\t\tsnapshot.workspace.sharing,\n\t\tnormalizeContextTrees(snapshot.contextTrees)\n\t]);\n\tconst sessionConfigHash = hashTuple([\n\t\t1,\n\t\tsnapshot.revision.session.sequence,\n\t\tsnapshot.revision.session.id,\n\t\tsnapshot.model ?? null,\n\t\tsnapshot.reasoningEffort ?? null,\n\t\tsnapshot.instructions.session ?? null,\n\t\tsnapshot.execution.approvalPolicy,\n\t\tsnapshot.execution.networkAccess,\n\t\tsnapshot.budget?.maxDurationMs ?? null\n\t]);\n\treturn {\n\t\tagentConfigHash,\n\t\tsessionConfigHash,\n\t\teffectiveSnapshotHash: hashTuple([\n\t\t\t1,\n\t\t\tagentConfigHash,\n\t\t\tsessionConfigHash\n\t\t])\n\t};\n}\nfunction computeDirectInputHash(input) {\n\tconst frame = DirectImMessageDeliveryRequestSchema.parse(input);\n\tconst payload = [\n\t\t1,\n\t\tframe.imMessageId,\n\t\tframe.sessionId,\n\t\tframe.agentId,\n\t\tframe.placementGeneration,\n\t\tframe.attention,\n\t\tframe.content.kind,\n\t\tframe.content.text,\n\t\tframe.content.providerRef,\n\t\tframe.content.history ?? [],\n\t\tframe.content.historyTruncated ?? false,\n\t\tframe.content.resources ?? [],\n\t\tcomputeRuntimeSnapshotHashes(frame.runtime).effectiveSnapshotHash,\n\t\tframe.deadlineAt ?? null\n\t];\n\treturn frame.replyRole === \"observer\" ? hashTuple([\n\t\t2,\n\t\t\"observer\",\n\t\t...payload.slice(1)\n\t]) : hashTuple(payload);\n}\nfunction computeRuntimeImMessageSemanticHash(input) {\n\tconst frame = input.type === \"im:deliver\" ? DirectImMessageDeliveryRequestSchema.parse(input) : RuntimeImSteerRequestSchema.parse(input);\n\tconst payload = [\n\t\t1,\n\t\tframe.imMessageId,\n\t\tframe.sessionId,\n\t\tframe.agentId,\n\t\tframe.placementGeneration,\n\t\tframe.attention,\n\t\tframe.content.kind,\n\t\tframe.content.text,\n\t\tframe.content.providerRef,\n\t\tframe.deadlineAt ?? null\n\t];\n\treturn frame.replyRole === \"observer\" ? hashTuple([\n\t\t2,\n\t\t\"observer\",\n\t\t...payload.slice(1)\n\t]) : hashTuple(payload);\n}\nfunction computeRuntimeImSteerInputHash(input) {\n\tconst frame = RuntimeImSteerRequestSchema.parse(input);\n\treturn hashTuple([\n\t\t1,\n\t\tframe.deliveryId,\n\t\tcomputeRuntimeImMessageSemanticHash(frame),\n\t\tframe.rootDeliveryId,\n\t\tframe.expectedTurnId\n\t]);\n}\nfunction computeReconcilePayloadHash(input) {\n\tconst frame = SessionReconcileRequestSchema.parse(input);\n\treturn hashTuple([\n\t\t1,\n\t\tframe.installationId,\n\t\tframe.sessionId,\n\t\tframe.agentId,\n\t\tframe.placementGeneration,\n\t\tframe.sessionKind ?? null,\n\t\tframe.creatorSessionId ?? null,\n\t\tframe.sessionCliProof?.proofId ?? null,\n\t\tframe.desired,\n\t\tframe.runtime ? computeRuntimeSnapshotHashes(frame.runtime).effectiveSnapshotHash : null\n\t]);\n}\nfunction computeTurnResultHash(input) {\n\tconst tuple = [\n\t\tinput.deliveryId,\n\t\tinput.turnId,\n\t\tinput.sessionId,\n\t\tinput.agentId,\n\t\tinput.placementGeneration,\n\t\tinput.outcome,\n\t\tinput.executionEffects,\n\t\tinput.finalText ?? null,\n\t\tinput.errorReason ?? null,\n\t\t[\n\t\t\tinput.usage?.inputTokens ?? null,\n\t\t\tinput.usage?.cachedInputTokens ?? null,\n\t\t\tinput.usage?.outputTokens ?? null\n\t\t],\n\t\t[input.traceSummary.lastSequence, input.traceSummary.droppedEvents]\n\t];\n\tif (input.outgoingReplies !== void 0) tuple.push(JSON.stringify(input.outgoingReplies, (_key, value) => {\n\t\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) return value;\n\t\tconst record = value;\n\t\treturn Object.fromEntries(Object.keys(record).sort().map((key) => [key, record[key]]));\n\t}));\n\treturn hashTuple(tuple);\n}\nfunction hashTuple(tuple) {\n\treturn createHash(\"sha256\").update(JSON.stringify(tuple), \"utf8\").digest(\"hex\");\n}\n//#endregion\n//#region src/session-cli.ts\nconst SESSION_CLI_DEFAULT_LIMIT = 20;\nconst SESSION_CLI_MAX_LIMIT = 100;\nconst SESSION_CLI_TASK_PREVIEW_MAX_BYTES = 256;\nconst SESSION_CLI_PROOF_HEADER = \"x-opentag-session-proof\";\nconst SessionCliTextSchema = z.string().min(1).refine((value) => Buffer.byteLength(value, \"utf8\") <= RUNTIME_DIRECT_TEXT_MAX_BYTES, { message: \"Session message exceeds the 16 KiB limit\" });\nconst SessionCliCreateRequestSchema = z.object({\n\tmessageId: z.string().uuid(),\n\tmessage: SessionCliTextSchema,\n\tmodel: RuntimeModelSchema.optional(),\n\treasoningEffort: RuntimeReasoningEffortSchema.optional(),\n\tmaxDurationMs: RuntimeMaxDurationMsSchema.optional()\n}).strict();\nconst SessionCliSendRequestSchema = z.object({\n\tmessageId: z.string().uuid(),\n\ttargetSessionId: z.string().uuid(),\n\tmessage: SessionCliTextSchema\n}).strict();\nconst SessionCliCommandStatusSchema = z.enum([\n\t\"accepted\",\n\t\"unreachable\",\n\t\"unknown\",\n\t\"rejected\"\n]);\nconst SessionCliCommandResponseSchema = z.object({\n\tmessageId: z.string().uuid(),\n\tstatus: SessionCliCommandStatusSchema,\n\tsessionId: z.string().uuid().optional(),\n\tcode: z.string().min(1).max(128).optional()\n}).strict();\nconst SessionCliListQuerySchema = z.object({\n\trecursive: z.boolean().default(false),\n\tlimit: z.number().int().min(1).max(100).default(20),\n\tcursor: z.string().min(1).max(2048).optional(),\n\tsince: z.string().datetime({ offset: true }).optional()\n}).strict();\nconst SessionCliListItemSchema = z.object({\n\tsessionId: z.string().uuid(),\n\tparentSessionId: z.string().uuid(),\n\tcreatedAt: z.string().datetime({ offset: true }),\n\tlastMessageAt: z.string().datetime({ offset: true }),\n\tlastDeliveryOutcome: z.enum([\n\t\t\"unknown\",\n\t\t\"accepted\",\n\t\t\"unreachable\",\n\t\t\"rejected\"\n\t]),\n\ttaskPreview: z.string()\n}).strict();\nconst SessionCliListResponseSchema = z.object({\n\titems: z.array(SessionCliListItemSchema).max(100),\n\tnextCursor: z.string().min(1).max(2048).optional()\n}).strict();\n/**\n* The Server-minted proof a managed Runtime hands to the in-Session CLI. The token is a bearer\n* credential bound to the exact Session/placement/execution connection; it is delivered only over\n* authenticated runtime channels (Local reconcile, Cloud verified frames) and worker stdin.\n*/\nconst SessionCliProofGrantSchema = z.object({\n\tproofId: z.string().uuid(),\n\ttoken: runtimeByteString(4096, \"Session CLI proof exceeds the 4 KiB limit\", 32)\n}).strict();\n//#endregion\n//#region src/runtime-credentials.ts\n/**\n* Runtime credential delegation contract (control + data planes).\n*\n* The control plane travels over the authenticated runtime business channel; the data plane is a\n* separate binary WebSocket authenticated by a single-use ticket. Schemas here are the only wire\n* authority: both planes use strict objects, bounded strings, and explicit enums. Nothing in this\n* module carries raw platform secrets — capabilities and tickets are opaque random values.\n*/\nconst RUNTIME_PROVIDER_PROXY_PATH = \"/api/v1/runtime/provider-proxy\";\nconst RUNTIME_CREDENTIAL_CAPABILITY_TTL_MS = 6e4;\nconst RUNTIME_CREDENTIAL_CAPABILITY_REFRESH_AFTER_MS = 3e4;\nconst RUNTIME_PROXY_TICKET_TTL_MS = 15e3;\nconst RUNTIME_EXECUTION_MAX_LIFETIME_MS = 864e5;\nconst RUNTIME_VALIDATION_RUN_TTL_MS = 6e4;\nconst PROVIDER_PROXY_HEADER_MAX_BYTES = 16384;\nconst PROVIDER_PROXY_CHUNK_MAX_BYTES = 65536;\nconst PROVIDER_PROXY_INITIAL_CREDIT_BYTES = 1048576;\nconst PROVIDER_PROXY_MAX_STREAMS_PER_EXECUTION = 8;\nconst PROVIDER_PROXY_MAX_STREAM_OPENS_PER_CONNECTION = 256;\nconst PROVIDER_PROXY_STREAM_REVALIDATE_INTERVAL_MS = 5e3;\nconst PROVIDER_PROXY_AUTH_TIMEOUT_MS = 5e3;\nconst PROVIDER_PROXY_MAX_FRAME_BYTES = 65540;\nconst RUNTIME_CLI_METADATA_MAX_REPOSITORIES = 100;\n/**\n* Reserved internal header carrying the pinned upstream host for GitHub proxy streams\n* (`github.com` for Git, `api.github.com` for REST/GraphQL). Set only by the trusted Runner\n* adapter; the Server validates it and never treats it as caller authority over the origin.\n*/\nconst RUNTIME_PROVIDER_ORIGIN_HEADER = \"x-opentag-provider-origin\";\n/**\n* Harmless placeholder the Server returns for the Feishu tenant-token endpoint. The real tenant\n* token never leaves the Server, and the Runner adapter replaces this sentinel with its\n* Sandbox-local handle before the native CLI sees it.\n*/\nconst FEISHU_TENANT_TOKEN_LOCAL_SENTINEL = \"opentag-local-handle-tenant-token\";\nconst RUNTIME_CREDENTIAL_PROVIDERS = [\n\t\"github\",\n\t\"slack\",\n\t\"feishu\"\n];\nconst RuntimeCredentialProviderSchema = z.enum(RUNTIME_CREDENTIAL_PROVIDERS);\nconst executionId = z.string().uuid();\nconst grantId = z.string().uuid();\nconst bindingId = z.string().min(1).max(128);\nconst requestId = RuntimeRequestIdSchema;\nconst isoDateTime = z.string().datetime({ offset: true });\nconst opaqueToken = runtimeByteString(512, \"The opaque token exceeds the 512-byte limit\", 32);\nconst ticket = runtimeByteString(512, \"The proxy ticket exceeds the 512-byte limit\", 32);\nconst scopeDigest = z.string().regex(/^[a-f0-9]{64}$/, \"Expected a lowercase SHA-256 digest\");\nconst revisionString = z.string().min(1).max(256);\nconst RuntimeExecutionSourceSchema = z.discriminatedUnion(\"kind\", [\n\tz.object({\n\t\tkind: z.literal(\"delivery\"),\n\t\tdeliveryId: RuntimeOpaqueIdSchema,\n\t\tturnId: RuntimeOpaqueIdSchema\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"session-message\"),\n\t\tmessageId: z.string().uuid()\n\t}).strict(),\n\tz.object({\n\t\tkind: z.literal(\"validation\"),\n\t\tvalidationRunId: z.string().uuid()\n\t}).strict()\n]);\nconst RuntimeExecutionSandboxSchema = z.object({\n\tsandboxId: z.string().uuid(),\n\tresourceUid: z.string().min(1).max(128),\n\tenvironmentGeneration: z.number().int().safe().positive()\n}).strict();\nconst RuntimeExecutionOpenRequestSchema = z.object({\n\ttype: z.literal(\"runtime:execution:open\"),\n\trequestId,\n\tsessionId: RuntimeOpaqueIdSchema,\n\tagentId: RuntimeOpaqueIdSchema,\n\tplacementGeneration: z.number().int().safe().positive(),\n\trunId: z.string().uuid(),\n\tsource: RuntimeExecutionSourceSchema,\n\tsandbox: RuntimeExecutionSandboxSchema.optional(),\n\t/**\n\t* Optional platform services the Client opts into (currently only `web`). Sent only when the\n\t* `runtime.webTools` capability was negotiated; older peers never see or accept this field.\n\t*/\n\tservices: z.array(RuntimeExecutionServiceRequestSchema).max(4).optional()\n}).strict();\nconst cliOutboxContext = RuntimeImOutboxContextSchema.optional();\nconst RuntimeFeishuCliMetadataSchema = z.object({\n\tprovider: z.literal(\"feishu\"),\n\tappId: z.string().max(512),\n\tteamBrand: z.enum([\"feishu\", \"lark\"]),\n\toutboxContext: cliOutboxContext\n}).strict();\nconst RuntimeSlackCliMetadataSchema = z.object({\n\tprovider: z.literal(\"slack\"),\n\tteamId: z.string().max(255),\n\tbotUserId: z.string().max(255),\n\toutboxContext: cliOutboxContext\n}).strict();\nconst RuntimeGitHubCliRepositorySchema = z.object({\n\trepositoryId: z.string().min(1).max(128),\n\tfullName: z.string().min(1).max(255),\n\trole: GitHubRepositoryRoleSchema,\n\taccess: GitHubRepositoryAccessSchema,\n\tbranch: GitBranchRefSchema.optional(),\n\tpublish: GitHubRepositoryPublishModeSchema.optional(),\n\tworkBranchPrefix: z.string().max(160).regex(/^refs\\/heads\\/opentag\\/[0-9a-f-]{36}\\/(?:code|context_tree)\\/$/).optional()\n}).strict();\nconst RuntimeGitHubCliMetadataSchema = z.object({\n\tprovider: z.literal(\"github\"),\n\tconnectionId: z.string().min(1).max(128),\n\trepositories: z.array(RuntimeGitHubCliRepositorySchema).max(100)\n}).strict();\n/**\n* Provider-discriminated, bounded non-secret CLI metadata. A provider variant carries only what\n* the native CLI needs (identity labels and repo scope); it never contains tokens, secrets,\n* signed URLs, or tenant material.\n*/\nconst RuntimeProviderCliMetadataSchema = z.discriminatedUnion(\"provider\", [\n\tRuntimeFeishuCliMetadataSchema,\n\tRuntimeSlackCliMetadataSchema,\n\tRuntimeGitHubCliMetadataSchema\n]).superRefine((cli, context) => {\n\tif (\"outboxContext\" in cli && cli.outboxContext && cli.outboxContext.provider !== cli.provider) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"outboxContext\", \"provider\"],\n\t\tmessage: \"The outbox context provider must match the CLI metadata provider\"\n\t});\n});\nconst RuntimeExecutionProviderSchema = z.discriminatedUnion(\"provider\", [\n\tz.object({\n\t\tprovider: z.literal(\"feishu\"),\n\t\tbindingId,\n\t\tcli: RuntimeFeishuCliMetadataSchema\n\t}).strict(),\n\tz.object({\n\t\tprovider: z.literal(\"slack\"),\n\t\tbindingId,\n\t\tcli: RuntimeSlackCliMetadataSchema\n\t}).strict(),\n\tz.object({\n\t\tprovider: z.literal(\"github\"),\n\t\tbindingId,\n\t\tcli: RuntimeGitHubCliMetadataSchema\n\t}).strict()\n]);\nconst RuntimeExecutionOpenRejectCodeSchema = z.enum([\n\t\"execution_not_ready\",\n\t\"execution_source_invalid\",\n\t\"execution_authority_denied\",\n\t\"placement_stale\",\n\t\"agent_mismatch\",\n\t\"sandbox_mismatch\",\n\t\"capability_unsupported\",\n\t\"owner_unavailable\"\n]);\nconst RuntimeExecutionOpenResultSchema = z.discriminatedUnion(\"status\", [z.object({\n\ttype: z.literal(\"runtime:execution:result\"),\n\trequestId,\n\tstatus: z.literal(\"succeeded\"),\n\texecutionId,\n\texpiresAt: isoDateTime,\n\tproviders: z.array(RuntimeExecutionProviderSchema).max(16),\n\t/**\n\t* E8: the managed Session's CLI proof, minted at the actual execution open for a Cloud\n\t* collaboration-negotiated connection. Present only on a succeeded open of a Session work\n\t* source; the trusted Runner relays it to the worker ephemerally and never journals it.\n\t*/\n\tsessionCliProof: SessionCliProofGrantSchema.optional(),\n\t/**\n\t* Granted platform services with their exact authorized scopes. Present only when the\n\t* `runtime.webTools` capability was negotiated; an empty providers list with a non-empty\n\t* services list is a real, authorized execution.\n\t*/\n\tservices: z.array(RuntimeExecutionServiceSchema).max(4).optional()\n}).strict(), z.object({\n\ttype: z.literal(\"runtime:execution:result\"),\n\trequestId,\n\tstatus: z.literal(\"rejected\"),\n\tcode: RuntimeExecutionOpenRejectCodeSchema\n}).strict()]);\nconst RuntimeCredentialAcquireRequestSchema = z.object({\n\ttype: z.literal(\"runtime:credential:acquire\"),\n\trequestId,\n\texecutionId,\n\tprovider: RuntimeCredentialProviderSchema,\n\tbindingId\n}).strict();\nconst RuntimeCredentialRenewRequestSchema = z.object({\n\ttype: z.literal(\"runtime:credential:renew\"),\n\trequestId,\n\texecutionId,\n\tgrantId\n}).strict();\nconst RuntimeCredentialRejectCodeSchema = z.enum([\n\t\"execution_unknown\",\n\t\"execution_closed\",\n\t\"execution_expired\",\n\t\"credential_scope_denied\",\n\t\"credential_stale\",\n\t\"binding_inactive\",\n\t\"provider_mismatch\",\n\t\"grant_mismatch\",\n\t\"owner_unavailable\"\n]);\nconst RuntimeCredentialResultSchema = z.discriminatedUnion(\"status\", [z.object({\n\ttype: z.literal(\"runtime:credential:result\"),\n\trequestId,\n\tstatus: z.literal(\"succeeded\"),\n\texecutionId,\n\tgrantId,\n\tprovider: RuntimeCredentialProviderSchema,\n\tbindingId,\n\topaqueToken,\n\texpiresAt: isoDateTime,\n\trefreshAfter: isoDateTime,\n\tscopeHash: scopeDigest,\n\tauthorizationRevision: revisionString,\n\tcredentialGeneration: revisionString,\n\tcli: RuntimeProviderCliMetadataSchema\n}).strict(), z.object({\n\ttype: z.literal(\"runtime:credential:result\"),\n\trequestId,\n\tstatus: z.literal(\"rejected\"),\n\tcode: RuntimeCredentialRejectCodeSchema\n}).strict()]);\nconst RuntimeExecutionCloseRequestSchema = z.object({\n\ttype: z.literal(\"runtime:execution:close\"),\n\trequestId,\n\texecutionId\n}).strict();\nconst RuntimeExecutionClosedResultSchema = z.object({\n\ttype: z.literal(\"runtime:execution:closed\"),\n\trequestId,\n\texecutionId,\n\tstatus: z.enum([\"succeeded\", \"rejected\"]),\n\tcode: z.enum([\"execution_unknown\", \"owner_unavailable\"]).optional()\n}).strict().superRefine((frame, context) => {\n\tif (frame.status === \"rejected\" && !frame.code) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"code\"],\n\t\tmessage: \"A rejected close requires a code\"\n\t});\n\tif (frame.status === \"succeeded\" && frame.code) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"code\"],\n\t\tmessage: \"A succeeded close forbids a code\"\n\t});\n});\nconst RuntimeProxyTicketRejectCodeSchema = z.enum([\n\t\"execution_unknown\",\n\t\"execution_closed\",\n\t\"capability_unsupported\",\n\t\"owner_unavailable\"\n]);\nconst RuntimeProxyTicketRequestSchema = z.object({\n\ttype: z.literal(\"runtime:proxy:ticket\"),\n\trequestId,\n\texecutionId\n}).strict();\nconst RuntimeProxyTicketResultSchema = z.discriminatedUnion(\"status\", [z.object({\n\ttype: z.literal(\"runtime:proxy:ticket:result\"),\n\trequestId,\n\tstatus: z.literal(\"succeeded\"),\n\texecutionId,\n\tticket,\n\texpiresAt: isoDateTime,\n\tpath: z.literal(RUNTIME_PROVIDER_PROXY_PATH)\n}).strict(), z.object({\n\ttype: z.literal(\"runtime:proxy:ticket:result\"),\n\trequestId,\n\tstatus: z.literal(\"rejected\"),\n\tcode: RuntimeProxyTicketRejectCodeSchema\n}).strict()]);\nconst RuntimeMcpGatewayRejectCodeSchema = z.enum([\n\t\"execution_unknown\",\n\t\"execution_closed\",\n\t\"capability_unsupported\",\n\t\"service_not_granted\",\n\t\"owner_unavailable\"\n]);\n/**\n* Web service refusal vocabulary. Deliberately its own enum rather than a reuse of the MCP one: the\n* two services have the same failure shapes today, but a future divergence (web has no path, MCP\n* has no scopes) should not force one service's contract to move because the other changed.\n*/\nconst RuntimeWebGatewayRejectCodeSchema = z.enum([\n\t\"execution_unknown\",\n\t\"execution_closed\",\n\t\"capability_unsupported\",\n\t\"service_not_granted\",\n\t\"owner_unavailable\"\n]);\nconst RuntimeMcpGatewayRequestSchema = z.object({\n\ttype: z.literal(\"runtime:mcp:gateway\"),\n\trequestId,\n\texecutionId\n}).strict();\n/**\n* The MCP gateway bearer for one execution.\n*\n* Its own frame rather than a field on the execution-open result, because the open result has never\n* carried a secret and both existing secrets in this protocol — capability tokens and proxy tickets\n* — are fetched this way. Only the path travels; the Client composes the URL against the server\n* origin it already pinned, so the Server never names a destination the Client will dial.\n*/\nconst RuntimeMcpGatewayResultSchema = z.discriminatedUnion(\"status\", [z.object({\n\ttype: z.literal(\"runtime:mcp:gateway:result\"),\n\trequestId,\n\tstatus: z.literal(\"succeeded\"),\n\texecutionId,\n\ttoken: opaqueToken,\n\texpiresAt: isoDateTime,\n\tpath: z.literal(MCP_GATEWAY_PATH)\n}).strict(), z.object({\n\ttype: z.literal(\"runtime:mcp:gateway:result\"),\n\trequestId,\n\tstatus: z.literal(\"rejected\"),\n\tcode: RuntimeMcpGatewayRejectCodeSchema\n}).strict()]);\nconst RuntimeWebGatewayRequestSchema = z.object({\n\ttype: z.literal(\"runtime:web:gateway\"),\n\trequestId,\n\texecutionId\n}).strict();\n/**\n* The execution-scoped web gateway bearer.\n*\n* Its own frame for the same reason the MCP bearer has one: the open result states the grant, and\n* every secret in this protocol is fetched separately. Unlike the MCP result there is no single\n* `path` field — the web service is two fixed routes that both ends already share as constants in\n* `./web-tools.ts`, so there is no Server-supplied destination for the Client to dial.\n*/\nconst RuntimeWebGatewayResultSchema = z.discriminatedUnion(\"status\", [z.object({\n\ttype: z.literal(\"runtime:web:gateway:result\"),\n\trequestId,\n\tstatus: z.literal(\"succeeded\"),\n\texecutionId,\n\ttoken: opaqueToken,\n\texpiresAt: isoDateTime\n}).strict(), z.object({\n\ttype: z.literal(\"runtime:web:gateway:result\"),\n\trequestId,\n\tstatus: z.literal(\"rejected\"),\n\tcode: RuntimeWebGatewayRejectCodeSchema\n}).strict()]);\nconst RuntimeCredentialRevokedCodeSchema = z.enum([\n\t\"execution_closed\",\n\t\"connection_replaced\",\n\t\"authorization_revoked\",\n\t\"policy_changed\",\n\t\"owner_lost\"\n]);\nconst RuntimeCredentialRevokedFrameSchema = z.object({\n\ttype: z.literal(\"runtime:credential:revoked\"),\n\texecutionId,\n\tcode: RuntimeCredentialRevokedCodeSchema\n}).strict();\nconst RuntimeCredentialClientFrameSchema = z.discriminatedUnion(\"type\", [\n\tRuntimeExecutionOpenRequestSchema,\n\tRuntimeCredentialAcquireRequestSchema,\n\tRuntimeCredentialRenewRequestSchema,\n\tRuntimeExecutionCloseRequestSchema,\n\tRuntimeProxyTicketRequestSchema,\n\tRuntimeMcpGatewayRequestSchema,\n\tRuntimeWebGatewayRequestSchema\n]);\nconst RuntimeCredentialServerFrameSchema = z.discriminatedUnion(\"type\", [\n\tRuntimeExecutionOpenResultSchema,\n\tRuntimeCredentialResultSchema,\n\tRuntimeExecutionClosedResultSchema,\n\tRuntimeProxyTicketResultSchema,\n\tRuntimeMcpGatewayResultSchema,\n\tRuntimeWebGatewayResultSchema,\n\tRuntimeCredentialRevokedFrameSchema\n]);\nconst streamIdSchema = z.number().int().min(1).max(2147483647);\nconst streamCreditBytesSchema = z.number().int().min(1).max(PROVIDER_PROXY_INITIAL_CREDIT_BYTES * 4);\nconst streamMethodSchema = z.enum([\n\t\"GET\",\n\t\"POST\",\n\t\"PUT\",\n\t\"PATCH\",\n\t\"DELETE\"\n]);\nconst streamPathSchema = runtimeByteString(8192, \"The provider path exceeds the 8 KiB limit\", 1);\nconst streamHeadersSchema = z.record(z.string().min(1).max(128), runtimeByteString(8192, \"A header value exceeds the 8 KiB limit\"));\nconst RuntimeProviderProxyAuthFrameSchema = z.object({\n\ttype: z.literal(\"auth\"),\n\tticket\n}).strict();\nconst RuntimeProviderProxyOpenFrameSchema = z.object({\n\ttype: z.literal(\"open\"),\n\tstreamId: streamIdSchema,\n\tcapability: opaqueToken,\n\tprovider: RuntimeCredentialProviderSchema,\n\tbindingId,\n\tmethod: streamMethodSchema,\n\tpath: streamPathSchema,\n\theaders: streamHeadersSchema\n}).strict();\nconst RuntimeProviderProxyReadyFrameSchema = z.object({\n\ttype: z.literal(\"ready\"),\n\texecutionId\n}).strict();\nconst RuntimeProviderProxyResponseFrameSchema = z.object({\n\ttype: z.literal(\"response\"),\n\tstreamId: streamIdSchema,\n\tstatus: z.number().int().min(100).max(599),\n\theaders: streamHeadersSchema\n}).strict();\nconst RuntimeProviderProxyEndFrameSchema = z.object({\n\ttype: z.literal(\"end\"),\n\tstreamId: streamIdSchema\n}).strict();\nconst RuntimeProviderProxyCancelFrameSchema = z.object({\n\ttype: z.literal(\"cancel\"),\n\tstreamId: streamIdSchema,\n\tcode: z.string().min(1).max(128).optional()\n}).strict();\nconst RuntimeProviderProxyCreditFrameSchema = z.object({\n\ttype: z.literal(\"credit\"),\n\tstreamId: streamIdSchema,\n\tbytes: streamCreditBytesSchema\n}).strict();\nconst RuntimeProviderProxyErrorFrameSchema = z.object({\n\ttype: z.literal(\"error\"),\n\tstreamId: streamIdSchema,\n\tcode: z.string().min(1).max(128)\n}).strict();\nconst RuntimeProviderProxyClientFrameSchema = z.discriminatedUnion(\"type\", [\n\tRuntimeProviderProxyOpenFrameSchema,\n\tRuntimeProviderProxyEndFrameSchema,\n\tRuntimeProviderProxyCancelFrameSchema,\n\tRuntimeProviderProxyCreditFrameSchema\n]);\nconst RuntimeProviderProxyServerFrameSchema = z.discriminatedUnion(\"type\", [\n\tRuntimeProviderProxyReadyFrameSchema,\n\tRuntimeProviderProxyResponseFrameSchema,\n\tRuntimeProviderProxyEndFrameSchema,\n\tRuntimeProviderProxyCancelFrameSchema,\n\tRuntimeProviderProxyCreditFrameSchema,\n\tRuntimeProviderProxyErrorFrameSchema\n]);\n/**\n* Binary data framing: a 4-byte big-endian uint32 stream identifier followed by 1..65536 payload\n* bytes. Returns `undefined` for malformed frames so callers can fail the connection closed.\n*/\nfunction encodeProviderProxyDataFrame(streamId, payload) {\n\tif (!Number.isSafeInteger(streamId) || streamId < 1 || streamId > 2147483647) throw new Error(\"The provider proxy stream id is out of range\");\n\tif (payload.byteLength < 1 || payload.byteLength > 65536) throw new Error(\"The provider proxy chunk size is out of range\");\n\tconst frame = new Uint8Array(payload.byteLength + 4);\n\tnew DataView(frame.buffer).setUint32(0, streamId, false);\n\tframe.set(payload, 4);\n\treturn frame;\n}\nfunction decodeProviderProxyDataFrame(frame) {\n\tif (frame.byteLength < 5 || frame.byteLength > 65540) return void 0;\n\tconst streamId = new DataView(frame.buffer, frame.byteOffset, frame.byteLength).getUint32(0, false);\n\tif (streamId < 1 || streamId > 2147483647) return void 0;\n\treturn {\n\t\tstreamId,\n\t\tpayload: frame.subarray(4)\n\t};\n}\n//#endregion\n//#region src/cloud-runner.ts\n/**\n* E3 Cloud Runner contract: the Session-owned Sandbox is materialized as exactly one Cloud Run\n* Instance that dials the Server over an outbound WebSocket and launches the native sandbox.\n*\n* The WebSocket protocol authenticates with a first-frame bootstrap bearer token (never a URL\n* token). The token claims (sandboxId/sessionId/environmentGeneration/resourceName) are verified\n* against the CURRENT database allocation on every connect, so a stale Runner from a replaced\n* environment generation can never attach to the new environment.\n*/\nconst RUNNER_WS_PROTOCOL_VERSION = 1;\n/**\n* E4 Cloud-delivery capability negotiated inside the existing protocol version 1 auth/welcome\n* exchange (E3 compatibility contract, `docs/cloud-runner-execution.md`). A new Runner requests it\n* in the auth frame; a Cloud-enabled Server echoes it in the welcome ONLY for a requesting\n* connection whose current allocation UID is already tracked. Legacy E3 channels never receive\n* E4 frames.\n*/\nconst RUNNER_CLOUD_DELIVERY_VERSION = 1;\n/**\n* E7 physical-instance reuse capability negotiated in the same auth/welcome exchange. A Runner\n* that holds a physical control credential requests it; the Server echoes it only after a\n* control-token attach resolved a current owner. Legacy Runners never send it, so they are never\n* asked to follow a Session-to-Session hand-off (idle deletion still saves them through E5).\n*/\nconst RUNNER_REUSE_VERSION = 1;\n/**\n* E8 Session-collaboration capability negotiated in the same auth/welcome exchange. The E8\n* Runner asks for it explicitly, and the Server echoes it ONLY for a requesting connection whose\n* Cloud allocation was fenced. Every `session:message:*` frame and the open-result\n* `sessionCliProof` field are gated on this echo, so an E7 Runner (same `runnerVersion` string,\n* strict frame schemas) never receives a field or frame it does not understand. A Runner that\n* does not request the capability keeps existing IM delivery unchanged. Deployment order is\n* Server-first with a pinned E8 Runner image: an E8 Runner against an old Server fails its auth\n* handshake (the strict E7 auth schema rejects the extra request field) instead of executing\n* without collaboration authority.\n*/\nconst RUNNER_SESSION_COLLABORATION_VERSION = 1;\n/** The Cloud Session-collaboration frame budget; mirrors the delivery run frame bound. */\nconst RUNNER_SESSION_MESSAGE_CONTEXT_REFINE = (value) => value.sessionKind === \"visible\" ? value.outboxContext !== void 0 : value.outboxContext === void 0;\n/** Server-mediated model proxy base path; the only paths below it are the source-owned allowlist. */\nconst CLOUD_MODEL_PROXY_PATH = \"/api/v1/cloud-model\";\n/** The single OpenAI-compatible operation E4 admits. */\nconst CLOUD_MODEL_CHAT_COMPLETIONS_PATH = `${CLOUD_MODEL_PROXY_PATH}/chat/completions`;\n/**\n* The two Cloud working context windows (tokens). The Server selects exactly one per issued grant\n* from the Router-verified native model window (>= 258,000 -> 258,000, >= 64,000 -> 64,000;\n* anything smaller or unverified is never issued); the Runner writes the value to Pi verbatim and\n* never re-derives a window from the model name.\n*/\nconst CLOUD_MODEL_CONTEXT_WINDOW_STANDARD = 64e3;\nconst CLOUD_MODEL_CONTEXT_WINDOW_EXTENDED = 258e3;\n/**\n* Platform ceiling for one issued Cloud output budget (tokens): the Router verifies at most this\n* native output limit, and the Server issues `min(ceiling, verified limit)` per grant.\n*/\nconst CLOUD_MODEL_OUTPUT_TOKEN_LIMIT = 8192;\n/** Runner control frames stay small; acceptance reports are bounded separately below. */\nconst RUNNER_WS_MAX_FRAME_BYTES = 262144;\n/** Bounded credential/config payloads: each document an Account may push for one acceptance run. */\nconst RUNNER_PI_CONFIG_DOCUMENT_MAX_CHARS = 32768;\n/** UTF-8 byte bound for a single Pi config document (non-ASCII text counts per byte). */\nconst RUNNER_PI_CONFIG_DOCUMENT_MAX_BYTES = 32768;\n/** Tightest dispatch budget: the serialized `kind/mode/piConfig` stdin document the worker reads. */\nconst RUNNER_ACCEPTANCE_WORKER_STDIN_MAX_BYTES = 131072;\nconst RUNNER_ACCEPTANCE_MODES = [\"offline\", \"real\"];\n/** The only model provider E3 real acceptance admits. */\nconst RUNNER_ACCEPTANCE_PROVIDER = \"deepseek\";\nconst UuidSchema = z.string().uuid();\nconst RequestIdSchema = z.string().min(1).max(256);\nconst ResourceNameSchema = z.string().min(1).max(1024);\nconst RunnerAcceptanceModeSchema = z.enum(RUNNER_ACCEPTANCE_MODES);\nconst ReportTextSchema = z.string().max(4096);\nconst RunnerAcceptanceEventWireSchema = z.object({\n\tname: z.string().min(1).max(256),\n\tstatus: z.enum([\n\t\t\"failed\",\n\t\t\"skipped\",\n\t\t\"passed\"\n\t]),\n\tdetail: ReportTextSchema.optional()\n}).strict();\nconst RunnerAcceptanceEvidenceWireSchema = z.object({\n\tcancel: z.object({\n\t\tlivePidsBeforeCancel: z.number().int().nonnegative(),\n\t\ttrackedPiPids: z.number().int().nonnegative()\n\t}).strict().optional(),\n\tskillsLoaded: z.array(z.string().min(1).max(256)).max(64).optional(),\n\ttools: z.object({\n\t\tnames: z.array(z.string().min(1).max(256)).max(128),\n\t\tsuccessfulCount: z.number().int().nonnegative()\n\t}).strict().optional()\n}).strict();\n/**\n* The identity document is accepted as bounded opaque evidence: it is emitted by the pinned\n* image and carries versions/SHAs only. Unknown extra keys are stripped rather than failing the\n* run, so a newer image does not break an older Server.\n*/\nconst RunnerIdentityWireSchema = z.object({\n\tversion: z.string().max(64).optional(),\n\tsourceSha: z.string().max(64).optional(),\n\tsourceDirty: z.boolean().optional(),\n\tchannel: z.string().max(32).optional(),\n\tnodeVersion: z.string().max(64).optional(),\n\tpiVersion: z.string().max(64).optional()\n}).strip();\nconst RunnerAcceptanceReportWireSchema = z.object({\n\tevents: z.array(RunnerAcceptanceEventWireSchema).max(256),\n\tevidence: RunnerAcceptanceEvidenceWireSchema.optional(),\n\tfailed: z.boolean(),\n\tfirstTaskMs: z.number().nonnegative().optional(),\n\tidentity: RunnerIdentityWireSchema.optional(),\n\tmodel: z.enum([\n\t\t\"failed\",\n\t\t\"skipped\",\n\t\t\"passed\"\n\t]),\n\toffline: z.enum([\"failed\", \"passed\"]),\n\tskillArguments: z.array(z.string().max(1024)).max(64).optional()\n}).strict();\n/** Minimal Pi configuration for one real acceptance run. Delivered per-request only; never persisted. */\nconst RunnerPiConfigDocumentSchema = z.string().min(1).max(RUNNER_PI_CONFIG_DOCUMENT_MAX_CHARS).superRefine((value, context) => {\n\tif (runtimeUtf8Length(value) > 32768) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: `Pi config documents exceed the ${RUNNER_PI_CONFIG_DOCUMENT_MAX_BYTES}-byte UTF-8 limit`\n\t});\n});\nconst RunnerPiConfigInputSchema = z.object({\n\tauthJson: RunnerPiConfigDocumentSchema,\n\tmodelsJson: RunnerPiConfigDocumentSchema.optional(),\n\tsettingsJson: RunnerPiConfigDocumentSchema.optional()\n}).strict();\n/**\n* The exact stdin document the Runner hands to the in-sandbox worker. It is the serialization\n* that counts toward the wire budget: JSON escaping (quotes, backslashes, control characters)\n* expands the document bytes, so the bound is measured on this string, not on each document.\n*/\nfunction serializeRunnerAcceptanceWorkerStdin(input) {\n\treturn JSON.stringify({\n\t\tkind: \"acceptance\",\n\t\tmode: input.mode,\n\t\t...input.piConfig ? { piConfig: input.piConfig } : {}\n\t});\n}\n/** Reject an acceptance command that would not fit the worker stdin and/or the control frame. */\nfunction checkRunnerAcceptanceWireBytes(value, context, serializedFrame) {\n\tif (value.piConfig && runtimeUtf8Length(serializeRunnerAcceptanceWorkerStdin(value)) > 131072) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"piConfig\"],\n\t\tmessage: `piConfig exceeds the ${RUNNER_ACCEPTANCE_WORKER_STDIN_MAX_BYTES}-byte serialized worker stdin budget`\n\t});\n\tif (serializedFrame !== void 0 && runtimeUtf8Length(serializedFrame) > 262144) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"piConfig\"],\n\t\tmessage: `The acceptance frame exceeds the ${RUNNER_WS_MAX_FRAME_BYTES}-byte control-channel budget`\n\t});\n}\nconst AccountSandboxRunnerAcceptanceRequestSchema = z.object({\n\tmode: RunnerAcceptanceModeSchema,\n\tpiConfig: RunnerPiConfigInputSchema.optional()\n}).strict().superRefine((value, context) => {\n\tif (value.mode === \"real\" && !value.piConfig) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"piConfig\"],\n\t\tmessage: \"Real acceptance requires piConfig\"\n\t});\n\tif (value.mode === \"offline\" && value.piConfig) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"piConfig\"],\n\t\tmessage: \"Offline acceptance must not carry piConfig\"\n\t});\n\tcheckRunnerAcceptanceWireBytes(value, context);\n});\n/** Both save and discard stop work, so each Account request must identify the observed allocation. */\nconst AccountSandboxRunnerStopRequestSchema = z.union([z.object({ environmentGeneration: z.number().int().nonnegative().safe() }).strict(), z.object({\n\tdiscardUnsavedChanges: z.literal(true),\n\tenvironmentGeneration: z.number().int().positive().safe()\n}).strict()]);\n/**\n* Native-sandbox/tool readiness as the Runner reported it after authentication. `runnerVersion`\n* is the pinned Runner build the image reports from its identity document; the Server requires\n* the exact configured version before an environment may become ready.\n*/\nconst RunnerReadinessSchema = z.object({\n\tsandboxName: z.string().min(1).max(128),\n\trootfs: z.string().min(1).max(512),\n\tnodeVersion: z.string().min(1).max(64),\n\tpiVersion: z.string().min(1).max(64),\n\trunnerVersion: z.string().min(1).max(64),\n\treportedAt: z.string().datetime()\n}).strict();\n/**\n* Runner state as an Account may read it. `runnerReady` is true only after an authenticated\n* Runner reported native sandbox/tool readiness for the CURRENT environment generation — never\n* from cloud provider readiness alone.\n*/\nconst AccountSandboxRunnerStatusResponseSchema = z.object({\n\tsandboxId: UuidSchema,\n\tsessionId: UuidSchema,\n\tlifecycle: SandboxLifecycleSchema,\n\tenvironmentGeneration: z.number().int().nonnegative(),\n\tcurrentResourceName: ResourceNameSchema.nullable(),\n\tcurrentResourceUid: z.string().min(1).max(128).nullable(),\n\tcurrentOperationName: ResourceNameSchema.nullable(),\n\trunnerConnected: z.boolean(),\n\trunnerReady: z.boolean(),\n\trunnerReadiness: RunnerReadinessSchema.nullable(),\n\tlastErrorCode: z.string().min(1).max(128).nullable(),\n\tlastErrorAt: z.string().datetime().nullable(),\n\tupdatedAt: z.string().datetime()\n}).strict();\nconst AccountSandboxRunnerAcceptanceResponseSchema = z.object({\n\trequestId: z.string().min(1).max(256),\n\tsandboxId: UuidSchema,\n\tenvironmentGeneration: z.number().int().nonnegative(),\n\tmode: RunnerAcceptanceModeSchema,\n\toutcome: z.enum([\n\t\t\"passed\",\n\t\t\"failed\",\n\t\t\"cancelled\"\n\t]),\n\treport: RunnerAcceptanceReportWireSchema.optional(),\n\tfailure: z.object({\n\t\tcode: z.string().min(1).max(128),\n\t\tmessage: z.string().min(1).max(2048)\n\t}).strict().optional()\n}).strict();\nconst FrameBase = { requestId: RequestIdSchema.optional() };\n/** First frame, Runner -> Server. The token is a Server-minted bootstrap bearer credential. */\nconst RunnerAuthFrameSchema = z.object({\n\t...FrameBase,\n\ttype: z.literal(\"auth\"),\n\ttoken: z.string().min(1).max(8192),\n\t/**\n\t* E4: an E4 Runner opts in to Cloud delivery frames. Additive and optional; an older Server\n\t* with a strict schema rejects the extra field, so deployment order is Server-first with a\n\t* pinned E4 Runner image (handoff contract). Legacy E3 Runners never set it.\n\t*/\n\tcloudDeliveryVersion: z.literal(1).optional(),\n\tworkspaceVersion: z.literal(1).optional(),\n\t/**\n\t* E8: opt in to Cloud Session collaboration. Only sent by a Runner build that can journal and\n\t* execute `session:message:*` frames; the Server echoes it in the welcome before any session\n\t* frame, proof-bearing open result, or Session-collaboration capability is used.\n\t*/\n\tsessionCollaborationVersion: z.literal(1).optional(),\n\t/** Opt in to renewal-only replies for an expired token of a still-live allocation. */\n\trenewExpired: z.literal(true).optional(),\n\t/**\n\t* E7: physical control credential, separate audience from the Session bootstrap bearer. It is\n\t* the only credential allowed to resolve a Runner to a DIFFERENT current holder after a\n\t* transfer; the Session token is never used for cross-assignment authority.\n\t*/\n\tcontrolToken: z.string().min(1).max(8192).optional(),\n\t/** E7: opt in to physical-instance reuse negotiation. Only sent with a control token. */\n\treuseVersion: z.literal(1).optional()\n}).strict();\nconst RunnerHeartbeatFrameSchema = z.object({\n\t...FrameBase,\n\ttype: z.literal(\"heartbeat\")\n}).strict();\n/** Runner -> Server after native sandbox + tool readiness was verified inside the Instance. */\nconst RunnerReadyFrameSchema = z.object({\n\t...FrameBase,\n\ttype: z.literal(\"runner:ready\"),\n\treadiness: RunnerReadinessSchema.omit({ reportedAt: true }),\n\tworkspaceRestored: z.literal(true).optional()\n}).strict();\nconst RunnerAcceptanceResultFrameSchema = z.object({\n\t...FrameBase,\n\ttype: z.literal(\"acceptance:result\"),\n\trequestId: RequestIdSchema,\n\toutcome: z.enum([\n\t\t\"passed\",\n\t\t\"failed\",\n\t\t\"cancelled\"\n\t]),\n\treport: RunnerAcceptanceReportWireSchema.optional(),\n\tfailure: z.object({\n\t\tcode: z.string().min(1).max(128),\n\t\tmessage: z.string().min(1).max(2048)\n\t}).strict().optional()\n}).strict();\n/** Execution-scoped, short-lived model call permission minted by the Server. */\nconst RunnerCloudModelGrantSchema = z.object({\n\t/** Server model-proxy base URL (fixed deployment origin + path; never an arbitrary URL). */\n\tbaseUrl: z.string().url().max(1024),\n\t/** Allowlisted model id the token is bound to; the proxy rejects any other model. */\n\tmodel: RuntimeModelSchema,\n\t/**\n\t* Opaque execution-scoped bearer token; never a platform master key. The 4096-byte budget is\n\t* the actual proxy bearer budget: a valid HS256 JWT with a 128-byte model id plus the wired\n\t* claims is well under 1 KiB, and the token must always fit the control frame.\n\t*/\n\ttoken: z.string().min(32).max(4096),\n\texpiresAt: z.string().datetime(),\n\t/**\n\t* The working context window the Server selected once from the Router-verified native window;\n\t* exactly one of the two Cloud tiers. The Runner writes it to the disposable Pi models.json\n\t* verbatim — no model-name guesses anywhere downstream.\n\t*/\n\tcontextWindow: z.union([z.literal(CLOUD_MODEL_CONTEXT_WINDOW_STANDARD), z.literal(CLOUD_MODEL_CONTEXT_WINDOW_EXTENDED)]),\n\t/**\n\t* The issued output budget: `min(CLOUD_MODEL_OUTPUT_TOKEN_LIMIT, Router-verified native\n\t* limit)`. The Runner writes it to Pi verbatim and the proxy clamps every request to it.\n\t*/\n\tmaxTokens: z.number().int().min(1).max(CLOUD_MODEL_OUTPUT_TOKEN_LIMIT)\n}).strict();\n/** Credential-relay grant forwarded only in one disposable worker stdin document. */\nconst RunnerCloudMcpGatewaySchema = z.object({\n\turl: z.string().url().max(1024),\n\ttoken: z.string().startsWith(\"otmg_\").max(4096)\n}).strict();\n/**\n* Web tools facts for one Cloud worker: the nonsecret per-execution socket descriptor inside the\n* Sandbox and the fixed packaged Pi extension path. Both are absolute in-Sandbox paths; no bearer,\n* Router key, or provider key is ever carried here — the trusted Runner parent holds the execution\n* bearer and the extension speaks only to its private socket.\n*/\nconst RunnerCloudWebToolsSchema = z.object({\n\textensionPath: z.string().startsWith(\"/\").max(512),\n\tsocketPath: z.string().startsWith(\"/\").max(200)\n}).strict();\nconst RunnerCloudDeliveryRunFrameSchema = z.object({\n\ttype: z.literal(\"delivery:run\"),\n\trequestId: RequestIdSchema,\n\t/** The exact persisted dispatch payload; `requestId` mirrors `delivery.requestId`. */\n\tdelivery: DirectImMessageDeliveryRequestSchema\n}).strict().superRefine((value, context) => {\n\tif (value.delivery.requestId !== value.requestId) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"requestId\"],\n\t\tmessage: \"Delivery request id mismatch\"\n\t});\n\tif (runtimeUtf8Length(JSON.stringify(value)) > 262144) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"delivery\"],\n\t\tmessage: \"The delivery frame exceeds the channel budget\"\n\t});\n});\nconst RunnerCloudDeliveryVerifiedFrameSchema = z.object({\n\ttype: z.literal(\"delivery:verified\"),\n\trequestId: RequestIdSchema,\n\t/**\n\t* \"verified\": durable custody is persisted and execution may start. \"rejected\": the Server\n\t* refused custody (stale generation/scope conflict); the Runner must not start and must\n\t* settle its journal entry without executing.\n\t*/\n\tstatus: z.enum([\"verified\", \"rejected\"]),\n\tcode: z.string().min(1).max(128).optional(),\n\t/** Present only on \"verified\" when the deployment model proxy is enabled. */\n\tmodel: RunnerCloudModelGrantSchema.optional()\n}).strict();\nconst RunnerCloudDeliveryCancelFrameSchema = z.object({\n\ttype: z.literal(\"delivery:cancel\"),\n\trequestId: RequestIdSchema.optional(),\n\tdeliveryId: RuntimeOpaqueIdSchema\n}).strict();\n/**\n* Server recovery query for one accepted delivery: the Runner answers from its durable journal\n* (never from memory alone). \"received\"/\"started\" entries are resumed/settled exactly once; a\n* missing entry means the allocation's writable state was lost and the turn outcome is unknown.\n*/\nconst RunnerCloudDeliveryQueryFrameSchema = z.object({\n\ttype: z.literal(\"delivery:query\"),\n\trequestId: RequestIdSchema,\n\tdeliveryId: RuntimeOpaqueIdSchema,\n\tturnId: RuntimeOpaqueIdSchema\n}).strict();\nconst RunnerCloudDeliveryQueryResultFrameSchema = z.object({\n\ttype: z.literal(\"delivery:query:result\"),\n\trequestId: RequestIdSchema,\n\tdeliveryId: RuntimeOpaqueIdSchema,\n\tturnId: RuntimeOpaqueIdSchema,\n\tphase: z.enum([\n\t\t\"none\",\n\t\t\"received\",\n\t\t\"started\",\n\t\t\"reported\"\n\t])\n}).strict();\nconst RunnerCloudDeliveryReportAckFrameSchema = z.object({\n\ttype: z.literal(\"delivery:report:ack\"),\n\trequestId: RequestIdSchema,\n\tturnId: RuntimeOpaqueIdSchema,\n\tstatus: z.enum([\n\t\t\"recorded\",\n\t\t\"already_recorded\",\n\t\t\"conflict\",\n\t\t\"stale_generation\"\n\t]),\n\tresultHash: z.string().regex(/^[a-f0-9]{64}$/)\n}).strict();\nconst RunnerCloudDeliveryReceivedFrameSchema = z.object({\n\ttype: z.literal(\"delivery:received\"),\n\trequestId: RequestIdSchema,\n\tdeliveryId: RuntimeOpaqueIdSchema,\n\t/** Runner-allocated Turn id; stable across receipt retransmissions of the same dispatch. */\n\tturnId: RuntimeOpaqueIdSchema\n}).strict();\n/** Server -> Runner dispatch of one authorized SessionMessage. `requestId` mirrors `message.requestId`. */\nconst RunnerCloudSessionMessageRunFrameSchema = z.object({\n\ttype: z.literal(\"session:message:run\"),\n\trequestId: RequestIdSchema,\n\tmessage: SessionMessageDeliveryRequestSchema,\n\t/**\n\t* The target Session's actual role. The Server derives it from the target Session row, never\n\t* from instruction prose or from missing credentials.\n\t*/\n\tsessionKind: z.enum([\"internal\", \"visible\"]),\n\t/**\n\t* The nonsecret bridge-derived IM outbox context. Present exactly for a visible target (the\n\t* Server requires an active binding), absent for an internal child so no IM material can ever\n\t* be fabricated for it.\n\t*/\n\toutboxContext: RuntimeImOutboxContextSchema.optional()\n}).strict().superRefine((value, context) => {\n\tif (value.message.requestId !== value.requestId) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"requestId\"],\n\t\tmessage: \"Session message request id mismatch\"\n\t});\n\tif (!RUNNER_SESSION_MESSAGE_CONTEXT_REFINE(value)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"outboxContext\"],\n\t\tmessage: \"A visible Session message requires outbox context and an internal one forbids it\"\n\t});\n\tif (runtimeUtf8Length(JSON.stringify(value)) > 262144) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"message\"],\n\t\tmessage: \"The Session message frame exceeds the channel budget\"\n\t});\n});\n/**\n* Runner -> Server receipt for one Session message dispatch. `accepted` means the message is\n* durably journaled (fsynced) under the exact allocation scope — the custody boundary the\n* Server's `accepted` outcome requires. `phase` is the Runner's journal phase for the entry: a\n* reconnect re-announcement of an already-started Turn says `started` so the Server refreshes its\n* liveness picture without minting a second permission. Rejected receipts carry no custody.\n*/\nconst RunnerCloudSessionMessageReceivedFrameSchema = z.discriminatedUnion(\"status\", [z.object({\n\ttype: z.literal(\"session:message:received\"),\n\trequestId: RequestIdSchema,\n\tmessageId: z.string().uuid(),\n\t/** Runner-allocated Turn id; stable across receipt retransmissions of the same message. */\n\tturnId: RuntimeOpaqueIdSchema,\n\tstatus: z.literal(\"accepted\"),\n\tphase: z.enum([\"received\", \"started\"])\n}).strict(), z.object({\n\ttype: z.literal(\"session:message:received\"),\n\trequestId: RequestIdSchema,\n\tmessageId: z.string().uuid(),\n\tstatus: z.literal(\"rejected\"),\n\treason: z.enum([\n\t\t\"client_busy\",\n\t\t\"input_conflict\",\n\t\t\"target_mismatch\"\n\t])\n}).strict()]);\n/**\n* Server -> Runner execution permission for one accepted Session message. Same semantics as\n* `delivery:verified`, keyed by the dispatch/journal request id: `verified` carries the\n* execution-scoped model grant; `rejected` retires a `received` journal entry that never started.\n*/\nconst RunnerCloudSessionMessageVerifiedFrameSchema = z.object({\n\ttype: z.literal(\"session:message:verified\"),\n\trequestId: RequestIdSchema,\n\tstatus: z.enum([\"verified\", \"rejected\"]),\n\tcode: z.string().min(1).max(128).optional(),\n\tmodel: RunnerCloudModelGrantSchema.optional()\n}).strict();\n/**\n* Server -> Runner cancellation of one journaled Session message (explicit stop). Best-effort\n* like the IM cancel frame: the durable journal entry stays authoritative until the Runner\n* retires it, and the Server never re-dispatches a cancelled message.\n*/\nconst RunnerCloudSessionMessageCancelFrameSchema = z.object({\n\ttype: z.literal(\"session:message:cancel\"),\n\trequestId: RequestIdSchema,\n\tmessageId: z.string().uuid()\n}).strict();\n/**\n* Runner -> Server terminal settlement signal for one journaled Session message. Best-effort\n* execution evidence (drives the Server's idle-reclaim busy picture and activity clock); it is\n* NOT a durable Turn Report — Session messages have no Server-side Turn columns by design.\n*/\nconst RunnerCloudSessionMessageSettledFrameSchema = z.object({\n\ttype: z.literal(\"session:message:settled\"),\n\t/** The dispatch/journal request id, for correlation and logs. */\n\trequestId: RequestIdSchema,\n\tmessageId: z.string().uuid(),\n\tturnId: RuntimeOpaqueIdSchema,\n\toutcome: z.enum([\n\t\t\"completed\",\n\t\t\"failed\",\n\t\t\"cancelled\",\n\t\t\"unknown\"\n\t])\n}).strict();\n/**\n* Server -> Runner terminal acknowledgement. `recorded` means the exact outcome was durably\n* committed now; `already_recorded` means an identical terminal result was already committed.\n* The Runner holds its immutable terminal result until this ack and replays it on reconnect; a\n* missing or uncommittable record never receives a success ack.\n*/\nconst RunnerCloudSessionMessageSettledAckFrameSchema = z.object({\n\ttype: z.literal(\"session:message:settled:ack\"),\n\trequestId: RequestIdSchema,\n\tmessageId: z.string().uuid(),\n\tturnId: RuntimeOpaqueIdSchema,\n\tstatus: z.enum([\"recorded\", \"already_recorded\"])\n}).strict();\nconst RunnerCloudDeliveryReportFrameSchema = z.object({\n\ttype: z.literal(\"delivery:report\"),\n\trequestId: RequestIdSchema,\n\treport: TurnReportRequestSchema\n}).strict();\n/** Runner -> Server tunnel of #633 credential control frames. */\nconst RunnerCredentialTunnelFrameSchema = z.object({\n\ttype: z.literal(\"credential:frame\"),\n\tframe: RuntimeCredentialClientFrameSchema\n}).strict();\n/** Server -> Runner tunnel of #633 credential control results. */\nconst RunnerCredentialTunnelResultFrameSchema = z.object({\n\ttype: z.literal(\"credential:frame\"),\n\tframe: RuntimeCredentialServerFrameSchema\n}).strict();\n/** Bounded stdin document the trusted Runner hands to the in-sandbox Turn worker. */\nconst RUNNER_CLOUD_TURN_WORKER_STDIN_MAX_BYTES = 262144;\nconst RunnerCloudTurnWorkerRequestSchema = z.object({\n\tkind: z.literal(\"turn\"),\n\t/** The exact delivery the Server dispatched (and persisted) for this Sandbox's Session. */\n\tdelivery: DirectImMessageDeliveryRequestSchema,\n\t/** Execution-scoped model grant minted at the verified boundary. */\n\tmodel: RunnerCloudModelGrantSchema,\n\tmcpGateway: RunnerCloudMcpGatewaySchema.optional(),\n\twebTools: RunnerCloudWebToolsSchema.optional(),\n\t/** In-sandbox absolute path of the per-turn public material directory (proxy manifest). */\n\texecutionDir: z.string().min(1).max(512),\n\t/**\n\t* Optional allocation-stable in-sandbox directory for Pi conversation continuity across the\n\t* turns of one Agent Session. When absent the worker uses its own default location inside the\n\t* disposable Sandbox. The trusted Runner only ever supplies an in-sandbox path.\n\t*/\n\tpiSessionDirectory: z.string().min(1).max(512).optional(),\n\t/**\n\t* E8 Session collaboration material for the Session's own CLI: the current Session-CLI proof\n\t* plus the Server URL the in-sandbox CLI must call. Present exactly when the Server minted a\n\t* proof at the verified boundary; stdin-only, never journaled or logged by the Runner.\n\t*/\n\tsessionCollaboration: z.object({\n\t\tproof: SessionCliProofGrantSchema,\n\t\tserverUrl: z.string().url().max(1024)\n\t}).strict().optional()\n}).strict().superRefine((value, context) => {\n\tif (runtimeUtf8Length(JSON.stringify(value)) > 262144) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"The Turn worker document exceeds its stdin budget\"\n\t});\n});\n/**\n* E8: the in-sandbox worker document for one accepted Session collaboration message. Same\n* boundary as the IM Turn document — the exact dispatched message, the execution-scoped grant,\n* and the per-execution public material directory — but carries the genuine SessionMessage\n* contract instead of any IM-shaped input.\n*/\nconst RunnerCloudSessionWorkerRequestSchema = z.object({\n\tkind: z.literal(\"session-message\"),\n\t/** The exact Session message the Server dispatched and the Runner journaled. */\n\tmessage: SessionMessageDeliveryRequestSchema,\n\t/** Execution-scoped model grant minted at the verified boundary. */\n\tmodel: RunnerCloudModelGrantSchema,\n\tmcpGateway: RunnerCloudMcpGatewaySchema.optional(),\n\twebTools: RunnerCloudWebToolsSchema.optional(),\n\t/** In-sandbox absolute path of the per-turn public material directory (proxy manifest). */\n\texecutionDir: z.string().min(1).max(512),\n\t/** Allocation-stable in-sandbox directory for Pi conversation continuity. */\n\tpiSessionDirectory: z.string().min(1).max(512).optional(),\n\t/**\n\t* The target Session's actual role, carried from the journaled run frame. `buildSessionMessageInput`\n\t* selects its visible/internal instruction mode from this value alone.\n\t*/\n\tsessionKind: z.enum([\"internal\", \"visible\"]),\n\t/**\n\t* The one absolute execution deadline the parent anchored when the Turn left its queue (never\n\t* at dispatch, so legitimate queue wait is not charged). The worker's own timeout and the\n\t* parent's exec backstop both derive from it, so a slow bridge/startup can never turn a real\n\t* `turn_timeout` into an `unknown`. Absent only from an older parent: the worker falls back\n\t* to the relative runtime budget.\n\t*/\n\tdeadlineAt: z.string().datetime({ offset: true }).optional(),\n\t/** Nonsecret outbox context, present exactly for a visible target. */\n\toutboxContext: RuntimeImOutboxContextSchema.optional(),\n\t/** E8 Session-CLI material for the target Session; stdin-only, never journaled or logged. */\n\tsessionCollaboration: z.object({\n\t\tproof: SessionCliProofGrantSchema,\n\t\tserverUrl: z.string().url().max(1024)\n\t}).strict().optional()\n}).strict().superRefine((value, context) => {\n\tif (!RUNNER_SESSION_MESSAGE_CONTEXT_REFINE(value)) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"outboxContext\"],\n\t\tmessage: \"A visible Session worker document requires outbox context and an internal one forbids it\"\n\t});\n\tif (runtimeUtf8Length(JSON.stringify(value)) > 262144) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"The Session worker document exceeds its stdin budget\"\n\t});\n});\n/** The backward-compatible in-sandbox worker document union: existing `turn` documents are unchanged. */\nconst RunnerCloudWorkerRequestSchema = z.discriminatedUnion(\"kind\", [RunnerCloudTurnWorkerRequestSchema, RunnerCloudSessionWorkerRequestSchema]);\n/** Serialize a Turn worker document, enforcing the stdin budget before any write. */\nfunction serializeRunnerCloudTurnWorkerStdin(input) {\n\tconst serialized = JSON.stringify({\n\t\tkind: \"turn\",\n\t\t...input\n\t});\n\tif (runtimeUtf8Length(serialized) > 262144) throw new Error(\"The Turn worker document exceeds its stdin budget\");\n\treturn serialized;\n}\n/** Serialize a Session-message worker document, enforcing the stdin budget before any write. */\nfunction serializeRunnerCloudSessionWorkerStdin(input) {\n\tconst serialized = JSON.stringify({\n\t\tkind: \"session-message\",\n\t\t...input\n\t});\n\tif (runtimeUtf8Length(serialized) > 262144) throw new Error(\"The Session worker document exceeds its stdin budget\");\n\treturn serialized;\n}\nconst RunnerClientFrameSchema = z.discriminatedUnion(\"type\", [\n\tRunnerAuthFrameSchema,\n\tRunnerHeartbeatFrameSchema,\n\tRunnerReadyFrameSchema,\n\tRunnerAcceptanceResultFrameSchema,\n\tRunnerCloudDeliveryReceivedFrameSchema,\n\tRunnerCloudDeliveryReportFrameSchema,\n\tRunnerCloudDeliveryQueryResultFrameSchema,\n\tRunnerCloudSessionMessageReceivedFrameSchema,\n\tRunnerCloudSessionMessageSettledFrameSchema,\n\tRunnerCredentialTunnelFrameSchema,\n\tRunnerWorkspaceSealResultFrameSchema\n]);\nconst RunnerWelcomeFrameSchema = z.object({\n\ttype: z.literal(\"server:welcome\"),\n\tprotocolVersion: z.literal(1),\n\tsandboxId: UuidSchema,\n\tsessionId: UuidSchema,\n\tenvironmentGeneration: z.number().int().nonnegative(),\n\tresourceName: ResourceNameSchema,\n\t/**\n\t* E4 capability echo. Present ONLY for a connection that requested\n\t* `cloudDeliveryVersion: 1` and whose Cloud allocation is enabled; the Client must not run\n\t* Cloud journal reconciliation or Cloud frame handlers without it.\n\t*/\n\tcloudDeliveryVersion: z.literal(1).optional(),\n\t/**\n\t* E4: verified Cloud UID of the CURRENT allocation, echoed by the Runner inside credential\n\t* execution-open sandbox facts. Required when `cloudDeliveryVersion` is present; a\n\t* Cloud-capable welcome with a null UID must be retried transiently until the UID is tracked\n\t* (the attach never publishes a Cloud welcome without it).\n\t*/\n\tresourceUid: z.string().min(1).max(128).nullable().optional(),\n\tworkspaceVersion: z.literal(1).optional(),\n\t/** E7: echo of the physical-reuse capability for a control-authenticated Runner. */\n\treuseVersion: z.literal(1).optional(),\n\t/** E8: echo of the Session-collaboration capability for a requesting, fenced connection. */\n\tsessionCollaborationVersion: z.literal(1).optional(),\n\theartbeatIntervalMs: z.number().int().positive(),\n\theartbeatTimeoutMs: z.number().int().positive()\n}).strict();\nconst RunnerAuthResultFrameSchema = z.object({\n\ttype: z.literal(\"auth:result\"),\n\trequestId: RequestIdSchema.optional(),\n\tok: z.boolean()\n}).strict();\nconst RunnerAcceptanceRunFrameSchema = z.object({\n\ttype: z.literal(\"acceptance:run\"),\n\trequestId: RequestIdSchema,\n\tmode: RunnerAcceptanceModeSchema,\n\t/** Absolute wall-clock deadline (Unix ms); the Runner cancels the run once it passes. */\n\tdeadlineAtMs: z.number().int().positive(),\n\tpiConfig: RunnerPiConfigInputSchema.optional()\n}).strict().superRefine((value, context) => {\n\tcheckRunnerAcceptanceWireBytes(value, context, JSON.stringify(value));\n});\nconst RunnerAcceptanceCancelFrameSchema = z.object({\n\ttype: z.literal(\"acceptance:cancel\"),\n\trequestId: RequestIdSchema\n}).strict();\nconst RunnerServerErrorFrameSchema = z.object({\n\ttype: z.literal(\"error\"),\n\tcode: z.string().min(1).max(128),\n\tmessage: z.string().min(1).max(2048)\n}).strict();\n/**\n* Liveness acknowledgement. The Server sends this in response to every Runner heartbeat and on a\n* cadence while the connection is healthy, so an idle but healthy Runner never mistakes silence\n* for a lost control channel. Carries no credential or state.\n*/\nconst RunnerServerHeartbeatFrameSchema = z.object({ type: z.literal(\"server:heartbeat\") }).strict();\n/**\n* Refreshed, same-scope bootstrap credential. Sent on welcome and at half the token TTL while the\n* authenticated connection stays current; the Runner keeps only the latest value in memory and\n* uses it for the next reconnect. Never sent to a stale or detached connection.\n*/\nconst RunnerServerCredentialFrameSchema = z.object({\n\ttype: z.literal(\"server:credential\"),\n\ttoken: z.string().min(1).max(8192),\n\t/** E7: refreshed physical control credential for the same immutable instance identity. */\n\tcontrolToken: z.string().min(1).max(8192).optional()\n}).strict();\nconst RunnerServerFrameSchema = z.discriminatedUnion(\"type\", [\n\tRunnerWelcomeFrameSchema,\n\tRunnerAuthResultFrameSchema,\n\tz.object({\n\t\ttype: z.literal(\"auth:renewed\"),\n\t\ttoken: z.string().min(1).max(8192).optional(),\n\t\t/** E7: a fresh physical control credential when only that credential could be renewed. */\n\t\tcontrolToken: z.string().min(1).max(8192).optional()\n\t}).strict().refine((frame) => frame.token !== void 0 || frame.controlToken !== void 0, { message: \"auth:renewed must carry at least one refreshed credential\" }),\n\tRunnerAcceptanceRunFrameSchema,\n\tRunnerAcceptanceCancelFrameSchema,\n\tRunnerServerHeartbeatFrameSchema,\n\tRunnerServerCredentialFrameSchema,\n\tRunnerServerErrorFrameSchema,\n\tRunnerCloudDeliveryRunFrameSchema,\n\tRunnerCloudDeliveryVerifiedFrameSchema,\n\tRunnerCloudDeliveryCancelFrameSchema,\n\tRunnerCloudDeliveryQueryFrameSchema,\n\tRunnerCloudDeliveryReportAckFrameSchema,\n\tRunnerCloudSessionMessageRunFrameSchema,\n\tRunnerCloudSessionMessageVerifiedFrameSchema,\n\tRunnerCloudSessionMessageCancelFrameSchema,\n\tRunnerCloudSessionMessageSettledAckFrameSchema,\n\tRunnerCredentialTunnelResultFrameSchema,\n\tRunnerWorkspaceSealFrameSchema\n]);\n/** WebSocket close codes used by the Runner control channel (private-use range). */\nconst RUNNER_WS_CLOSE = {\n\tauthFailed: 4401,\n\tprotocolError: 4400,\n\tstaleScope: 4409,\n\treplaced: 4412,\n\t/** A live, heartbeating connection already owns this scope; the newcomer is rejected. */\n\tduplicate: 4413,\n\tshuttingDown: 1001\n};\n//#endregion\n//#region src/structured-errors.ts\n/** Maximum UTF-8 bytes allowed for a structured diagnostic message. */\nconst STRUCTURED_ERROR_MESSAGE_MAX_BYTES = 2048;\n/** Maximum UTF-8 bytes allowed for a diagnostic request identifier. */\nconst STRUCTURED_ERROR_REQUEST_ID_MAX_BYTES = 256;\n/** Maximum number of nested causes retained by the redaction and serialization helpers. */\nconst STRUCTURED_ERROR_MAX_CAUSE_DEPTH = 8;\n/** Maximum UTF-8 bytes emitted by {@link boundedSerialize}. */\nconst BOUNDED_DIAGNOSTIC_SERIALIZATION_BYTES = 16384;\n/** Maximum UTF-8 bytes allowed for each string value crossing a log boundary. */\nconst STRUCTURED_ERROR_LOG_FIELD_MAX_BYTES = 4096;\nconst STRUCTURED_ERROR_SERIALIZATION_MAX_DEPTH = 8;\nconst STRUCTURED_ERROR_SERIALIZATION_MAX_KEYS = 64;\nconst STRUCTURED_ERROR_SERIALIZATION_MAX_ARRAY_ITEMS = 32;\nconst StructuredErrorCodeSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9_.:-]{0,119}$/);\n/** The stable high-level class used for operational routing and dashboards. */\nconst StructuredErrorCategorySchema = z.enum([\n\t\"validation\",\n\t\"auth\",\n\t\"authorization\",\n\t\"unavailable\",\n\t\"timeout\",\n\t\"internal\",\n\t\"conflict\",\n\t\"not_found\",\n\t\"rate_limit\",\n\t\"protocol\",\n\t\"configuration\",\n\t\"cancelled\",\n\t\"dependency\"\n]);\n/** The safe retry policy for a failure. Retries must still respect operation idempotency. */\nconst ErrorRetryabilitySchema = z.enum([\n\t\"never\",\n\t\"immediate\",\n\t\"backoff\",\n\t\"after_auth\"\n]);\n/** The lifecycle boundary at which an error was observed. */\nconst StructuredErrorPhaseSchema = z.enum([\n\t\"validation\",\n\t\"authentication\",\n\t\"authorization\",\n\t\"configuration\",\n\t\"startup\",\n\t\"request\",\n\t\"transport\",\n\t\"provider\",\n\t\"persistence\",\n\t\"dispatch\",\n\t\"socket\",\n\t\"scheduler\",\n\t\"worker\",\n\t\"serialization\",\n\t\"shutdown\",\n\t\"unknown\"\n]);\nconst StructuredErrorMessageSchema = z.string().min(1).max(STRUCTURED_ERROR_MESSAGE_MAX_BYTES);\n/** A recursively nested, deliberately small representation of a root cause. */\nconst StructuredErrorCauseSchema = z.lazy(() => z.object({\n\tcode: StructuredErrorCodeSchema.optional(),\n\tcategory: StructuredErrorCategorySchema.optional(),\n\tretryability: ErrorRetryabilitySchema.optional(),\n\tphase: StructuredErrorPhaseSchema.optional(),\n\tmessage: StructuredErrorMessageSchema,\n\tcause: StructuredErrorCauseSchema.optional()\n}).strict());\nconst StructuredErrorSchema = z.object({\n\tcode: StructuredErrorCodeSchema,\n\tcategory: StructuredErrorCategorySchema,\n\tretryability: ErrorRetryabilitySchema,\n\tphase: StructuredErrorPhaseSchema,\n\trequestId: z.string().min(1).max(256).optional(),\n\tmessage: StructuredErrorMessageSchema,\n\tcause: StructuredErrorCauseSchema.optional()\n}).strict();\n/** A transport-neutral event envelope for logs, counters, and traces. */\nconst DiagnosticEventSchema = z.object({\n\ttype: z.literal(\"diagnostic.error\"),\n\toccurredAt: z.string().datetime({ offset: true }),\n\terror: StructuredErrorSchema\n}).strict();\nconst RetryabilitySchema = ErrorRetryabilitySchema;\nconst ErrorPhaseSchema = StructuredErrorPhaseSchema;\nconst REDACTED = \"[REDACTED]\";\nconst CIRCULAR = \"[CIRCULAR]\";\nconst TRUNCATED = \"[TRUNCATED]\";\nconst UNSERIALIZABLE = \"[UNSERIALIZABLE]\";\nconst SENSITIVE_KEY_PARTS = [\n\t\"authorization\",\n\t\"cookie\",\n\t\"token\",\n\t\"secret\",\n\t\"credential\",\n\t\"password\",\n\t\"passwd\",\n\t\"api_key\",\n\t\"apikey\",\n\t\"bearer_key\",\n\t\"access_key\",\n\t\"refresh_key\",\n\t\"private_key\",\n\t\"request_body\",\n\t\"response_body\",\n\t\"body\",\n\t\"payload\",\n\t\"prompt\",\n\t\"tool_input\",\n\t\"tool_output\"\n];\n/**\n* Keys that read as sensitive but are known-safe *structural* names.\n*\n* Redaction runs over whatever a command returns, and a substring match on \"authorization\" or\n* \"credential\" would blank a whole subtree whose *name* merely resembles a secret. MCP's\n* authorization summary is exactly that: a field called `authorization` carrying `hasCredential`,\n* `status`, and an expiry — no secret anywhere in it. Left unlisted, the CLI printed `authKind none`\n* for a stored Bearer key, because the object it formatted had been replaced by `[REDACTED]`.\n*\n* These are exact key names, not substrings: the exemption must not reopen the door for\n* `authorizationHeader`, `credentialCiphertext`, or anything else that could actually hold a value.\n*/\nconst SAFE_STRUCTURAL_KEYS = /* @__PURE__ */ new Set([\n\t\"authorization\",\n\t\"authorization_server\",\n\t\"access_token_expires_at\",\n\t\"has_credential\"\n]);\n/**\n* The one exempted name that also spells a real credential carrier.\n*\n* `authorization_server`, `access_token_expires_at`, and `has_credential` are OpenTag's own field\n* names — a URL, a timestamp, and a flag — so they are safe however they are spelled. `authorization`\n* is not: the very same key is an HTTP header in every log line and error object containing one, and\n* this feature can send a key verbatim (`authScheme: \"\"`), which is exactly the shape that leaks.\n*/\nconst SAFE_STRUCTURAL_OBJECT_ONLY_KEYS = /* @__PURE__ */ new Set([\"authorization\"]);\n/**\n* The MCP authorization summary's own field names.\n*\n* An exemption for `authorization` cannot rest on the value merely being a container: a secret rides\n* along just as easily one level down (`{ authorization: { value: \"sk-live\" } }`, or an array, both\n* of which undici's raw headers can produce). Requiring the object to carry the summary's own fields\n* is what distinguishes the DTO from a wrapper, and it is checked before the value is descended into\n* so a summary's scalar fields keep their ordinary treatment.\n*/\nconst AUTHORIZATION_SUMMARY_FIELDS = [\n\t\"kind\",\n\t\"status\",\n\t\"has_credential\"\n];\n/**\n* Whether an exempted key's value is the structural summary the exemption exists for.\n*\n* Every field, not any one of them. `.some()` accepted an object carrying a single summary field, and\n* nested redaction is key-name-only, so `{authorization: {kind: \"bearer\", value: \"sk-live\"}}` kept its\n* secret — an object that merely mentions `kind` is not the DTO.\n*/\nfunction isAuthorizationSummary(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n\tconst keys = Object.keys(value).map((key) => normalizedKey(key));\n\treturn AUTHORIZATION_SUMMARY_FIELDS.every((field) => keys.includes(field));\n}\n/**\n* Whether a key carries a secret, given the value it carries.\n*\n* The value participates because a name alone cannot decide: `authorization` is a structural summary\n* in the MCP DTO and a raw credential in a header dump.\n*/\nfunction isSensitiveKey(key, value) {\n\tconst normalized = normalizedKey(key);\n\tif (SAFE_STRUCTURAL_KEYS.has(normalized)) {\n\t\tif (!SAFE_STRUCTURAL_OBJECT_ONLY_KEYS.has(normalized) || isAuthorizationSummary(value)) return false;\n\t}\n\treturn SENSITIVE_KEY_PARTS.some((part) => normalized.includes(part) || plainLowercaseKey(key).includes(part));\n}\nfunction plainLowercaseKey(key) {\n\treturn key.toLowerCase().replaceAll(\"-\", \"_\");\n}\nfunction normalizedKey(key) {\n\treturn key.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\").toLowerCase().replaceAll(\"-\", \"_\");\n}\nconst CREDENTIAL_HEADER_PATTERN = /\\b(?:authorization|proxy-authorization|cookie|set-cookie)[ \\t]*[\"']?[ \\t]*[:=][ \\t]*/giu;\nconst SERIALIZED_CREDENTIAL_FIELD_PATTERN = /\\\\+(?:[\"'])(?:authorization|proxy-authorization|cookie|set-cookie)\\\\+(?:[\"'])[ \\t]*[:=][ \\t]*/giu;\nconst SERIALIZED_SIBLING_FIELD_PATTERN = /^[ \\t]*\\\\+(?:[\"'])[A-Za-z0-9_.-]+\\\\+(?:[\"'])[ \\t]*:/u;\nfunction lineBreakStart(value, from) {\n\tconst carriageReturn = value.indexOf(\"\\r\", from);\n\tconst lineFeed = value.indexOf(\"\\n\", from);\n\tif (carriageReturn === -1) return lineFeed;\n\tif (lineFeed === -1) return carriageReturn;\n\treturn Math.min(carriageReturn, lineFeed);\n}\nfunction lineBreakEnd(value, start) {\n\tif (value[start] === \"\\r\" && value[start + 1] === \"\\n\") return start + 2;\n\treturn start + 1;\n}\nfunction headerNameColonAt(value, from) {\n\tlet cursor = from;\n\twhile (value[cursor] === \" \" || value[cursor] === \"\t\") cursor += 1;\n\treturn /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+[ \\t]*:/u.test(value.slice(cursor));\n}\nfunction lineStart(value, from) {\n\tconst carriageReturn = value.lastIndexOf(\"\\r\", from - 1);\n\tconst lineFeed = value.lastIndexOf(\"\\n\", from - 1);\n\treturn Math.max(carriageReturn, lineFeed) + 1;\n}\nfunction lineIndentation(value, from) {\n\tlet cursor = from;\n\twhile (value[cursor] === \" \" || value[cursor] === \"\t\") cursor += 1;\n\treturn cursor - from;\n}\nfunction listPrefixedHeaderOffset(value, from) {\n\tlet cursor = from;\n\tif (value[cursor] === \"-\" || value[cursor] === \"*\" || value[cursor] === \"+\") cursor += 1;\n\telse {\n\t\tconst numberStart = cursor;\n\t\twhile (/\\d/u.test(value[cursor] ?? \"\")) cursor += 1;\n\t\tif (cursor === numberStart || value[cursor] !== \".\" && value[cursor] !== \")\") return void 0;\n\t\tcursor += 1;\n\t}\n\tif (value[cursor] !== \" \" && value[cursor] !== \"\t\") return void 0;\n\twhile (value[cursor] === \" \" || value[cursor] === \"\t\") cursor += 1;\n\treturn cursor;\n}\nfunction isInlineCredentialPrefix(value, lineStartOffset, offset) {\n\tif (enclosingQuoteAt(value, offset) !== void 0) return true;\n\tlet cursor = offset - 1;\n\twhile (cursor >= lineStartOffset && (value[cursor] === \" \" || value[cursor] === \"\t\")) cursor -= 1;\n\treturn \"{[(,;=\".includes(value[cursor] ?? \"\");\n}\nfunction isLineAnchoredCredentialHeader(value, offset) {\n\tconst start = lineStart(value, offset);\n\tif (offset === start) return true;\n\tlet cursor = start;\n\twhile (value[cursor] === \" \" || value[cursor] === \"\t\") cursor += 1;\n\tif (cursor === offset) return headerNameColonAt(value, offset);\n\tif (listPrefixedHeaderOffset(value, cursor) === offset) return headerNameColonAt(value, offset);\n\treturn headerNameColonAt(value, offset) && !isInlineCredentialPrefix(value, start, offset);\n}\nfunction credentialHeaderValueEnd(value, from, headerIndentation) {\n\tlet cursor = from;\n\twhile (true) {\n\t\tconst breakStart = lineBreakStart(value, cursor);\n\t\tif (breakStart === -1) return value.length;\n\t\tconst breakEnd = lineBreakEnd(value, breakStart);\n\t\tif (lineIndentation(value, breakEnd) <= headerIndentation) return breakStart;\n\t\tcursor = breakEnd;\n\t}\n}\nfunction isCredentialQuote(character) {\n\treturn character === \"\\\"\" || character === \"'\";\n}\nfunction isApostrophe(value, position, character) {\n\treturn character === \"'\" && /[A-Za-z0-9]/u.test(value[position - 1] ?? \"\") && /[A-Za-z0-9]/u.test(value[position + 1] ?? \"\");\n}\nfunction advanceEnclosingQuote(value, position, quote, character) {\n\tif (character === \"\\r\" || character === \"\\n\") return void 0;\n\tif (quote === void 0) {\n\t\tif (!isCredentialQuote(character) || isApostrophe(value, position, character)) return void 0;\n\t\treturn character;\n\t}\n\treturn quote === character ? void 0 : quote;\n}\nfunction enclosingQuoteAt(value, position) {\n\tlet quote;\n\tfor (let cursor = 0; cursor < position; cursor += 1) {\n\t\tconst character = value[cursor] ?? \"\";\n\t\tif (character === \"\\\\\") {\n\t\t\tcursor += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tquote = advanceEnclosingQuote(value, cursor, quote, character);\n\t}\n\treturn quote;\n}\nfunction inlineQuotedCredentialValueEnd(value, from, quote) {\n\tfor (let cursor = from + 1; cursor < value.length; cursor += 1) {\n\t\tconst character = value[cursor];\n\t\tif (character === \"\\\\\") {\n\t\t\tcursor += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === quote) return cursor + 1;\n\t\tif (character === \"\\r\" || character === \"\\n\") return cursor;\n\t}\n\treturn value.length;\n}\nfunction enclosingQuotedCredentialValueEnd(value, from, quote) {\n\tfor (let cursor = from; cursor < value.length; cursor += 1) {\n\t\tconst character = value[cursor];\n\t\tif (character === \"\\\\\") {\n\t\t\tcursor += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === quote) return cursor;\n\t\tif (character === \"\\r\" || character === \"\\n\") return cursor;\n\t}\n\treturn value.length;\n}\nfunction inlineUnquotedCredentialValueEnd(value, from) {\n\tfor (let cursor = from; cursor < value.length; cursor += 1) if (\",;}\\\"'\\r\\n\".includes(value[cursor] ?? \"\")) return cursor;\n\treturn value.length;\n}\nfunction advanceStructuralScan(state, character, opener, closer) {\n\tif (state.quote !== void 0) {\n\t\tif (state.escaped) state.escaped = false;\n\t\telse if (character === \"\\\\\") state.escaped = true;\n\t\telse if (character === state.quote) state.quote = void 0;\n\t\treturn false;\n\t}\n\tif (isCredentialQuote(character)) state.quote = character;\n\telse if (character === opener) state.depth += 1;\n\telse if (character === closer) state.depth -= 1;\n\treturn state.depth === 0;\n}\nfunction structuralCredentialValueEnd(value, from) {\n\tconst opener = value[from];\n\tif (opener !== \"[\") return from;\n\tconst closer = \"]\";\n\tconst state = { depth: 0 };\n\tfor (let cursor = from; cursor < value.length; cursor += 1) if (advanceStructuralScan(state, value[cursor] ?? \"\", opener, closer)) return cursor + 1;\n\treturn value.length;\n}\nfunction inlineCredentialValueEnd(value, from, enclosingQuote) {\n\tconst openingQuote = value[from];\n\tif (isCredentialQuote(openingQuote)) return {\n\t\tend: inlineQuotedCredentialValueEnd(value, from, openingQuote),\n\t\treplacement: `${openingQuote}${REDACTED}${openingQuote}`\n\t};\n\tif (openingQuote === \"[\") return {\n\t\tend: structuralCredentialValueEnd(value, from),\n\t\treplacement: `\"${REDACTED}\"`\n\t};\n\tif (enclosingQuote !== void 0) return {\n\t\tend: enclosingQuotedCredentialValueEnd(value, from, enclosingQuote),\n\t\treplacement: REDACTED\n\t};\n\treturn {\n\t\tend: inlineUnquotedCredentialValueEnd(value, from),\n\t\treplacement: REDACTED\n\t};\n}\nfunction decodeSerializationEscape(value, position) {\n\tconst escapeCode = value[position + 1];\n\tif (escapeCode === void 0) return void 0;\n\tif (escapeCode === \"\\\"\" || escapeCode === \"\\\\\" || escapeCode === \"/\") return {\n\t\tnext: position + 2,\n\t\tvalue: escapeCode\n\t};\n\tconst shortValue = {\n\t\tb: \"\\b\",\n\t\tf: \"\\f\",\n\t\tn: \"\\n\",\n\t\tr: \"\\r\",\n\t\tt: \"\t\"\n\t}[escapeCode];\n\tif (shortValue !== void 0) return {\n\t\tnext: position + 2,\n\t\tvalue: shortValue\n\t};\n\tif (escapeCode !== \"u\") return void 0;\n\tconst hexadecimal = value.slice(position + 2, position + 6);\n\tif (!/^[0-9A-Fa-f]{4}$/u.test(hexadecimal)) return void 0;\n\treturn {\n\t\tnext: position + 6,\n\t\tvalue: String.fromCharCode(Number.parseInt(hexadecimal, 16))\n\t};\n}\nfunction decodeSerializationCharacter(value, position) {\n\tconst character = value[position];\n\tif (character === void 0) return void 0;\n\treturn character === \"\\\\\" ? decodeSerializationEscape(value, position) : {\n\t\tnext: position + 1,\n\t\tvalue: character\n\t};\n}\nfunction encodeSerializationCharacter(character) {\n\tif (character === \"\\\"\") return \"\\\\\\\"\";\n\tif (character === \"\\\\\") return \"\\\\\\\\\";\n\tif (character === \"\\b\") return \"\\\\b\";\n\tif (character === \"\\f\") return \"\\\\f\";\n\tif (character === \"\\n\") return \"\\\\n\";\n\tif (character === \"\\r\") return \"\\\\r\";\n\tif (character === \"\t\") return \"\\\\t\";\n\tif (character.charCodeAt(0) <= 31) return `\\\\u${character.charCodeAt(0).toString(16).padStart(4, \"0\")}`;\n\treturn character;\n}\nfunction encodeOneSerializationLayer(value) {\n\tlet output = \"\";\n\tfor (const character of value) output += encodeSerializationCharacter(character);\n\treturn output;\n}\nfunction serializedQuotedValueEnd(value, from, quote) {\n\tlet cursor = from;\n\tlet escaped = false;\n\twhile (cursor < value.length) {\n\t\tconst decodedCharacter = decodeSerializationCharacter(value, cursor);\n\t\tif (decodedCharacter === void 0) return void 0;\n\t\tcursor = decodedCharacter.next;\n\t\tif (escaped) escaped = false;\n\t\telse if (decodedCharacter.value === \"\\\\\") escaped = true;\n\t\telse if (decodedCharacter.value === quote) return cursor;\n\t}\n}\nfunction serializedStructuralValueEnd(value, from, opener, closer) {\n\tconst state = { depth: 0 };\n\tlet cursor = from;\n\twhile (cursor < value.length) {\n\t\tconst decodedCharacter = decodeSerializationCharacter(value, cursor);\n\t\tif (decodedCharacter === void 0) return void 0;\n\t\tcursor = decodedCharacter.next;\n\t\tif (advanceStructuralScan(state, decodedCharacter.value, opener, closer)) return cursor;\n\t}\n}\nfunction serializedUnquotedValueEnd(value, from) {\n\tlet cursor = from;\n\twhile (cursor < value.length) {\n\t\tconst character = value[cursor];\n\t\tif (character !== \"\\\\\") {\n\t\t\tif (\",;}\\\"'\\r\\n\".includes(character ?? \"\")) return cursor;\n\t\t\tcursor += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst decodedCharacter = decodeSerializationCharacter(value, cursor);\n\t\tif (decodedCharacter === void 0) return void 0;\n\t\tcursor = decodedCharacter.next;\n\t}\n\treturn cursor;\n}\nfunction serializedQuoteDelimiterAt(value, from) {\n\tlet cursor = from;\n\twhile (value[cursor] === \"\\\\\") cursor += 1;\n\tconst quote = value[cursor];\n\tif (!isCredentialQuote(quote)) return void 0;\n\treturn {\n\t\tend: cursor + 1,\n\t\tquote,\n\t\tslashCount: cursor - from\n\t};\n}\nfunction isSerializedValueBoundary(value, from) {\n\tlet cursor = from;\n\twhile (value[cursor] === \" \" || value[cursor] === \"\t\") cursor += 1;\n\treturn cursor === value.length || \",}]\".includes(value[cursor] ?? \"\") || value[cursor] === \"\\r\" || value[cursor] === \"\\n\";\n}\nfunction fallbackSerializedQuotedValueEnd(value, opening) {\n\tlet cursor = opening.end;\n\twhile (cursor < value.length) {\n\t\tconst candidate = serializedQuoteDelimiterAt(value, cursor);\n\t\tif (candidate !== void 0 && candidate.quote === opening.quote && candidate.slashCount === opening.slashCount && isSerializedValueBoundary(value, candidate.end)) return candidate.end;\n\t\tcursor = candidate?.end ?? cursor + 1;\n\t}\n}\nfunction fallbackSerializedValueEnd(value, from) {\n\tconst openingQuote = serializedQuoteDelimiterAt(value, from);\n\tif (openingQuote !== void 0) return fallbackSerializedQuotedValueEnd(value, openingQuote) ?? value.length;\n\tfor (let cursor = from; cursor < value.length; cursor += 1) {\n\t\tconst character = value[cursor];\n\t\tif (character === \",\" && SERIALIZED_SIBLING_FIELD_PATTERN.test(value.slice(cursor + 1))) return cursor;\n\t\tif (character === \"}\" || character === \"\\r\" || character === \"\\n\") return cursor;\n\t}\n\treturn value.length;\n}\nfunction serializedCredentialValueSpan(value, from) {\n\tconst firstCharacter = decodeSerializationCharacter(value, from);\n\tif (firstCharacter === void 0) return {\n\t\tcomplete: false,\n\t\tend: fallbackSerializedValueEnd(value, from)\n\t};\n\tlet end;\n\tif (isCredentialQuote(firstCharacter.value)) end = serializedQuotedValueEnd(value, firstCharacter.next, firstCharacter.value);\n\telse if (firstCharacter.value === \"[\" || firstCharacter.value === \"{\") {\n\t\tconst closer = firstCharacter.value === \"[\" ? \"]\" : \"}\";\n\t\tend = serializedStructuralValueEnd(value, from, firstCharacter.value, closer);\n\t} else if (firstCharacter.value !== \"\\\\\") end = serializedUnquotedValueEnd(value, from);\n\treturn end === void 0 ? {\n\t\tcomplete: false,\n\t\tend: fallbackSerializedValueEnd(value, from)\n\t} : {\n\t\tcomplete: true,\n\t\tend\n\t};\n}\nfunction scrubDecodedCredentialHeaders(value) {\n\tlet matched = false;\n\tlet output = \"\";\n\tlet cursor = 0;\n\tCREDENTIAL_HEADER_PATTERN.lastIndex = 0;\n\tfor (let match = CREDENTIAL_HEADER_PATTERN.exec(value); match; match = CREDENTIAL_HEADER_PATTERN.exec(value)) {\n\t\tmatched = true;\n\t\tconst offset = match.index;\n\t\tconst lineAnchored = isLineAnchoredCredentialHeader(value, offset);\n\t\tconst valueStart = offset + match[0].length;\n\t\tconst valueEnd = lineAnchored ? {\n\t\t\tend: credentialHeaderValueEnd(value, valueStart, lineIndentation(value, lineStart(value, offset))),\n\t\t\treplacement: REDACTED\n\t\t} : inlineCredentialValueEnd(value, valueStart, enclosingQuoteAt(value, offset));\n\t\toutput += value.slice(cursor, offset);\n\t\toutput += `${match[0]}${valueEnd.replacement}`;\n\t\tcursor = valueEnd.end;\n\t\tCREDENTIAL_HEADER_PATTERN.lastIndex = cursor;\n\t}\n\treturn {\n\t\tmatched,\n\t\tvalue: output + value.slice(cursor)\n\t};\n}\nconst SERIALIZED_REDACTED_VALUE = encodeOneSerializationLayer(`\"${REDACTED}\"`);\nfunction scrubSerializedCredentialField(value, fieldStart, valueStart) {\n\treturn `${value.slice(fieldStart, valueStart)}${SERIALIZED_REDACTED_VALUE}`;\n}\nfunction scrubSerializedCredentialFields(value) {\n\tlet output = \"\";\n\tlet cursor = 0;\n\tSERIALIZED_CREDENTIAL_FIELD_PATTERN.lastIndex = 0;\n\tfor (let match = SERIALIZED_CREDENTIAL_FIELD_PATTERN.exec(value); match; match = SERIALIZED_CREDENTIAL_FIELD_PATTERN.exec(value)) {\n\t\tconst fieldStart = match.index;\n\t\tif (fieldStart < cursor) continue;\n\t\tconst valueStart = fieldStart + match[0].length;\n\t\tconst valueSpan = serializedCredentialValueSpan(value, valueStart);\n\t\toutput += value.slice(cursor, fieldStart);\n\t\toutput += scrubSerializedCredentialField(value, fieldStart, valueStart);\n\t\tcursor = valueSpan.end;\n\t\tSERIALIZED_CREDENTIAL_FIELD_PATTERN.lastIndex = cursor;\n\t}\n\treturn output + value.slice(cursor);\n}\nfunction scrubCredentialHeaders(value) {\n\treturn scrubDecodedCredentialHeaders(scrubSerializedCredentialFields(value)).value;\n}\nfunction scrubString(value) {\n\treturn scrubCredentialHeaders(value).replace(/\\bBearer\\s+[^\\s,;}\\]]+/giu, \"Bearer [REDACTED]\").replace(/\\b(Basic|Digest|Negotiate)\\s+[^\\s,;}\\]]+/giu, \"$1 [REDACTED]\").replace(/([?&](?:access_token|refresh_token|client_secret|token|secret|password|api[_-]?key)=)[^&#\\s]+/giu, \"$1[REDACTED]\").replace(/(\\b(?:token|secret|password|credential|api[_-]?key)\\s*[:=]\\s*)[^\\s,;}\\]]+/giu, \"$1[REDACTED]\").replace(/(postgres(?:ql)?:\\/\\/)[^\\s/@]+(?::[^\\s/@]*)?@/giu, \"$1[REDACTED]@\");\n}\nfunction redactErrorValue(value, seen, depth) {\n\tconst error = value;\n\tconst output = {\n\t\tname: scrubString(error.name),\n\t\tmessage: scrubString(error.message)\n\t};\n\tif (typeof error.code === \"string\") output.code = scrubString(error.code);\n\tif (error.cause !== void 0) output.cause = redactValue(error.cause, seen, depth + 1);\n\treturn output;\n}\nfunction redactArray(value, seen, depth) {\n\treturn value.map((item) => redactValue(item, seen, depth + 1));\n}\nfunction redactObject(value, seen, depth) {\n\tconst output = {};\n\tfor (const [key, child] of Object.entries(value)) output[key] = isSensitiveKey(key, child) ? REDACTED : redactValue(child, seen, depth + 1);\n\treturn output;\n}\n/** The log serializer's caps, applied on top of redaction rather than inside it. */\nfunction capDepth(value, seen, depth) {\n\tif (value === null || value === void 0 || typeof value !== \"object\") return value;\n\tif (depth >= 8) return TRUNCATED;\n\tif (seen.has(value)) return CIRCULAR;\n\tseen.add(value);\n\tif (Array.isArray(value)) return value.slice(0, 32).map((item) => capDepth(item, seen, depth + 1));\n\tconst output = {};\n\tfor (const [key, child] of Object.entries(value).slice(0, 64)) output[key] = capDepth(child, seen, depth + 1);\n\treturn output;\n}\nfunction redactValue(value, seen, depth) {\n\tif (value === null || value === void 0 || typeof value === \"boolean\" || typeof value === \"number\") return value;\n\tif (typeof value === \"string\") return scrubString(value);\n\tif (typeof value === \"bigint\") return String(value);\n\tif (typeof value === \"function\" || typeof value === \"symbol\") return `[${typeof value}]`;\n\tif (seen.has(value)) return CIRCULAR;\n\tseen.add(value);\n\tif (value instanceof Error) return redactErrorValue(value, seen, depth);\n\tif (Array.isArray(value)) return redactArray(value, seen, depth);\n\treturn redactObject(value, seen, depth);\n}\n/** Return a detached, recursively redacted copy. The input object is never mutated. */\nfunction redactSensitive(value) {\n\treturn redactValue(value, /* @__PURE__ */ new WeakSet(), 0);\n}\nfunction utf8ByteLength(value) {\n\treturn new TextEncoder().encode(value).byteLength;\n}\nfunction truncateUtf8(value, maxBytes) {\n\tif (maxBytes <= 0) return \"\";\n\tif (utf8ByteLength(value) <= maxBytes) return value;\n\tconst suffix = `...${TRUNCATED}`;\n\tif (maxBytes <= utf8ByteLength(suffix)) {\n\t\tlet output = \"\";\n\t\tfor (const character of value) {\n\t\t\tif (utf8ByteLength(output + character) > maxBytes) break;\n\t\t\toutput += character;\n\t\t}\n\t\treturn output;\n\t}\n\tconst available = Math.max(0, maxBytes - utf8ByteLength(suffix));\n\tlet output = \"\";\n\tfor (const character of value) {\n\t\tif (utf8ByteLength(output + character) > available) break;\n\t\toutput += character;\n\t}\n\treturn output + suffix;\n}\nfunction capLogStringValues(value, seen) {\n\tif (typeof value === \"string\") return truncateUtf8(value, STRUCTURED_ERROR_LOG_FIELD_MAX_BYTES);\n\tif (value === null || value === void 0 || typeof value !== \"object\") return value;\n\tif (seen.has(value)) return CIRCULAR;\n\tseen.add(value);\n\tif (Array.isArray(value)) return value.map((item) => capLogStringValues(item, seen));\n\tconst output = {};\n\tfor (const [key, child] of Object.entries(value)) output[key] = capLogStringValues(child, seen);\n\treturn output;\n}\n/**\n* Return a detached, recursively redacted copy with the log serializer's caps: a UTF-8 bound on every\n* string, and a depth and breadth limit on the structure itself.\n*/\nfunction redactForLog(value) {\n\treturn capLogStringValues(capDepth(redactSensitive(value), /* @__PURE__ */ new WeakSet(), 0), /* @__PURE__ */ new WeakSet());\n}\n/**\n* Redact and JSON-serialize an arbitrary diagnostic payload within a fixed UTF-8 byte budget.\n* The result is always a string and may be a valid JSON truncation envelope when it exceeds the budget.\n*/\nfunction boundedSerialize(value, maxBytes = BOUNDED_DIAGNOSTIC_SERIALIZATION_BYTES) {\n\tconst budget = Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : BOUNDED_DIAGNOSTIC_SERIALIZATION_BYTES;\n\tlet serialized;\n\ttry {\n\t\tserialized = JSON.stringify(redactSensitive(value)) ?? \"null\";\n\t} catch {\n\t\tserialized = JSON.stringify(UNSERIALIZABLE);\n\t}\n\tif (utf8ByteLength(serialized) <= budget) return serialized;\n\tconst prefix = \"{\\\"truncated\\\":true,\\\"preview\\\":\";\n\tconst suffix = \"}\";\n\tconst available = Math.max(0, budget - utf8ByteLength(prefix) - utf8ByteLength(suffix) - 2);\n\tconst preview = truncateUtf8(serialized, available);\n\tlet result = `${prefix}${JSON.stringify(preview)}${suffix}`;\n\twhile (utf8ByteLength(result) > budget && preview.length > 0) {\n\t\tconst shorter = truncateUtf8(preview, Math.max(0, utf8ByteLength(preview) - 8));\n\t\tif (shorter === preview) break;\n\t\tresult = `${prefix}${JSON.stringify(shorter)}${suffix}`;\n\t}\n\treturn utf8ByteLength(result) <= budget ? result : truncateUtf8(result, budget);\n}\nconst redactDiagnostic = redactSensitive;\nconst serializeDiagnostic = boundedSerialize;\n//#endregion\n//#region src/error-report.ts\n/** Maximum length of the redacted error message accepted by the relay. */\nconst ERROR_REPORT_MESSAGE_MAX_LENGTH = 4096;\n/** Maximum length of the redacted stack trace accepted by the relay. */\nconst ERROR_REPORT_STACK_MAX_LENGTH = 16384;\n/** Maximum length of every other free-form field (version, command, user agent, ...). */\nconst ERROR_REPORT_FIELD_MAX_LENGTH = 512;\n/** Maximum length of the query-free page URL a web report may carry. */\nconst ERROR_REPORT_URL_MAX_LENGTH = 2048;\nconst TRUNCATED_SUFFIX = \"...[TRUNCATED]\";\nconst ErrorReportSourceSchema = z.enum([\"web\", \"cli\"]);\nconst shortField = z.string().min(1).max(512);\n/**\n* One client-side failure relayed to the server for forwarding to an error tracker.\n*\n* The client redacts before sending and the server redacts again before forwarding; the schema only\n* bounds what may cross the wire. No token or cookie field exists, and `url` never carries a query\n* string or fragment.\n*\n* The identifiers below are attribution, not authorization. The relay is anonymous, so every one of\n* them is chosen by the caller and a report that names an Account only says that whoever posted it\n* claimed to be that Account. Read them as a lead to follow, never as proof of who someone is.\n*/\nconst ErrorReportRequestSchema = z.object({\n\tsource: ErrorReportSourceSchema,\n\tmessage: z.string().min(1).max(ERROR_REPORT_MESSAGE_MAX_LENGTH),\n\tstack: z.string().min(1).max(ERROR_REPORT_STACK_MAX_LENGTH).optional(),\n\tcode: StructuredErrorCodeSchema.optional(),\n\tversion: shortField.optional(),\n\tchannel: ChannelNameSchema.optional(),\n\tenvironment: shortField.optional(),\n\t/** Correlates the forwarded tracker event with the server log line that holds the full context. */\n\treportId: shortField.optional(),\n\t/** The Account this client believed it was signed in as; absent before sign-in. */\n\tuserId: shortField.optional(),\n\t/** Web only: the matched route template, such as `/agents/:agentId`, which `url` cannot give. */\n\troute: shortField.optional(),\n\t/** CLI only: operating system, architecture, and runtime version. */\n\tplatform: shortField.optional(),\n\t/** CLI only: the Computer this OpenTag home is bound to, when one is. */\n\tcomputerId: shortField.optional(),\n\tinstallationId: shortField.optional(),\n\t/** CLI only: present when the failure happened inside an Agent turn. */\n\tagentId: shortField.optional(),\n\tsessionId: shortField.optional(),\n\tturnId: shortField.optional(),\n\t/** CLI only: the Agent runtime provider, such as `claude-code`. */\n\tprovider: shortField.optional(),\n\t/** Web only: an HTTP(S) document URL; query string, fragment, and credentials are stripped on parse. */\n\turl: z.string().min(1).max(ERROR_REPORT_URL_MAX_LENGTH).transform((value, context) => {\n\t\tconst sanitized = sanitizeErrorReportUrl(value);\n\t\tif (sanitized === void 0) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage: \"Must be an HTTP(S) URL\"\n\t\t\t});\n\t\t\treturn z.NEVER;\n\t\t}\n\t\treturn sanitized;\n\t}).optional(),\n\t/** CLI only: the command path without user arguments, such as `agent create`. */\n\tcommand: shortField.optional(),\n\tuserAgent: shortField.optional(),\n\toccurredAt: z.string().datetime({ offset: true })\n}).strict();\nfunction truncate(value, maxLength) {\n\tif (value.length <= maxLength) return value;\n\treturn `${value.slice(0, Math.max(0, maxLength - 14))}${TRUNCATED_SUFFIX}`;\n}\nfunction redactText(value, maxLength) {\n\treturn truncate(redactSensitive(value), maxLength);\n}\n/** Drop everything from a URL that can carry a secret or a per-user value: query, fragment, and credentials. */\nfunction sanitizeErrorReportUrl(value) {\n\ttry {\n\t\tconst url = new URL(value);\n\t\tif (![\"http:\", \"https:\"].includes(url.protocol)) return void 0;\n\t\turl.search = \"\";\n\t\turl.hash = \"\";\n\t\turl.username = \"\";\n\t\turl.password = \"\";\n\t\treturn truncate(url.toString(), ERROR_REPORT_URL_MAX_LENGTH);\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction isErrorLike(value) {\n\treturn value instanceof Error || typeof value === \"object\" && value !== null && \"message\" in value;\n}\n/** Read an `Error`, a `DOMException`, or any `{ message, stack?, code? }` object the same way. */\nfunction errorParts(error) {\n\tif (isErrorLike(error)) {\n\t\tconst message = typeof error.message === \"string\" ? error.message : \"\";\n\t\tconst name = typeof error.name === \"string\" ? error.name : \"\";\n\t\treturn {\n\t\t\tmessage: message || name || \"Unknown error\",\n\t\t\t...typeof error.stack === \"string\" && error.stack.length > 0 ? { stack: error.stack } : {},\n\t\t\t...typeof error.code === \"string\" ? { code: error.code } : {}\n\t\t};\n\t}\n\tif (typeof error === \"string\" && error.length > 0) return { message: error };\n\treturn { message: \"Unknown error\" };\n}\nconst SHORT_METADATA_FIELDS = Object.keys({\n\tagentId: true,\n\tcommand: true,\n\tcomputerId: true,\n\tenvironment: true,\n\tinstallationId: true,\n\tplatform: true,\n\tprovider: true,\n\treportId: true,\n\troute: true,\n\tsessionId: true,\n\tturnId: true,\n\tuserAgent: true,\n\tuserId: true,\n\tversion: true\n});\n/**\n* Build a relay request from a thrown value. Message and stack are redacted and bounded here so\n* every client sends the same shape, and optional metadata is dropped when it is empty or invalid\n* rather than making the whole report fail validation.\n*/\nfunction createErrorReport(error, metadata) {\n\tconst parts = errorParts(error);\n\tconst code = metadata.code ?? parts.code;\n\tconst url = metadata.url ? sanitizeErrorReportUrl(metadata.url) : void 0;\n\tconst shortFields = {};\n\tfor (const key of SHORT_METADATA_FIELDS) {\n\t\tconst value = metadata[key];\n\t\tif (value) shortFields[key] = redactText(value, 512);\n\t}\n\treturn {\n\t\tsource: metadata.source,\n\t\tmessage: redactText(parts.message, ERROR_REPORT_MESSAGE_MAX_LENGTH),\n\t\t...parts.stack ? { stack: redactText(parts.stack, ERROR_REPORT_STACK_MAX_LENGTH) } : {},\n\t\t...code && StructuredErrorCodeSchema.safeParse(code).success ? { code } : {},\n\t\t...metadata.channel ? { channel: metadata.channel } : {},\n\t\t...url ? { url } : {},\n\t\t...shortFields,\n\t\toccurredAt: metadata.occurredAt ?? (/* @__PURE__ */ new Date()).toISOString()\n\t};\n}\n//#endregion\n//#region src/github-management.ts\n/**\n* GitHub management API contract: the Account-facing DTOs of the deployment-level GitHub App\n* integration — availability, connection overview, authorization start, repository discovery, and\n* the OAuth callback outcome the fixed local return surfaces receive.\n*\n* Every schema here is strict and browser-compatible. None of them ever carries secrets: no\n* credential ciphertext or key IDs, no OAuth state/session values, no PKCE material, and no GitHub\n* tokens. The numeric-ID and version-string rules of `github-integration.ts` apply throughout.\n*/\n/** The OAuth callback returns only to fixed local surfaces, carrying this bounded outcome. */\nconst GITHUB_OAUTH_OUTCOME_PARAM = \"github_oauth\";\nconst GITHUB_OAUTH_ERROR_PARAM = \"github_oauth_error\";\nconst GITHUB_OAUTH_OUTCOME_SUCCESS = \"success\";\nconst GITHUB_OAUTH_OUTCOME_ERROR = \"error\";\n/** A bounded public error code is the only failure detail a return surface ever receives. */\nconst GitHubOAuthOutcomeSearchSchema = z.object({\n\t[GITHUB_OAUTH_OUTCOME_PARAM]: z.enum([GITHUB_OAUTH_OUTCOME_SUCCESS, GITHUB_OAUTH_OUTCOME_ERROR]),\n\t[GITHUB_OAUTH_ERROR_PARAM]: z.string().min(1).max(120).optional()\n}).strict();\n/**\n* Public management error codes a caller may branch on. Everything else the integration reports is\n* one of the `GITHUB_CONNECTION_ERROR_CODES` persisted on the connection status DTO.\n*/\nconst GITHUB_MANAGEMENT_ERROR_CODES = {\n\t/** The deployment has no GitHub App configured; the UI must explain, never demo. */\n\tINTEGRATION_UNAVAILABLE: GITHUB_CONNECTION_ERROR_CODES.INTEGRATION_UNAVAILABLE,\n\tUPSTREAM_UNAVAILABLE: GITHUB_CONNECTION_ERROR_CODES.UPSTREAM_UNAVAILABLE,\n\tUPSTREAM_ERROR: GITHUB_CONNECTION_ERROR_CODES.UPSTREAM_ERROR,\n\tRATE_LIMITED: GITHUB_CONNECTION_ERROR_CODES.RATE_LIMITED,\n\t/** The GitHub App does not issue expiring user tokens; the deployment must enable them. */\n\tTOKEN_LIFETIME_UNSUPPORTED: GITHUB_CONNECTION_ERROR_CODES.TOKEN_LIFETIME_UNSUPPORTED,\n\t/** The connected user's live admission no longer covers a requested binding. */\n\tADMISSION_INSTALLATION_MISSING: GITHUB_CONNECTION_ERROR_CODES.ADMISSION_INSTALLATION_MISSING,\n\tADMISSION_REPOSITORY_MISSING: GITHUB_CONNECTION_ERROR_CODES.ADMISSION_REPOSITORY_MISSING,\n\tADMISSION_PERMISSION_INSUFFICIENT: GITHUB_CONNECTION_ERROR_CODES.ADMISSION_PERMISSION_INSUFFICIENT,\n\t/** GitHub returned an identity for the configured App that does not match — upstream integrity. */\n\tAPP_IDENTITY_MISMATCH: GITHUB_CONNECTION_ERROR_CODES.APP_IDENTITY_MISMATCH,\n\t/** The user denied the authorization on GitHub. */\n\tOAUTH_DENIED: GITHUB_CONNECTION_ERROR_CODES.OAUTH_DENIED,\n\t/** The callback arrived without an authenticated Account session. */\n\tOAUTH_AUTHENTICATION_REQUIRED: \"GITHUB_OAUTH_AUTHENTICATION_REQUIRED\"\n};\n/**\n* Whether this deployment offers the GitHub integration, with the configured App's public numeric\n* ID. Unavailable integrations return this metadata on every management route so the UI can explain\n* the state; `appId` is null while unconfigured.\n*/\nconst GitHubIntegrationAvailabilitySchema = z.object({\n\tavailable: z.boolean(),\n\tgithubHost: z.literal(\"github.com\"),\n\tappId: GitHubDecimalIdSchema.nullable()\n}).strict();\n/** The Account's integration overview: deployment availability plus its current connection, if any. */\nconst GitHubIntegrationOverviewSchema = z.object({\n\tavailability: GitHubIntegrationAvailabilitySchema,\n\tconnection: GitHubConnectionStatusSchema.nullable()\n}).strict();\n/**\n* Starts (or restarts) the OAuth round trip. `create` opens a new connection — or restarts the\n* in-flight flow of a still-pending one; `reauthorize`/`replace` act on the current connection. The\n* server never accepts an App override: the configured deployment App is the only one a flow uses.\n*/\nconst StartGitHubAuthorizationRequestSchema = z.object({\n\tintent: GitHubOAuthFlowIntentSchema,\n\treturnSurface: GitHubOAuthReturnSurfaceSchema.default(\"account-integrations\"),\n\tagentId: z.string().uuid().nullable().default(null)\n}).strict().superRefine((value, context) => {\n\tif (value.returnSurface === \"account-integrations\" && value.agentId !== null) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"agentId\"],\n\t\tmessage: \"Only an agent-integrations flow names its return Agent\"\n\t});\n\tif (value.returnSurface === \"agent-integrations\" && value.agentId === null) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"agentId\"],\n\t\tmessage: \"An agent-integrations flow requires its return Agent\"\n\t});\n});\n/**\n* The started authorization: the exact GitHub authorize URL the browser navigates to, the\n* connection the flow belongs to, and when the one-time state expires. The URL is always on\n* github.com and already carries the state and PKCE challenge; neither is returned separately.\n*/\nconst StartGitHubAuthorizationResponseSchema = z.object({\n\tconnectionId: z.string().uuid(),\n\tauthorizationUrl: z.string().url().max(2048),\n\texpiresAt: z.string().datetime()\n}).strict();\n/** Installation metadata as far as repository discovery and the UI need it. */\nconst GitHubDiscoveredInstallationSchema = z.object({\n\tinstallationId: GitHubDecimalIdSchema,\n\taccountLogin: z.string().min(1).max(100),\n\taccountType: z.enum([\"User\", \"Organization\"]),\n\trepositorySelection: z.enum([\"all\", \"selected\"]),\n\tsuspended: z.boolean()\n}).strict();\n/**\n* One repository the connected user can reach through the configured App's installations. The\n* stable numeric IDs route authorization; `fullName` and `defaultBranch` are display/default\n* metadata only. `permissions` is GitHub's verdict for this exact user on this exact repository.\n*/\nconst GitHubDiscoveredRepositorySchema = z.object({\n\tinstallationId: GitHubDecimalIdSchema,\n\trepositoryId: GitHubDecimalIdSchema,\n\tfullName: GitHubRepositoryFullNameSchema,\n\tprivate: z.boolean(),\n\tdefaultBranch: z.string().min(1).max(255).nullable(),\n\tpermissions: z.object({\n\t\tpull: z.boolean(),\n\t\tpush: z.boolean()\n\t}).strict()\n}).strict();\nconst GITHUB_REPOSITORY_DISCOVERY_MAX_INSTALLATIONS = 500;\nconst GITHUB_REPOSITORY_DISCOVERY_PAGE_SIZE = 100;\n/**\n* One page of the repository discovery stream. `installations` repeats the current installation\n* list on every page so a late reader can render install state without a second call; `nextCursor`\n* is an opaque server-owned continuation — callers treat it as unreadable and never construct one.\n* One installation is listed at most ten pages deep; `truncatedInstallations` names every\n* installation whose repositories exceed that bound, so a partial listing is always explicit and\n* never presented as exhaustive.\n*/\nconst GitHubRepositoryDiscoveryPageSchema = z.object({\n\tinstallations: z.array(GitHubDiscoveredInstallationSchema).max(500),\n\trepositories: z.array(GitHubDiscoveredRepositorySchema).max(100),\n\tnextCursor: z.string().min(1).max(512).nullable(),\n\ttruncatedInstallations: z.array(GitHubDecimalIdSchema).max(500).optional()\n}).strict();\n/** The discovery query: an optional opaque continuation cursor. */\nconst GitHubRepositoryDiscoveryQuerySchema = z.object({ cursor: z.string().min(1).max(512).optional() }).strict();\n//#endregion\n//#region src/health.ts\nconst ServerHealthSchema = z.object({\n\tstatus: z.literal(\"ok\"),\n\tservice: z.literal(\"opentag-server\")\n}).strict();\n//#endregion\n//#region src/http-paths.ts\nconst API_V1_PREFIX = \"/api/v1\";\nconst AGENT_BY_ID_TEMPLATE = `${API_V1_PREFIX}/agents/:agentId`;\nconst AGENT_SETUP_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/setup`;\nconst AGENT_SETUP_REFRESH_TEMPLATE = `${AGENT_SETUP_TEMPLATE}/refresh`;\nconst AGENT_CONFIG_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/config`;\nconst AGENT_RUNTIME_TEST_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/runtime-test`;\nconst AGENT_USAGE_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/usage`;\nconst AGENT_CLOUD_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/cloud`;\nfunction agentCloudPath(agentId, options = {}) {\n\tconst query = new URLSearchParams();\n\tif (options.cursor !== void 0) query.set(\"cursor\", options.cursor);\n\tif (options.limit !== void 0) query.set(\"limit\", String(options.limit));\n\tif (options.sessionId !== void 0) query.set(\"sessionId\", options.sessionId);\n\tconst suffix = query.toString();\n\treturn `${API_V1_PREFIX}/agents/${encodeURIComponent(agentId)}/cloud${suffix ? `?${suffix}` : \"\"}`;\n}\nconst AGENT_SUSPEND_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/suspend`;\nconst AGENT_REACTIVATE_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/reactivate`;\nconst AGENT_COMPUTER_REBIND_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/computer/rebind`;\nconst AGENT_IM_BINDING_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/im-binding`;\nconst AGENT_IM_BINDING_HANDOFF_TEMPLATE = `${AGENT_IM_BINDING_TEMPLATE}/handoff`;\nconst AGENT_IM_BINDING_CONFIG_TEMPLATE = `${AGENT_IM_BINDING_TEMPLATE}/config`;\nconst AGENT_IM_BINDING_UNBIND_TEMPLATE = `${AGENT_IM_BINDING_TEMPLATE}/unbind`;\nconst AGENT_FEISHU_SETUP_ATTEMPTS_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/im-binding/feishu/setup-attempts`;\nconst FEISHU_SETUP_ATTEMPT_TEMPLATE = `${API_V1_PREFIX}/im-bindings/feishu/setup-attempts/:attemptId`;\nconst FEISHU_SETUP_ATTEMPT_CHECK_TEMPLATE = `${FEISHU_SETUP_ATTEMPT_TEMPLATE}/check`;\nconst AGENT_SLACK_OAUTH_START_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/im-binding/slack/oauth/start`;\nconst AGENT_SLACK_EVENTS_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/im-binding/slack/events`;\nconst IM_BINDING_BY_ID_TEMPLATE = `${API_V1_PREFIX}/im-bindings/:imBindingId`;\nconst IM_BINDING_DIAGNOSTICS_TEMPLATE = `${IM_BINDING_BY_ID_TEMPLATE}/diagnostics`;\nconst SLACK_EVENTS_PATH = `${API_V1_PREFIX}/im-bindings/slack/events`;\nconst SLACK_OAUTH_CALLBACK_PATH = `${API_V1_PREFIX}/im-bindings/slack/oauth/callback`;\nconst GITHUB_INTEGRATION_PATH = `${API_V1_PREFIX}/integrations/github`;\nconst GITHUB_INTEGRATION_AUTHORIZATION_PATH = `${GITHUB_INTEGRATION_PATH}/authorization`;\nconst GITHUB_INTEGRATION_REPOSITORIES_PATH = `${GITHUB_INTEGRATION_PATH}/repositories`;\nconst GITHUB_INTEGRATION_BINDINGS_PATH = `${GITHUB_INTEGRATION_PATH}/bindings`;\nconst GITHUB_INTEGRATION_DISCONNECT_PATH = `${GITHUB_INTEGRATION_PATH}/disconnect`;\nconst GITHUB_OAUTH_CALLBACK_PATH = `${GITHUB_INTEGRATION_PATH}/oauth/callback`;\nconst GITHUB_WEBHOOK_PATH = `${GITHUB_INTEGRATION_PATH}/webhook`;\nconst RUNTIME_IM_RESOURCE_TEMPLATE = `${API_V1_PREFIX}/runtime/im-messages/:imMessageId/resources/:ordinal`;\nconst RUNTIME_INTERNAL_SESSIONS_PATH = `${API_V1_PREFIX}/runtime/sessions/internal`;\nconst RUNTIME_SESSION_MESSAGES_PATH = `${API_V1_PREFIX}/runtime/session-messages`;\nconst RUNTIME_SESSIONS_PATH = `${API_V1_PREFIX}/runtime/sessions`;\nconst RUNTIME_DURABLE_WORK_PATH = `${API_V1_PREFIX}/runtime/durable-work`;\n/**\n* Account-native management collections. Ownership comes only from the authenticated Account.\n*/\nconst ACCOUNT_AGENTS_PATH = `${API_V1_PREFIX}/agents`;\nconst ACCOUNT_AGENT_CREATION_INTENT_TEMPLATE = `${ACCOUNT_AGENTS_PATH}/creation-intents/:creationIntentId`;\nconst ACCOUNT_COMPUTERS_PATH = `${API_V1_PREFIX}/computers`;\n/** One Account-owned Computer; `DELETE` retires it and revokes its machine credential. */\nconst ACCOUNT_COMPUTER_BY_ID_TEMPLATE = `${ACCOUNT_COMPUTERS_PATH}/:computerId`;\nconst ACCOUNT_COMPUTER_DISCONNECT_TEMPLATE = `${ACCOUNT_COMPUTER_BY_ID_TEMPLATE}/disconnect`;\nconst ACCOUNT_CLOUD_COMPUTER_PATH = `${ACCOUNT_COMPUTERS_PATH}/cloud`;\n/** The Router-sourced Cloud model choices; read-only and authenticated like the sibling Cloud routes. */\nconst ACCOUNT_CLOUD_MODELS_PATH = `${ACCOUNT_CLOUD_COMPUTER_PATH}/models`;\nconst ACCOUNT_COMPUTER_CONNECT_CODES_PATH = `${API_V1_PREFIX}/computer-connect-codes`;\nconst ACCOUNT_SANDBOXES_PATH = `${API_V1_PREFIX}/sandboxes`;\nconst ACCOUNT_SANDBOX_TEMPLATE = `${ACCOUNT_SANDBOXES_PATH}/:sandboxId`;\nconst ACCOUNT_SANDBOX_RUNNER_TEMPLATE = `${ACCOUNT_SANDBOX_TEMPLATE}/runner`;\nconst ACCOUNT_SANDBOX_RUNNER_START_TEMPLATE = `${ACCOUNT_SANDBOX_RUNNER_TEMPLATE}/start`;\nconst ACCOUNT_SANDBOX_RUNNER_STOP_TEMPLATE = `${ACCOUNT_SANDBOX_RUNNER_TEMPLATE}/stop`;\nconst ACCOUNT_SANDBOX_RUNNER_ACCEPTANCE_TEMPLATE = `${ACCOUNT_SANDBOX_RUNNER_TEMPLATE}/acceptance`;\n/**\n* Outbound control channel a Cloud Runner dials from inside its Cloud Run Instance. No token ever\n* travels in the URL; authentication is a first-frame bootstrap bearer credential.\n*/\nconst SANDBOX_RUNNER_WEBSOCKET_PATH = `${API_V1_PREFIX}/sandbox-runners/ws`;\nconst ACCOUNT_COMPUTER_CONNECT_CODE_TEMPLATE = `${ACCOUNT_COMPUTER_CONNECT_CODES_PATH}/:connectCodeId`;\nconst ACCOUNT_SETUP_COMPLETE_PATH = `${API_V1_PREFIX}/me/setup/complete`;\nconst ACCOUNT_SETUP_RESET_PATH = `${API_V1_PREFIX}/me/setup/reset`;\nconst INTERNAL_NAVIGATION_VISIBILITY_PATH = `${API_V1_PREFIX}/internal/navigation-visibility`;\nconst ACCOUNT_TASKS_PATH = `${API_V1_PREFIX}/sessions`;\nconst TASK_BY_ID_TEMPLATE = `${ACCOUNT_TASKS_PATH}/:sessionId`;\nconst TASK_CANCEL_TEMPLATE = `${TASK_BY_ID_TEMPLATE}/cancel`;\n/** Read-only paged subresource of the Task's platform-confirmed outbound IM replies. */\nconst TASK_REPLIES_TEMPLATE = `${TASK_BY_ID_TEMPLATE}/replies`;\nconst MCP_SERVERS_PATH = `${API_V1_PREFIX}/mcp-servers`;\nconst MCP_SERVER_BY_ID_TEMPLATE = `${MCP_SERVERS_PATH}/:mcpServerId`;\nconst MCP_OAUTH_CALLBACK_PATH = `${MCP_SERVERS_PATH}/oauth/callback`;\nconst AGENT_MCP_SERVERS_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/mcp-servers`;\nconst AGENT_MCP_SERVER_TEMPLATE = `${AGENT_MCP_SERVERS_TEMPLATE}/:mcpServerId`;\nconst AGENT_MCP_AUTHORIZATION_TEMPLATE = `${AGENT_MCP_SERVER_TEMPLATE}/authorization`;\nconst AGENT_MCP_AUTHORIZATION_OAUTH_TEMPLATE = `${AGENT_MCP_AUTHORIZATION_TEMPLATE}/oauth`;\nconst AGENT_MCP_PROBE_TEMPLATE = `${AGENT_MCP_SERVER_TEMPLATE}/probe`;\n/** A public static document describing this deployment as an OAuth client (CIMD). */\nconst MCP_CLIENT_METADATA_PATH = \"/oauth/client-metadata.json\";\nconst AGENT_SKILLS_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/skills`;\nconst AGENT_SKILL_TEMPLATE = `${AGENT_SKILLS_TEMPLATE}/:skillId`;\nconst AGENT_SKILL_BUNDLE_TEMPLATE = `${AGENT_SKILL_TEMPLATE}/bundle`;\nconst COMPUTER_AGENT_SKILLS_TEMPLATE = `${API_V1_PREFIX}/computer/agents/:agentId/skills`;\nconst COMPUTER_AGENT_SKILL_BUNDLE_TEMPLATE = `${COMPUTER_AGENT_SKILLS_TEMPLATE}/:skillId/bundle`;\nconst RUNTIME_SKILLS_PATH = `${API_V1_PREFIX}/runtime/skills`;\nconst RUNTIME_SKILL_BUNDLE_TEMPLATE = `${RUNTIME_SKILLS_PATH}/:name/bundle`;\nconst RUNTIME_AGENT_PATH = `${API_V1_PREFIX}/runtime/agent`;\nconst RUNTIME_AGENT_MCP_SERVERS_PATH = `${RUNTIME_AGENT_PATH}/mcp-servers`;\nconst RUNTIME_AGENT_MCP_SERVERS_AVAILABLE_PATH = `${RUNTIME_AGENT_MCP_SERVERS_PATH}/available`;\nconst RUNTIME_AGENT_MCP_SERVER_TEMPLATE = `${RUNTIME_AGENT_MCP_SERVERS_PATH}/:mcpServerId`;\nconst HTTP_PATHS = {\n\taccountAgents: ACCOUNT_AGENTS_PATH,\n\taccountCloudComputer: ACCOUNT_CLOUD_COMPUTER_PATH,\n\taccountCloudModels: ACCOUNT_CLOUD_MODELS_PATH,\n\taccountComputerConnectCodes: ACCOUNT_COMPUTER_CONNECT_CODES_PATH,\n\taccountComputers: ACCOUNT_COMPUTERS_PATH,\n\taccountComputerById: ACCOUNT_COMPUTER_BY_ID_TEMPLATE,\n\taccountSandboxes: ACCOUNT_SANDBOXES_PATH,\n\tsandboxRunnerWebSocket: SANDBOX_RUNNER_WEBSOCKET_PATH,\n\taccountSetupComplete: ACCOUNT_SETUP_COMPLETE_PATH,\n\taccountSetupReset: ACCOUNT_SETUP_RESET_PATH,\n\tinternalNavigationVisibility: INTERNAL_NAVIGATION_VISIBILITY_PATH,\n\taccountTasks: ACCOUNT_TASKS_PATH,\n\tagentById: AGENT_BY_ID_TEMPLATE,\n\tslackEvents: SLACK_EVENTS_PATH,\n\tgithubIntegration: GITHUB_INTEGRATION_PATH,\n\tgithubOAuthCallback: GITHUB_OAUTH_CALLBACK_PATH,\n\tgithubWebhook: GITHUB_WEBHOOK_PATH,\n\tmcpServers: MCP_SERVERS_PATH,\n\tmcpOAuthCallback: MCP_OAUTH_CALLBACK_PATH,\n\tmcpClientMetadata: MCP_CLIENT_METADATA_PATH,\n\tslackOAuthCallback: SLACK_OAUTH_CALLBACK_PATH,\n\tauthConnectExchange: `${API_V1_PREFIX}/auth/connect/exchange`,\n\tcomputerConnectExchange: `${API_V1_PREFIX}/computer/connect/exchange`,\n\tauthBrowserLogout: `${API_V1_PREFIX}/auth/browser/logout`,\n\tauthBrowserSessionStatus: `${API_V1_PREFIX}/auth/browser/session-status`,\n\tauthDevCallback: `${API_V1_PREFIX}/auth/dev/callback`,\n\tauthEmailSignIn: `${API_V1_PREFIX}/auth/email/sign-in`,\n\tauthEmailSignUp: `${API_V1_PREFIX}/auth/email/sign-up`,\n\tauthGoogleStart: `${API_V1_PREFIX}/auth/google/start`,\n\tauthProviders: `${API_V1_PREFIX}/auth/providers`,\n\tauthRefresh: `${API_V1_PREFIX}/auth/refresh`,\n\tcomputerRuntimeWebSocket: `${API_V1_PREFIX}/computer/ws`,\n\t/** Anonymous relay for client-side failures; see docs/error-reporting.md. */\n\terrorReports: `${API_V1_PREFIX}/error-reports`,\n\truntimeInternalSessions: RUNTIME_INTERNAL_SESSIONS_PATH,\n\truntimeSessionMessages: RUNTIME_SESSION_MESSAGES_PATH,\n\truntimeSessions: RUNTIME_SESSIONS_PATH,\n\truntimeSkills: RUNTIME_SKILLS_PATH,\n\truntimeDurableWork: RUNTIME_DURABLE_WORK_PATH,\n\tme: `${API_V1_PREFIX}/me`,\n\tmeConnectCodes: `${API_V1_PREFIX}/me/connect-codes`\n};\nfunction taskByIdPath(sessionId) {\n\treturn `${ACCOUNT_TASKS_PATH}/${encodeURIComponent(sessionId)}`;\n}\nfunction taskCancelPath(sessionId) {\n\treturn `${taskByIdPath(sessionId)}/cancel`;\n}\nfunction taskRepliesPath(sessionId) {\n\treturn `${taskByIdPath(sessionId)}/replies`;\n}\nfunction accountComputerConnectCodePath(connectCodeId) {\n\treturn `${ACCOUNT_COMPUTER_CONNECT_CODES_PATH}/${encodeURIComponent(connectCodeId)}`;\n}\nfunction accountSandboxPath(sandboxId) {\n\treturn `${ACCOUNT_SANDBOXES_PATH}/${encodeURIComponent(sandboxId)}`;\n}\nfunction accountSandboxRunnerPath(sandboxId) {\n\treturn `${accountSandboxPath(sandboxId)}/runner`;\n}\nfunction accountSandboxRunnerStartPath(sandboxId) {\n\treturn `${accountSandboxRunnerPath(sandboxId)}/start`;\n}\nfunction accountSandboxRunnerStopPath(sandboxId) {\n\treturn `${accountSandboxRunnerPath(sandboxId)}/stop`;\n}\nfunction accountSandboxRunnerAcceptancePath(sandboxId) {\n\treturn `${accountSandboxRunnerPath(sandboxId)}/acceptance`;\n}\n/** The exact WSS URL a Runner dials, derived from the configured backend origin (never caller input). */\nfunction sandboxRunnerWebSocketUrl(backendOrigin) {\n\tconst url = new URL(SANDBOX_RUNNER_WEBSOCKET_PATH, backendOrigin);\n\turl.protocol = url.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n\treturn url.toString();\n}\nfunction accountComputerByIdPath(computerId) {\n\treturn `${ACCOUNT_COMPUTERS_PATH}/${encodeURIComponent(computerId)}`;\n}\nfunction accountComputerDisconnectPath(computerId) {\n\treturn `${accountComputerByIdPath(computerId)}/disconnect`;\n}\nfunction agentByIdPath(agentId) {\n\treturn `${API_V1_PREFIX}/agents/${encodeURIComponent(agentId)}`;\n}\nfunction accountAgentCreationIntentPath(creationIntentId) {\n\treturn `${ACCOUNT_AGENTS_PATH}/creation-intents/${encodeURIComponent(creationIntentId)}`;\n}\nfunction agentSetupPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/setup`;\n}\nfunction agentSetupRefreshPath(agentId) {\n\treturn `${agentSetupPath(agentId)}/refresh`;\n}\nfunction agentConfigPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/config`;\n}\nfunction agentRuntimeTestPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/runtime-test`;\n}\nfunction agentUsagePath(agentId, windowDays) {\n\tconst query = new URLSearchParams({ days: String(windowDays) });\n\treturn `${agentByIdPath(agentId)}/usage?${query.toString()}`;\n}\nfunction agentSuspendPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/suspend`;\n}\nfunction agentReactivatePath(agentId) {\n\treturn `${agentByIdPath(agentId)}/reactivate`;\n}\nfunction agentComputerRebindPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/computer/rebind`;\n}\nfunction agentImBindingPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/im-binding`;\n}\nfunction agentImBindingHandoffPath(agentId) {\n\treturn `${agentImBindingPath(agentId)}/handoff`;\n}\nfunction agentImBindingConfigPath(agentId) {\n\treturn `${agentImBindingPath(agentId)}/config`;\n}\nfunction agentImBindingUnbindPath(agentId) {\n\treturn `${agentImBindingPath(agentId)}/unbind`;\n}\nfunction agentFeishuSetupAttemptsPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/im-binding/feishu/setup-attempts`;\n}\nfunction feishuSetupAttemptPath(attemptId) {\n\treturn `${API_V1_PREFIX}/im-bindings/feishu/setup-attempts/${encodeURIComponent(attemptId)}`;\n}\nfunction feishuSetupAttemptCancelPath(attemptId) {\n\treturn `${feishuSetupAttemptPath(attemptId)}/cancel`;\n}\nfunction feishuSetupAttemptCheckPath(attemptId) {\n\treturn `${feishuSetupAttemptPath(attemptId)}/check`;\n}\nfunction agentSlackOAuthStartPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/im-binding/slack/oauth/start`;\n}\nfunction agentSlackEventsPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/im-binding/slack/events`;\n}\nfunction githubIntegrationPath() {\n\treturn GITHUB_INTEGRATION_PATH;\n}\nfunction githubIntegrationAuthorizationPath() {\n\treturn GITHUB_INTEGRATION_AUTHORIZATION_PATH;\n}\nfunction githubIntegrationRepositoriesPath(cursor) {\n\tif (cursor === void 0) return GITHUB_INTEGRATION_REPOSITORIES_PATH;\n\treturn `${GITHUB_INTEGRATION_REPOSITORIES_PATH}?${new URLSearchParams({ cursor }).toString()}`;\n}\nfunction githubIntegrationBindingsPath() {\n\treturn GITHUB_INTEGRATION_BINDINGS_PATH;\n}\nfunction githubIntegrationDisconnectPath() {\n\treturn GITHUB_INTEGRATION_DISCONNECT_PATH;\n}\nfunction imBindingDisablePath(imBindingId) {\n\treturn `${API_V1_PREFIX}/im-bindings/${encodeURIComponent(imBindingId)}/disable`;\n}\nfunction imBindingDiagnosticsPath(imBindingId) {\n\treturn `${API_V1_PREFIX}/im-bindings/${encodeURIComponent(imBindingId)}/diagnostics`;\n}\nfunction mcpServersPath() {\n\treturn MCP_SERVERS_PATH;\n}\nfunction mcpServerPath(mcpServerId) {\n\treturn `${MCP_SERVERS_PATH}/${encodeURIComponent(mcpServerId)}`;\n}\nfunction agentMcpServersPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/mcp-servers`;\n}\nfunction agentMcpServerPath(agentId, mcpServerId) {\n\treturn `${agentMcpServersPath(agentId)}/${encodeURIComponent(mcpServerId)}`;\n}\nfunction agentMcpAuthorizationPath(agentId, mcpServerId) {\n\treturn `${agentMcpServerPath(agentId, mcpServerId)}/authorization`;\n}\nfunction agentMcpAuthorizationOAuthPath(agentId, mcpServerId) {\n\treturn `${agentMcpAuthorizationPath(agentId, mcpServerId)}/oauth`;\n}\nfunction agentMcpProbePath(agentId, mcpServerId) {\n\treturn `${agentMcpServerPath(agentId, mcpServerId)}/probe`;\n}\nfunction runtimeImResourcePath(imMessageId, ordinal, input) {\n\tconst query = new URLSearchParams({\n\t\tsessionId: input.sessionId,\n\t\tinstanceId: input.instanceId,\n\t\tplacementGeneration: String(input.placementGeneration)\n\t});\n\treturn `${API_V1_PREFIX}/runtime/im-messages/${encodeURIComponent(imMessageId)}/resources/${ordinal}?${query.toString()}`;\n}\nfunction runtimeWebSocketUrl(serverUrl) {\n\tconst url = new URL(HTTP_PATHS.computerRuntimeWebSocket, serverUrl);\n\turl.protocol = url.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n\treturn url.toString();\n}\nfunction runtimeDurableWorkPath(kind, key) {\n\treturn `${RUNTIME_DURABLE_WORK_PATH}/${encodeURIComponent(kind)}/${encodeURIComponent(key)}`;\n}\nconst AGENT_CONTEXT_TREE_TEMPLATE = `${AGENT_BY_ID_TEMPLATE}/context-tree`;\nfunction agentContextTreePath(agentId) {\n\treturn `${agentByIdPath(agentId)}/context-tree`;\n}\nfunction agentSkillsPath(agentId) {\n\treturn `${agentByIdPath(agentId)}/skills`;\n}\nfunction agentSkillPath(agentId, skillId) {\n\treturn `${agentSkillsPath(agentId)}/${encodeURIComponent(skillId)}`;\n}\nfunction agentSkillBundlePath(agentId, skillId) {\n\treturn `${agentSkillPath(agentId, skillId)}/bundle`;\n}\nfunction computerAgentSkillsPath(agentId) {\n\treturn `${API_V1_PREFIX}/computer/agents/${encodeURIComponent(agentId)}/skills`;\n}\nfunction computerAgentSkillBundlePath(agentId, skillId) {\n\treturn `${computerAgentSkillsPath(agentId)}/${encodeURIComponent(skillId)}/bundle`;\n}\nfunction runtimeAgentMcpServerPath(mcpServerId) {\n\treturn `${RUNTIME_AGENT_MCP_SERVERS_PATH}/${encodeURIComponent(mcpServerId)}`;\n}\nfunction runtimeSkillBundlePath(name) {\n\treturn `${RUNTIME_SKILLS_PATH}/${encodeURIComponent(name)}/bundle`;\n}\n//#endregion\n//#region src/runtime-configuration-options.ts\nconst RUNTIME_CONFIGURATION_OPTIONS = {\n\tcodex: {\n\t\tmodelSuggestions: [\n\t\t\t\"gpt-5.6-sol\",\n\t\t\t\"gpt-5.6-terra\",\n\t\t\t\"gpt-5.6-luna\",\n\t\t\t\"gpt-5.3-codex\"\n\t\t],\n\t\treasoningEffortAllowedValues: [\n\t\t\t\"minimal\",\n\t\t\t\"low\",\n\t\t\t\"medium\",\n\t\t\t\"high\",\n\t\t\t\"xhigh\"\n\t\t]\n\t},\n\t\"claude-code\": {\n\t\tmodelSuggestions: [\n\t\t\t\"claude-opus-5\",\n\t\t\t\"claude-sonnet-5\",\n\t\t\t\"claude-haiku-4-5\"\n\t\t],\n\t\treasoningEffortAllowedValues: [\n\t\t\t\"low\",\n\t\t\t\"medium\",\n\t\t\t\"high\",\n\t\t\t\"xhigh\",\n\t\t\t\"max\"\n\t\t]\n\t},\n\tpi: {\n\t\tmodelSuggestions: [\n\t\t\t\"claude-opus-4-7\",\n\t\t\t\"claude-sonnet-4\",\n\t\t\t\"gpt-5.6-sol\"\n\t\t],\n\t\treasoningEffortAllowedValues: [\n\t\t\t\"off\",\n\t\t\t\"minimal\",\n\t\t\t\"low\",\n\t\t\t\"medium\",\n\t\t\t\"high\",\n\t\t\t\"xhigh\",\n\t\t\t\"max\"\n\t\t]\n\t}\n};\nfunction getRuntimeConfigurationOptions(provider) {\n\treturn RUNTIME_CONFIGURATION_OPTIONS[provider];\n}\n//#endregion\n//#region src/sign-in-destination.ts\n/** Where a sign-in lands when it was not asked to land anywhere in particular. */\nconst DEFAULT_SIGN_IN_DESTINATION = \"/agents\";\n/**\n* The single contract for where any sign-in may land.\n*\n* It lives here rather than on the server because the password form navigates the browser itself, while the redirect\n* providers hand their destination to the server. Two implementations of \"is this a local path\" would eventually\n* disagree, and the half that was more permissive would be the one an attacker used.\n*\n* Returns the destination, or `undefined` when it is not an allowed local path — the caller decides whether that is a\n* rejected request or a silent fall back to {@link DEFAULT_SIGN_IN_DESTINATION}.\n*/\nfunction resolveSignInDestination(value) {\n\tconst next = value ?? \"/agents\";\n\tif (next.length > 1024 || next.includes(\"\\\\\") || next.includes(\"#\") || next.startsWith(\"//\") || Array.from(next).some((character) => {\n\t\tconst code = character.charCodeAt(0);\n\t\treturn code < 32 || code === 127;\n\t})) return;\n\tif (/^\\/(?:agents(?:\\/[^?#]*)?|settings(?:\\/[^?#]*)?|login)(?:\\?[^#]*)?$/.test(next)) return next;\n}\n//#endregion\n//#region src/task.ts\nconst TaskStatusSchema = z.enum([\n\t\"queued\",\n\t\"running\",\n\t\"completed\",\n\t\"failed\",\n\t\"cancelled\",\n\t\"expired\",\n\t\"ended\",\n\t\"idle\"\n]);\nconst TaskSessionKindSchema = z.enum([\"channel\", \"thread\"]);\n/** The delivery `reason` a queued message carries once its Account withdrew it before any worker took it. */\nconst TASK_CANCELLED_DELIVERY_REASON = \"cancelled\";\nconst TASK_AUTO_TITLE_MAX_GRAPHEMES = 80;\nconst TASK_TITLE_MAX_LENGTH = 120;\nconst taskTitleSegmenter = new Intl.Segmenter(void 0, { granularity: \"grapheme\" });\nfunction taskTitleLength(value) {\n\tlet length = 0;\n\tfor (const _segment of taskTitleSegmenter.segment(value)) length += 1;\n\treturn length;\n}\nconst TaskTitleSchema = z.string().trim().min(1).refine((value) => taskTitleLength(value) <= 120, { message: `Task title must contain at most 120 characters` });\n/** Manual Task title input. `null` explicitly clears the manual override. */\nconst TaskTitleUpdateRequestSchema = z.object({ title: TaskTitleSchema.nullable() }).strict();\nconst TaskSummarySchema = z.object({\n\tid: z.string().uuid(),\n\tagent: z.object({\n\t\tid: z.string().uuid(),\n\t\tname: z.string().min(1),\n\t\tdisplayName: z.string().min(1),\n\t\truntimeProvider: AgentRuntimeProviderSchema\n\t}).strict(),\n\tsource: z.object({\n\t\tprovider: ImProviderSchema,\n\t\tconversationKind: ImConversationKindSchema,\n\t\tchannelId: z.string().min(1),\n\t\tthreadKey: z.string().min(1).nullable()\n\t}).strict(),\n\tsessionKind: TaskSessionKindSchema,\n\ttitle: TaskTitleSchema,\n\tstatus: TaskStatusSchema,\n\tcreatedAt: z.string().datetime(),\n\tendedAt: z.string().datetime().nullable(),\n\tlastActivityAt: z.string().datetime()\n}).strict();\nconst ListTasksResponseSchema = z.object({\n\ttasks: z.array(TaskSummarySchema),\n\tnextCursor: z.string().min(1).nullable()\n}).strict();\nconst TaskTitleUpdateResponseSchema = z.object({ task: TaskSummarySchema }).strict();\n/**\n* The Task after its queued deliveries were withdrawn. The withdrawal is the topic's latest\n* activity, so the status reads `cancelled` until a later Turn runs in the topic.\n*/\nconst TaskCancelResponseSchema = z.object({ task: TaskSummarySchema }).strict();\n/** Browser-safe attachment metadata; provider resource keys remain on the Server. */\nconst TaskAttachmentSchema = ImResourceDescriptorSchema.omit({ providerResourceKey: true });\nconst TaskTurnSchema = z.object({\n\tdeliveryId: z.string().uuid(),\n\tattention: ImAttentionSchema,\n\tdelivery: z.object({\n\t\tstate: z.enum([\n\t\t\t\"pending\",\n\t\t\t\"accepted\",\n\t\t\t\"steered\",\n\t\t\t\"terminal_rejected\",\n\t\t\t\"expired\"\n\t\t]),\n\t\tisRunning: z.boolean().optional(),\n\t\tattemptCount: z.number().int().nonnegative(),\n\t\tacceptedAt: z.string().datetime().nullable(),\n\t\tsteeredAt: z.string().datetime().nullable(),\n\t\texpiresAt: z.string().datetime(),\n\t\treason: z.string().nullable(),\n\t\tlastErrorCode: z.string().nullable()\n\t}).strict(),\n\tmessage: z.object({\n\t\tid: z.string().uuid(),\n\t\texternalMessageId: z.string().min(1),\n\t\toperation: ImMessageOperationSchema,\n\t\tauthorKind: ImAuthorKindSchema,\n\t\tauthorDisplayName: z.string().nullable(),\n\t\tfallbackText: z.string(),\n\t\tattachments: z.array(TaskAttachmentSchema).max(16).optional(),\n\t\ttruncated: z.boolean(),\n\t\toccurredAt: z.string().datetime()\n\t}).strict(),\n\tabsorbedBy: z.object({\n\t\tdeliveryId: z.string().uuid(),\n\t\tturnId: z.string().min(1)\n\t}).strict().nullable(),\n\treport: z.object({\n\t\tturnId: z.string().min(1),\n\t\toutcome: z.enum([\n\t\t\t\"completed\",\n\t\t\t\"failed\",\n\t\t\t\"cancelled\",\n\t\t\t\"unknown\"\n\t\t]),\n\t\texecutionEffects: z.enum([\n\t\t\t\"not_started\",\n\t\t\t\"may_have_occurred\",\n\t\t\t\"completed\"\n\t\t]),\n\t\tfinalText: z.string().nullable(),\n\t\terrorReason: z.string().nullable(),\n\t\tusage: z.object({\n\t\t\tinputTokens: z.number().int().nonnegative().nullable(),\n\t\t\tcachedInputTokens: z.number().int().nonnegative().nullable(),\n\t\t\toutputTokens: z.number().int().nonnegative().nullable()\n\t\t}).strict().nullable(),\n\t\ttraceSummary: z.object({\n\t\t\tlastSequence: z.number().int().nonnegative(),\n\t\t\tdroppedEvents: z.number().int().nonnegative()\n\t\t}).strict(),\n\t\toutgoingReplies: TurnOutgoingReplySnapshotSchema.nullable(),\n\t\treportedAt: z.string().datetime()\n\t}).strict().nullable()\n}).strict();\n/** When a captured reply's time comes from the platform versus the Server's own observation. */\nconst TaskReplyTimeSourceSchema = z.enum([\"provider\", \"observed\"]);\n/**\n* One confirmed outbound IM message of a Task's scope, captured by the Server provider proxy.\n* The record proves a platform-confirmed send; it is never a runtime summary, a fabricated Turn,\n* or a request body. An empty list says there is no record, not that nothing was sent.\n*/\nconst TaskReplySchema = z.object({\n\tid: z.string().uuid(),\n\tprovider: ImProviderSchema,\n\tchannelId: z.string().min(1),\n\texternalMessageId: z.string().min(1),\n\tauthorKind: ImAuthorKindSchema,\n\tauthorDisplayName: z.string().nullable(),\n\t/** Native message type the platform reported; null on records captured before it was kept. */\n\tmessageType: z.string().min(1).nullable(),\n\t/** False means the send is confirmed but no usable body was captured; never inferred from text. */\n\tcontentAvailable: z.boolean(),\n\tfallbackText: z.string(),\n\tattachments: z.array(TaskAttachmentSchema).max(16).optional(),\n\ttruncated: z.boolean(),\n\toccurredAt: z.string().datetime(),\n\ttimeSource: TaskReplyTimeSourceSchema\n}).strict();\nconst ListTaskRepliesResponseSchema = z.object({\n\titems: z.array(TaskReplySchema),\n\tnextCursor: z.string().min(1).nullable()\n}).strict();\nconst TaskInternalSessionSchema = z.object({\n\tid: z.string().uuid(),\n\tcreatedBySessionId: z.string().uuid(),\n\tcreatedAt: z.string().datetime(),\n\tendedAt: z.string().datetime().nullable(),\n\truntimeModel: z.string().nullable(),\n\truntimeReasoningEffort: z.string().nullable()\n}).strict();\nconst TaskCollaborationMessageSchema = z.object({\n\tid: z.string().uuid(),\n\tsourceSessionId: z.string().uuid(),\n\ttargetSessionId: z.string().uuid(),\n\tcontent: z.string().min(1),\n\toutcome: z.enum([\n\t\t\"unknown\",\n\t\t\"accepted\",\n\t\t\"unreachable\",\n\t\t\"rejected\"\n\t]),\n\tattemptCount: z.number().int().nonnegative(),\n\tlastErrorCode: z.string().nullable(),\n\tcreatedAt: z.string().datetime(),\n\tupdatedAt: z.string().datetime()\n}).strict();\nconst TaskDetailSchema = z.object({\n\ttask: TaskSummarySchema,\n\tturns: z.array(TaskTurnSchema),\n\tinternalSessions: z.array(TaskInternalSessionSchema),\n\tcollaborationMessages: z.array(TaskCollaborationMessageSchema),\n\tnextCursor: z.string().min(1).nullable()\n}).strict();\n//#endregion\nexport { AGENT_MCP_PROBE_TEMPLATE as $, RuntimeProviderProxyReadyFrameSchema as $a, RuntimeProviderReadinessObservationSchema as $c, WEB_FETCH_TIMEOUT_CAP_MS as $d, RUNTIME_MCP_SERVICE as $f, RUNTIME_ID_MAX_BYTES as $g, PROVIDER_READINESS_V1_HEADER as $h, RunnerServerHeartbeatFrameSchema as $i, CreateMCPServerRequestSchema as $l, ImContentBlockSchema as $m, taskRepliesPath as $n, RuntimeDurableWorkListResponseSchema as $o, AgentSetupRuntimeStateSchema as $p, CLOUD_MODEL_CONTEXT_WINDOW_EXTENDED as $r, HeartbeatResultV1FrameSchema as $s, accountComputerDisconnectPath as $t, UpdateMCPServerRequestSchema as $u, ACCOUNT_COMPUTER_CONNECT_CODE_TEMPLATE as A, RuntimeCredentialServerFrameSchema as Aa, RUNTIME_REQUIRED_SERVER_CAPABILITIES as Ac, GitHubRepositoryBindingSchema as Ad, WebSearchParamsSchema as Af, AgentListActivitySchema as Ag, ComputerImCliReadinessCollectionSchema as Ah, RunnerCloudDeliveryReportFrameSchema as Ai, SKILL_MAX_PATH_BYTES as Al, SlackConfigurationResultSchema as Am, agentUsagePath as An, EffectiveRuntimeSnapshotSchema as Ao, AGENT_SETUP_ACTION_KINDS as Ap, STRUCTURED_ERROR_LOG_FIELD_MAX_BYTES as Ar, runtimeUsageTotalTokens as As, MCP_OAUTH_CALLBACK_PATH as At, MCP_ERROR_CODES as Au, ACCOUNT_TASKS_PATH as B, RuntimeGitHubCliMetadataSchema as Ba, RuntimeConnectionIdSchema as Bc, RuntimeExecutionServiceRequestSchema as Bd, parseWebDomain as Bf, AgentUsageDetailSchema as Bg, ImCliReadinessStatusSchema as Bh, RunnerCloudSessionWorkerRequestSchema as Bi, SkillInstallMarkerSchema as Bl, CLOUD_MODEL_OPTIONS_MAX_MODELS as Bm, githubIntegrationRepositoriesPath as Bn, ProviderCliValidationGrantFrameSchema as Bo, AgentCreationRecoveryActionSchema as Bp, StructuredErrorMessageSchema as Br, AuthFrameSchema as Bs, RUNTIME_SESSIONS_PATH as Bt, MCP_OAUTH_OUTCOME_SUCCESS as Bu, ACCOUNT_AGENTS_PATH as C, RuntimeCredentialClientFrameSchema as Ca, RUNTIME_PROVIDER_CLI_VALIDATION_MAX_RETRIES as Cc, GitHubDelegatedImSenderSchema as Cd, WebFetchItemSchema as Cf, AGENT_USAGE_WINDOW_OPTIONS as Cg, ComputerConnectCodeExchangeRequestSchema as Ch, RunnerAuthResultFrameSchema as Ci, SKILL_ERROR_CODES as Cl, ProviderCliHandoffPhaseSchema as Cm, agentSetupRefreshPath as Cn, AgentRuntimeTestCancelFrameSchema as Co, PasswordSchema as Cp, createErrorReport as Cr, computeDirectInputHash as Cs, GITHUB_OAUTH_CALLBACK_PATH as Ct, MCPServerDetailSchema as Cu, ACCOUNT_COMPUTERS_PATH as D, RuntimeCredentialResultSchema as Da, RUNTIME_PROVIDER_READINESS_V2 as Dc, GitHubOAuthFlowPhaseSchema as Dd, WebGatewayFetchRequestSchema as Df, AgentDetailSchema as Dg, ComputerConnectCodeStateSchema as Dh, RunnerCloudDeliveryQueryResultFrameSchema as Di, SKILL_MARKER_FILE as Dl, SLACK_SUBSCRIBED_BOT_EVENTS as Dm, agentSlackEventsPath as Dn, AgentTraceEventSchema as Do, UserDisplayNameSchema as Dp, ErrorPhaseSchema as Dr, computeRuntimeSnapshotHashes as Ds, IM_BINDING_DIAGNOSTICS_TEMPLATE as Dt, MCPToolSnapshotSchema as Du, ACCOUNT_CLOUD_MODELS_PATH as E, RuntimeCredentialRenewRequestSchema as Ea, RUNTIME_PROVIDER_READINESS_V1_PROVIDERS as Ec, GitHubOAuthFlowIntentSchema as Ed, WebFetchResultSchema as Ef, AgentCreationIntentResultSchema as Eg, ComputerConnectCodeModeSchema as Eh, RunnerCloudDeliveryQueryFrameSchema as Ei, SKILL_MANIFEST_FILE as El, SLACK_REQUIRED_BOT_SCOPES as Em, agentSkillsPath as En, AgentTraceBatchSchema as Eo, UpdateUserProfileRequestSchema as Ep, DiagnosticEventSchema as Er, computeRuntimeImSteerInputHash as Es, IM_BINDING_BY_ID_TEMPLATE as Et, MCPServerUrlSchema as Eu, ACCOUNT_SANDBOX_RUNNER_STOP_TEMPLATE as F, RuntimeExecutionOpenResultSchema as Fa, RuntimeCapabilityNameSchema as Fc, GitHubVersionStringSchema as Fd, WebToolErrorEnvelopeSchema as Ff, AgentRuntimeTestFailureCodeSchema as Fg, ComputerProviderReadinessSchema as Fh, RunnerCloudSessionMessageReceivedFrameSchema as Fi, SKILL_UPLOAD_CONTENT_TYPE as Fl, UnbindAgentMessagingRequestSchema as Fm, feishuSetupAttemptPath as Fn, ProviderCliCancelFrameSchema as Fo, AGENT_SETUP_MESSAGING_BLOCKER_CODES as Fp, STRUCTURED_ERROR_SERIALIZATION_MAX_DEPTH as Fr, TurnOutgoingReplyContentSchema as Fs, RUNTIME_AGENT_MCP_SERVER_TEMPLATE as Ft, MCP_MAX_EXTRA_HEADER_VALUE_BYTES as Fu, AGENT_CONTEXT_TREE_TEMPLATE as G, RuntimeProviderCliMetadataSchema as Ga, RuntimeImCliReadinessCollectionSchema as Gc, RUNTIME_WEB_SEARCH_PATH as Gd, MCP_GATEWAY_ERROR_CODES as Gf, ListAgentsResponseSchema as Gg, LocalPreparationCheckSchema as Gh, RunnerHeartbeatFrameSchema as Gi, SKILL_DESCRIPTION_MAX_LENGTH as Gl, SessionPlacementSchema as Gm, runtimeAgentMcpServerPath as Gn, RUNTIME_IM_HISTORY_MAX_BYTES as Go, AgentSetupComputerComponentStatusSchema as Gp, redactForLog as Gr, ComputerRegisterFrameSchema as Gs, SLACK_EVENTS_PATH as Gt, MCP_SUPPORTED_PROTOCOL_VERSIONS as Gu, AGENT_CLOUD_TEMPLATE as H, RuntimeMcpGatewayRejectCodeSchema as Ha, RuntimeFrameEnvelopeSchema as Hc, RuntimeMcpExecutionServiceSchema as Hd, parseWebTimeoutHeader as Hf, AgentUsageWindowDaysSchema as Hg, IntegrationCredentialExecutionStatusSchema as Hh, RunnerCloudWorkerRequestSchema as Hi, SkillSourceSchema as Hl, CloudModelOptionsSchema as Hm, imBindingDisablePath as Hn, ProviderCliValidationRunFrameSchema as Ho, AgentSetupBlockerSchema as Hp, StructuredErrorSchema as Hr, AuthV1FrameSchema as Hs, RUNTIME_SKILLS_PATH as Ht, MCP_PROBE_MAX_TOOLS as Hu, ACCOUNT_SANDBOX_RUNNER_TEMPLATE as I, RuntimeExecutionProviderSchema as Ia, RuntimeCapabilityOffersSchema as Ic, UpdateGitHubConnectionBindingsRequestSchema as Id, WebToolTimeRangeSchema as If, AgentRuntimeTestRequestSchema as Ig, IM_CLI_PROVIDERS as Ih, RunnerCloudSessionMessageRunFrameSchema as Ii, SkillArchiveFormatSchema as Il, hasRequiredFeishuTenantScopes as Im, githubIntegrationAuthorizationPath as In, ProviderCliExpectedIdentitySchema as Io, AGENT_SETUP_REQUIRED_IM_CLI_PROVIDERS as Ip, STRUCTURED_ERROR_SERIALIZATION_MAX_KEYS as Ir, TurnOutgoingReplyMsgTypeSchema as Is, RUNTIME_AGENT_PATH as It, MCP_MODERN_PROTOCOL_VERSION as Iu, AGENT_IM_BINDING_HANDOFF_TEMPLATE as J, RuntimeProviderProxyClientFrameSchema as Ja, RuntimeProtocolRangeSchema as Jc, RouterWebFetchRequestSchema as Jd, MCP_GATEWAY_PATH as Jf, UpdateAgentRequestSchema as Jg, LocalPreparationWarningSchema as Jh, RunnerReadinessSchema as Ji, SkillManifestSchema as Jl, AccountSandboxResponseSchema as Jm, runtimeSkillBundlePath as Jn, RUNTIME_TRACE_BATCH_MAX_EVENTS as Jo, AgentSetupImCliComponentStatusSchema as Jp, AccountSandboxRunnerAcceptanceRequestSchema as Jr, ComputerRegisterResultV2FrameSchema as Js, TASK_CANCEL_TEMPLATE as Jt, MCP_TOOL_NAME_MAX_BYTES as Ju, AGENT_FEISHU_SETUP_ATTEMPTS_TEMPLATE as K, RuntimeProviderProxyAuthFrameSchema as Ka, RuntimeImCliReadinessObservationSchema as Kc, RUNTIME_WEB_SERVICE as Kd, MCP_GATEWAY_MAX_TOOLS as Kf, RebindAgentComputerRequestSchema as Kg, LocalPreparationComponentSchema as Kh, RunnerIdentityWireSchema as Ki, SKILL_MANIFEST_MAX_BYTES as Kl, SessionSchema as Km, runtimeDurableWorkPath as Kn, RUNTIME_IM_RESOURCE_MAX_COUNT as Ko, AgentSetupComputerStateSchema as Kp, redactSensitive as Kr, ComputerRegisterResultFrameSchema as Ks, SLACK_OAUTH_CALLBACK_PATH as Kt, MCP_TOOL_DESCRIPTION_MAX_BYTES as Ku, ACCOUNT_SANDBOX_TEMPLATE as L, RuntimeExecutionSandboxSchema as La, RuntimeCapabilityRangeSchema as Lc, canonicalizeGitHubRepositoryBindings as Ld, capWebTimeoutMs as Lf, AgentRuntimeTestResponseSchema as Lg, INTEGRATION_CREDENTIAL_EXECUTION_REASONS as Lh, RunnerCloudSessionMessageSettledAckFrameSchema as Li, SkillArchiveSha256Schema as Ll, hasRequiredSlackBotScopes as Lm, githubIntegrationBindingsPath as Ln, ProviderCliPrewarmFrameSchema as Lo, AGENT_SETUP_RETURN_SURFACES as Lp, StructuredErrorCategorySchema as Lr, TurnOutgoingReplySchema as Ls, RUNTIME_DURABLE_WORK_PATH as Lt, MCP_OAUTH_ERROR_PARAM as Lu, ACCOUNT_SANDBOXES_PATH as M, RuntimeExecutionClosedResultSchema as Ma, RUNTIME_SUPPORTED_PROTOCOL_VERSIONS as Mc, GitHubRepositoryFullNameSchema as Md, WebSearchResultSchema as Mf, AgentNameSchema as Mg, ComputerKindSchema as Mh, RunnerCloudDeliveryVerifiedFrameSchema as Mi, SKILL_REPLACE_HEADER as Ml, SlackOAuthReturnSurfaceSchema as Mm, computerAgentSkillsPath as Mn, InputRejectReasonSchema as Mo, AGENT_SETUP_CLOUD_COMPONENT_STATUSES as Mp, STRUCTURED_ERROR_MESSAGE_MAX_BYTES as Mr, RUNTIME_OUTGOING_REPLY_RAW_MAX_BYTES as Ms, MCP_SERVER_BY_ID_TEMPLATE as Mt, MCP_LEGACY_PROTOCOL_VERSIONS as Mu, ACCOUNT_SANDBOX_RUNNER_ACCEPTANCE_TEMPLATE as N, RuntimeExecutionOpenRejectCodeSchema as Na, RUNTIME_V0_CAPABILITIES as Nc, GitHubRepositoryPublishModeSchema as Nd, WebToolDepthSchema as Nf, AgentRuntimeConfigSchema as Ng, ComputerPlatformSchema as Nh, RunnerCloudModelGrantSchema as Ni, SKILL_SHA256_HEADER as Nl, StartSlackOAuthRequestSchema as Nm, feishuSetupAttemptCancelPath as Nn, InternalSessionRuntimeOverridesSchema as No, AGENT_SETUP_COMPUTER_COMPONENT_STATUSES as Np, STRUCTURED_ERROR_REQUEST_ID_MAX_BYTES as Nr, RUNTIME_OUTGOING_REPLY_SNAPSHOT_MAX_BYTES as Ns, RUNTIME_AGENT_MCP_SERVERS_AVAILABLE_PATH as Nt, MCP_MAX_EXTRA_HEADERS as Nu, ACCOUNT_COMPUTER_BY_ID_TEMPLATE as O, RuntimeCredentialRevokedCodeSchema as Oa, RUNTIME_PROVIDER_READINESS_V2_PROVIDERS as Oc, GitHubOAuthReturnSurfaceSchema as Od, WebGatewaySearchRequestSchema as Of, AgentDisplayNameSchema as Og, ComputerConnectCodeStatusSchema as Oh, RunnerCloudDeliveryReceivedFrameSchema as Oi, SKILL_MAX_ENTRIES as Ol, SlackBindingActivationSchema as Om, agentSlackOAuthStartPath as On, ClientRuntimeBusinessFrameSchema as Oo, UserProfileSchema as Op, ErrorRetryabilitySchema as Or, computeTurnResultHash as Os, INTERNAL_NAVIGATION_VISIBILITY_PATH as Ot, MCP_ACCOUNT_TOOL_SNAPSHOT_MAX_BYTES as Ou, ACCOUNT_SANDBOX_RUNNER_START_TEMPLATE as P, RuntimeExecutionOpenRequestSchema as Pa, RuntimeCapabilitiesSchema as Pc, GitHubRepositoryRoleSchema as Pd, WebToolErrorCodeSchema as Pf, AgentRuntimeProviderSchema as Pg, ComputerProviderReadinessCollectionSchema as Ph, RunnerCloudSessionMessageCancelFrameSchema as Pi, SKILL_UNPACKED_MAX_BYTES as Pl, StartSlackOAuthResponseSchema as Pm, feishuSetupAttemptCheckPath as Pn, ProviderCliArtifactStatusFrameSchema as Po, AGENT_SETUP_IM_CLI_COMPONENT_STATUSES as Pp, STRUCTURED_ERROR_SERIALIZATION_MAX_ARRAY_ITEMS as Pr, RUNTIME_OUTGOING_REPLY_TEXT_MAX_BYTES as Ps, RUNTIME_AGENT_MCP_SERVERS_PATH as Pt, MCP_MAX_EXTRA_HEADERS_BYTES as Pu, AGENT_MCP_AUTHORIZATION_TEMPLATE as Q, RuntimeProviderProxyOpenFrameSchema as Qa, RuntimeProviderReadinessNegotiationV2Schema as Qc, WEB_FETCH_RESPONSE_MAX_BYTES as Qd, McpGatewayErrorCodeSchema as Qf, RUNTIME_DEFAULT_MAX_DURATION_MS as Qg, PROVIDER_CLI_VALIDATION_RETRY_REASONS as Qh, RunnerServerFrameSchema as Qi, AttachMCPServerRequestSchema as Ql, ImAuthorKindSchema as Qm, taskCancelPath as Qn, RuntimeDurableWorkKindSchema as Qo, AgentSetupRuntimeComponentStatusSchema as Qp, CLOUD_MODEL_CHAT_COMPLETIONS_PATH as Qr, HeartbeatResultFrameSchema as Qs, accountComputerConnectCodePath as Qt, UpdateMCPBindingRequestSchema as Qu, ACCOUNT_SETUP_COMPLETE_PATH as R, RuntimeExecutionSourceSchema as Ra, RuntimeChannelTargetSchema as Rc, githubAgentScopeAllowsTaskDelegation as Rd, deriveWebIdempotencyKey as Rf, AgentStatusSchema as Rg, INTEGRATION_CREDENTIAL_EXECUTION_STATUSES as Rh, RunnerCloudSessionMessageSettledFrameSchema as Ri, SkillDetailSchema as Rl, AgentCloudOverviewQuerySchema as Rm, githubIntegrationDisconnectPath as Rn, ProviderCliPrewarmResultFrameSchema as Ro, AGENT_SETUP_RUNTIME_COMPONENT_STATUSES as Rp, StructuredErrorCauseSchema as Rr, TurnOutgoingReplySnapshotSchema as Rs, RUNTIME_IM_RESOURCE_TEMPLATE as Rt, MCP_OAUTH_OUTCOME_ERROR as Ru, getRuntimeConfigurationOptions as S, RuntimeCredentialAcquireRequestSchema as Sa, RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES as Sc, GitHubDelegatedImSenderIdSchema as Sd, WebFetchItemFailureSchema as Sf, AGENT_USAGE_WINDOW_DAYS as Sg, COMPUTER_RUNTIME_PROVIDER_CAPABILITY as Sh, RunnerAuthFrameSchema as Si, SKILL_ARCHIVE_MAX_BYTES as Sl, ImProviderSchema as Sm, agentSetupPath as Sn, SessionCliSendRequestSchema as So, PASSWORD_MIN_LENGTH as Sp, ErrorReportSourceSchema as Sr, TurnReportResultSchema as Ss, GITHUB_INTEGRATION_REPOSITORIES_PATH as St, MCPServerDescriptionSchema as Su, ACCOUNT_CLOUD_COMPUTER_PATH as T, RuntimeCredentialRejectCodeSchema as Ta, RUNTIME_PROVIDER_READINESS_V1 as Tc, GitHubOAuthContextSchema as Td, WebFetchParamsSchema as Tf, AgentCreationIntentIdSchema as Tg, ComputerConnectCodeIssueResponseSchema as Th, RunnerCloudDeliveryCancelFrameSchema as Ti, SKILL_FORMAT_HEADER as Tl, SLACK_OAUTH_RETURN_SURFACES as Tm, agentSkillPath as Tn, AgentRuntimeTestResultFrameSchema as To, RefreshTokenResponseSchema as Tp, BOUNDED_DIAGNOSTIC_SERIALIZATION_BYTES as Tr, computeRuntimeImMessageSemanticHash as Ts, HTTP_PATHS as Tt, MCPServerSchema as Tu, AGENT_COMPUTER_REBIND_TEMPLATE as U, RuntimeMcpGatewayRequestSchema as Ua, RuntimeHeartbeatIntervalMsSchema as Uc, RuntimeWebExecutionServiceSchema as Ud, webServiceScopeForOperation as Uf, CreateAgentRequestSchema as Ug, LocalComputerPreparationResultSchema as Uh, RunnerCredentialTunnelFrameSchema as Ui, SkillStorageStatusSchema as Ul, CloudSessionSummarySchema as Um, mcpServerPath as Un, RUNTIME_DIRECT_TEXT_MAX_BYTES as Uo, AgentSetupCloudComponentStatusSchema as Up, boundedSerialize as Ur, AuthV2FrameSchema as Us, RUNTIME_SKILL_BUNDLE_TEMPLATE as Ut, MCP_PROBE_MAX_TOOLS_BYTES as Uu, AGENT_BY_ID_TEMPLATE as V, RuntimeGitHubCliRepositorySchema as Va, RuntimeErrorFrameSchema as Vc, RuntimeExecutionServiceSchema as Vd, parseWebTargetUrl as Vf, AgentUsageSummarySchema as Vg, IntegrationCredentialExecutionReasonSchema as Vh, RunnerCloudTurnWorkerRequestSchema as Vi, SkillSchema as Vl, CloudAvailabilitySchema as Vm, imBindingDiagnosticsPath as Vn, ProviderCliValidationResultFrameSchema as Vo, AgentSetupActionSchema as Vp, StructuredErrorPhaseSchema as Vr, AuthResultFrameSchema as Vs, RUNTIME_SESSION_MESSAGES_PATH as Vt, MCP_OAUTH_SERVER_PARAM as Vu, AGENT_CONFIG_TEMPLATE as W, RuntimeMcpGatewayResultSchema as Wa, RuntimeHeartbeatTimeoutMsSchema as Wc, RUNTIME_WEB_FETCH_PATH as Wd, MCP_GATEWAY_ALLOWED_TOOL_RULE as Wf, CreateAgentRuntimeConfigSchema as Wg, LocalPreparationActionSchema as Wh, RunnerCredentialTunnelResultFrameSchema as Wi, UpdateSkillRequestSchema as Wl, SessionKindSchema as Wm, mcpServersPath as Wn, RUNTIME_FINAL_TEXT_MAX_BYTES as Wo, AgentSetupComponentSchema as Wp, redactDiagnostic as Wr, ClientRuntimeFrameSchema as Ws, SANDBOX_RUNNER_WEBSOCKET_PATH as Wt, MCP_RESERVED_HEADER_NAMES as Wu, AGENT_IM_BINDING_UNBIND_TEMPLATE as X, RuntimeProviderProxyEndFrameSchema as Xa, RuntimeProviderReadinessNegotiationSchema as Xc, RuntimeWebServiceScopeSchema as Xd, MCP_GATEWAY_SERVER_NAME as Xf, AGENT_SLUG_MAX_LENGTH as Xg, PROVIDER_CLI_PUBLIC_FAILURE_REASONS as Xh, RunnerServerCredentialFrameSchema as Xi, isReservedSkillName as Xl, ExternalMentionSchema as Xm, sandboxRunnerWebSocketUrl as Xn, RetainedTurnReportClaimSchema as Xo, AgentSetupMessagingStateSchema as Xp, AccountSandboxRunnerStatusResponseSchema as Xr, ComputerRegisterV2FrameSchema as Xs, accountAgentCreationIntentPath as Xt, StartMCPOAuthRequestSchema as Xu, AGENT_IM_BINDING_TEMPLATE as Y, RuntimeProviderProxyCreditFrameSchema as Ya, RuntimeProviderReadinessCollectionSchema as Yc, RouterWebSearchRequestSchema as Yd, MCP_GATEWAY_REQUEST_MAX_BYTES as Yf, UpdateAgentRuntimeConfigSchema as Yg, PROVIDER_CLI_ARTIFACT_PUBLIC_REASONS as Yh, RunnerReadyFrameSchema as Yi, SkillNameSchema as Yl, SandboxLifecycleSchema as Ym, runtimeWebSocketUrl as Yn, RUNTIME_TRACE_EVENT_MAX_BYTES as Yo, AgentSetupMessagingBlockerCodeSchema as Yp, AccountSandboxRunnerAcceptanceResponseSchema as Yr, ComputerRegisterV1FrameSchema as Ys, TASK_REPLIES_TEMPLATE as Yt, SetMCPAuthorizationRequestSchema as Yu, AGENT_MCP_AUTHORIZATION_OAUTH_TEMPLATE as Z, RuntimeProviderProxyErrorFrameSchema as Za, RuntimeProviderReadinessNegotiationV1Schema as Zc, WEB_DOMAIN_MAX_BYTES as Zd, MCP_GATEWAY_TOOL_NAME_MAX_BYTES as Zf, OPENTAG_PLATFORM_INSTRUCTIONS as Zg, PROVIDER_CLI_REASON_V2_HEADER as Zh, RunnerServerErrorFrameSchema as Zi, parseSkillManifest as Zl, ImAttentionSchema as Zm, taskByIdPath as Zn, RuntimeDurableFailureSchema as Zo, AgentSetupReturnSurfaceSchema as Zp, AccountSandboxRunnerStopRequestSchema as Zr, HeartbeatFrameSchema as Zs, accountComputerByIdPath as Zt, StartMCPOAuthResponseSchema as Zu, TaskTitleUpdateRequestSchema as _, RUNTIME_EXECUTION_MAX_LIFETIME_MS as _a, RUNTIME_PROTOCOL_VERSION as _c, GitHubAgentScopeSchema as _d, WEB_TOOL_ERROR_CODES as _f, compareSemVer as _g, AccountComputerConnectCodeCreateRequestSchema as _h, RunnerAcceptanceEvidenceWireSchema as _i, ErrorEnvelopeSchema as _l, ImBindingIdentitySchema as _m, agentMcpProbePath as _n, SessionCliCreateRequestSchema as _o, EmailAddressSchema as _p, ERROR_REPORT_FIELD_MAX_LENGTH as _r, SessionMessageDeliveryResultSchema as _s, FEISHU_SETUP_ATTEMPT_TEMPLATE as _t, MCPProbeResponseSchema as _u, TASK_TITLE_MAX_LENGTH as a, RuntimeModelSchema as a_, PROVIDER_PROXY_AUTH_TIMEOUT_MS as aa, RUNTIME_AGENT_RUNTIME_TEST_TIMEOUT_MS as ac, ContextTreeOperationResultFrameSchema as ad, WEB_LANGUAGE_MAX_CODEPOINTS as af, ProviderReadinessStatusSchema as ag, ImResourceDescriptorSchema as ah, RUNNER_ACCEPTANCE_WORKER_STDIN_MAX_BYTES as ai, ServerWelcomeFrameSchema as al, CreateFeishuSetupAttemptRequestSchema as am, agentByIdPath as an, RuntimeSlackCliMetadataSchema as ao, RUNNER_WORKSPACE_VERSION as ap, GITHUB_OAUTH_OUTCOME_SUCCESS as ar, RuntimeImHistoryItemSchema as as, AGENT_SETUP_TEMPLATE as at, MCPAuthKindSchema as au, DEFAULT_SIGN_IN_DESTINATION as b, RUNTIME_PROXY_TICKET_TTL_MS as ba, RUNTIME_PROVIDER_CLI_REQUIREMENT_OPERATION as bc, GitHubConnectionStatusSchema as bd, WEB_URL_MAX_BYTES as bf, AGENT_RUNTIME_PROVIDERS as bg, CLOUD_IDENTITY_CAPABILITY_HEADER as bh, RunnerAcceptanceResultFrameSchema as bi, RuntimeSkillManifestEntrySchema as bl, ImBindingSummarySchema as bm, agentReactivatePath as bn, SessionCliListResponseSchema as bo, MeResponseSchema as bp, ERROR_REPORT_URL_MAX_LENGTH as br, TurnFailureReasonSchema as bs, GITHUB_INTEGRATION_DISCONNECT_PATH as bt, MCPProtocolEraSchema as bu, TaskCollaborationMessageSchema as c, CONTEXT_TREES_MAX as c_, PROVIDER_PROXY_INITIAL_CREDIT_BYTES as ca, RUNTIME_CLIENT_CAPABILITY_OFFERS as cc, GITHUB_AGENT_SCOPE_MAX_DELEGATED_IM_SENDERS as cd, WEB_REQUEST_MAX_BYTES as cf, providerCliArtifactFailureIsManual as cg, AccountCloudComputerEnsureResponseSchema as ch, RUNNER_PI_CONFIG_DOCUMENT_MAX_BYTES as ci, advertisedProviderReadiness as cl, FeishuSetupActivationReasonSchema as cm, agentConfigPath as cn, RuntimeWebGatewayResultSchema as co, RunnerWorkspaceSealResultFrameSchema as cp, GitHubDiscoveredInstallationSchema as cr, RuntimeImSteerRequestSchema as cs, AGENT_SKILL_TEMPLATE as ct, MCPAuthorizationSummarySchema as cu, TaskReplySchema as d, ContextTreeRepositorySchema as d_, PROVIDER_PROXY_MAX_STREAM_OPENS_PER_CONNECTION as da, RUNTIME_HEARTBEAT_INTERVAL_MIN_MS as dc, GITHUB_OAUTH_RETURN_SURFACES as dd, WEB_SEARCH_LIMIT_MAX as df, requestsProviderCliReasonV2 as dg, AccountSetupResetModeSchema as dh, RUNNER_SESSION_COLLABORATION_VERSION as di, negotiateRuntimeCapabilities as dl, FeishuSetupIntentSchema as dm, agentImBindingConfigPath as dn, SESSION_CLI_DEFAULT_LIMIT as do, AuthProvidersResponseSchema as dp, GitHubIntegrationOverviewSchema as dr, RuntimeRevisionSchema as ds, AGENT_SUSPEND_TEMPLATE as dt, MCPClientRegistrationSourceSchema as du, RUNTIME_INSTRUCTIONS_MAX_BYTES as e_, RunnerWelcomeFrameSchema as ea, HeartbeatResultV2FrameSchema as ec, normalizeExtraHeaders as ed, WEB_FETCH_URLS_MAX as ef, PROVIDER_READINESS_V2_HEADER as eg, ImContentV1Schema as eh, CLOUD_MODEL_CONTEXT_WINDOW_STANDARD as ei, RuntimeProviderReadinessV1ProviderSchema as el, AgentSetupRuntimeUnavailableReasonSchema as em, accountSandboxPath as en, RuntimeProviderProxyResponseFrameSchema as eo, RuntimeMcpServiceScopeSchema as ep, ServerHealthSchema as er, RuntimeDurableWorkRecordSchema as es, AGENT_MCP_SERVERS_TEMPLATE as et, ListAgentMCPServersResponseSchema as eu, TaskReplyTimeSourceSchema as f, ContextTreesSchema as f_, PROVIDER_PROXY_STREAM_REVALIDATE_INTERVAL_MS as fa, RUNTIME_HEARTBEAT_TIMEOUT_MAX_MS as fc, GITHUB_REPOSITORY_BINDINGS_MAX_AGENT_SCOPES as fd, WEB_SEARCH_QUERY_MAX_CODEPOINTS as ff, requestsProviderReadinessV1 as fg, AccountSetupResetRequestSchema as fh, RUNNER_WS_CLOSE as fi, runtimeFrameByteLength as fl, FeishuSetupStateSchema as fm, agentImBindingHandoffPath as fn, SESSION_CLI_MAX_LIMIT as fo, BrowserSessionStatusResponseSchema as fp, GitHubOAuthOutcomeSearchSchema as fr, RuntimeSequenceSchema as fs, AGENT_USAGE_TEMPLATE as ft, MCPCustomAuthHeaderSchema as fu, TaskTitleSchema as g, RUNTIME_CREDENTIAL_PROVIDERS as ga, RUNTIME_PROTOCOL_V2 as gc, GitBranchRefSchema as gd, WEB_TOOLS_PROTOCOL_VERSION as gf, SemVerStringSchema as gg, ListAccountComputersResponseSchema as gh, RunnerAcceptanceEventWireSchema as gi, ErrorDetailSchema as gl, ImBindingHandoffStatusSchema as gm, agentMcpAuthorizationPath as gn, SessionCliCommandStatusSchema as go, ConnectCodeIssueResponseSchema as gp, StartGitHubAuthorizationResponseSchema as gr, SessionMessageDeliveryRequestSchema as gs, FEISHU_SETUP_ATTEMPT_CHECK_TEMPLATE as gt, MCPOverrideSourcesSchema as gu, TaskSummarySchema as h, RUNTIME_CREDENTIAL_CAPABILITY_TTL_MS as ha, RUNTIME_PROTOCOL_V1 as hc, GITHUB_REPOSITORY_BINDINGS_SCHEMA_VERSION as hd, WEB_TIMEOUT_HEADER as hf, SEMVER_PATTERN as hg, InternalNavigationVisibilitySchema as hh, RunnerAcceptanceCancelFrameSchema as hi, ErrorCodeSchema as hl, ImBindingDiagnosticsSchema as hm, agentMcpAuthorizationOAuthPath as hn, SessionCliCommandResponseSchema as ho, ConnectCodeIssueRequestSchema as hp, StartGitHubAuthorizationRequestSchema as hr, ServerRuntimeBusinessFrameSchema as hs, COMPUTER_AGENT_SKILL_BUNDLE_TEMPLATE as ht, MCPOAuthOutcomeSearchSchema as hu, TASK_CANCELLED_DELIVERY_REASON as i, RuntimeMaxDurationMsSchema as i_, FEISHU_TENANT_TOKEN_LOCAL_SENTINEL as ia, RUNTIME_AGENT_RUNTIME_TEST_MAX_PENDING as ic, ContextTreeOperationResponseSchema as id, WEB_IDEMPOTENCY_NAMESPACE as if, ProviderCliValidationRetryReasonSchema as ig, ImOutboundContentMetaSchema as ih, RUNNER_ACCEPTANCE_PROVIDER as ii, ServerRuntimeFrameSchema as il, projectAgentSetupComponents as im, accountSandboxRunnerStopPath as in, RuntimeProxyTicketResultSchema as io, RUNNER_WORKSPACE_TIMEOUT_MS as ip, GITHUB_OAUTH_OUTCOME_PARAM as ir, RuntimeImDeliveryContentSchema as is, AGENT_SETUP_REFRESH_TEMPLATE as it, MCPAuthHeaderNameSchema as iu, ACCOUNT_COMPUTER_DISCONNECT_TEMPLATE as j, RuntimeExecutionCloseRequestSchema as ja, RUNTIME_SERVER_CAPABILITY_OFFERS as jc, GitHubRepositoryBindingsSchema as jd, WebSearchResultItemSchema as jf, AgentListItemSchema as jg, ComputerImCliReadinessSchema as jh, RunnerCloudDeliveryRunFrameSchema as ji, SKILL_MAX_PER_AGENT as jl, SlackIdentityClosureSchema as jm, computerAgentSkillBundlePath as jn, ImMessageDeliveryResultSchema as jo, AGENT_SETUP_BLOCKER_CODES as jp, STRUCTURED_ERROR_MAX_CAUSE_DEPTH as jr, RUNTIME_OUTGOING_REPLY_MAX_COUNT as js, MCP_SERVERS_PATH as jt, MCP_ERROR_CODE_METADATA as ju, ACCOUNT_COMPUTER_CONNECT_CODES_PATH as k, RuntimeCredentialRevokedFrameSchema as ka, RUNTIME_REQUIRED_CLIENT_CAPABILITIES as kc, GitHubRepositoryAccessSchema as kd, WebSearchExecutionRequestSchema as kf, AgentInstructionsSchema as kg, ComputerConnectionStatusSchema as kh, RunnerCloudDeliveryReportAckFrameSchema as ki, SKILL_MAX_LISTED_FILES as kl, SlackConfigurationIntentSchema as km, agentSuspendPath as kn, DirectImMessageDeliveryRequestSchema as ko, AGENT_CREATION_RECOVERY_ACTIONS as kp, RetryabilitySchema as kr, hashTuple as ks, MCP_CLIENT_METADATA_PATH as kt, MCP_AUTH_KINDS as ku, TaskDetailSchema as l, ContextTreeAliasSchema as l_, PROVIDER_PROXY_MAX_FRAME_BYTES as la, RUNTIME_CLIENT_CAPABILITY_TTL_MS as lc, GITHUB_AGENT_SCOPE_MAX_DELEGATED_SESSION_AGENTS as ld, WEB_SEARCH_DOMAINS_MAX as lf, publicProviderCliArtifactReason as lg, AccountComputerSummarySchema as lh, RUNNER_PI_CONFIG_DOCUMENT_MAX_CHARS as li, missingRuntimeCapabilities as ll, FeishuSetupActivationSchema as lm, agentContextTreePath as ln, decodeProviderProxyDataFrame as lo, ChannelNameSchema as lp, GitHubDiscoveredRepositorySchema as lr, RuntimeImSteerResultSchema as ls, AGENT_SLACK_EVENTS_TEMPLATE as lt, MCPAvailableServerSchema as lu, TaskStatusSchema as m, RUNTIME_CREDENTIAL_CAPABILITY_REFRESH_AFTER_MS as ma, RUNTIME_MAX_FRAME_BYTES as mc, GITHUB_REPOSITORY_BINDINGS_MAX_REPOSITORIES as md, WEB_SEARCH_TIMEOUT_CAP_MS as mf, withComputerRuntimeProviderSupport as mg, CompleteAccountSetupRequestSchema as mh, RUNNER_WS_PROTOCOL_VERSION as mi, ErrorCategorySchema as ml, ImBindingCredentialStatusSchema as mm, agentImBindingUnbindPath as mn, SESSION_CLI_TASK_PREVIEW_MAX_BYTES as mo, ConnectCodeExchangeResponseSchema as mp, GitHubRepositoryDiscoveryQuerySchema as mr, RuntimeUsageSchema as ms, COMPUTER_AGENT_SKILLS_TEMPLATE as mt, MCPExtraHeadersSchema as mu, ListTasksResponseSchema as n, RuntimeInstructionSchema as n_, serializeRunnerCloudSessionWorkerStdin as na, HeartbeatV2FrameSchema as nc, ContextTreeOperationFrameSchema as nd, WEB_GATEWAY_SEARCH_PATH as nf, ProviderCliPublicFailureReasonSchema as ng, ImMessageDirectionSchema as nh, CLOUD_MODEL_PROXY_PATH as ni, RuntimeRequestIdSchema as nl, AgentSetupSnapshotSchema as nm, accountSandboxRunnerPath as nn, RuntimeProxyTicketRejectCodeSchema as no, RUNNER_WORKSPACE_ARCHIVE_MAX_BYTES as np, GITHUB_OAUTH_ERROR_PARAM as nr, RuntimeImCredentialGrantRequestSchema as ns, AGENT_REACTIVATE_TEMPLATE as nt, ListMCPServersResponseSchema as nu, TaskAttachmentSchema as o, RuntimeReasoningEffortSchema as o_, PROVIDER_PROXY_CHUNK_MAX_BYTES as oa, RUNTIME_AGENT_RUNTIME_TEST_TTL_MS as oc, BeginGitHubAuthorizationRequestSchema as od, WEB_PAGE_BODY_MAX_BYTES as of, classifyProviderCliArtifactFailure as og, NormalizedInboundImEventSchema as oh, RUNNER_CLOUD_DELIVERY_VERSION as oi, ServerWelcomeV1FrameSchema as ol, FEISHU_REQUIRED_TENANT_SCOPES as om, agentCloudPath as on, RuntimeWebGatewayRejectCodeSchema as oo, RunnerWorkspaceObjectSchema as op, GITHUB_REPOSITORY_DISCOVERY_MAX_INSTALLATIONS as or, RuntimeImOutboxContextSchema as os, AGENT_SKILLS_TEMPLATE as ot, MCPAuthSchemeSchema as ou, TaskSessionKindSchema as p, normalizeContextTrees as p_, RUNTIME_CLI_METADATA_MAX_REPOSITORIES as pa, RUNTIME_HEARTBEAT_TIMEOUT_MIN_MS as pc, GITHUB_REPOSITORY_BINDINGS_MAX_BYTES as pd, WEB_SEARCH_RESPONSE_MAX_BYTES as pf, requestsProviderReadinessV2 as pg, COMPUTER_ACCESS_CAPABILITY_HEADER as ph, RUNNER_WS_MAX_FRAME_BYTES as pi, runtimeNegotiatedCapabilitiesEqual as pl, ImBindingAdminDetailSchema as pm, agentImBindingPath as pn, SESSION_CLI_PROOF_HEADER as po, ConnectCodeExchangeRequestSchema as pp, GitHubRepositoryDiscoveryPageSchema as pr, RuntimeSha256Schema as ps, API_V1_PREFIX as pt, MCPEffectiveConfigSchema as pu, AGENT_IM_BINDING_CONFIG_TEMPLATE as q, RuntimeProviderProxyCancelFrameSchema as qa, RuntimeNegotiatedCapabilitiesSchema as qc, RouterGatewayErrorSchema as qd, MCP_GATEWAY_NAME_SEPARATOR as qf, ReceiveModeSchema as qg, LocalPreparationStatusSchema as qh, RunnerPiConfigInputSchema as qi, SKILL_RESERVED_NAMES as ql, AccountSandboxEnsureRequestSchema as qm, runtimeImResourcePath as qn, RUNTIME_MVP_RETAINED_REPORT_LIMIT as qo, AgentSetupExpectedMessagingStateSchema as qp, serializeDiagnostic as qr, ComputerRegisterResultV1FrameSchema as qs, TASK_BY_ID_TEMPLATE as qt, MCP_TOOL_INPUT_SCHEMA_MAX_BYTES as qu, TASK_AUTO_TITLE_MAX_GRAPHEMES as r, RuntimeInstructionsSchema as r_, serializeRunnerCloudTurnWorkerStdin as ra, RUNTIME_AGENT_RUNTIME_TEST_CLEANUP_MS as rc, ContextTreeOperationRequestSchema as rd, WEB_IDEMPOTENCY_KEY_MAX_BYTES as rf, ProviderCliValidationResultReasonSchema as rg, ImMessageOperationSchema as rh, RUNNER_ACCEPTANCE_MODES as ri, RuntimeRequiredCapabilitiesSchema as rl, AgentSetupStageSchema as rm, accountSandboxRunnerStartPath as rn, RuntimeProxyTicketRequestSchema as ro, RUNNER_WORKSPACE_PATH as rp, GITHUB_OAUTH_OUTCOME_ERROR as rr, RuntimeImCredentialGrantResultSchema as rs, AGENT_RUNTIME_TEST_TEMPLATE as rt, MCPAgentServerSchema as ru, TaskCancelResponseSchema as s, renderPlatformInstructions as s_, PROVIDER_PROXY_HEADER_MAX_BYTES as sa, RUNTIME_CAPABILITY as sc, CreateGitHubConnectionRequestSchema as sd, WEB_PUBLISHED_AT_MAX_BYTES as sf, clientSupportsComputerRuntimeProvider as sg, ProviderInboundContextSchema as sh, RUNNER_CLOUD_TURN_WORKER_STDIN_MAX_BYTES as si, ServerWelcomeV2FrameSchema as sl, FEISHU_SETUP_ACTIVATION_REASONS as sm, agentComputerRebindPath as sn, RuntimeWebGatewayRequestSchema as so, RunnerWorkspaceSealFrameSchema as sp, GITHUB_REPOSITORY_DISCOVERY_PAGE_SIZE as sr, RuntimeImResourceReferenceSchema as ss, AGENT_SKILL_BUNDLE_TEMPLATE as st, MCPAuthorizationStatusSchema as su, ListTaskRepliesResponseSchema as t, RUNTIME_MAX_DURATION_MS as t_, serializeRunnerAcceptanceWorkerStdin as ta, HeartbeatV1FrameSchema as tc, probedServerDescription as td, WEB_GATEWAY_FETCH_PATH as tf, ProviderCliArtifactPublicReasonSchema as tg, ImConversationKindSchema as th, CLOUD_MODEL_OUTPUT_TOKEN_LIMIT as ti, RuntimeProviderReadinessV2ProviderSchema as tl, AgentSetupSlackOAuthContextSchema as tm, accountSandboxRunnerAcceptancePath as tn, RuntimeProviderProxyServerFrameSchema as to, composeGatewayToolName as tp, GITHUB_MANAGEMENT_ERROR_CODES as tr, RuntimeDurableWorkStatusSchema as ts, AGENT_MCP_SERVER_TEMPLATE as tt, ListAvailableMCPServersResponseSchema as tu, TaskInternalSessionSchema as u, ContextTreeConnectionSchema as u_, PROVIDER_PROXY_MAX_STREAMS_PER_EXECUTION as ua, RUNTIME_HEARTBEAT_INTERVAL_MAX_MS as uc, GITHUB_CONNECTION_ERROR_CODES as ud, WEB_SEARCH_LIMIT_DEFAULT as uf, requestsCloudIdentityV1 as ug, AccountSetupCompletionSchema as uh, RUNNER_REUSE_VERSION as ui, negotiateProviderReadinessFromHeaders as ul, FeishuSetupAttemptSchema as um, agentFeishuSetupAttemptsPath as un, encodeProviderProxyDataFrame as uo, AuthIdentityProviderSchema as up, GitHubIntegrationAvailabilitySchema as ur, RuntimeProviderMessageRefSchema as us, AGENT_SLACK_OAUTH_START_TEMPLATE as ut, MCPBindingOverridesSchema as uu, TaskTitleUpdateResponseSchema as v, RUNTIME_PROVIDER_ORIGIN_HEADER as va, RUNTIME_PROVIDER_CLI_ARTIFACT_TTL_MS as vc, GitHubAgentScopeTaskDelegationSchema as vd, WEB_TOOL_PREVIEW_PAGE_MAX_BYTES as vf, isSemVer as vg, AccountComputerConnectCodeIssueRequestSchema as vh, RunnerAcceptanceModeSchema as vi, ValidationIssueSchema as vl, ImBindingMessagingExpectationSchema as vm, agentMcpServerPath as vn, SessionCliListItemSchema as vo, EmailSignInRequestSchema as vp, ERROR_REPORT_MESSAGE_MAX_LENGTH as vr, SessionReconcileRequestSchema as vs, GITHUB_INTEGRATION_AUTHORIZATION_PATH as vt, MCPProbeSnapshotSchema as vu, ACCOUNT_AGENT_CREATION_INTENT_TEMPLATE as w, RuntimeCredentialProviderSchema as wa, RUNTIME_PROVIDER_CLI_VALIDATION_TIMEOUT_MS as wc, GitHubLoginSessionHashSchema as wd, WebFetchItemSuccessSchema as wf, AgentAdminConfigSchema as wg, ComputerConnectCodeExchangeResponseSchema as wh, RunnerClientFrameSchema as wi, SKILL_ERROR_CODE_METADATA as wl, ProviderCliHandoffProgressSchema as wm, agentSkillBundlePath as wn, AgentRuntimeTestRequestFrameSchema as wo, RefreshTokenRequestSchema as wp, sanitizeErrorReportUrl as wr, computeReconcilePayloadHash as ws, GITHUB_WEBHOOK_PATH as wt, MCPServerNameSchema as wu, resolveSignInDestination as x, RUNTIME_VALIDATION_RUN_TTL_MS as xa, RUNTIME_PROVIDER_CLI_VALIDATION_GRANT_TTL_MS as xc, GitHubDecimalIdSchema as xd, WebFetchExecutionRequestSchema as xf, AGENT_RUNTIME_TEST_FAILURE_CODES as xg, CLOUD_IDENTITY_CAPABILITY_VERSION as xh, RunnerAcceptanceRunFrameSchema as xi, RuntimeSkillManifestSchema as xl, ImBindingUnbindRequiredDetailSchema as xm, agentRuntimeTestPath as xn, SessionCliProofGrantSchema as xo, PASSWORD_MAX_LENGTH as xp, ErrorReportRequestSchema as xr, TurnReportRequestSchema as xs, GITHUB_INTEGRATION_PATH as xt, MCPServerAgentSchema as xu, TaskTurnSchema as y, RUNTIME_PROVIDER_PROXY_PATH as ya, RUNTIME_PROVIDER_CLI_CREDENTIAL_TTL_MS as yc, GitHubConnectionStateSchema as yd, WEB_TOOL_RESULT_MAX_BYTES as yf, parseSemVer as yg, AccountComputerConnectCodeRepairRequestSchema as yh, RunnerAcceptanceReportWireSchema as yi, ListAgentSkillsResponseSchema as yl, ImBindingStateSchema as ym, agentMcpServersPath as yn, SessionCliListQuerySchema as yo, EmailSignUpRequestSchema as yp, ERROR_REPORT_STACK_MAX_LENGTH as yr, SessionReconcileResultSchema as ys, GITHUB_INTEGRATION_BINDINGS_PATH as yt, MCPProbeStateSchema as yu, ACCOUNT_SETUP_RESET_PATH as z, RuntimeFeishuCliMetadataSchema as za, RuntimeClientCapabilitiesSchema as zc, isValidGitRefName as zd, normalizeWebTargetUrl as zf, AgentSummarySchema as zg, ImCliProviderSchema as zh, RunnerCloudSessionMessageVerifiedFrameSchema as zi, SkillFileEntrySchema as zl, AgentCloudOverviewSchema as zm, githubIntegrationPath as zn, ProviderCliRequirementFrameSchema as zo, AGENT_SETUP_STAGES as zp, StructuredErrorCodeSchema as zr, TurnOutgoingReplyUnavailableReasonSchema as zs, RUNTIME_INTERNAL_SESSIONS_PATH as zt, MCP_OAUTH_OUTCOME_PARAM as zu };\n\n//# sourceMappingURL=task-BXtm5kVZ.mjs.map","import { $ as AGENT_MCP_PROBE_TEMPLATE, $a as RuntimeProviderProxyReadyFrameSchema, $c as RuntimeProviderReadinessObservationSchema, $d as WEB_FETCH_TIMEOUT_CAP_MS, $f as RUNTIME_MCP_SERVICE, $g as RUNTIME_ID_MAX_BYTES, $h as PROVIDER_READINESS_V1_HEADER, $i as RunnerServerHeartbeatFrameSchema, $l as CreateMCPServerRequestSchema, $m as ImContentBlockSchema, $n as taskRepliesPath, $o as RuntimeDurableWorkListResponseSchema, $p as AgentSetupRuntimeStateSchema, $r as CLOUD_MODEL_CONTEXT_WINDOW_EXTENDED, $t as accountComputerDisconnectPath, $u as UpdateMCPServerRequestSchema, A as ACCOUNT_COMPUTER_CONNECT_CODE_TEMPLATE, Aa as RuntimeCredentialServerFrameSchema, Ac as RUNTIME_REQUIRED_SERVER_CAPABILITIES, Ad as GitHubRepositoryBindingSchema, Af as WebSearchParamsSchema, Ag as AgentListActivitySchema, Ah as ComputerImCliReadinessCollectionSchema, Ai as RunnerCloudDeliveryReportFrameSchema, Al as SKILL_MAX_PATH_BYTES, Am as SlackConfigurationResultSchema, An as agentUsagePath, Ao as EffectiveRuntimeSnapshotSchema, Ap as AGENT_SETUP_ACTION_KINDS, Ar as STRUCTURED_ERROR_LOG_FIELD_MAX_BYTES, As as runtimeUsageTotalTokens, At as MCP_OAUTH_CALLBACK_PATH, Au as MCP_ERROR_CODES, B as ACCOUNT_TASKS_PATH, Ba as RuntimeGitHubCliMetadataSchema, Bc as RuntimeConnectionIdSchema, Bd as RuntimeExecutionServiceRequestSchema, Bf as parseWebDomain, Bg as AgentUsageDetailSchema, Bh as ImCliReadinessStatusSchema, Bi as RunnerCloudSessionWorkerRequestSchema, Bl as SkillInstallMarkerSchema, Bm as CLOUD_MODEL_OPTIONS_MAX_MODELS, Bn as githubIntegrationRepositoriesPath, Bo as ProviderCliValidationGrantFrameSchema, Bp as AgentCreationRecoveryActionSchema, Br as StructuredErrorMessageSchema, Bs as AuthFrameSchema, Bu as MCP_OAUTH_OUTCOME_SUCCESS, C as ACCOUNT_AGENTS_PATH, Ca as RuntimeCredentialClientFrameSchema, Cc as RUNTIME_PROVIDER_CLI_VALIDATION_MAX_RETRIES, Cd as GitHubDelegatedImSenderSchema, Cf as WebFetchItemSchema, Cg as AGENT_USAGE_WINDOW_OPTIONS, Ch as ComputerConnectCodeExchangeRequestSchema, Ci as RunnerAuthResultFrameSchema, Cl as SKILL_ERROR_CODES, Cm as ProviderCliHandoffPhaseSchema, Cn as agentSetupRefreshPath, Co as AgentRuntimeTestCancelFrameSchema, Cp as PasswordSchema, Cr as createErrorReport, Cs as computeDirectInputHash, Ct as GITHUB_OAUTH_CALLBACK_PATH, Cu as MCPServerDetailSchema, D as ACCOUNT_COMPUTERS_PATH, Da as RuntimeCredentialResultSchema, Dc as RUNTIME_PROVIDER_READINESS_V2, Dd as GitHubOAuthFlowPhaseSchema, Df as WebGatewayFetchRequestSchema, Dg as AgentDetailSchema, Dh as ComputerConnectCodeStateSchema, Di as RunnerCloudDeliveryQueryResultFrameSchema, Dl as SKILL_MARKER_FILE, Dm as SLACK_SUBSCRIBED_BOT_EVENTS, Dn as agentSlackEventsPath, Do as AgentTraceEventSchema, Dp as UserDisplayNameSchema, Dr as ErrorPhaseSchema, Ds as computeRuntimeSnapshotHashes, Dt as IM_BINDING_DIAGNOSTICS_TEMPLATE, Du as MCPToolSnapshotSchema, E as ACCOUNT_CLOUD_MODELS_PATH, Ea as RuntimeCredentialRenewRequestSchema, Ec as RUNTIME_PROVIDER_READINESS_V1_PROVIDERS, Ed as GitHubOAuthFlowIntentSchema, Ef as WebFetchResultSchema, Eg as AgentCreationIntentResultSchema, Eh as ComputerConnectCodeModeSchema, Ei as RunnerCloudDeliveryQueryFrameSchema, El as SKILL_MANIFEST_FILE, Em as SLACK_REQUIRED_BOT_SCOPES, En as agentSkillsPath, Eo as AgentTraceBatchSchema, Ep as UpdateUserProfileRequestSchema, Er as DiagnosticEventSchema, Es as computeRuntimeImSteerInputHash, Et as IM_BINDING_BY_ID_TEMPLATE, Eu as MCPServerUrlSchema, F as ACCOUNT_SANDBOX_RUNNER_STOP_TEMPLATE, Fa as RuntimeExecutionOpenResultSchema, Fd as GitHubVersionStringSchema, Ff as WebToolErrorEnvelopeSchema, Fg as AgentRuntimeTestFailureCodeSchema, Fh as ComputerProviderReadinessSchema, Fi as RunnerCloudSessionMessageReceivedFrameSchema, Fl as SKILL_UPLOAD_CONTENT_TYPE, Fm as UnbindAgentMessagingRequestSchema, Fn as feishuSetupAttemptPath, Fo as ProviderCliCancelFrameSchema, Fp as AGENT_SETUP_MESSAGING_BLOCKER_CODES, Fr as STRUCTURED_ERROR_SERIALIZATION_MAX_DEPTH, Fs as TurnOutgoingReplyContentSchema, Ft as RUNTIME_AGENT_MCP_SERVER_TEMPLATE, Fu as MCP_MAX_EXTRA_HEADER_VALUE_BYTES, G as AGENT_CONTEXT_TREE_TEMPLATE, Ga as RuntimeProviderCliMetadataSchema, Gc as RuntimeImCliReadinessCollectionSchema, Gd as RUNTIME_WEB_SEARCH_PATH, Gf as MCP_GATEWAY_ERROR_CODES, Gg as ListAgentsResponseSchema, Gh as LocalPreparationCheckSchema, Gi as RunnerHeartbeatFrameSchema, Gl as SKILL_DESCRIPTION_MAX_LENGTH, Gm as SessionPlacementSchema, Gn as runtimeAgentMcpServerPath, Go as RUNTIME_IM_HISTORY_MAX_BYTES, Gp as AgentSetupComputerComponentStatusSchema, Gr as redactForLog, Gs as ComputerRegisterFrameSchema, Gt as SLACK_EVENTS_PATH, Gu as MCP_SUPPORTED_PROTOCOL_VERSIONS, H as AGENT_CLOUD_TEMPLATE, Ha as RuntimeMcpGatewayRejectCodeSchema, Hc as RuntimeFrameEnvelopeSchema, Hd as RuntimeMcpExecutionServiceSchema, Hf as parseWebTimeoutHeader, Hg as AgentUsageWindowDaysSchema, Hh as IntegrationCredentialExecutionStatusSchema, Hi as RunnerCloudWorkerRequestSchema, Hl as SkillSourceSchema, Hm as CloudModelOptionsSchema, Hn as imBindingDisablePath, Ho as ProviderCliValidationRunFrameSchema, Hp as AgentSetupBlockerSchema, Hr as StructuredErrorSchema, Hs as AuthV1FrameSchema, Ht as RUNTIME_SKILLS_PATH, Hu as MCP_PROBE_MAX_TOOLS, I as ACCOUNT_SANDBOX_RUNNER_TEMPLATE, Ia as RuntimeExecutionProviderSchema, Ic as RuntimeCapabilityOffersSchema, Id as UpdateGitHubConnectionBindingsRequestSchema, If as WebToolTimeRangeSchema, Ig as AgentRuntimeTestRequestSchema, Ih as IM_CLI_PROVIDERS, Ii as RunnerCloudSessionMessageRunFrameSchema, Il as SkillArchiveFormatSchema, Im as hasRequiredFeishuTenantScopes, In as githubIntegrationAuthorizationPath, Io as ProviderCliExpectedIdentitySchema, Ip as AGENT_SETUP_REQUIRED_IM_CLI_PROVIDERS, Ir as STRUCTURED_ERROR_SERIALIZATION_MAX_KEYS, Is as TurnOutgoingReplyMsgTypeSchema, It as RUNTIME_AGENT_PATH, Iu as MCP_MODERN_PROTOCOL_VERSION, J as AGENT_IM_BINDING_HANDOFF_TEMPLATE, Ja as RuntimeProviderProxyClientFrameSchema, Jc as RuntimeProtocolRangeSchema, Jd as RouterWebFetchRequestSchema, Jf as MCP_GATEWAY_PATH, Jg as UpdateAgentRequestSchema, Ji as RunnerReadinessSchema, Jl as SkillManifestSchema, Jm as AccountSandboxResponseSchema, Jn as runtimeSkillBundlePath, Jo as RUNTIME_TRACE_BATCH_MAX_EVENTS, Jp as AgentSetupImCliComponentStatusSchema, Jr as AccountSandboxRunnerAcceptanceRequestSchema, Jt as TASK_CANCEL_TEMPLATE, Ju as MCP_TOOL_NAME_MAX_BYTES, K as AGENT_FEISHU_SETUP_ATTEMPTS_TEMPLATE, Ka as RuntimeProviderProxyAuthFrameSchema, Kc as RuntimeImCliReadinessObservationSchema, Kd as RUNTIME_WEB_SERVICE, Kf as MCP_GATEWAY_MAX_TOOLS, Kg as RebindAgentComputerRequestSchema, Kh as LocalPreparationComponentSchema, Ki as RunnerIdentityWireSchema, Kl as SKILL_MANIFEST_MAX_BYTES, Km as SessionSchema, Kn as runtimeDurableWorkPath, Ko as RUNTIME_IM_RESOURCE_MAX_COUNT, Kp as AgentSetupComputerStateSchema, Kr as redactSensitive, Ks as ComputerRegisterResultFrameSchema, Kt as SLACK_OAUTH_CALLBACK_PATH, Ku as MCP_TOOL_DESCRIPTION_MAX_BYTES, L as ACCOUNT_SANDBOX_TEMPLATE, La as RuntimeExecutionSandboxSchema, Lc as RuntimeCapabilityRangeSchema, Ld as canonicalizeGitHubRepositoryBindings, Lf as capWebTimeoutMs, Lg as AgentRuntimeTestResponseSchema, Lh as INTEGRATION_CREDENTIAL_EXECUTION_REASONS, Li as RunnerCloudSessionMessageSettledAckFrameSchema, Ll as SkillArchiveSha256Schema, Lm as hasRequiredSlackBotScopes, Ln as githubIntegrationBindingsPath, Lo as ProviderCliPrewarmFrameSchema, Lp as AGENT_SETUP_RETURN_SURFACES, Lr as StructuredErrorCategorySchema, Ls as TurnOutgoingReplySchema, Lt as RUNTIME_DURABLE_WORK_PATH, Lu as MCP_OAUTH_ERROR_PARAM, M as ACCOUNT_SANDBOXES_PATH, Ma as RuntimeExecutionClosedResultSchema, Mc as RUNTIME_SUPPORTED_PROTOCOL_VERSIONS, Md as GitHubRepositoryFullNameSchema, Mf as WebSearchResultSchema, Mg as AgentNameSchema, Mh as ComputerKindSchema, Mi as RunnerCloudDeliveryVerifiedFrameSchema, Ml as SKILL_REPLACE_HEADER, Mm as SlackOAuthReturnSurfaceSchema, Mn as computerAgentSkillsPath, Mo as InputRejectReasonSchema, Mp as AGENT_SETUP_CLOUD_COMPONENT_STATUSES, Mr as STRUCTURED_ERROR_MESSAGE_MAX_BYTES, Ms as RUNTIME_OUTGOING_REPLY_RAW_MAX_BYTES, Mt as MCP_SERVER_BY_ID_TEMPLATE, Mu as MCP_LEGACY_PROTOCOL_VERSIONS, N as ACCOUNT_SANDBOX_RUNNER_ACCEPTANCE_TEMPLATE, Na as RuntimeExecutionOpenRejectCodeSchema, Nc as RUNTIME_V0_CAPABILITIES, Nd as GitHubRepositoryPublishModeSchema, Nf as WebToolDepthSchema, Ng as AgentRuntimeConfigSchema, Nh as ComputerPlatformSchema, Ni as RunnerCloudModelGrantSchema, Nl as SKILL_SHA256_HEADER, Nm as StartSlackOAuthRequestSchema, Nn as feishuSetupAttemptCancelPath, No as InternalSessionRuntimeOverridesSchema, Np as AGENT_SETUP_COMPUTER_COMPONENT_STATUSES, Nr as STRUCTURED_ERROR_REQUEST_ID_MAX_BYTES, Ns as RUNTIME_OUTGOING_REPLY_SNAPSHOT_MAX_BYTES, Nt as RUNTIME_AGENT_MCP_SERVERS_AVAILABLE_PATH, Nu as MCP_MAX_EXTRA_HEADERS, O as ACCOUNT_COMPUTER_BY_ID_TEMPLATE, Oa as RuntimeCredentialRevokedCodeSchema, Oc as RUNTIME_PROVIDER_READINESS_V2_PROVIDERS, Od as GitHubOAuthReturnSurfaceSchema, Of as WebGatewaySearchRequestSchema, Og as AgentDisplayNameSchema, Oh as ComputerConnectCodeStatusSchema, Oi as RunnerCloudDeliveryReceivedFrameSchema, Ol as SKILL_MAX_ENTRIES, Om as SlackBindingActivationSchema, On as agentSlackOAuthStartPath, Oo as ClientRuntimeBusinessFrameSchema, Op as UserProfileSchema, Or as ErrorRetryabilitySchema, Os as computeTurnResultHash, Ou as MCP_ACCOUNT_TOOL_SNAPSHOT_MAX_BYTES, P as ACCOUNT_SANDBOX_RUNNER_START_TEMPLATE, Pa as RuntimeExecutionOpenRequestSchema, Pc as RuntimeCapabilitiesSchema, Pd as GitHubRepositoryRoleSchema, Pf as WebToolErrorCodeSchema, Pg as AgentRuntimeProviderSchema, Ph as ComputerProviderReadinessCollectionSchema, Pi as RunnerCloudSessionMessageCancelFrameSchema, Pl as SKILL_UNPACKED_MAX_BYTES, Pm as StartSlackOAuthResponseSchema, Pn as feishuSetupAttemptCheckPath, Po as ProviderCliArtifactStatusFrameSchema, Pp as AGENT_SETUP_IM_CLI_COMPONENT_STATUSES, Pr as STRUCTURED_ERROR_SERIALIZATION_MAX_ARRAY_ITEMS, Ps as RUNTIME_OUTGOING_REPLY_TEXT_MAX_BYTES, Pt as RUNTIME_AGENT_MCP_SERVERS_PATH, Pu as MCP_MAX_EXTRA_HEADERS_BYTES, Q as AGENT_MCP_AUTHORIZATION_TEMPLATE, Qa as RuntimeProviderProxyOpenFrameSchema, Qd as WEB_FETCH_RESPONSE_MAX_BYTES, Qf as McpGatewayErrorCodeSchema, Qg as RUNTIME_DEFAULT_MAX_DURATION_MS, Qh as PROVIDER_CLI_VALIDATION_RETRY_REASONS, Qi as RunnerServerFrameSchema, Ql as AttachMCPServerRequestSchema, Qm as ImAuthorKindSchema, Qn as taskCancelPath, Qo as RuntimeDurableWorkKindSchema, Qp as AgentSetupRuntimeComponentStatusSchema, Qr as CLOUD_MODEL_CHAT_COMPLETIONS_PATH, Qs as HeartbeatResultFrameSchema, Qt as accountComputerConnectCodePath, Qu as UpdateMCPBindingRequestSchema, R as ACCOUNT_SETUP_COMPLETE_PATH, Ra as RuntimeExecutionSourceSchema, Rc as RuntimeChannelTargetSchema, Rd as githubAgentScopeAllowsTaskDelegation, Rf as deriveWebIdempotencyKey, Rg as AgentStatusSchema, Rh as INTEGRATION_CREDENTIAL_EXECUTION_STATUSES, Ri as RunnerCloudSessionMessageSettledFrameSchema, Rl as SkillDetailSchema, Rm as AgentCloudOverviewQuerySchema, Rn as githubIntegrationDisconnectPath, Ro as ProviderCliPrewarmResultFrameSchema, Rp as AGENT_SETUP_RUNTIME_COMPONENT_STATUSES, Rr as StructuredErrorCauseSchema, Rs as TurnOutgoingReplySnapshotSchema, Rt as RUNTIME_IM_RESOURCE_TEMPLATE, Ru as MCP_OAUTH_OUTCOME_ERROR, S as getRuntimeConfigurationOptions, Sa as RuntimeCredentialAcquireRequestSchema, Sc as RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES, Sd as GitHubDelegatedImSenderIdSchema, Sf as WebFetchItemFailureSchema, Sg as AGENT_USAGE_WINDOW_DAYS, Sh as COMPUTER_RUNTIME_PROVIDER_CAPABILITY, Si as RunnerAuthFrameSchema, Sl as SKILL_ARCHIVE_MAX_BYTES, Sm as ImProviderSchema, Sn as agentSetupPath, So as SessionCliSendRequestSchema, Sp as PASSWORD_MIN_LENGTH, Sr as ErrorReportSourceSchema, Ss as TurnReportResultSchema, St as GITHUB_INTEGRATION_REPOSITORIES_PATH, Su as MCPServerDescriptionSchema, T as ACCOUNT_CLOUD_COMPUTER_PATH, Ta as RuntimeCredentialRejectCodeSchema, Tc as RUNTIME_PROVIDER_READINESS_V1, Td as GitHubOAuthContextSchema, Tf as WebFetchParamsSchema, Tg as AgentCreationIntentIdSchema, Th as ComputerConnectCodeIssueResponseSchema, Ti as RunnerCloudDeliveryCancelFrameSchema, Tl as SKILL_FORMAT_HEADER, Tm as SLACK_OAUTH_RETURN_SURFACES, Tn as agentSkillPath, To as AgentRuntimeTestResultFrameSchema, Tp as RefreshTokenResponseSchema, Tr as BOUNDED_DIAGNOSTIC_SERIALIZATION_BYTES, Ts as computeRuntimeImMessageSemanticHash, Tt as HTTP_PATHS, Tu as MCPServerSchema, U as AGENT_COMPUTER_REBIND_TEMPLATE, Ua as RuntimeMcpGatewayRequestSchema, Uc as RuntimeHeartbeatIntervalMsSchema, Ud as RuntimeWebExecutionServiceSchema, Uf as webServiceScopeForOperation, Ug as CreateAgentRequestSchema, Uh as LocalComputerPreparationResultSchema, Ui as RunnerCredentialTunnelFrameSchema, Ul as SkillStorageStatusSchema, Um as CloudSessionSummarySchema, Un as mcpServerPath, Uo as RUNTIME_DIRECT_TEXT_MAX_BYTES, Up as AgentSetupCloudComponentStatusSchema, Ur as boundedSerialize, Us as AuthV2FrameSchema, Ut as RUNTIME_SKILL_BUNDLE_TEMPLATE, Uu as MCP_PROBE_MAX_TOOLS_BYTES, V as AGENT_BY_ID_TEMPLATE, Va as RuntimeGitHubCliRepositorySchema, Vc as RuntimeErrorFrameSchema, Vd as RuntimeExecutionServiceSchema, Vf as parseWebTargetUrl, Vg as AgentUsageSummarySchema, Vh as IntegrationCredentialExecutionReasonSchema, Vi as RunnerCloudTurnWorkerRequestSchema, Vl as SkillSchema, Vm as CloudAvailabilitySchema, Vn as imBindingDiagnosticsPath, Vo as ProviderCliValidationResultFrameSchema, Vp as AgentSetupActionSchema, Vr as StructuredErrorPhaseSchema, Vs as AuthResultFrameSchema, Vu as MCP_OAUTH_SERVER_PARAM, W as AGENT_CONFIG_TEMPLATE, Wa as RuntimeMcpGatewayResultSchema, Wc as RuntimeHeartbeatTimeoutMsSchema, Wd as RUNTIME_WEB_FETCH_PATH, Wf as MCP_GATEWAY_ALLOWED_TOOL_RULE, Wg as CreateAgentRuntimeConfigSchema, Wh as LocalPreparationActionSchema, Wi as RunnerCredentialTunnelResultFrameSchema, Wl as UpdateSkillRequestSchema, Wm as SessionKindSchema, Wn as mcpServersPath, Wo as RUNTIME_FINAL_TEXT_MAX_BYTES, Wp as AgentSetupComponentSchema, Wr as redactDiagnostic, Ws as ClientRuntimeFrameSchema, Wt as SANDBOX_RUNNER_WEBSOCKET_PATH, Wu as MCP_RESERVED_HEADER_NAMES, X as AGENT_IM_BINDING_UNBIND_TEMPLATE, Xa as RuntimeProviderProxyEndFrameSchema, Xc as RuntimeProviderReadinessNegotiationSchema, Xd as RuntimeWebServiceScopeSchema, Xf as MCP_GATEWAY_SERVER_NAME, Xg as AGENT_SLUG_MAX_LENGTH, Xh as PROVIDER_CLI_PUBLIC_FAILURE_REASONS, Xi as RunnerServerCredentialFrameSchema, Xl as isReservedSkillName, Xm as ExternalMentionSchema, Xn as sandboxRunnerWebSocketUrl, Xo as RetainedTurnReportClaimSchema, Xp as AgentSetupMessagingStateSchema, Xr as AccountSandboxRunnerStatusResponseSchema, Xs as ComputerRegisterV2FrameSchema, Xt as accountAgentCreationIntentPath, Xu as StartMCPOAuthRequestSchema, Y as AGENT_IM_BINDING_TEMPLATE, Ya as RuntimeProviderProxyCreditFrameSchema, Yc as RuntimeProviderReadinessCollectionSchema, Yd as RouterWebSearchRequestSchema, Yf as MCP_GATEWAY_REQUEST_MAX_BYTES, Yg as UpdateAgentRuntimeConfigSchema, Yh as PROVIDER_CLI_ARTIFACT_PUBLIC_REASONS, Yi as RunnerReadyFrameSchema, Yl as SkillNameSchema, Ym as SandboxLifecycleSchema, Yn as runtimeWebSocketUrl, Yo as RUNTIME_TRACE_EVENT_MAX_BYTES, Yp as AgentSetupMessagingBlockerCodeSchema, Yr as AccountSandboxRunnerAcceptanceResponseSchema, Ys as ComputerRegisterV1FrameSchema, Yt as TASK_REPLIES_TEMPLATE, Yu as SetMCPAuthorizationRequestSchema, Z as AGENT_MCP_AUTHORIZATION_OAUTH_TEMPLATE, Za as RuntimeProviderProxyErrorFrameSchema, Zd as WEB_DOMAIN_MAX_BYTES, Zf as MCP_GATEWAY_TOOL_NAME_MAX_BYTES, Zg as OPENTAG_PLATFORM_INSTRUCTIONS, Zh as PROVIDER_CLI_REASON_V2_HEADER, Zi as RunnerServerErrorFrameSchema, Zl as parseSkillManifest, Zm as ImAttentionSchema, Zn as taskByIdPath, Zo as RuntimeDurableFailureSchema, Zp as AgentSetupReturnSurfaceSchema, Zr as AccountSandboxRunnerStopRequestSchema, Zs as HeartbeatFrameSchema, Zt as accountComputerByIdPath, Zu as StartMCPOAuthResponseSchema, _ as TaskTitleUpdateRequestSchema, _a as RUNTIME_EXECUTION_MAX_LIFETIME_MS, _c as RUNTIME_PROTOCOL_VERSION, _d as GitHubAgentScopeSchema, _f as WEB_TOOL_ERROR_CODES, _g as compareSemVer, _h as AccountComputerConnectCodeCreateRequestSchema, _i as RunnerAcceptanceEvidenceWireSchema, _l as ErrorEnvelopeSchema, _m as ImBindingIdentitySchema, _n as agentMcpProbePath, _o as SessionCliCreateRequestSchema, _p as EmailAddressSchema, _r as ERROR_REPORT_FIELD_MAX_LENGTH, _s as SessionMessageDeliveryResultSchema, _t as FEISHU_SETUP_ATTEMPT_TEMPLATE, _u as MCPProbeResponseSchema, a as TASK_TITLE_MAX_LENGTH, a_ as RuntimeModelSchema, aa as PROVIDER_PROXY_AUTH_TIMEOUT_MS, ac as RUNTIME_AGENT_RUNTIME_TEST_TIMEOUT_MS, ad as ContextTreeOperationResultFrameSchema, af as WEB_LANGUAGE_MAX_CODEPOINTS, ag as ProviderReadinessStatusSchema, ah as ImResourceDescriptorSchema, ai as RUNNER_ACCEPTANCE_WORKER_STDIN_MAX_BYTES, al as ServerWelcomeFrameSchema, am as CreateFeishuSetupAttemptRequestSchema, an as agentByIdPath, ao as RuntimeSlackCliMetadataSchema, ap as RUNNER_WORKSPACE_VERSION, ar as GITHUB_OAUTH_OUTCOME_SUCCESS, as as RuntimeImHistoryItemSchema, at as AGENT_SETUP_TEMPLATE, au as MCPAuthKindSchema, b as DEFAULT_SIGN_IN_DESTINATION, ba as RUNTIME_PROXY_TICKET_TTL_MS, bc as RUNTIME_PROVIDER_CLI_REQUIREMENT_OPERATION, bd as GitHubConnectionStatusSchema, bf as WEB_URL_MAX_BYTES, bg as AGENT_RUNTIME_PROVIDERS, bh as CLOUD_IDENTITY_CAPABILITY_HEADER, bi as RunnerAcceptanceResultFrameSchema, bl as RuntimeSkillManifestEntrySchema, bm as ImBindingSummarySchema, bn as agentReactivatePath, bo as SessionCliListResponseSchema, bp as MeResponseSchema, br as ERROR_REPORT_URL_MAX_LENGTH, bs as TurnFailureReasonSchema, bt as GITHUB_INTEGRATION_DISCONNECT_PATH, bu as MCPProtocolEraSchema, c as TaskCollaborationMessageSchema, c_ as CONTEXT_TREES_MAX, ca as PROVIDER_PROXY_INITIAL_CREDIT_BYTES, cc as RUNTIME_CLIENT_CAPABILITY_OFFERS, cd as GITHUB_AGENT_SCOPE_MAX_DELEGATED_IM_SENDERS, cf as WEB_REQUEST_MAX_BYTES, cg as providerCliArtifactFailureIsManual, ch as AccountCloudComputerEnsureResponseSchema, ci as RUNNER_PI_CONFIG_DOCUMENT_MAX_BYTES, cl as advertisedProviderReadiness, cm as FeishuSetupActivationReasonSchema, cn as agentConfigPath, co as RuntimeWebGatewayResultSchema, cp as RunnerWorkspaceSealResultFrameSchema, cr as GitHubDiscoveredInstallationSchema, cs as RuntimeImSteerRequestSchema, ct as AGENT_SKILL_TEMPLATE, cu as MCPAuthorizationSummarySchema, d as TaskReplySchema, d_ as ContextTreeRepositorySchema, da as PROVIDER_PROXY_MAX_STREAM_OPENS_PER_CONNECTION, dc as RUNTIME_HEARTBEAT_INTERVAL_MIN_MS, dd as GITHUB_OAUTH_RETURN_SURFACES, df as WEB_SEARCH_LIMIT_MAX, dg as requestsProviderCliReasonV2, dh as AccountSetupResetModeSchema, di as RUNNER_SESSION_COLLABORATION_VERSION, dl as negotiateRuntimeCapabilities, dm as FeishuSetupIntentSchema, dn as agentImBindingConfigPath, do as SESSION_CLI_DEFAULT_LIMIT, dp as AuthProvidersResponseSchema, dr as GitHubIntegrationOverviewSchema, ds as RuntimeRevisionSchema, dt as AGENT_SUSPEND_TEMPLATE, du as MCPClientRegistrationSourceSchema, e_ as RUNTIME_INSTRUCTIONS_MAX_BYTES, ea as RunnerWelcomeFrameSchema, ed as normalizeExtraHeaders, ef as WEB_FETCH_URLS_MAX, eg as PROVIDER_READINESS_V2_HEADER, eh as ImContentV1Schema, ei as CLOUD_MODEL_CONTEXT_WINDOW_STANDARD, em as AgentSetupRuntimeUnavailableReasonSchema, en as accountSandboxPath, eo as RuntimeProviderProxyResponseFrameSchema, ep as RuntimeMcpServiceScopeSchema, er as ServerHealthSchema, es as RuntimeDurableWorkRecordSchema, et as AGENT_MCP_SERVERS_TEMPLATE, eu as ListAgentMCPServersResponseSchema, f as TaskReplyTimeSourceSchema, f_ as ContextTreesSchema, fa as PROVIDER_PROXY_STREAM_REVALIDATE_INTERVAL_MS, fc as RUNTIME_HEARTBEAT_TIMEOUT_MAX_MS, fd as GITHUB_REPOSITORY_BINDINGS_MAX_AGENT_SCOPES, ff as WEB_SEARCH_QUERY_MAX_CODEPOINTS, fg as requestsProviderReadinessV1, fh as AccountSetupResetRequestSchema, fi as RUNNER_WS_CLOSE, fl as runtimeFrameByteLength, fm as FeishuSetupStateSchema, fn as agentImBindingHandoffPath, fo as SESSION_CLI_MAX_LIMIT, fp as BrowserSessionStatusResponseSchema, fr as GitHubOAuthOutcomeSearchSchema, fs as RuntimeSequenceSchema, ft as AGENT_USAGE_TEMPLATE, fu as MCPCustomAuthHeaderSchema, g as TaskTitleSchema, ga as RUNTIME_CREDENTIAL_PROVIDERS, gc as RUNTIME_PROTOCOL_V2, gd as GitBranchRefSchema, gf as WEB_TOOLS_PROTOCOL_VERSION, gg as SemVerStringSchema, gh as ListAccountComputersResponseSchema, gi as RunnerAcceptanceEventWireSchema, gl as ErrorDetailSchema, gm as ImBindingHandoffStatusSchema, gn as agentMcpAuthorizationPath, go as SessionCliCommandStatusSchema, gp as ConnectCodeIssueResponseSchema, gr as StartGitHubAuthorizationResponseSchema, gs as SessionMessageDeliveryRequestSchema, gt as FEISHU_SETUP_ATTEMPT_CHECK_TEMPLATE, gu as MCPOverrideSourcesSchema, h as TaskSummarySchema, ha as RUNTIME_CREDENTIAL_CAPABILITY_TTL_MS, hc as RUNTIME_PROTOCOL_V1, hd as GITHUB_REPOSITORY_BINDINGS_SCHEMA_VERSION, hf as WEB_TIMEOUT_HEADER, hg as SEMVER_PATTERN, hh as InternalNavigationVisibilitySchema, hi as RunnerAcceptanceCancelFrameSchema, hl as ErrorCodeSchema, hm as ImBindingDiagnosticsSchema, hn as agentMcpAuthorizationOAuthPath, ho as SessionCliCommandResponseSchema, hp as ConnectCodeIssueRequestSchema, hr as StartGitHubAuthorizationRequestSchema, hs as ServerRuntimeBusinessFrameSchema, ht as COMPUTER_AGENT_SKILL_BUNDLE_TEMPLATE, hu as MCPOAuthOutcomeSearchSchema, i as TASK_CANCELLED_DELIVERY_REASON, i_ as RuntimeMaxDurationMsSchema, ia as FEISHU_TENANT_TOKEN_LOCAL_SENTINEL, ic as RUNTIME_AGENT_RUNTIME_TEST_MAX_PENDING, id as ContextTreeOperationResponseSchema, if as WEB_IDEMPOTENCY_NAMESPACE, ig as ProviderCliValidationRetryReasonSchema, ih as ImOutboundContentMetaSchema, ii as RUNNER_ACCEPTANCE_PROVIDER, il as ServerRuntimeFrameSchema, im as projectAgentSetupComponents, in as accountSandboxRunnerStopPath, io as RuntimeProxyTicketResultSchema, ip as RUNNER_WORKSPACE_TIMEOUT_MS, ir as GITHUB_OAUTH_OUTCOME_PARAM, is as RuntimeImDeliveryContentSchema, it as AGENT_SETUP_REFRESH_TEMPLATE, iu as MCPAuthHeaderNameSchema, j as ACCOUNT_COMPUTER_DISCONNECT_TEMPLATE, ja as RuntimeExecutionCloseRequestSchema, jc as RUNTIME_SERVER_CAPABILITY_OFFERS, jd as GitHubRepositoryBindingsSchema, jf as WebSearchResultItemSchema, jg as AgentListItemSchema, jh as ComputerImCliReadinessSchema, ji as RunnerCloudDeliveryRunFrameSchema, jl as SKILL_MAX_PER_AGENT, jm as SlackIdentityClosureSchema, jn as computerAgentSkillBundlePath, jo as ImMessageDeliveryResultSchema, jp as AGENT_SETUP_BLOCKER_CODES, jr as STRUCTURED_ERROR_MAX_CAUSE_DEPTH, js as RUNTIME_OUTGOING_REPLY_MAX_COUNT, jt as MCP_SERVERS_PATH, ju as MCP_ERROR_CODE_METADATA, k as ACCOUNT_COMPUTER_CONNECT_CODES_PATH, ka as RuntimeCredentialRevokedFrameSchema, kc as RUNTIME_REQUIRED_CLIENT_CAPABILITIES, kd as GitHubRepositoryAccessSchema, kf as WebSearchExecutionRequestSchema, kg as AgentInstructionsSchema, kh as ComputerConnectionStatusSchema, ki as RunnerCloudDeliveryReportAckFrameSchema, kl as SKILL_MAX_LISTED_FILES, km as SlackConfigurationIntentSchema, kn as agentSuspendPath, ko as DirectImMessageDeliveryRequestSchema, kp as AGENT_CREATION_RECOVERY_ACTIONS, kr as RetryabilitySchema, ks as hashTuple, kt as MCP_CLIENT_METADATA_PATH, ku as MCP_AUTH_KINDS, l as TaskDetailSchema, l_ as ContextTreeAliasSchema, la as PROVIDER_PROXY_MAX_FRAME_BYTES, lc as RUNTIME_CLIENT_CAPABILITY_TTL_MS, ld as GITHUB_AGENT_SCOPE_MAX_DELEGATED_SESSION_AGENTS, lf as WEB_SEARCH_DOMAINS_MAX, lg as publicProviderCliArtifactReason, lh as AccountComputerSummarySchema, li as RUNNER_PI_CONFIG_DOCUMENT_MAX_CHARS, ll as missingRuntimeCapabilities, lm as FeishuSetupActivationSchema, ln as agentContextTreePath, lo as decodeProviderProxyDataFrame, lp as ChannelNameSchema, lr as GitHubDiscoveredRepositorySchema, ls as RuntimeImSteerResultSchema, lt as AGENT_SLACK_EVENTS_TEMPLATE, lu as MCPAvailableServerSchema, m as TaskStatusSchema, ma as RUNTIME_CREDENTIAL_CAPABILITY_REFRESH_AFTER_MS, mc as RUNTIME_MAX_FRAME_BYTES, md as GITHUB_REPOSITORY_BINDINGS_MAX_REPOSITORIES, mf as WEB_SEARCH_TIMEOUT_CAP_MS, mg as withComputerRuntimeProviderSupport, mh as CompleteAccountSetupRequestSchema, mi as RUNNER_WS_PROTOCOL_VERSION, ml as ErrorCategorySchema, mm as ImBindingCredentialStatusSchema, mn as agentImBindingUnbindPath, mo as SESSION_CLI_TASK_PREVIEW_MAX_BYTES, mp as ConnectCodeExchangeResponseSchema, mr as GitHubRepositoryDiscoveryQuerySchema, ms as RuntimeUsageSchema, mt as COMPUTER_AGENT_SKILLS_TEMPLATE, mu as MCPExtraHeadersSchema, n as ListTasksResponseSchema, n_ as RuntimeInstructionSchema, na as serializeRunnerCloudSessionWorkerStdin, nc as HeartbeatV2FrameSchema, nd as ContextTreeOperationFrameSchema, nf as WEB_GATEWAY_SEARCH_PATH, ng as ProviderCliPublicFailureReasonSchema, nh as ImMessageDirectionSchema, ni as CLOUD_MODEL_PROXY_PATH, nl as RuntimeRequestIdSchema, nm as AgentSetupSnapshotSchema, nn as accountSandboxRunnerPath, no as RuntimeProxyTicketRejectCodeSchema, np as RUNNER_WORKSPACE_ARCHIVE_MAX_BYTES, nr as GITHUB_OAUTH_ERROR_PARAM, ns as RuntimeImCredentialGrantRequestSchema, nt as AGENT_REACTIVATE_TEMPLATE, nu as ListMCPServersResponseSchema, o as TaskAttachmentSchema, o_ as RuntimeReasoningEffortSchema, oa as PROVIDER_PROXY_CHUNK_MAX_BYTES, oc as RUNTIME_AGENT_RUNTIME_TEST_TTL_MS, od as BeginGitHubAuthorizationRequestSchema, of as WEB_PAGE_BODY_MAX_BYTES, og as classifyProviderCliArtifactFailure, oh as NormalizedInboundImEventSchema, oi as RUNNER_CLOUD_DELIVERY_VERSION, ol as ServerWelcomeV1FrameSchema, om as FEISHU_REQUIRED_TENANT_SCOPES, on as agentCloudPath, oo as RuntimeWebGatewayRejectCodeSchema, op as RunnerWorkspaceObjectSchema, or as GITHUB_REPOSITORY_DISCOVERY_MAX_INSTALLATIONS, os as RuntimeImOutboxContextSchema, ot as AGENT_SKILLS_TEMPLATE, ou as MCPAuthSchemeSchema, p as TaskSessionKindSchema, p_ as normalizeContextTrees, pa as RUNTIME_CLI_METADATA_MAX_REPOSITORIES, pc as RUNTIME_HEARTBEAT_TIMEOUT_MIN_MS, pd as GITHUB_REPOSITORY_BINDINGS_MAX_BYTES, pf as WEB_SEARCH_RESPONSE_MAX_BYTES, pg as requestsProviderReadinessV2, ph as COMPUTER_ACCESS_CAPABILITY_HEADER, pi as RUNNER_WS_MAX_FRAME_BYTES, pl as runtimeNegotiatedCapabilitiesEqual, pm as ImBindingAdminDetailSchema, pn as agentImBindingPath, po as SESSION_CLI_PROOF_HEADER, pp as ConnectCodeExchangeRequestSchema, pr as GitHubRepositoryDiscoveryPageSchema, ps as RuntimeSha256Schema, pt as API_V1_PREFIX, pu as MCPEffectiveConfigSchema, q as AGENT_IM_BINDING_CONFIG_TEMPLATE, qa as RuntimeProviderProxyCancelFrameSchema, qc as RuntimeNegotiatedCapabilitiesSchema, qd as RouterGatewayErrorSchema, qf as MCP_GATEWAY_NAME_SEPARATOR, qg as ReceiveModeSchema, qi as RunnerPiConfigInputSchema, ql as SKILL_RESERVED_NAMES, qm as AccountSandboxEnsureRequestSchema, qn as runtimeImResourcePath, qo as RUNTIME_MVP_RETAINED_REPORT_LIMIT, qp as AgentSetupExpectedMessagingStateSchema, qr as serializeDiagnostic, qt as TASK_BY_ID_TEMPLATE, qu as MCP_TOOL_INPUT_SCHEMA_MAX_BYTES, r as TASK_AUTO_TITLE_MAX_GRAPHEMES, r_ as RuntimeInstructionsSchema, ra as serializeRunnerCloudTurnWorkerStdin, rc as RUNTIME_AGENT_RUNTIME_TEST_CLEANUP_MS, rd as ContextTreeOperationRequestSchema, rf as WEB_IDEMPOTENCY_KEY_MAX_BYTES, rg as ProviderCliValidationResultReasonSchema, rh as ImMessageOperationSchema, ri as RUNNER_ACCEPTANCE_MODES, rm as AgentSetupStageSchema, rn as accountSandboxRunnerStartPath, ro as RuntimeProxyTicketRequestSchema, rp as RUNNER_WORKSPACE_PATH, rr as GITHUB_OAUTH_OUTCOME_ERROR, rs as RuntimeImCredentialGrantResultSchema, rt as AGENT_RUNTIME_TEST_TEMPLATE, ru as MCPAgentServerSchema, s as TaskCancelResponseSchema, s_ as renderPlatformInstructions, sa as PROVIDER_PROXY_HEADER_MAX_BYTES, sc as RUNTIME_CAPABILITY, sd as CreateGitHubConnectionRequestSchema, sf as WEB_PUBLISHED_AT_MAX_BYTES, sg as clientSupportsComputerRuntimeProvider, sh as ProviderInboundContextSchema, si as RUNNER_CLOUD_TURN_WORKER_STDIN_MAX_BYTES, sl as ServerWelcomeV2FrameSchema, sm as FEISHU_SETUP_ACTIVATION_REASONS, sn as agentComputerRebindPath, so as RuntimeWebGatewayRequestSchema, sp as RunnerWorkspaceSealFrameSchema, sr as GITHUB_REPOSITORY_DISCOVERY_PAGE_SIZE, ss as RuntimeImResourceReferenceSchema, st as AGENT_SKILL_BUNDLE_TEMPLATE, su as MCPAuthorizationStatusSchema, t as ListTaskRepliesResponseSchema, t_ as RUNTIME_MAX_DURATION_MS, ta as serializeRunnerAcceptanceWorkerStdin, tc as HeartbeatV1FrameSchema, td as probedServerDescription, tf as WEB_GATEWAY_FETCH_PATH, tg as ProviderCliArtifactPublicReasonSchema, th as ImConversationKindSchema, ti as CLOUD_MODEL_OUTPUT_TOKEN_LIMIT, tm as AgentSetupSlackOAuthContextSchema, tn as accountSandboxRunnerAcceptancePath, to as RuntimeProviderProxyServerFrameSchema, tp as composeGatewayToolName, tr as GITHUB_MANAGEMENT_ERROR_CODES, ts as RuntimeDurableWorkStatusSchema, tt as AGENT_MCP_SERVER_TEMPLATE, tu as ListAvailableMCPServersResponseSchema, u as TaskInternalSessionSchema, u_ as ContextTreeConnectionSchema, ua as PROVIDER_PROXY_MAX_STREAMS_PER_EXECUTION, uc as RUNTIME_HEARTBEAT_INTERVAL_MAX_MS, ud as GITHUB_CONNECTION_ERROR_CODES, uf as WEB_SEARCH_LIMIT_DEFAULT, ug as requestsCloudIdentityV1, uh as AccountSetupCompletionSchema, ui as RUNNER_REUSE_VERSION, ul as negotiateProviderReadinessFromHeaders, um as FeishuSetupAttemptSchema, un as agentFeishuSetupAttemptsPath, uo as encodeProviderProxyDataFrame, up as AuthIdentityProviderSchema, ur as GitHubIntegrationAvailabilitySchema, us as RuntimeProviderMessageRefSchema, ut as AGENT_SLACK_OAUTH_START_TEMPLATE, uu as MCPBindingOverridesSchema, v as TaskTitleUpdateResponseSchema, va as RUNTIME_PROVIDER_ORIGIN_HEADER, vc as RUNTIME_PROVIDER_CLI_ARTIFACT_TTL_MS, vd as GitHubAgentScopeTaskDelegationSchema, vf as WEB_TOOL_PREVIEW_PAGE_MAX_BYTES, vg as isSemVer, vh as AccountComputerConnectCodeIssueRequestSchema, vi as RunnerAcceptanceModeSchema, vl as ValidationIssueSchema, vm as ImBindingMessagingExpectationSchema, vn as agentMcpServerPath, vo as SessionCliListItemSchema, vp as EmailSignInRequestSchema, vr as ERROR_REPORT_MESSAGE_MAX_LENGTH, vs as SessionReconcileRequestSchema, vt as GITHUB_INTEGRATION_AUTHORIZATION_PATH, vu as MCPProbeSnapshotSchema, w as ACCOUNT_AGENT_CREATION_INTENT_TEMPLATE, wa as RuntimeCredentialProviderSchema, wc as RUNTIME_PROVIDER_CLI_VALIDATION_TIMEOUT_MS, wd as GitHubLoginSessionHashSchema, wf as WebFetchItemSuccessSchema, wg as AgentAdminConfigSchema, wh as ComputerConnectCodeExchangeResponseSchema, wi as RunnerClientFrameSchema, wl as SKILL_ERROR_CODE_METADATA, wm as ProviderCliHandoffProgressSchema, wn as agentSkillBundlePath, wo as AgentRuntimeTestRequestFrameSchema, wp as RefreshTokenRequestSchema, wr as sanitizeErrorReportUrl, ws as computeReconcilePayloadHash, wt as GITHUB_WEBHOOK_PATH, wu as MCPServerNameSchema, x as resolveSignInDestination, xa as RUNTIME_VALIDATION_RUN_TTL_MS, xc as RUNTIME_PROVIDER_CLI_VALIDATION_GRANT_TTL_MS, xd as GitHubDecimalIdSchema, xf as WebFetchExecutionRequestSchema, xg as AGENT_RUNTIME_TEST_FAILURE_CODES, xh as CLOUD_IDENTITY_CAPABILITY_VERSION, xi as RunnerAcceptanceRunFrameSchema, xl as RuntimeSkillManifestSchema, xm as ImBindingUnbindRequiredDetailSchema, xn as agentRuntimeTestPath, xo as SessionCliProofGrantSchema, xp as PASSWORD_MAX_LENGTH, xr as ErrorReportRequestSchema, xs as TurnReportRequestSchema, xt as GITHUB_INTEGRATION_PATH, xu as MCPServerAgentSchema, y as TaskTurnSchema, ya as RUNTIME_PROVIDER_PROXY_PATH, yc as RUNTIME_PROVIDER_CLI_CREDENTIAL_TTL_MS, yd as GitHubConnectionStateSchema, yf as WEB_TOOL_RESULT_MAX_BYTES, yg as parseSemVer, yh as AccountComputerConnectCodeRepairRequestSchema, yi as RunnerAcceptanceReportWireSchema, yl as ListAgentSkillsResponseSchema, ym as ImBindingStateSchema, yn as agentMcpServersPath, yo as SessionCliListQuerySchema, yp as EmailSignUpRequestSchema, yr as ERROR_REPORT_STACK_MAX_LENGTH, ys as SessionReconcileResultSchema, yt as GITHUB_INTEGRATION_BINDINGS_PATH, yu as MCPProbeStateSchema, za as RuntimeFeishuCliMetadataSchema, zc as RuntimeClientCapabilitiesSchema, zd as isValidGitRefName, zf as normalizeWebTargetUrl, zg as AgentSummarySchema, zh as ImCliProviderSchema, zi as RunnerCloudSessionMessageVerifiedFrameSchema, zl as SkillFileEntrySchema, zm as AgentCloudOverviewSchema, zn as githubIntegrationPath, zo as ProviderCliRequirementFrameSchema, zp as AGENT_SETUP_STAGES, zr as StructuredErrorCodeSchema, zs as TurnOutgoingReplyUnavailableReasonSchema, zu as MCP_OAUTH_OUTCOME_PARAM } from \"./task-BXtm5kVZ.mjs\";\nimport { z } from \"zod\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n//#region src/agent-self.ts\nconst UpdateSelfAgentRuntimeConfigSchema = z.object({\n\tmodel: RuntimeModelSchema.nullable().optional(),\n\treasoningEffort: RuntimeReasoningEffortSchema.nullable().optional(),\n\tinstructions: AgentInstructionsSchema.optional()\n}).strict().refine((value) => Object.keys(value).length > 0, { message: \"At least one runtime config field must be updated\" });\nconst UpdateSelfAgentRequestSchema = z.object({\n\texpectedRevision: z.number().int().min(1),\n\truntimeConfig: UpdateSelfAgentRuntimeConfigSchema\n}).strict();\n/** The only binding change an Agent may make to its own mount: enable or disable it. */\nconst UpdateSelfMCPBindingRequestSchema = z.object({ enabled: z.boolean() }).strict();\n//#endregion\n//#region src/channel-config.json\nvar channel_config_default = {\n\tdev: {\n\t\t\"binName\": \"opentag-dev\",\n\t\t\"defaultHomeDirectory\": \".opentag-dev\",\n\t\t\"defaultServerUrl\": \"http://127.0.0.1:8000\",\n\t\t\"displayName\": \"OpenTag Dev\",\n\t\t\"packageName\": \"open-tag\",\n\t\t\"serviceId\": \"opentag-dev\"\n\t},\n\tstaging: {\n\t\t\"binName\": \"opentag-staging\",\n\t\t\"defaultHomeDirectory\": \".opentag-staging\",\n\t\t\"displayName\": \"OpenTag Staging\",\n\t\t\"packageName\": \"open-tag-staging\",\n\t\t\"serviceId\": \"opentag-staging\"\n\t},\n\tprod: {\n\t\t\"binName\": \"opentag\",\n\t\t\"defaultHomeDirectory\": \".opentag\",\n\t\t\"displayName\": \"OpenTag\",\n\t\t\"packageName\": \"open-tag\",\n\t\t\"serviceId\": \"opentag\"\n\t}\n};\n//#endregion\n//#region src/channel.ts\nconst ServiceIdSchema = z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);\nconst ChannelDefinitionSchema = z.object({\n\tbinName: z.string().min(1),\n\tdefaultHomeDirectory: z.string().startsWith(\".\"),\n\tdefaultServerUrl: z.string().url().optional(),\n\tdisplayName: z.string().min(1),\n\tpackageName: z.string().min(1),\n\tserviceId: ServiceIdSchema\n}).strict();\nconst channelDefinitions = z.object({\n\tdev: ChannelDefinitionSchema,\n\tprod: ChannelDefinitionSchema,\n\tstaging: ChannelDefinitionSchema\n}).parse(channel_config_default);\nfunction getChannelConfig(channel, userHome = homedir()) {\n\tconst definition = channelDefinitions[channel];\n\treturn {\n\t\tbinName: definition.binName,\n\t\tchannel,\n\t\tdefaultHome: join(userHome, definition.defaultHomeDirectory),\n\t\t...definition.defaultServerUrl ? { defaultServerUrl: definition.defaultServerUrl } : {},\n\t\tdisplayName: definition.displayName,\n\t\tpackageName: definition.packageName,\n\t\tserviceId: definition.serviceId\n\t};\n}\n//#endregion\n//#region src/client-version.ts\n/** Minimum Client release line admitted by Computer connect-code exchange and runtime registration. */\nconst MINIMUM_SUPPORTED_CLIENT_VERSION = \"0.0.2\";\n/** Uses SemVer precedence: prereleases of 0.0.2 remain below the supported 0.0.2 floor. */\nfunction isSupportedClientVersion(value) {\n\tconst parsed = parseSemVer(value);\n\tif (!parsed) return false;\n\tif (parsed.major > 0) return true;\n\tif (parsed.minor > 0) return true;\n\tif (parsed.patch > 2) return true;\n\treturn parsed.patch === 2 && parsed.prerelease.length === 0;\n}\nfunction unsupportedClientVersionMessage() {\n\treturn `Client version must be ${MINIMUM_SUPPORTED_CLIENT_VERSION} or newer`;\n}\n//#endregion\nexport { ACCOUNT_AGENTS_PATH, ACCOUNT_AGENT_CREATION_INTENT_TEMPLATE, ACCOUNT_CLOUD_COMPUTER_PATH, ACCOUNT_CLOUD_MODELS_PATH, ACCOUNT_COMPUTERS_PATH, ACCOUNT_COMPUTER_BY_ID_TEMPLATE, ACCOUNT_COMPUTER_CONNECT_CODES_PATH, ACCOUNT_COMPUTER_CONNECT_CODE_TEMPLATE, ACCOUNT_COMPUTER_DISCONNECT_TEMPLATE, ACCOUNT_SANDBOXES_PATH, ACCOUNT_SANDBOX_RUNNER_ACCEPTANCE_TEMPLATE, ACCOUNT_SANDBOX_RUNNER_START_TEMPLATE, ACCOUNT_SANDBOX_RUNNER_STOP_TEMPLATE, ACCOUNT_SANDBOX_RUNNER_TEMPLATE, ACCOUNT_SANDBOX_TEMPLATE, ACCOUNT_SETUP_COMPLETE_PATH, ACCOUNT_TASKS_PATH, AGENT_BY_ID_TEMPLATE, AGENT_CLOUD_TEMPLATE, AGENT_COMPUTER_REBIND_TEMPLATE, AGENT_CONFIG_TEMPLATE, AGENT_CONTEXT_TREE_TEMPLATE, AGENT_CREATION_RECOVERY_ACTIONS, AGENT_FEISHU_SETUP_ATTEMPTS_TEMPLATE, AGENT_IM_BINDING_CONFIG_TEMPLATE, AGENT_IM_BINDING_HANDOFF_TEMPLATE, AGENT_IM_BINDING_TEMPLATE, AGENT_IM_BINDING_UNBIND_TEMPLATE, AGENT_MCP_AUTHORIZATION_OAUTH_TEMPLATE, AGENT_MCP_AUTHORIZATION_TEMPLATE, AGENT_MCP_PROBE_TEMPLATE, AGENT_MCP_SERVERS_TEMPLATE, AGENT_MCP_SERVER_TEMPLATE, AGENT_REACTIVATE_TEMPLATE, AGENT_RUNTIME_PROVIDERS, AGENT_RUNTIME_TEST_FAILURE_CODES, AGENT_RUNTIME_TEST_TEMPLATE, AGENT_SETUP_ACTION_KINDS, AGENT_SETUP_BLOCKER_CODES, AGENT_SETUP_CLOUD_COMPONENT_STATUSES, AGENT_SETUP_COMPUTER_COMPONENT_STATUSES, AGENT_SETUP_IM_CLI_COMPONENT_STATUSES, AGENT_SETUP_MESSAGING_BLOCKER_CODES, AGENT_SETUP_REFRESH_TEMPLATE, AGENT_SETUP_REQUIRED_IM_CLI_PROVIDERS, AGENT_SETUP_RETURN_SURFACES, AGENT_SETUP_RUNTIME_COMPONENT_STATUSES, AGENT_SETUP_STAGES, AGENT_SETUP_TEMPLATE, AGENT_SKILLS_TEMPLATE, AGENT_SKILL_BUNDLE_TEMPLATE, AGENT_SKILL_TEMPLATE, AGENT_SLACK_EVENTS_TEMPLATE, AGENT_SLACK_OAUTH_START_TEMPLATE, AGENT_SLUG_MAX_LENGTH, AGENT_SUSPEND_TEMPLATE, AGENT_USAGE_TEMPLATE, AGENT_USAGE_WINDOW_DAYS, AGENT_USAGE_WINDOW_OPTIONS, API_V1_PREFIX, AccountCloudComputerEnsureResponseSchema, AccountComputerConnectCodeCreateRequestSchema, AccountComputerConnectCodeIssueRequestSchema, AccountComputerConnectCodeRepairRequestSchema, AccountComputerSummarySchema, AccountSandboxEnsureRequestSchema, AccountSandboxResponseSchema, AccountSandboxRunnerAcceptanceRequestSchema, AccountSandboxRunnerAcceptanceResponseSchema, AccountSandboxRunnerStatusResponseSchema, AccountSandboxRunnerStopRequestSchema, AccountSetupCompletionSchema, AccountSetupResetModeSchema, AccountSetupResetRequestSchema, AgentAdminConfigSchema, AgentCloudOverviewQuerySchema, AgentCloudOverviewSchema, AgentCreationIntentIdSchema, AgentCreationIntentResultSchema, AgentCreationRecoveryActionSchema, AgentDetailSchema, AgentDisplayNameSchema, AgentListActivitySchema, AgentListItemSchema, AgentNameSchema, AgentRuntimeConfigSchema, AgentRuntimeProviderSchema, AgentRuntimeTestCancelFrameSchema, AgentRuntimeTestFailureCodeSchema, AgentRuntimeTestRequestFrameSchema, AgentRuntimeTestRequestSchema, AgentRuntimeTestResponseSchema, AgentRuntimeTestResultFrameSchema, AgentSetupActionSchema, AgentSetupBlockerSchema, AgentSetupCloudComponentStatusSchema, AgentSetupComponentSchema, AgentSetupComputerComponentStatusSchema, AgentSetupComputerStateSchema, AgentSetupExpectedMessagingStateSchema, AgentSetupImCliComponentStatusSchema, AgentSetupMessagingBlockerCodeSchema, AgentSetupMessagingStateSchema, AgentSetupReturnSurfaceSchema, AgentSetupRuntimeComponentStatusSchema, AgentSetupRuntimeStateSchema, AgentSetupRuntimeUnavailableReasonSchema, AgentSetupSlackOAuthContextSchema, AgentSetupSnapshotSchema, AgentSetupStageSchema, AgentStatusSchema, AgentSummarySchema, AgentTraceBatchSchema, AgentTraceEventSchema, AgentUsageDetailSchema, AgentUsageSummarySchema, AgentUsageWindowDaysSchema, AttachMCPServerRequestSchema, AuthFrameSchema, AuthIdentityProviderSchema, AuthProvidersResponseSchema, AuthResultFrameSchema, AuthV1FrameSchema, AuthV2FrameSchema, BOUNDED_DIAGNOSTIC_SERIALIZATION_BYTES, BeginGitHubAuthorizationRequestSchema, BrowserSessionStatusResponseSchema, CLOUD_IDENTITY_CAPABILITY_HEADER, CLOUD_IDENTITY_CAPABILITY_VERSION, CLOUD_MODEL_CHAT_COMPLETIONS_PATH, CLOUD_MODEL_CONTEXT_WINDOW_EXTENDED, CLOUD_MODEL_CONTEXT_WINDOW_STANDARD, CLOUD_MODEL_OPTIONS_MAX_MODELS, CLOUD_MODEL_OUTPUT_TOKEN_LIMIT, CLOUD_MODEL_PROXY_PATH, COMPUTER_ACCESS_CAPABILITY_HEADER, COMPUTER_AGENT_SKILLS_TEMPLATE, COMPUTER_AGENT_SKILL_BUNDLE_TEMPLATE, COMPUTER_RUNTIME_PROVIDER_CAPABILITY, CONTEXT_TREES_MAX, ChannelNameSchema, ClientRuntimeBusinessFrameSchema, ClientRuntimeFrameSchema, CloudAvailabilitySchema, CloudModelOptionsSchema, CloudSessionSummarySchema, CompleteAccountSetupRequestSchema, ComputerConnectCodeExchangeRequestSchema, ComputerConnectCodeExchangeResponseSchema, ComputerConnectCodeIssueResponseSchema, ComputerConnectCodeModeSchema, ComputerConnectCodeStateSchema, ComputerConnectCodeStatusSchema, ComputerConnectionStatusSchema, ComputerImCliReadinessCollectionSchema, ComputerImCliReadinessSchema, ComputerKindSchema, ComputerPlatformSchema, ComputerProviderReadinessCollectionSchema, ComputerProviderReadinessSchema, ComputerRegisterFrameSchema, ComputerRegisterResultFrameSchema, ComputerRegisterV1FrameSchema, ComputerRegisterV2FrameSchema, ConnectCodeExchangeRequestSchema, ConnectCodeExchangeResponseSchema, ConnectCodeIssueRequestSchema, ConnectCodeIssueResponseSchema, ContextTreeAliasSchema, ContextTreeConnectionSchema, ContextTreeOperationFrameSchema, ContextTreeOperationRequestSchema, ContextTreeOperationResponseSchema, ContextTreeOperationResultFrameSchema, ContextTreeRepositorySchema, ContextTreesSchema, CreateAgentRequestSchema, CreateAgentRuntimeConfigSchema, CreateFeishuSetupAttemptRequestSchema, CreateGitHubConnectionRequestSchema, CreateMCPServerRequestSchema, DEFAULT_SIGN_IN_DESTINATION, DiagnosticEventSchema, DirectImMessageDeliveryRequestSchema, ERROR_REPORT_FIELD_MAX_LENGTH, ERROR_REPORT_MESSAGE_MAX_LENGTH, ERROR_REPORT_STACK_MAX_LENGTH, ERROR_REPORT_URL_MAX_LENGTH, EffectiveRuntimeSnapshotSchema, EmailAddressSchema, EmailSignInRequestSchema, EmailSignUpRequestSchema, ErrorCategorySchema, ErrorCodeSchema, ErrorDetailSchema, ErrorEnvelopeSchema, ErrorPhaseSchema, ErrorReportRequestSchema, ErrorReportSourceSchema, ErrorRetryabilitySchema, ExternalMentionSchema, FEISHU_REQUIRED_TENANT_SCOPES, FEISHU_SETUP_ACTIVATION_REASONS, FEISHU_SETUP_ATTEMPT_CHECK_TEMPLATE, FEISHU_SETUP_ATTEMPT_TEMPLATE, FEISHU_TENANT_TOKEN_LOCAL_SENTINEL, FeishuSetupActivationReasonSchema, FeishuSetupActivationSchema, FeishuSetupAttemptSchema, FeishuSetupIntentSchema, FeishuSetupStateSchema, GITHUB_AGENT_SCOPE_MAX_DELEGATED_IM_SENDERS, GITHUB_AGENT_SCOPE_MAX_DELEGATED_SESSION_AGENTS, GITHUB_CONNECTION_ERROR_CODES, GITHUB_INTEGRATION_AUTHORIZATION_PATH, GITHUB_INTEGRATION_BINDINGS_PATH, GITHUB_INTEGRATION_DISCONNECT_PATH, GITHUB_INTEGRATION_PATH, GITHUB_INTEGRATION_REPOSITORIES_PATH, GITHUB_MANAGEMENT_ERROR_CODES, GITHUB_OAUTH_CALLBACK_PATH, GITHUB_OAUTH_ERROR_PARAM, GITHUB_OAUTH_OUTCOME_ERROR, GITHUB_OAUTH_OUTCOME_PARAM, GITHUB_OAUTH_OUTCOME_SUCCESS, GITHUB_OAUTH_RETURN_SURFACES, GITHUB_REPOSITORY_BINDINGS_MAX_AGENT_SCOPES, GITHUB_REPOSITORY_BINDINGS_MAX_BYTES, GITHUB_REPOSITORY_BINDINGS_MAX_REPOSITORIES, GITHUB_REPOSITORY_BINDINGS_SCHEMA_VERSION, GITHUB_REPOSITORY_DISCOVERY_MAX_INSTALLATIONS, GITHUB_REPOSITORY_DISCOVERY_PAGE_SIZE, GITHUB_WEBHOOK_PATH, GitBranchRefSchema, GitHubAgentScopeSchema, GitHubAgentScopeTaskDelegationSchema, GitHubConnectionStateSchema, GitHubConnectionStatusSchema, GitHubDecimalIdSchema, GitHubDelegatedImSenderIdSchema, GitHubDelegatedImSenderSchema, GitHubDiscoveredInstallationSchema, GitHubDiscoveredRepositorySchema, GitHubIntegrationAvailabilitySchema, GitHubIntegrationOverviewSchema, GitHubLoginSessionHashSchema, GitHubOAuthContextSchema, GitHubOAuthFlowIntentSchema, GitHubOAuthFlowPhaseSchema, GitHubOAuthOutcomeSearchSchema, GitHubOAuthReturnSurfaceSchema, GitHubRepositoryAccessSchema, GitHubRepositoryBindingSchema, GitHubRepositoryBindingsSchema, GitHubRepositoryDiscoveryPageSchema, GitHubRepositoryDiscoveryQuerySchema, GitHubRepositoryFullNameSchema, GitHubRepositoryPublishModeSchema, GitHubRepositoryRoleSchema, GitHubVersionStringSchema, HTTP_PATHS, HeartbeatFrameSchema, HeartbeatResultFrameSchema, HeartbeatV1FrameSchema, HeartbeatV2FrameSchema, IM_BINDING_BY_ID_TEMPLATE, IM_BINDING_DIAGNOSTICS_TEMPLATE, IM_CLI_PROVIDERS, INTEGRATION_CREDENTIAL_EXECUTION_REASONS, INTEGRATION_CREDENTIAL_EXECUTION_STATUSES, ImAttentionSchema, ImAuthorKindSchema, ImBindingAdminDetailSchema, ImBindingCredentialStatusSchema, ImBindingDiagnosticsSchema, ImBindingHandoffStatusSchema, ImBindingIdentitySchema, ImBindingMessagingExpectationSchema, ImBindingStateSchema, ImBindingSummarySchema, ImBindingUnbindRequiredDetailSchema, ImCliProviderSchema, ImCliReadinessStatusSchema, ImContentBlockSchema, ImContentV1Schema, ImConversationKindSchema, ImMessageDeliveryResultSchema, ImMessageDirectionSchema, ImMessageOperationSchema, ImOutboundContentMetaSchema, ImProviderSchema, ImResourceDescriptorSchema, InputRejectReasonSchema, IntegrationCredentialExecutionReasonSchema, IntegrationCredentialExecutionStatusSchema, InternalNavigationVisibilitySchema, InternalSessionRuntimeOverridesSchema, ListAccountComputersResponseSchema, ListAgentMCPServersResponseSchema, ListAgentSkillsResponseSchema, ListAgentsResponseSchema, ListAvailableMCPServersResponseSchema, ListMCPServersResponseSchema, ListTaskRepliesResponseSchema, ListTasksResponseSchema, LocalComputerPreparationResultSchema, LocalPreparationActionSchema, LocalPreparationCheckSchema, LocalPreparationComponentSchema, MCPAgentServerSchema, MCPAuthHeaderNameSchema, MCPAuthKindSchema, MCPAuthSchemeSchema, MCPAuthorizationStatusSchema, MCPAuthorizationSummarySchema, MCPAvailableServerSchema, MCPBindingOverridesSchema, MCPClientRegistrationSourceSchema, MCPCustomAuthHeaderSchema, MCPEffectiveConfigSchema, MCPExtraHeadersSchema, MCPOAuthOutcomeSearchSchema, MCPOverrideSourcesSchema, MCPProbeResponseSchema, MCPProbeSnapshotSchema, MCPProbeStateSchema, MCPProtocolEraSchema, MCPServerAgentSchema, MCPServerDescriptionSchema, MCPServerDetailSchema, MCPServerNameSchema, MCPServerSchema, MCPServerUrlSchema, MCPToolSnapshotSchema, MCP_ACCOUNT_TOOL_SNAPSHOT_MAX_BYTES, MCP_AUTH_KINDS, MCP_CLIENT_METADATA_PATH, MCP_ERROR_CODES, MCP_ERROR_CODE_METADATA, MCP_GATEWAY_ALLOWED_TOOL_RULE, MCP_GATEWAY_ERROR_CODES, MCP_GATEWAY_MAX_TOOLS, MCP_GATEWAY_NAME_SEPARATOR, MCP_GATEWAY_PATH, MCP_GATEWAY_REQUEST_MAX_BYTES, MCP_GATEWAY_SERVER_NAME, MCP_GATEWAY_TOOL_NAME_MAX_BYTES, MCP_LEGACY_PROTOCOL_VERSIONS, MCP_MAX_EXTRA_HEADERS, MCP_MAX_EXTRA_HEADERS_BYTES, MCP_MAX_EXTRA_HEADER_VALUE_BYTES, MCP_MODERN_PROTOCOL_VERSION, MCP_OAUTH_CALLBACK_PATH, MCP_OAUTH_ERROR_PARAM, MCP_OAUTH_OUTCOME_ERROR, MCP_OAUTH_OUTCOME_PARAM, MCP_OAUTH_OUTCOME_SUCCESS, MCP_OAUTH_SERVER_PARAM, MCP_PROBE_MAX_TOOLS, MCP_PROBE_MAX_TOOLS_BYTES, MCP_RESERVED_HEADER_NAMES, MCP_SERVERS_PATH, MCP_SERVER_BY_ID_TEMPLATE, MCP_SUPPORTED_PROTOCOL_VERSIONS, MCP_TOOL_DESCRIPTION_MAX_BYTES, MCP_TOOL_INPUT_SCHEMA_MAX_BYTES, MCP_TOOL_NAME_MAX_BYTES, MINIMUM_SUPPORTED_CLIENT_VERSION, McpGatewayErrorCodeSchema, MeResponseSchema, NormalizedInboundImEventSchema, OPENTAG_PLATFORM_INSTRUCTIONS, PASSWORD_MAX_LENGTH, PASSWORD_MIN_LENGTH, PROVIDER_CLI_ARTIFACT_PUBLIC_REASONS, PROVIDER_CLI_PUBLIC_FAILURE_REASONS, PROVIDER_CLI_REASON_V2_HEADER, PROVIDER_CLI_VALIDATION_RETRY_REASONS, PROVIDER_PROXY_AUTH_TIMEOUT_MS, PROVIDER_PROXY_CHUNK_MAX_BYTES, PROVIDER_PROXY_HEADER_MAX_BYTES, PROVIDER_PROXY_INITIAL_CREDIT_BYTES, PROVIDER_PROXY_MAX_FRAME_BYTES, PROVIDER_PROXY_MAX_STREAMS_PER_EXECUTION, PROVIDER_PROXY_MAX_STREAM_OPENS_PER_CONNECTION, PROVIDER_PROXY_STREAM_REVALIDATE_INTERVAL_MS, PROVIDER_READINESS_V1_HEADER, PROVIDER_READINESS_V2_HEADER, PasswordSchema, ProviderCliArtifactPublicReasonSchema, ProviderCliArtifactStatusFrameSchema, ProviderCliCancelFrameSchema, ProviderCliExpectedIdentitySchema, ProviderCliHandoffPhaseSchema, ProviderCliHandoffProgressSchema, ProviderCliPrewarmFrameSchema, ProviderCliPrewarmResultFrameSchema, ProviderCliPublicFailureReasonSchema, ProviderCliRequirementFrameSchema, ProviderCliValidationGrantFrameSchema, ProviderCliValidationResultFrameSchema, ProviderCliValidationResultReasonSchema, ProviderCliValidationRetryReasonSchema, ProviderCliValidationRunFrameSchema, ProviderInboundContextSchema, ProviderReadinessStatusSchema, RUNNER_ACCEPTANCE_MODES, RUNNER_ACCEPTANCE_PROVIDER, RUNNER_ACCEPTANCE_WORKER_STDIN_MAX_BYTES, RUNNER_CLOUD_DELIVERY_VERSION, RUNNER_CLOUD_TURN_WORKER_STDIN_MAX_BYTES, RUNNER_PI_CONFIG_DOCUMENT_MAX_BYTES, RUNNER_PI_CONFIG_DOCUMENT_MAX_CHARS, RUNNER_REUSE_VERSION, RUNNER_SESSION_COLLABORATION_VERSION, RUNNER_WORKSPACE_ARCHIVE_MAX_BYTES, RUNNER_WORKSPACE_PATH, RUNNER_WORKSPACE_TIMEOUT_MS, RUNNER_WORKSPACE_VERSION, RUNNER_WS_CLOSE, RUNNER_WS_MAX_FRAME_BYTES, RUNNER_WS_PROTOCOL_VERSION, RUNTIME_AGENT_MCP_SERVERS_AVAILABLE_PATH, RUNTIME_AGENT_MCP_SERVERS_PATH, RUNTIME_AGENT_MCP_SERVER_TEMPLATE, RUNTIME_AGENT_PATH, RUNTIME_AGENT_RUNTIME_TEST_CLEANUP_MS, RUNTIME_AGENT_RUNTIME_TEST_MAX_PENDING, RUNTIME_AGENT_RUNTIME_TEST_TIMEOUT_MS, RUNTIME_AGENT_RUNTIME_TEST_TTL_MS, RUNTIME_CAPABILITY, RUNTIME_CLIENT_CAPABILITY_OFFERS, RUNTIME_CLIENT_CAPABILITY_TTL_MS, RUNTIME_CLI_METADATA_MAX_REPOSITORIES, RUNTIME_CREDENTIAL_CAPABILITY_REFRESH_AFTER_MS, RUNTIME_CREDENTIAL_CAPABILITY_TTL_MS, RUNTIME_CREDENTIAL_PROVIDERS, RUNTIME_DEFAULT_MAX_DURATION_MS, RUNTIME_DIRECT_TEXT_MAX_BYTES, RUNTIME_DURABLE_WORK_PATH, RUNTIME_EXECUTION_MAX_LIFETIME_MS, RUNTIME_FINAL_TEXT_MAX_BYTES, RUNTIME_HEARTBEAT_INTERVAL_MAX_MS, RUNTIME_HEARTBEAT_INTERVAL_MIN_MS, RUNTIME_HEARTBEAT_TIMEOUT_MAX_MS, RUNTIME_HEARTBEAT_TIMEOUT_MIN_MS, RUNTIME_ID_MAX_BYTES, RUNTIME_IM_HISTORY_MAX_BYTES, RUNTIME_IM_RESOURCE_MAX_COUNT, RUNTIME_IM_RESOURCE_TEMPLATE, RUNTIME_INSTRUCTIONS_MAX_BYTES, RUNTIME_MAX_DURATION_MS, RUNTIME_MAX_FRAME_BYTES, RUNTIME_MCP_SERVICE, RUNTIME_MVP_RETAINED_REPORT_LIMIT, RUNTIME_OUTGOING_REPLY_MAX_COUNT, RUNTIME_OUTGOING_REPLY_RAW_MAX_BYTES, RUNTIME_OUTGOING_REPLY_SNAPSHOT_MAX_BYTES, RUNTIME_OUTGOING_REPLY_TEXT_MAX_BYTES, RUNTIME_PROTOCOL_V1, RUNTIME_PROTOCOL_V2, RUNTIME_PROTOCOL_VERSION, RUNTIME_PROVIDER_CLI_ARTIFACT_TTL_MS, RUNTIME_PROVIDER_CLI_CREDENTIAL_TTL_MS, RUNTIME_PROVIDER_CLI_REQUIREMENT_OPERATION, RUNTIME_PROVIDER_CLI_VALIDATION_GRANT_TTL_MS, RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES, RUNTIME_PROVIDER_CLI_VALIDATION_MAX_RETRIES, RUNTIME_PROVIDER_CLI_VALIDATION_TIMEOUT_MS, RUNTIME_PROVIDER_ORIGIN_HEADER, RUNTIME_PROVIDER_PROXY_PATH, RUNTIME_PROVIDER_READINESS_V1, RUNTIME_PROVIDER_READINESS_V1_PROVIDERS, RUNTIME_PROVIDER_READINESS_V2, RUNTIME_PROVIDER_READINESS_V2_PROVIDERS, RUNTIME_PROXY_TICKET_TTL_MS, RUNTIME_REQUIRED_CLIENT_CAPABILITIES, RUNTIME_REQUIRED_SERVER_CAPABILITIES, RUNTIME_SERVER_CAPABILITY_OFFERS, RUNTIME_SKILLS_PATH, RUNTIME_SKILL_BUNDLE_TEMPLATE, RUNTIME_SUPPORTED_PROTOCOL_VERSIONS, RUNTIME_TRACE_BATCH_MAX_EVENTS, RUNTIME_TRACE_EVENT_MAX_BYTES, RUNTIME_V0_CAPABILITIES, RUNTIME_VALIDATION_RUN_TTL_MS, RUNTIME_WEB_FETCH_PATH, RUNTIME_WEB_SEARCH_PATH, RUNTIME_WEB_SERVICE, RebindAgentComputerRequestSchema, ReceiveModeSchema, RefreshTokenRequestSchema, RefreshTokenResponseSchema, RetainedTurnReportClaimSchema, RetryabilitySchema, RouterGatewayErrorSchema, RouterWebFetchRequestSchema, RouterWebSearchRequestSchema, RunnerAcceptanceCancelFrameSchema, RunnerAcceptanceEventWireSchema, RunnerAcceptanceEvidenceWireSchema, RunnerAcceptanceModeSchema, RunnerAcceptanceReportWireSchema, RunnerAcceptanceResultFrameSchema, RunnerAcceptanceRunFrameSchema, RunnerAuthFrameSchema, RunnerAuthResultFrameSchema, RunnerClientFrameSchema, RunnerCloudDeliveryCancelFrameSchema, RunnerCloudDeliveryQueryFrameSchema, RunnerCloudDeliveryQueryResultFrameSchema, RunnerCloudDeliveryReceivedFrameSchema, RunnerCloudDeliveryReportAckFrameSchema, RunnerCloudDeliveryReportFrameSchema, RunnerCloudDeliveryRunFrameSchema, RunnerCloudDeliveryVerifiedFrameSchema, RunnerCloudModelGrantSchema, RunnerCloudSessionMessageCancelFrameSchema, RunnerCloudSessionMessageReceivedFrameSchema, RunnerCloudSessionMessageRunFrameSchema, RunnerCloudSessionMessageSettledAckFrameSchema, RunnerCloudSessionMessageSettledFrameSchema, RunnerCloudSessionMessageVerifiedFrameSchema, RunnerCloudSessionWorkerRequestSchema, RunnerCloudTurnWorkerRequestSchema, RunnerCloudWorkerRequestSchema, RunnerCredentialTunnelFrameSchema, RunnerCredentialTunnelResultFrameSchema, RunnerHeartbeatFrameSchema, RunnerIdentityWireSchema, RunnerPiConfigInputSchema, RunnerReadinessSchema, RunnerReadyFrameSchema, RunnerServerCredentialFrameSchema, RunnerServerErrorFrameSchema, RunnerServerFrameSchema, RunnerServerHeartbeatFrameSchema, RunnerWelcomeFrameSchema, RunnerWorkspaceObjectSchema, RunnerWorkspaceSealFrameSchema, RunnerWorkspaceSealResultFrameSchema, RuntimeCapabilitiesSchema, RuntimeCapabilityOffersSchema, RuntimeCapabilityRangeSchema, RuntimeChannelTargetSchema, RuntimeClientCapabilitiesSchema, RuntimeConnectionIdSchema, RuntimeCredentialAcquireRequestSchema, RuntimeCredentialClientFrameSchema, RuntimeCredentialProviderSchema, RuntimeCredentialRejectCodeSchema, RuntimeCredentialRenewRequestSchema, RuntimeCredentialResultSchema, RuntimeCredentialRevokedCodeSchema, RuntimeCredentialRevokedFrameSchema, RuntimeCredentialServerFrameSchema, RuntimeDurableFailureSchema, RuntimeDurableWorkKindSchema, RuntimeDurableWorkListResponseSchema, RuntimeDurableWorkRecordSchema, RuntimeDurableWorkStatusSchema, RuntimeErrorFrameSchema, RuntimeExecutionCloseRequestSchema, RuntimeExecutionClosedResultSchema, RuntimeExecutionOpenRejectCodeSchema, RuntimeExecutionOpenRequestSchema, RuntimeExecutionOpenResultSchema, RuntimeExecutionProviderSchema, RuntimeExecutionSandboxSchema, RuntimeExecutionServiceRequestSchema, RuntimeExecutionServiceSchema, RuntimeExecutionSourceSchema, RuntimeFeishuCliMetadataSchema, RuntimeFrameEnvelopeSchema, RuntimeGitHubCliMetadataSchema, RuntimeGitHubCliRepositorySchema, RuntimeHeartbeatIntervalMsSchema, RuntimeHeartbeatTimeoutMsSchema, RuntimeImCliReadinessCollectionSchema, RuntimeImCliReadinessObservationSchema, RuntimeImCredentialGrantRequestSchema, RuntimeImCredentialGrantResultSchema, RuntimeImDeliveryContentSchema, RuntimeImHistoryItemSchema, RuntimeImOutboxContextSchema, RuntimeImResourceReferenceSchema, RuntimeImSteerRequestSchema, RuntimeImSteerResultSchema, RuntimeInstructionSchema, RuntimeInstructionsSchema, RuntimeMaxDurationMsSchema, RuntimeMcpExecutionServiceSchema, RuntimeMcpGatewayRejectCodeSchema, RuntimeMcpGatewayRequestSchema, RuntimeMcpGatewayResultSchema, RuntimeMcpServiceScopeSchema, RuntimeModelSchema, RuntimeNegotiatedCapabilitiesSchema, RuntimeProtocolRangeSchema, RuntimeProviderCliMetadataSchema, RuntimeProviderMessageRefSchema, RuntimeProviderProxyAuthFrameSchema, RuntimeProviderProxyCancelFrameSchema, RuntimeProviderProxyClientFrameSchema, RuntimeProviderProxyCreditFrameSchema, RuntimeProviderProxyEndFrameSchema, RuntimeProviderProxyErrorFrameSchema, RuntimeProviderProxyOpenFrameSchema, RuntimeProviderProxyReadyFrameSchema, RuntimeProviderProxyResponseFrameSchema, RuntimeProviderProxyServerFrameSchema, RuntimeProviderReadinessCollectionSchema, RuntimeProviderReadinessNegotiationSchema, RuntimeProviderReadinessObservationSchema, RuntimeProxyTicketRejectCodeSchema, RuntimeProxyTicketRequestSchema, RuntimeProxyTicketResultSchema, RuntimeReasoningEffortSchema, RuntimeRequestIdSchema, RuntimeRevisionSchema, RuntimeSequenceSchema, RuntimeSha256Schema, RuntimeSkillManifestEntrySchema, RuntimeSkillManifestSchema, RuntimeSlackCliMetadataSchema, RuntimeUsageSchema, RuntimeWebExecutionServiceSchema, RuntimeWebGatewayRejectCodeSchema, RuntimeWebGatewayRequestSchema, RuntimeWebGatewayResultSchema, RuntimeWebServiceScopeSchema, SANDBOX_RUNNER_WEBSOCKET_PATH, SEMVER_PATTERN, SESSION_CLI_DEFAULT_LIMIT, SESSION_CLI_MAX_LIMIT, SESSION_CLI_PROOF_HEADER, SESSION_CLI_TASK_PREVIEW_MAX_BYTES, SKILL_ARCHIVE_MAX_BYTES, SKILL_DESCRIPTION_MAX_LENGTH, SKILL_ERROR_CODES, SKILL_ERROR_CODE_METADATA, SKILL_FORMAT_HEADER, SKILL_MANIFEST_FILE, SKILL_MANIFEST_MAX_BYTES, SKILL_MARKER_FILE, SKILL_MAX_ENTRIES, SKILL_MAX_LISTED_FILES, SKILL_MAX_PATH_BYTES, SKILL_MAX_PER_AGENT, SKILL_REPLACE_HEADER, SKILL_RESERVED_NAMES, SKILL_SHA256_HEADER, SKILL_UNPACKED_MAX_BYTES, SKILL_UPLOAD_CONTENT_TYPE, SLACK_EVENTS_PATH, SLACK_OAUTH_CALLBACK_PATH, SLACK_OAUTH_RETURN_SURFACES, SLACK_REQUIRED_BOT_SCOPES, SLACK_SUBSCRIBED_BOT_EVENTS, STRUCTURED_ERROR_LOG_FIELD_MAX_BYTES, STRUCTURED_ERROR_MAX_CAUSE_DEPTH, STRUCTURED_ERROR_MESSAGE_MAX_BYTES, STRUCTURED_ERROR_REQUEST_ID_MAX_BYTES, STRUCTURED_ERROR_SERIALIZATION_MAX_ARRAY_ITEMS, STRUCTURED_ERROR_SERIALIZATION_MAX_DEPTH, STRUCTURED_ERROR_SERIALIZATION_MAX_KEYS, SandboxLifecycleSchema, SemVerStringSchema, ServerHealthSchema, ServerRuntimeBusinessFrameSchema, ServerRuntimeFrameSchema, ServerWelcomeFrameSchema, ServerWelcomeV1FrameSchema, ServerWelcomeV2FrameSchema, ServiceIdSchema, SessionCliCommandResponseSchema, SessionCliCommandStatusSchema, SessionCliCreateRequestSchema, SessionCliListItemSchema, SessionCliListQuerySchema, SessionCliListResponseSchema, SessionCliProofGrantSchema, SessionCliSendRequestSchema, SessionKindSchema, SessionMessageDeliveryRequestSchema, SessionMessageDeliveryResultSchema, SessionPlacementSchema, SessionReconcileRequestSchema, SessionReconcileResultSchema, SessionSchema, SetMCPAuthorizationRequestSchema, SkillArchiveFormatSchema, SkillArchiveSha256Schema, SkillDetailSchema, SkillFileEntrySchema, SkillInstallMarkerSchema, SkillManifestSchema, SkillNameSchema, SkillSchema, SkillSourceSchema, SkillStorageStatusSchema, SlackBindingActivationSchema, SlackConfigurationIntentSchema, SlackConfigurationResultSchema, SlackIdentityClosureSchema, SlackOAuthReturnSurfaceSchema, StartGitHubAuthorizationRequestSchema, StartGitHubAuthorizationResponseSchema, StartMCPOAuthRequestSchema, StartMCPOAuthResponseSchema, StartSlackOAuthRequestSchema, StartSlackOAuthResponseSchema, StructuredErrorCategorySchema, StructuredErrorCauseSchema, StructuredErrorCodeSchema, StructuredErrorMessageSchema, StructuredErrorPhaseSchema, StructuredErrorSchema, TASK_AUTO_TITLE_MAX_GRAPHEMES, TASK_BY_ID_TEMPLATE, TASK_CANCELLED_DELIVERY_REASON, TASK_CANCEL_TEMPLATE, TASK_REPLIES_TEMPLATE, TASK_TITLE_MAX_LENGTH, TaskAttachmentSchema, TaskCancelResponseSchema, TaskCollaborationMessageSchema, TaskDetailSchema, TaskInternalSessionSchema, TaskReplySchema, TaskReplyTimeSourceSchema, TaskSessionKindSchema, TaskStatusSchema, TaskSummarySchema, TaskTitleSchema, TaskTitleUpdateRequestSchema, TaskTitleUpdateResponseSchema, TaskTurnSchema, TurnFailureReasonSchema, TurnOutgoingReplyContentSchema, TurnOutgoingReplyMsgTypeSchema, TurnOutgoingReplySchema, TurnOutgoingReplySnapshotSchema, TurnOutgoingReplyUnavailableReasonSchema, TurnReportRequestSchema, TurnReportResultSchema, UnbindAgentMessagingRequestSchema, UpdateAgentRequestSchema, UpdateAgentRuntimeConfigSchema, UpdateGitHubConnectionBindingsRequestSchema, UpdateMCPBindingRequestSchema, UpdateMCPServerRequestSchema, UpdateSelfAgentRequestSchema, UpdateSelfAgentRuntimeConfigSchema, UpdateSelfMCPBindingRequestSchema, UpdateSkillRequestSchema, UpdateUserProfileRequestSchema, UserDisplayNameSchema, UserProfileSchema, ValidationIssueSchema, WEB_DOMAIN_MAX_BYTES, WEB_FETCH_RESPONSE_MAX_BYTES, WEB_FETCH_TIMEOUT_CAP_MS, WEB_FETCH_URLS_MAX, WEB_GATEWAY_FETCH_PATH, WEB_GATEWAY_SEARCH_PATH, WEB_IDEMPOTENCY_KEY_MAX_BYTES, WEB_IDEMPOTENCY_NAMESPACE, WEB_LANGUAGE_MAX_CODEPOINTS, WEB_PAGE_BODY_MAX_BYTES, WEB_PUBLISHED_AT_MAX_BYTES, WEB_REQUEST_MAX_BYTES, WEB_SEARCH_DOMAINS_MAX, WEB_SEARCH_LIMIT_DEFAULT, WEB_SEARCH_LIMIT_MAX, WEB_SEARCH_QUERY_MAX_CODEPOINTS, WEB_SEARCH_RESPONSE_MAX_BYTES, WEB_SEARCH_TIMEOUT_CAP_MS, WEB_TIMEOUT_HEADER, WEB_TOOLS_PROTOCOL_VERSION, WEB_TOOL_ERROR_CODES, WEB_TOOL_PREVIEW_PAGE_MAX_BYTES, WEB_TOOL_RESULT_MAX_BYTES, WEB_URL_MAX_BYTES, WebFetchExecutionRequestSchema, WebFetchItemFailureSchema, WebFetchItemSchema, WebFetchItemSuccessSchema, WebFetchParamsSchema, WebFetchResultSchema, WebGatewayFetchRequestSchema, WebGatewaySearchRequestSchema, WebSearchExecutionRequestSchema, WebSearchParamsSchema, WebSearchResultItemSchema, WebSearchResultSchema, WebToolDepthSchema, WebToolErrorCodeSchema, WebToolErrorEnvelopeSchema, WebToolTimeRangeSchema, accountAgentCreationIntentPath, accountComputerByIdPath, accountComputerConnectCodePath, accountComputerDisconnectPath, accountSandboxPath, accountSandboxRunnerAcceptancePath, accountSandboxRunnerPath, accountSandboxRunnerStartPath, accountSandboxRunnerStopPath, advertisedProviderReadiness, agentByIdPath, agentCloudPath, agentComputerRebindPath, agentConfigPath, agentContextTreePath, agentFeishuSetupAttemptsPath, agentImBindingConfigPath, agentImBindingHandoffPath, agentImBindingPath, agentImBindingUnbindPath, agentMcpAuthorizationOAuthPath, agentMcpAuthorizationPath, agentMcpProbePath, agentMcpServerPath, agentMcpServersPath, agentReactivatePath, agentRuntimeTestPath, agentSetupPath, agentSetupRefreshPath, agentSkillBundlePath, agentSkillPath, agentSkillsPath, agentSlackEventsPath, agentSlackOAuthStartPath, agentSuspendPath, agentUsagePath, boundedSerialize, canonicalizeGitHubRepositoryBindings, capWebTimeoutMs, classifyProviderCliArtifactFailure, clientSupportsComputerRuntimeProvider, compareSemVer, composeGatewayToolName, computeDirectInputHash, computeReconcilePayloadHash, computeRuntimeImMessageSemanticHash, computeRuntimeImSteerInputHash, computeRuntimeSnapshotHashes, computeTurnResultHash, computerAgentSkillBundlePath, computerAgentSkillsPath, createErrorReport, decodeProviderProxyDataFrame, deriveWebIdempotencyKey, encodeProviderProxyDataFrame, feishuSetupAttemptCancelPath, feishuSetupAttemptCheckPath, feishuSetupAttemptPath, getChannelConfig, getRuntimeConfigurationOptions, githubAgentScopeAllowsTaskDelegation, githubIntegrationAuthorizationPath, githubIntegrationBindingsPath, githubIntegrationDisconnectPath, githubIntegrationPath, githubIntegrationRepositoriesPath, hasRequiredFeishuTenantScopes, hasRequiredSlackBotScopes, hashTuple, imBindingDiagnosticsPath, imBindingDisablePath, isReservedSkillName, isSemVer, isSupportedClientVersion, isValidGitRefName, mcpServerPath, mcpServersPath, missingRuntimeCapabilities, negotiateProviderReadinessFromHeaders, negotiateRuntimeCapabilities, normalizeContextTrees, normalizeExtraHeaders, normalizeWebTargetUrl, parseSemVer, parseSkillManifest, parseWebDomain, parseWebTargetUrl, parseWebTimeoutHeader, probedServerDescription, projectAgentSetupComponents, providerCliArtifactFailureIsManual, publicProviderCliArtifactReason, redactDiagnostic, redactForLog, redactSensitive, renderPlatformInstructions, requestsCloudIdentityV1, requestsProviderCliReasonV2, requestsProviderReadinessV1, requestsProviderReadinessV2, resolveSignInDestination, runtimeAgentMcpServerPath, runtimeDurableWorkPath, runtimeFrameByteLength, runtimeImResourcePath, runtimeNegotiatedCapabilitiesEqual, runtimeSkillBundlePath, runtimeUsageTotalTokens, runtimeWebSocketUrl, sandboxRunnerWebSocketUrl, sanitizeErrorReportUrl, serializeDiagnostic, serializeRunnerAcceptanceWorkerStdin, serializeRunnerCloudSessionWorkerStdin, serializeRunnerCloudTurnWorkerStdin, taskByIdPath, taskCancelPath, taskRepliesPath, unsupportedClientVersionMessage, webServiceScopeForOperation, withComputerRuntimeProviderSupport };\n\n//# sourceMappingURL=index.mjs.map","'use strict'\n\n// **************************************************************\n// * Code initially copied/adapted from \"pony-cause\" npm module *\n// * Please upstream improvements there                         *\n// **************************************************************\n\nconst isErrorLike = (err) => {\n  return err && typeof err.message === 'string'\n}\n\n/**\n * @param {Error|{ cause?: unknown|(()=>err)}} err\n * @returns {Error|Object|undefined}\n */\nconst getErrorCause = (err) => {\n  if (!err) return\n\n  /** @type {unknown} */\n  // @ts-ignore\n  const cause = err.cause\n\n  // VError / NError style causes\n  if (typeof cause === 'function') {\n    // @ts-ignore\n    const causeResult = err.cause()\n\n    return isErrorLike(causeResult)\n      ? causeResult\n      : undefined\n  } else {\n    return isErrorLike(cause)\n      ? cause\n      : undefined\n  }\n}\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set<Error>} seen\n * @returns {string}\n */\nconst _stackWithCauses = (err, seen) => {\n  if (!isErrorLike(err)) return ''\n\n  const stack = err.stack || ''\n\n  // Ensure we don't go circular or crazily deep\n  if (seen.has(err)) {\n    return stack + '\\ncauses have become circular...'\n  }\n\n  const cause = getErrorCause(err)\n\n  if (cause) {\n    seen.add(err)\n    return (stack + '\\ncaused by: ' + _stackWithCauses(cause, seen))\n  } else {\n    return stack\n  }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst stackWithCauses = (err) => _stackWithCauses(err, new Set())\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set<Error>} seen\n * @param {boolean} [skip]\n * @returns {string}\n */\nconst _messageWithCauses = (err, seen, skip) => {\n  if (!isErrorLike(err)) return ''\n\n  const message = skip ? '' : (err.message || '')\n\n  // Ensure we don't go circular or crazily deep\n  if (seen.has(err)) {\n    return message + ': ...'\n  }\n\n  const cause = getErrorCause(err)\n\n  if (cause) {\n    seen.add(err)\n\n    // @ts-ignore\n    const skipIfVErrorStyleCause = typeof err.cause === 'function'\n\n    return (message +\n      (skipIfVErrorStyleCause ? '' : ': ') +\n      _messageWithCauses(cause, seen, skipIfVErrorStyleCause))\n  } else {\n    return message\n  }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst messageWithCauses = (err) => _messageWithCauses(err, new Set())\n\nmodule.exports = {\n  isErrorLike,\n  getErrorCause,\n  stackWithCauses,\n  messageWithCauses\n}\n","'use strict'\n\nconst seen = Symbol('circular-ref-tag')\nconst rawSymbol = Symbol('pino-raw-err-ref')\n\nconst pinoErrProto = Object.create({}, {\n  type: {\n    enumerable: true,\n    writable: true,\n    value: undefined\n  },\n  message: {\n    enumerable: true,\n    writable: true,\n    value: undefined\n  },\n  stack: {\n    enumerable: true,\n    writable: true,\n    value: undefined\n  },\n  aggregateErrors: {\n    enumerable: true,\n    writable: true,\n    value: undefined\n  },\n  raw: {\n    enumerable: false,\n    get: function () {\n      return this[rawSymbol]\n    },\n    set: function (val) {\n      this[rawSymbol] = val\n    }\n  }\n})\nObject.defineProperty(pinoErrProto, rawSymbol, {\n  writable: true,\n  value: {}\n})\n\nmodule.exports = {\n  pinoErrProto,\n  pinoErrorSymbols: {\n    seen,\n    rawSymbol\n  }\n}\n","'use strict'\n\nmodule.exports = errSerializer\n\nconst { messageWithCauses, stackWithCauses, isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errSerializer (err) {\n  if (!isErrorLike(err)) {\n    return err\n  }\n\n  err[seen] = undefined // tag to prevent re-looking at this\n  const _err = Object.create(pinoErrProto)\n  _err.type = toString.call(err.constructor) === '[object Function]'\n    ? err.constructor.name\n    : err.name\n  _err.message = messageWithCauses(err)\n  _err.stack = stackWithCauses(err)\n\n  if (Array.isArray(err.errors)) {\n    _err.aggregateErrors = err.errors.map(err => errSerializer(err))\n  }\n\n  for (const key in err) {\n    if (_err[key] === undefined) {\n      const val = err[key]\n      if (isErrorLike(val)) {\n        // We append cause messages and stacks to _err, therefore skipping causes here\n        if (key !== 'cause' && !Object.prototype.hasOwnProperty.call(val, seen)) {\n          _err[key] = errSerializer(val)\n        }\n      } else {\n        _err[key] = val\n      }\n    }\n  }\n\n  delete err[seen] // clean up tag in case err is serialized again later\n  _err.raw = err\n  return _err\n}\n","'use strict'\n\nmodule.exports = errWithCauseSerializer\n\nconst { isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errWithCauseSerializer (err) {\n  if (!isErrorLike(err)) {\n    return err\n  }\n\n  err[seen] = undefined // tag to prevent re-looking at this\n  const _err = Object.create(pinoErrProto)\n  _err.type = toString.call(err.constructor) === '[object Function]'\n    ? err.constructor.name\n    : err.name\n  _err.message = err.message\n  _err.stack = err.stack\n\n  if (Array.isArray(err.errors)) {\n    _err.aggregateErrors = err.errors.map(err => errWithCauseSerializer(err))\n  }\n\n  if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) {\n    _err.cause = errWithCauseSerializer(err.cause)\n  }\n\n  for (const key in err) {\n    if (_err[key] === undefined) {\n      const val = err[key]\n      if (isErrorLike(val)) {\n        if (!Object.prototype.hasOwnProperty.call(val, seen)) {\n          _err[key] = errWithCauseSerializer(val)\n        }\n      } else {\n        _err[key] = val\n      }\n    }\n  }\n\n  delete err[seen] // clean up tag in case err is serialized again later\n  _err.raw = err\n  return _err\n}\n","'use strict'\n\nmodule.exports = {\n  mapHttpRequest,\n  reqSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-req-ref')\nconst pinoReqProto = Object.create({}, {\n  id: {\n    enumerable: true,\n    writable: true,\n    value: ''\n  },\n  method: {\n    enumerable: true,\n    writable: true,\n    value: ''\n  },\n  url: {\n    enumerable: true,\n    writable: true,\n    value: ''\n  },\n  query: {\n    enumerable: true,\n    writable: true,\n    value: ''\n  },\n  params: {\n    enumerable: true,\n    writable: true,\n    value: ''\n  },\n  headers: {\n    enumerable: true,\n    writable: true,\n    value: {}\n  },\n  remoteAddress: {\n    enumerable: true,\n    writable: true,\n    value: ''\n  },\n  remotePort: {\n    enumerable: true,\n    writable: true,\n    value: ''\n  },\n  raw: {\n    enumerable: false,\n    get: function () {\n      return this[rawSymbol]\n    },\n    set: function (val) {\n      this[rawSymbol] = val\n    }\n  }\n})\nObject.defineProperty(pinoReqProto, rawSymbol, {\n  writable: true,\n  value: {}\n})\n\nfunction reqSerializer (req) {\n  // req.info is for hapi compat.\n  const connection = req.info || req.socket\n  const _req = Object.create(pinoReqProto)\n  _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)))\n  _req.method = req.method\n  // req.originalUrl is for expressjs compat.\n  if (req.originalUrl) {\n    _req.url = req.originalUrl\n  } else {\n    const path = req.path\n    // path for safe hapi compat.\n    _req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined)\n  }\n\n  if (req.query) {\n    _req.query = req.query\n  }\n\n  if (req.params) {\n    _req.params = req.params\n  }\n\n  _req.headers = req.headers\n  _req.remoteAddress = connection && connection.remoteAddress\n  _req.remotePort = connection && connection.remotePort\n  // req.raw is  for hapi compat/equivalence\n  _req.raw = req.raw || req\n  return _req\n}\n\nfunction mapHttpRequest (req) {\n  return {\n    req: reqSerializer(req)\n  }\n}\n","'use strict'\n\nmodule.exports = {\n  mapHttpResponse,\n  resSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-res-ref')\nconst pinoResProto = Object.create({}, {\n  statusCode: {\n    enumerable: true,\n    writable: true,\n    value: 0\n  },\n  headers: {\n    enumerable: true,\n    writable: true,\n    value: ''\n  },\n  raw: {\n    enumerable: false,\n    get: function () {\n      return this[rawSymbol]\n    },\n    set: function (val) {\n      this[rawSymbol] = val\n    }\n  }\n})\nObject.defineProperty(pinoResProto, rawSymbol, {\n  writable: true,\n  value: {}\n})\n\nfunction resSerializer (res) {\n  const _res = Object.create(pinoResProto)\n  _res.statusCode = res.headersSent ? res.statusCode : null\n  _res.headers = res.getHeaders ? res.getHeaders() : res._headers\n  _res.raw = res\n  return _res\n}\n\nfunction mapHttpResponse (res) {\n  return {\n    res: resSerializer(res)\n  }\n}\n","'use strict'\n\nconst errSerializer = require('./lib/err')\nconst errWithCauseSerializer = require('./lib/err-with-cause')\nconst reqSerializers = require('./lib/req')\nconst resSerializers = require('./lib/res')\n\nmodule.exports = {\n  err: errSerializer,\n  errWithCause: errWithCauseSerializer,\n  mapHttpRequest: reqSerializers.mapHttpRequest,\n  mapHttpResponse: resSerializers.mapHttpResponse,\n  req: reqSerializers.reqSerializer,\n  res: resSerializers.resSerializer,\n\n  wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {\n    if (customSerializer === errSerializer) return customSerializer\n    return function wrapErrSerializer (err) {\n      return customSerializer(errSerializer(err))\n    }\n  },\n\n  wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {\n    if (customSerializer === reqSerializers.reqSerializer) return customSerializer\n    return function wrappedReqSerializer (req) {\n      return customSerializer(reqSerializers.reqSerializer(req))\n    }\n  },\n\n  wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {\n    if (customSerializer === resSerializers.resSerializer) return customSerializer\n    return function wrappedResSerializer (res) {\n      return customSerializer(resSerializers.resSerializer(res))\n    }\n  }\n}\n","'use strict'\n\nfunction noOpPrepareStackTrace (_, stack) {\n  return stack\n}\n\nmodule.exports = function getCallers () {\n  const originalPrepare = Error.prepareStackTrace\n  Error.prepareStackTrace = noOpPrepareStackTrace\n  const stack = new Error().stack\n  Error.prepareStackTrace = originalPrepare\n\n  if (!Array.isArray(stack)) {\n    return undefined\n  }\n\n  const entries = stack.slice(2)\n\n  const fileNames = []\n\n  for (const entry of entries) {\n    if (!entry) {\n      continue\n    }\n\n    fileNames.push(entry.getFileName())\n  }\n\n  return fileNames\n}\n","'use strict'\n\nfunction deepClone (obj) {\n  if (obj === null || typeof obj !== 'object') {\n    return obj\n  }\n\n  if (obj instanceof Date) {\n    return new Date(obj.getTime())\n  }\n\n  if (obj instanceof Array) {\n    const cloned = []\n    for (let i = 0; i < obj.length; i++) {\n      cloned[i] = deepClone(obj[i])\n    }\n    return cloned\n  }\n\n  if (typeof obj === 'object') {\n    const cloned = Object.create(Object.getPrototypeOf(obj))\n    for (const key in obj) {\n      if (Object.prototype.hasOwnProperty.call(obj, key)) {\n        cloned[key] = deepClone(obj[key])\n      }\n    }\n    return cloned\n  }\n\n  return obj\n}\n\nfunction parsePath (path) {\n  const parts = []\n  let current = ''\n  let inBrackets = false\n  let inQuotes = false\n  let quoteChar = ''\n\n  for (let i = 0; i < path.length; i++) {\n    const char = path[i]\n\n    if (!inBrackets && char === '.') {\n      if (current) {\n        parts.push(current)\n        current = ''\n      }\n    } else if (char === '[') {\n      if (current) {\n        parts.push(current)\n        current = ''\n      }\n      inBrackets = true\n    } else if (char === ']' && inBrackets) {\n      // Always push the current value when closing brackets, even if it's an empty string\n      parts.push(current)\n      current = ''\n      inBrackets = false\n      inQuotes = false\n    } else if ((char === '\"' || char === \"'\") && inBrackets) {\n      if (!inQuotes) {\n        inQuotes = true\n        quoteChar = char\n      } else if (char === quoteChar) {\n        inQuotes = false\n        quoteChar = ''\n      } else {\n        current += char\n      }\n    } else {\n      current += char\n    }\n  }\n\n  if (current) {\n    parts.push(current)\n  }\n\n  return parts\n}\n\nfunction setValue (obj, parts, value) {\n  let current = obj\n\n  for (let i = 0; i < parts.length - 1; i++) {\n    const key = parts[i]\n    // Type safety: Check if current is an object before using 'in' operator\n    if (typeof current !== 'object' || current === null || !(key in current)) {\n      return false // Path doesn't exist, don't create it\n    }\n    if (typeof current[key] !== 'object' || current[key] === null) {\n      return false // Path doesn't exist properly\n    }\n    current = current[key]\n  }\n\n  const lastKey = parts[parts.length - 1]\n  if (lastKey === '*') {\n    if (Array.isArray(current)) {\n      for (let i = 0; i < current.length; i++) {\n        current[i] = value\n      }\n    } else if (typeof current === 'object' && current !== null) {\n      for (const key in current) {\n        if (Object.prototype.hasOwnProperty.call(current, key)) {\n          current[key] = value\n        }\n      }\n    }\n  } else {\n    // Type safety: Check if current is an object before using 'in' operator\n    if (typeof current === 'object' && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) {\n      current[lastKey] = value\n    }\n  }\n  return true\n}\n\nfunction removeKey (obj, parts) {\n  let current = obj\n\n  for (let i = 0; i < parts.length - 1; i++) {\n    const key = parts[i]\n    // Type safety: Check if current is an object before using 'in' operator\n    if (typeof current !== 'object' || current === null || !(key in current)) {\n      return false // Path doesn't exist, don't create it\n    }\n    if (typeof current[key] !== 'object' || current[key] === null) {\n      return false // Path doesn't exist properly\n    }\n    current = current[key]\n  }\n\n  const lastKey = parts[parts.length - 1]\n  if (lastKey === '*') {\n    if (Array.isArray(current)) {\n      // For arrays, we can't really \"remove\" all items as that would change indices\n      // Instead, we set them to undefined which will be omitted by JSON.stringify\n      for (let i = 0; i < current.length; i++) {\n        current[i] = undefined\n      }\n    } else if (typeof current === 'object' && current !== null) {\n      for (const key in current) {\n        if (Object.prototype.hasOwnProperty.call(current, key)) {\n          delete current[key]\n        }\n      }\n    }\n  } else {\n    // Type safety: Check if current is an object before using 'in' operator\n    if (typeof current === 'object' && current !== null && lastKey in current && Object.prototype.hasOwnProperty.call(current, lastKey)) {\n      delete current[lastKey]\n    }\n  }\n  return true\n}\n\n// Sentinel object to distinguish between undefined value and non-existent path\nconst PATH_NOT_FOUND = Symbol('PATH_NOT_FOUND')\n\nfunction getValueIfExists (obj, parts) {\n  let current = obj\n\n  for (const part of parts) {\n    if (current === null || current === undefined) {\n      return PATH_NOT_FOUND\n    }\n    // Type safety: Check if current is an object before property access\n    if (typeof current !== 'object' || current === null) {\n      return PATH_NOT_FOUND\n    }\n    // Check if the property exists before accessing it\n    if (!(part in current)) {\n      return PATH_NOT_FOUND\n    }\n    current = current[part]\n  }\n\n  return current\n}\n\nfunction getValue (obj, parts) {\n  let current = obj\n\n  for (const part of parts) {\n    if (current === null || current === undefined) {\n      return undefined\n    }\n    // Type safety: Check if current is an object before property access\n    if (typeof current !== 'object' || current === null) {\n      return undefined\n    }\n    current = current[part]\n  }\n\n  return current\n}\n\nfunction redactPaths (obj, paths, censor, remove = false) {\n  for (const path of paths) {\n    const parts = parsePath(path)\n\n    if (parts.includes('*')) {\n      redactWildcardPath(obj, parts, censor, path, remove)\n    } else {\n      if (remove) {\n        removeKey(obj, parts)\n      } else {\n        // Get value only if path exists - single traversal\n        const value = getValueIfExists(obj, parts)\n        if (value === PATH_NOT_FOUND) {\n          continue\n        }\n\n        const actualCensor = typeof censor === 'function'\n          ? censor(value, parts)\n          : censor\n        setValue(obj, parts, actualCensor)\n      }\n    }\n  }\n}\n\nfunction redactWildcardPath (obj, parts, censor, originalPath, remove = false) {\n  const wildcardIndex = parts.indexOf('*')\n\n  if (wildcardIndex === parts.length - 1) {\n    const parentParts = parts.slice(0, -1)\n    let current = obj\n\n    for (const part of parentParts) {\n      if (current === null || current === undefined) return\n      // Type safety: Check if current is an object before property access\n      if (typeof current !== 'object' || current === null) return\n      current = current[part]\n    }\n\n    if (Array.isArray(current)) {\n      if (remove) {\n        // For arrays, set all items to undefined which will be omitted by JSON.stringify\n        for (let i = 0; i < current.length; i++) {\n          current[i] = undefined\n        }\n      } else {\n        for (let i = 0; i < current.length; i++) {\n          const indexPath = [...parentParts, i.toString()]\n          const actualCensor = typeof censor === 'function'\n            ? censor(current[i], indexPath)\n            : censor\n          current[i] = actualCensor\n        }\n      }\n    } else if (typeof current === 'object' && current !== null) {\n      if (remove) {\n        // Collect keys to delete to avoid issues with deleting during iteration\n        const keysToDelete = []\n        for (const key in current) {\n          if (Object.prototype.hasOwnProperty.call(current, key)) {\n            keysToDelete.push(key)\n          }\n        }\n        for (const key of keysToDelete) {\n          delete current[key]\n        }\n      } else {\n        for (const key in current) {\n          const keyPath = [...parentParts, key]\n          const actualCensor = typeof censor === 'function'\n            ? censor(current[key], keyPath)\n            : censor\n          current[key] = actualCensor\n        }\n      }\n    }\n  } else {\n    redactIntermediateWildcard(obj, parts, censor, wildcardIndex, originalPath, remove)\n  }\n}\n\nfunction redactIntermediateWildcard (obj, parts, censor, wildcardIndex, originalPath, remove = false) {\n  const beforeWildcard = parts.slice(0, wildcardIndex)\n  const afterWildcard = parts.slice(wildcardIndex + 1)\n  const pathArray = [] // Cached array to avoid allocations\n\n  function traverse (current, pathLength) {\n    if (pathLength === beforeWildcard.length) {\n      if (Array.isArray(current)) {\n        for (let i = 0; i < current.length; i++) {\n          pathArray[pathLength] = i.toString()\n          traverse(current[i], pathLength + 1)\n        }\n      } else if (typeof current === 'object' && current !== null) {\n        for (const key in current) {\n          pathArray[pathLength] = key\n          traverse(current[key], pathLength + 1)\n        }\n      }\n    } else if (pathLength < beforeWildcard.length) {\n      const nextKey = beforeWildcard[pathLength]\n      // Type safety: Check if current is an object before using 'in' operator\n      if (current && typeof current === 'object' && current !== null && nextKey in current) {\n        pathArray[pathLength] = nextKey\n        traverse(current[nextKey], pathLength + 1)\n      }\n    } else {\n      // Check if afterWildcard contains more wildcards\n      if (afterWildcard.includes('*')) {\n        // Recursively handle remaining wildcards\n        // Wrap censor to prepend current path context\n        const wrappedCensor = typeof censor === 'function'\n          ? (value, path) => {\n              const fullPath = [...pathArray.slice(0, pathLength), ...path]\n              return censor(value, fullPath)\n            }\n          : censor\n        redactWildcardPath(current, afterWildcard, wrappedCensor, originalPath, remove)\n      } else {\n        // No more wildcards, apply the redaction directly\n        if (remove) {\n          removeKey(current, afterWildcard)\n        } else {\n          const actualCensor = typeof censor === 'function'\n            ? censor(getValue(current, afterWildcard), [...pathArray.slice(0, pathLength), ...afterWildcard])\n            : censor\n          setValue(current, afterWildcard, actualCensor)\n        }\n      }\n    }\n  }\n\n  if (beforeWildcard.length === 0) {\n    traverse(obj, 0)\n  } else {\n    let current = obj\n    for (let i = 0; i < beforeWildcard.length; i++) {\n      const part = beforeWildcard[i]\n      if (current === null || current === undefined) return\n      // Type safety: Check if current is an object before property access\n      if (typeof current !== 'object' || current === null) return\n      current = current[part]\n      pathArray[i] = part\n    }\n    if (current !== null && current !== undefined) {\n      traverse(current, beforeWildcard.length)\n    }\n  }\n}\n\nfunction buildPathStructure (pathsToClone) {\n  if (pathsToClone.length === 0) {\n    return null // No paths to redact\n  }\n\n  // Parse all paths and organize by depth\n  const pathStructure = new Map()\n  for (const path of pathsToClone) {\n    const parts = parsePath(path)\n    let current = pathStructure\n    for (let i = 0; i < parts.length; i++) {\n      const part = parts[i]\n      if (!current.has(part)) {\n        current.set(part, new Map())\n      }\n      current = current.get(part)\n    }\n  }\n  return pathStructure\n}\n\nfunction selectiveClone (obj, pathStructure) {\n  if (!pathStructure) {\n    return obj // No paths to redact, return original\n  }\n\n  function cloneSelectively (source, pathMap, depth = 0) {\n    if (!pathMap || pathMap.size === 0) {\n      return source // No more paths to clone, return reference\n    }\n\n    if (source === null || typeof source !== 'object') {\n      return source\n    }\n\n    if (source instanceof Date) {\n      return new Date(source.getTime())\n    }\n\n    if (Array.isArray(source)) {\n      const cloned = []\n      for (let i = 0; i < source.length; i++) {\n        const indexStr = i.toString()\n        if (pathMap.has(indexStr) || pathMap.has('*')) {\n          cloned[i] = cloneSelectively(source[i], pathMap.get(indexStr) || pathMap.get('*'))\n        } else {\n          cloned[i] = source[i] // Share reference for non-redacted items\n        }\n      }\n      return cloned\n    }\n\n    // Handle objects\n    const cloned = Object.create(Object.getPrototypeOf(source))\n    for (const key in source) {\n      if (Object.prototype.hasOwnProperty.call(source, key)) {\n        if (pathMap.has(key) || pathMap.has('*')) {\n          cloned[key] = cloneSelectively(source[key], pathMap.get(key) || pathMap.get('*'))\n        } else {\n          cloned[key] = source[key] // Share reference for non-redacted properties\n        }\n      }\n    }\n    return cloned\n  }\n\n  return cloneSelectively(obj, pathStructure)\n}\n\nfunction validatePath (path) {\n  if (typeof path !== 'string') {\n    throw new Error('Paths must be (non-empty) strings')\n  }\n\n  if (path === '') {\n    throw new Error('Invalid redaction path ()')\n  }\n\n  // Check for double dots\n  if (path.includes('..')) {\n    throw new Error(`Invalid redaction path (${path})`)\n  }\n\n  // Check for comma-separated paths (invalid syntax)\n  if (path.includes(',')) {\n    throw new Error(`Invalid redaction path (${path})`)\n  }\n\n  // Check for unmatched brackets\n  let bracketCount = 0\n  let inQuotes = false\n  let quoteChar = ''\n\n  for (let i = 0; i < path.length; i++) {\n    const char = path[i]\n\n    if ((char === '\"' || char === \"'\") && bracketCount > 0) {\n      if (!inQuotes) {\n        inQuotes = true\n        quoteChar = char\n      } else if (char === quoteChar) {\n        inQuotes = false\n        quoteChar = ''\n      }\n    } else if (char === '[' && !inQuotes) {\n      bracketCount++\n    } else if (char === ']' && !inQuotes) {\n      bracketCount--\n      if (bracketCount < 0) {\n        throw new Error(`Invalid redaction path (${path})`)\n      }\n    }\n  }\n\n  if (bracketCount !== 0) {\n    throw new Error(`Invalid redaction path (${path})`)\n  }\n}\n\nfunction validatePaths (paths) {\n  if (!Array.isArray(paths)) {\n    throw new TypeError('paths must be an array')\n  }\n\n  for (const path of paths) {\n    validatePath(path)\n  }\n}\n\nfunction slowRedact (options = {}) {\n  const {\n    paths = [],\n    censor = '[REDACTED]',\n    serialize = JSON.stringify,\n    strict = true,\n    remove = false\n  } = options\n\n  // Validate paths upfront to match fast-redact behavior\n  validatePaths(paths)\n\n  // Build path structure once during setup, not on every call\n  const pathStructure = buildPathStructure(paths)\n\n  return function redact (obj) {\n    if (strict && (obj === null || typeof obj !== 'object')) {\n      if (obj === null || obj === undefined) {\n        return serialize ? serialize(obj) : obj\n      }\n      if (typeof obj !== 'object') {\n        return serialize ? serialize(obj) : obj\n      }\n    }\n\n    // Only clone paths that need redaction\n    const cloned = selectiveClone(obj, pathStructure)\n    const original = obj // Keep reference to original for restore\n\n    let actualCensor = censor\n    if (typeof censor === 'function') {\n      actualCensor = censor\n    }\n\n    redactPaths(cloned, paths, actualCensor, remove)\n\n    if (serialize === false) {\n      cloned.restore = function () {\n        return deepClone(original) // Full clone only when restore is called\n      }\n      return cloned\n    }\n\n    if (typeof serialize === 'function') {\n      return serialize(cloned)\n    }\n\n    return JSON.stringify(cloned)\n  }\n}\n\nmodule.exports = slowRedact\n","'use strict'\n\nconst setLevelSym = Symbol('pino.setLevel')\nconst getLevelSym = Symbol('pino.getLevel')\nconst levelValSym = Symbol('pino.levelVal')\nconst levelCompSym = Symbol('pino.levelComp')\nconst useLevelLabelsSym = Symbol('pino.useLevelLabels')\nconst useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')\nconst mixinSym = Symbol('pino.mixin')\n\nconst lsCacheSym = Symbol('pino.lsCache')\nconst chindingsSym = Symbol('pino.chindings')\n\nconst asJsonSym = Symbol('pino.asJson')\nconst writeSym = Symbol('pino.write')\nconst redactFmtSym = Symbol('pino.redactFmt')\n\nconst timeSym = Symbol('pino.time')\nconst timeSliceIndexSym = Symbol('pino.timeSliceIndex')\nconst streamSym = Symbol('pino.stream')\nconst stringifySym = Symbol('pino.stringify')\nconst stringifySafeSym = Symbol('pino.stringifySafe')\nconst stringifiersSym = Symbol('pino.stringifiers')\nconst endSym = Symbol('pino.end')\nconst formatOptsSym = Symbol('pino.formatOpts')\nconst messageKeySym = Symbol('pino.messageKey')\nconst errorKeySym = Symbol('pino.errorKey')\nconst nestedKeySym = Symbol('pino.nestedKey')\nconst nestedKeyStrSym = Symbol('pino.nestedKeyStr')\nconst mixinMergeStrategySym = Symbol('pino.mixinMergeStrategy')\nconst msgPrefixSym = Symbol('pino.msgPrefix')\n\nconst wildcardFirstSym = Symbol('pino.wildcardFirst')\n\n// public symbols, no need to use the same pino\n// version for these\nconst serializersSym = Symbol.for('pino.serializers')\nconst formattersSym = Symbol.for('pino.formatters')\nconst hooksSym = Symbol.for('pino.hooks')\nconst needsMetadataGsym = Symbol.for('pino.metadata')\n\nmodule.exports = {\n  setLevelSym,\n  getLevelSym,\n  levelValSym,\n  levelCompSym,\n  useLevelLabelsSym,\n  mixinSym,\n  lsCacheSym,\n  chindingsSym,\n  asJsonSym,\n  writeSym,\n  serializersSym,\n  redactFmtSym,\n  timeSym,\n  timeSliceIndexSym,\n  streamSym,\n  stringifySym,\n  stringifySafeSym,\n  stringifiersSym,\n  endSym,\n  formatOptsSym,\n  messageKeySym,\n  errorKeySym,\n  nestedKeySym,\n  wildcardFirstSym,\n  needsMetadataGsym,\n  useOnlyCustomLevelsSym,\n  formattersSym,\n  hooksSym,\n  nestedKeyStrSym,\n  mixinMergeStrategySym,\n  msgPrefixSym\n}\n","'use strict'\n\nconst Redact = require('@pinojs/redact')\nconst { redactFmtSym, wildcardFirstSym } = require('./symbols')\n\n// Custom rx regex equivalent to fast-redact's rx\nconst rx = /[^.[\\]]+|\\[([^[\\]]*?)\\]/g\n\nconst CENSOR = '[Redacted]'\nconst strict = false // TODO should this be configurable?\n\nfunction redaction (opts, serialize) {\n  const { paths, censor, remove } = handle(opts)\n\n  const shape = paths.reduce((o, str) => {\n    rx.lastIndex = 0\n    const first = rx.exec(str)\n    const next = rx.exec(str)\n\n    // ns is the top-level path segment, brackets + quoting removed.\n    let ns = first[1] !== undefined\n      ? first[1].replace(/^(?:\"|'|`)(.*)(?:\"|'|`)$/, '$1')\n      : first[0]\n\n    if (ns === '*') {\n      ns = wildcardFirstSym\n    }\n\n    // top level key:\n    if (next === null) {\n      o[ns] = null\n      return o\n    }\n\n    // path with at least two segments:\n    // if ns is already redacted at the top level, ignore lower level redactions\n    if (o[ns] === null) {\n      return o\n    }\n\n    const { index } = next\n    const nextPath = `${str.substr(index, str.length - 1)}`\n\n    o[ns] = o[ns] || []\n\n    // shape is a mix of paths beginning with literal values and wildcard\n    // paths [ \"a.b.c\", \"*.b.z\" ] should reduce to a shape of\n    // { \"a\": [ \"b.c\", \"b.z\" ], *: [ \"b.z\" ] }\n    // note: \"b.z\" is in both \"a\" and * arrays because \"a\" matches the wildcard.\n    // (* entry has wildcardFirstSym as key)\n    if (ns !== wildcardFirstSym && o[ns].length === 0) {\n      // first time ns's get all '*' redactions so far\n      o[ns].push(...(o[wildcardFirstSym] || []))\n    }\n\n    if (ns === wildcardFirstSym) {\n      // new * path gets added to all previously registered literal ns's.\n      Object.keys(o).forEach(function (k) {\n        if (o[k]) {\n          o[k].push(nextPath)\n        }\n      })\n    }\n\n    o[ns].push(nextPath)\n    return o\n  }, {})\n\n  // the redactor assigned to the format symbol key\n  // provides top level redaction for instances where\n  // an object is interpolated into the msg string\n  const result = {\n    [redactFmtSym]: Redact({ paths, censor, serialize, strict, remove })\n  }\n\n  const topCensor = (...args) => {\n    return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)\n  }\n\n  return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {\n    // top level key:\n    if (shape[k] === null) {\n      o[k] = (value) => topCensor(value, [k])\n    } else {\n      const wrappedCensor = typeof censor === 'function'\n        ? (value, path) => {\n            return censor(value, [k, ...path])\n          }\n        : censor\n      o[k] = Redact({\n        paths: shape[k],\n        censor: wrappedCensor,\n        serialize,\n        strict,\n        remove\n      })\n    }\n    return o\n  }, result)\n}\n\nfunction handle (opts) {\n  if (Array.isArray(opts)) {\n    opts = { paths: opts, censor: CENSOR }\n    return opts\n  }\n  let { paths, censor = CENSOR, remove } = opts\n  if (Array.isArray(paths) === false) { throw Error('pino – redact must contain an array of strings') }\n  if (remove === true) censor = undefined\n\n  return { paths, censor, remove }\n}\n\nmodule.exports = redaction\n","'use strict'\n\nconst nullTime = () => ''\n\nconst epochTime = () => `,\"time\":${Date.now()}`\n\nconst unixTime = () => `,\"time\":${Math.round(Date.now() / 1000.0)}`\n\nconst isoTime = () => `,\"time\":\"${new Date(Date.now()).toISOString()}\"` // using Date.now() for testability\n\nconst NS_PER_MS = 1_000_000n\nconst NS_PER_SEC = 1_000_000_000n\n\nconst startWallTimeNs = BigInt(Date.now()) * NS_PER_MS\nconst startHrTime = process.hrtime.bigint()\n\nconst isoTimeNano = () => {\n  const elapsedNs = process.hrtime.bigint() - startHrTime\n  const currentTimeNs = startWallTimeNs + elapsedNs\n\n  const secondsSinceEpoch = currentTimeNs / NS_PER_SEC\n  const nanosWithinSecond = currentTimeNs % NS_PER_SEC\n\n  const msSinceEpoch = Number(secondsSinceEpoch * 1000n + nanosWithinSecond / 1_000_000n)\n  const date = new Date(msSinceEpoch)\n\n  const year = date.getUTCFullYear()\n  const month = (date.getUTCMonth() + 1).toString().padStart(2, '0')\n  const day = date.getUTCDate().toString().padStart(2, '0')\n  const hours = date.getUTCHours().toString().padStart(2, '0')\n  const minutes = date.getUTCMinutes().toString().padStart(2, '0')\n  const seconds = date.getUTCSeconds().toString().padStart(2, '0')\n\n  return `,\"time\":\"${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${nanosWithinSecond\n    .toString()\n    .padStart(9, '0')}Z\"`\n}\n\nmodule.exports = { nullTime, epochTime, unixTime, isoTime, isoTimeNano }\n","'use strict'\nfunction tryStringify (o) {\n  try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format\n\nfunction format(f, args, opts) {\n  var ss = (opts && opts.stringify) || tryStringify\n  var offset = 1\n  if (typeof f === 'object' && f !== null) {\n    var len = args.length + offset\n    if (len === 1) return f\n    var objects = new Array(len)\n    objects[0] = ss(f)\n    for (var index = 1; index < len; index++) {\n      objects[index] = ss(args[index])\n    }\n    return objects.join(' ')\n  }\n  if (typeof f !== 'string') {\n    return f\n  }\n  var argLen = args.length\n  if (argLen === 0) return f\n  var str = ''\n  var a = 1 - offset\n  var lastPos = -1\n  var flen = (f && f.length) || 0\n  for (var i = 0; i < flen;) {\n    if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n      lastPos = lastPos > -1 ? lastPos : 0\n      switch (f.charCodeAt(i + 1)) {\n        case 100: // 'd'\n        case 102: // 'f'\n          if (a >= argLen)\n            break\n          if (args[a] == null)  break\n          if (lastPos < i)\n            str += f.slice(lastPos, i)\n          str += Number(args[a])\n          lastPos = i + 2\n          i++\n          break\n        case 105: // 'i'\n          if (a >= argLen)\n            break\n          if (args[a] == null)  break\n          if (lastPos < i)\n            str += f.slice(lastPos, i)\n          str += Math.floor(Number(args[a]))\n          lastPos = i + 2\n          i++\n          break\n        case 79: // 'O'\n        case 111: // 'o'\n        case 106: // 'j'\n          if (a >= argLen)\n            break\n          if (args[a] === undefined) break\n          if (lastPos < i)\n            str += f.slice(lastPos, i)\n          var type = typeof args[a]\n          if (type === 'string') {\n            str += '\\'' + args[a] + '\\''\n            lastPos = i + 2\n            i++\n            break\n          }\n          if (type === 'function') {\n            str += args[a].name || '<anonymous>'\n            lastPos = i + 2\n            i++\n            break\n          }\n          str += ss(args[a])\n          lastPos = i + 2\n          i++\n          break\n        case 115: // 's'\n          if (a >= argLen)\n            break\n          if (lastPos < i)\n            str += f.slice(lastPos, i)\n          str += String(args[a])\n          lastPos = i + 2\n          i++\n          break\n        case 37: // '%'\n          if (lastPos < i)\n            str += f.slice(lastPos, i)\n          str += '%'\n          lastPos = i + 2\n          i++\n          a--\n          break\n      }\n      ++a\n    }\n    ++i\n  }\n  if (lastPos === -1)\n    return f\n  else if (lastPos < flen) {\n    str += f.slice(lastPos)\n  }\n\n  return str\n}\n","'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n  const nil = new Int32Array(new SharedArrayBuffer(4))\n\n  function sleep (ms) {\n    // also filters out NaN, non-number types, including empty strings, but allows bigints\n    const valid = ms > 0 && ms < Infinity \n    if (valid === false) {\n      if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n        throw TypeError('sleep: ms must be a number')\n      }\n      throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n    }\n\n    Atomics.wait(nil, 0, 0, Number(ms))\n  }\n  module.exports = sleep\n} else {\n\n  function sleep (ms) {\n    // also filters out NaN, non-number types, including empty strings, but allows bigints\n    const valid = ms > 0 && ms < Infinity \n    if (valid === false) {\n      if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n        throw TypeError('sleep: ms must be a number')\n      }\n      throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n    }\n    const target = Date.now() + Number(ms)\n    while (target > Date.now()){}\n  }\n\n  module.exports = sleep\n\n}\n","'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n  sonic._opening = true\n  sonic._writing = true\n  sonic._asyncDrainScheduled = false\n\n  // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n  // for sync mode, there is no way to add a listener that will receive these\n\n  function fileOpened (err, fd) {\n    if (err) {\n      sonic._reopening = false\n      sonic._writing = false\n      sonic._opening = false\n\n      if (sonic.sync) {\n        process.nextTick(() => {\n          if (sonic.listenerCount('error') > 0) {\n            sonic.emit('error', err)\n          }\n        })\n      } else {\n        sonic.emit('error', err)\n      }\n      return\n    }\n\n    const reopening = sonic._reopening\n\n    sonic.fd = fd\n    sonic.file = file\n    sonic._reopening = false\n    sonic._opening = false\n    sonic._writing = false\n\n    if (sonic.sync) {\n      process.nextTick(() => sonic.emit('ready'))\n    } else {\n      sonic.emit('ready')\n    }\n\n    if (sonic.destroyed) {\n      return\n    }\n\n    // start\n    if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n      sonic._actualWrite()\n    } else if (reopening) {\n      process.nextTick(() => sonic.emit('drain'))\n    }\n  }\n\n  const flags = sonic.append ? 'a' : 'w'\n  const mode = sonic.mode\n\n  if (sonic.sync) {\n    try {\n      if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n      const fd = fs.openSync(file, flags, mode)\n      fileOpened(null, fd)\n    } catch (err) {\n      fileOpened(err)\n      throw err\n    }\n  } else if (sonic.mkdir) {\n    fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n      if (err) return fileOpened(err)\n      fs.open(file, flags, mode, fileOpened)\n    })\n  } else {\n    fs.open(file, flags, mode, fileOpened)\n  }\n}\n\nfunction SonicBoom (opts) {\n  if (!(this instanceof SonicBoom)) {\n    return new SonicBoom(opts)\n  }\n\n  let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n  fd = fd || dest\n\n  this._len = 0\n  this.fd = -1\n  this._bufs = []\n  this._lens = []\n  this._writing = false\n  this._ending = false\n  this._reopening = false\n  this._asyncDrainScheduled = false\n  this._flushPending = false\n  this._hwm = Math.max(minLength || 0, 16387)\n  this.file = null\n  this.destroyed = false\n  this.minLength = minLength || 0\n  this.maxLength = maxLength || 0\n  this.maxWrite = maxWrite || MAX_WRITE\n  this._periodicFlush = periodicFlush || 0\n  this._periodicFlushTimer = undefined\n  this.sync = sync || false\n  this.writable = true\n  this._fsync = fsync || false\n  this.append = append || false\n  this.mode = mode\n  this.retryEAGAIN = retryEAGAIN || (() => true)\n  this.mkdir = mkdir || false\n\n  let fsWriteSync\n  let fsWrite\n  if (contentMode === kContentModeBuffer) {\n    this._writingBuf = kEmptyBuffer\n    this.write = writeBuffer\n    this.flush = flushBuffer\n    this.flushSync = flushBufferSync\n    this._actualWrite = actualWriteBuffer\n    fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n    fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n  } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n    this._writingBuf = ''\n    this.write = write\n    this.flush = flush\n    this.flushSync = flushSync\n    this._actualWrite = actualWrite\n    fsWriteSync = () => {\n      if (Buffer.isBuffer(this._writingBuf)) {\n        return fs.writeSync(this.fd, this._writingBuf)\n      }\n      return fs.writeSync(this.fd, this._writingBuf, 'utf8')\n    }\n    fsWrite = () => {\n      if (Buffer.isBuffer(this._writingBuf)) {\n        return fs.write(this.fd, this._writingBuf, this.release)\n      }\n      return fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n    }\n  } else {\n    throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n  }\n\n  if (typeof fd === 'number') {\n    this.fd = fd\n    process.nextTick(() => this.emit('ready'))\n  } else if (typeof fd === 'string') {\n    openFile(fd, this)\n  } else {\n    throw new Error('SonicBoom supports only file descriptors and files')\n  }\n  if (this.minLength >= this.maxWrite) {\n    throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n  }\n\n  this.release = (err, n) => {\n    if (err) {\n      if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n        if (this.sync) {\n          // This error code should not happen in sync mode, because it is\n          // not using the underlining operating system asynchronous functions.\n          // However it happens, and so we handle it.\n          // Ref: https://github.com/pinojs/pino/issues/783\n          try {\n            sleep(BUSY_WRITE_TIMEOUT)\n            this.release(undefined, 0)\n          } catch (err) {\n            this.release(err)\n          }\n        } else {\n          // Let's give the destination some time to process the chunk.\n          setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n        }\n      } else {\n        this._writing = false\n\n        this.emit('error', err)\n      }\n      return\n    }\n\n    this.emit('write', n)\n    const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n    this._len = releasedBufObj.len\n    this._writingBuf = releasedBufObj.writingBuf\n\n    if (this._writingBuf.length) {\n      if (!this.sync) {\n        fsWrite()\n        return\n      }\n\n      try {\n        do {\n          const n = fsWriteSync()\n          const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n          this._len = releasedBufObj.len\n          this._writingBuf = releasedBufObj.writingBuf\n        } while (this._writingBuf.length)\n      } catch (err) {\n        this.release(err)\n        return\n      }\n    }\n\n    if (this._fsync) {\n      fs.fsyncSync(this.fd)\n    }\n\n    const len = this._len\n    if (this._reopening) {\n      this._writing = false\n      this._reopening = false\n      this.reopen()\n    } else if (len > this.minLength) {\n      this._actualWrite()\n    } else if (this._ending) {\n      if (len > 0) {\n        this._actualWrite()\n      } else {\n        this._writing = false\n        actualClose(this)\n      }\n    } else {\n      this._writing = false\n      if (this.sync) {\n        if (!this._asyncDrainScheduled) {\n          this._asyncDrainScheduled = true\n          process.nextTick(emitDrain, this)\n        }\n      } else {\n        this.emit('drain')\n      }\n    }\n  }\n\n  this.on('newListener', function (name) {\n    if (name === 'drain') {\n      this._asyncDrainScheduled = false\n    }\n  })\n\n  if (this._periodicFlush !== 0) {\n    this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n    this._periodicFlushTimer.unref()\n  }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n  if (typeof writingBuf === 'string') {\n    writingBuf = Buffer.from(writingBuf)\n  }\n\n  len = Math.max(len - n, 0)\n  writingBuf = writingBuf.subarray(n)\n  return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n  const hasListeners = sonic.listenerCount('drain') > 0\n  if (!hasListeners) return\n  sonic._asyncDrainScheduled = false\n  sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n  if (bufs.length === 0) {\n    return kEmptyBuffer\n  }\n\n  if (bufs.length === 1) {\n    return bufs[0]\n  }\n\n  return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n  if (this.destroyed) {\n    throw new Error('SonicBoom destroyed')\n  }\n\n  data = '' + data\n  const dataLen = Buffer.byteLength(data)\n  const len = this._len + dataLen\n  const bufs = this._bufs\n\n  if (this.maxLength && len > this.maxLength) {\n    this.emit('drop', data)\n    return this._len < this._hwm\n  }\n\n  if (\n    bufs.length === 0 ||\n    Buffer.byteLength(bufs[bufs.length - 1]) + dataLen > this.maxWrite\n  ) {\n    bufs.push(data)\n  } else {\n    bufs[bufs.length - 1] += data\n  }\n\n  this._len = len\n\n  if (!this._writing && this._len >= this.minLength) {\n    this._actualWrite()\n  }\n\n  return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n  if (this.destroyed) {\n    throw new Error('SonicBoom destroyed')\n  }\n\n  const len = this._len + data.length\n  const bufs = this._bufs\n  const lens = this._lens\n\n  if (this.maxLength && len > this.maxLength) {\n    this.emit('drop', data)\n    return this._len < this._hwm\n  }\n\n  if (\n    bufs.length === 0 ||\n    lens[lens.length - 1] + data.length > this.maxWrite\n  ) {\n    bufs.push([data])\n    lens.push(data.length)\n  } else {\n    bufs[bufs.length - 1].push(data)\n    lens[lens.length - 1] += data.length\n  }\n\n  this._len = len\n\n  if (!this._writing && this._len >= this.minLength) {\n    this._actualWrite()\n  }\n\n  return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n  this._flushPending = true\n  const onDrain = () => {\n    // only if _fsync is false to avoid double fsync\n    if (!this._fsync) {\n      try {\n        fs.fsync(this.fd, (err) => {\n          this._flushPending = false\n          cb(err)\n        })\n      } catch (err) {\n        cb(err)\n      }\n    } else {\n      this._flushPending = false\n      cb()\n    }\n    this.off('error', onError)\n  }\n  const onError = (err) => {\n    this._flushPending = false\n    cb(err)\n    this.off('drain', onDrain)\n  }\n\n  this.once('drain', onDrain)\n  this.once('error', onError)\n}\n\nfunction flush (cb) {\n  if (cb != null && typeof cb !== 'function') {\n    throw new Error('flush cb must be a function')\n  }\n\n  if (this.destroyed) {\n    const error = new Error('SonicBoom destroyed')\n    if (cb) {\n      cb(error)\n      return\n    }\n\n    throw error\n  }\n\n  if (this.minLength <= 0) {\n    cb?.()\n    return\n  }\n\n  if (cb) {\n    callFlushCallbackOnDrain.call(this, cb)\n  }\n\n  if (this._writing) {\n    return\n  }\n\n  if (this._bufs.length === 0) {\n    this._bufs.push('')\n  }\n\n  this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n  if (cb != null && typeof cb !== 'function') {\n    throw new Error('flush cb must be a function')\n  }\n\n  if (this.destroyed) {\n    const error = new Error('SonicBoom destroyed')\n    if (cb) {\n      cb(error)\n      return\n    }\n\n    throw error\n  }\n\n  if (this.minLength <= 0) {\n    cb?.()\n    return\n  }\n\n  if (cb) {\n    callFlushCallbackOnDrain.call(this, cb)\n  }\n\n  if (this._writing) {\n    return\n  }\n\n  if (this._bufs.length === 0) {\n    this._bufs.push([])\n    this._lens.push(0)\n  }\n\n  this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n  if (this.destroyed) {\n    throw new Error('SonicBoom destroyed')\n  }\n\n  if (this._opening) {\n    this.once('ready', () => {\n      this.reopen(file)\n    })\n    return\n  }\n\n  if (this._ending) {\n    return\n  }\n\n  if (!this.file) {\n    throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n  }\n\n  if (file) {\n    this.file = file\n  }\n  this._reopening = true\n\n  if (this._writing) {\n    return\n  }\n\n  const fd = this.fd\n  this.once('ready', () => {\n    if (fd !== this.fd) {\n      fs.close(fd, (err) => {\n        if (err) {\n          return this.emit('error', err)\n        }\n      })\n    }\n  })\n\n  openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n  if (this.destroyed) {\n    throw new Error('SonicBoom destroyed')\n  }\n\n  if (this._opening) {\n    this.once('ready', () => {\n      this.end()\n    })\n    return\n  }\n\n  if (this._ending) {\n    return\n  }\n\n  this._ending = true\n\n  if (this._writing) {\n    return\n  }\n\n  if (this._len > 0 && this.fd >= 0) {\n    this._actualWrite()\n  } else {\n    actualClose(this)\n  }\n}\n\nfunction flushSync () {\n  if (this.destroyed) {\n    throw new Error('SonicBoom destroyed')\n  }\n\n  if (this.fd < 0) {\n    throw new Error('sonic boom is not ready yet')\n  }\n\n  if (!this._writing && this._writingBuf.length > 0) {\n    this._bufs.unshift(this._writingBuf)\n    this._writingBuf = ''\n  }\n\n  let buf = ''\n  while (this._bufs.length || buf.length) {\n    if (buf.length <= 0) {\n      buf = this._bufs[0]\n    }\n    try {\n      const n = Buffer.isBuffer(buf)\n        ? fs.writeSync(this.fd, buf)\n        : fs.writeSync(this.fd, buf, 'utf8')\n      const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n      buf = releasedBufObj.writingBuf\n      this._len = releasedBufObj.len\n      if (buf.length <= 0) {\n        this._bufs.shift()\n      }\n    } catch (err) {\n      const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n      if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n        throw err\n      }\n\n      sleep(BUSY_WRITE_TIMEOUT)\n    }\n  }\n\n  try {\n    fs.fsyncSync(this.fd)\n  } catch {\n    // Skip the error. The fd might not support fsync.\n  }\n}\n\nfunction flushBufferSync () {\n  if (this.destroyed) {\n    throw new Error('SonicBoom destroyed')\n  }\n\n  if (this.fd < 0) {\n    throw new Error('sonic boom is not ready yet')\n  }\n\n  if (!this._writing && this._writingBuf.length > 0) {\n    this._bufs.unshift([this._writingBuf])\n    this._writingBuf = kEmptyBuffer\n  }\n\n  let buf = kEmptyBuffer\n  while (this._bufs.length || buf.length) {\n    if (buf.length <= 0) {\n      buf = mergeBuf(this._bufs[0], this._lens[0])\n    }\n    try {\n      const n = fs.writeSync(this.fd, buf)\n      buf = buf.subarray(n)\n      this._len = Math.max(this._len - n, 0)\n      if (buf.length <= 0) {\n        this._bufs.shift()\n        this._lens.shift()\n      }\n    } catch (err) {\n      const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n      if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n        throw err\n      }\n\n      sleep(BUSY_WRITE_TIMEOUT)\n    }\n  }\n}\n\nSonicBoom.prototype.destroy = function () {\n  if (this.destroyed) {\n    return\n  }\n  actualClose(this)\n}\n\nfunction actualWrite () {\n  const release = this.release\n  this._writing = true\n  this._writingBuf = this._writingBuf.length ? this._writingBuf : this._bufs.shift() || ''\n\n  if (this.sync) {\n    try {\n      const written = Buffer.isBuffer(this._writingBuf)\n        ? fs.writeSync(this.fd, this._writingBuf)\n        : fs.writeSync(this.fd, this._writingBuf, 'utf8')\n      release(null, written)\n    } catch (err) {\n      release(err)\n    }\n  } else {\n    fs.write(this.fd, this._writingBuf, release)\n  }\n}\n\nfunction actualWriteBuffer () {\n  const release = this.release\n  this._writing = true\n  this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n  if (this.sync) {\n    try {\n      const written = fs.writeSync(this.fd, this._writingBuf)\n      release(null, written)\n    } catch (err) {\n      release(err)\n    }\n  } else {\n    // fs.write will need to copy string to buffer anyway so\n    // we do it here to avoid the overhead of calculating the buffer size\n    // in releaseWritingBuf.\n    if (kCopyBuffer) {\n      this._writingBuf = Buffer.from(this._writingBuf)\n    }\n    fs.write(this.fd, this._writingBuf, release)\n  }\n}\n\nfunction actualClose (sonic) {\n  if (sonic.fd === -1) {\n    sonic.once('ready', actualClose.bind(null, sonic))\n    return\n  }\n\n  if (sonic._periodicFlushTimer !== undefined) {\n    clearInterval(sonic._periodicFlushTimer)\n  }\n\n  sonic.destroyed = true\n  sonic._bufs = []\n  sonic._lens = []\n\n  assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n  try {\n    fs.fsync(sonic.fd, closeWrapped)\n  } catch {\n  }\n\n  function closeWrapped () {\n    // We skip errors in fsync\n\n    if (sonic.fd !== 1 && sonic.fd !== 2) {\n      fs.close(sonic.fd, done)\n    } else {\n      done()\n    }\n  }\n\n  function done (err) {\n    if (err) {\n      sonic.emit('error', err)\n      return\n    }\n\n    if (sonic._ending && !sonic._writing) {\n      sonic.emit('finish')\n    }\n    sonic.emit('close')\n  }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n","'use strict'\n\nconst refs = {\n  exit: [],\n  beforeExit: []\n}\nconst functions = {\n  exit: onExit,\n  beforeExit: onBeforeExit\n}\n\nlet registry\n\nfunction ensureRegistry () {\n  if (registry === undefined) {\n    registry = new FinalizationRegistry(clear)\n  }\n}\n\nfunction install (event) {\n  if (refs[event].length > 0) {\n    return\n  }\n\n  process.on(event, functions[event])\n}\n\nfunction uninstall (event) {\n  if (refs[event].length > 0) {\n    return\n  }\n  process.removeListener(event, functions[event])\n  if (refs.exit.length === 0 && refs.beforeExit.length === 0) {\n    registry = undefined\n  }\n}\n\nfunction onExit () {\n  callRefs('exit')\n}\n\nfunction onBeforeExit () {\n  callRefs('beforeExit')\n}\n\nfunction callRefs (event) {\n  for (const ref of refs[event]) {\n    const obj = ref.deref()\n    const fn = ref.fn\n\n    // This should always happen, however GC is\n    // undeterministic so it might not happen.\n    /* istanbul ignore else */\n    if (obj !== undefined) {\n      fn(obj, event)\n    }\n  }\n  refs[event] = []\n}\n\nfunction clear (ref) {\n  for (const event of ['exit', 'beforeExit']) {\n    const index = refs[event].indexOf(ref)\n    refs[event].splice(index, index + 1)\n    uninstall(event)\n  }\n}\n\nfunction _register (event, obj, fn) {\n  if (obj === undefined) {\n    throw new Error('the object can\\'t be undefined')\n  }\n  install(event)\n  const ref = new WeakRef(obj)\n  ref.fn = fn\n\n  ensureRegistry()\n  registry.register(obj, ref)\n  refs[event].push(ref)\n}\n\nfunction register (obj, fn) {\n  _register('exit', obj, fn)\n}\n\nfunction registerBeforeExit (obj, fn) {\n  _register('beforeExit', obj, fn)\n}\n\nfunction unregister (obj) {\n  if (registry === undefined) {\n    return\n  }\n  registry.unregister(obj)\n  for (const event of ['exit', 'beforeExit']) {\n    refs[event] = refs[event].filter((ref) => {\n      const _obj = ref.deref()\n      return _obj && _obj !== obj\n    })\n    uninstall(event)\n  }\n}\n\nmodule.exports = {\n  register,\n  registerBeforeExit,\n  unregister\n}\n","","'use strict'\n\n// Maximum wait time for a single waitAsync call\n// Used as a fallback poll interval in case notifications are missed\n// Keep this low enough for good throughput but high enough to not busy-loop\nconst WAIT_MS = 10000\n\nfunction wait (state, index, expected, timeout, done) {\n  const max = timeout === Infinity ? Infinity : Date.now() + timeout\n\n  const check = () => {\n    const current = Atomics.load(state, index)\n    if (current === expected) {\n      done(null, 'ok')\n      return\n    }\n\n    if (max !== Infinity && Date.now() > max) {\n      done(null, 'timed-out')\n      return\n    }\n\n    // Wait for any change from current value\n    const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now()))\n    const result = Atomics.waitAsync(state, index, current, remaining)\n\n    if (result.async) {\n      result.value.then(check)\n    } else {\n      // Value already changed (not-equal) - recheck on next tick\n      setImmediate(check)\n    }\n  }\n\n  check()\n}\n\nfunction waitDiff (state, index, expected, timeout, done) {\n  const max = timeout === Infinity ? Infinity : Date.now() + timeout\n\n  const check = () => {\n    const current = Atomics.load(state, index)\n    if (current !== expected) {\n      done(null, 'ok')\n      return\n    }\n\n    if (max !== Infinity && Date.now() > max) {\n      done(null, 'timed-out')\n      return\n    }\n\n    // Wait for value to change from expected.\n    // If we are notified, resume immediately even if the value cycled back\n    // to the same number before we could re-read it.\n    const remaining = max === Infinity ? WAIT_MS : Math.min(WAIT_MS, Math.max(1, max - Date.now()))\n    const result = Atomics.waitAsync(state, index, expected, remaining)\n\n    if (result.async) {\n      result.value.then((res) => {\n        if (res === 'ok') {\n          done(null, 'ok')\n          return\n        }\n\n        check()\n      })\n    } else {\n      // Value already changed (not-equal) - recheck on next tick\n      setImmediate(check)\n    }\n  }\n\n  check()\n}\n\nmodule.exports = { wait, waitDiff }\n","'use strict'\n\nconst SEQ_INDEX = 2\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n  WRITE_INDEX,\n  READ_INDEX,\n  SEQ_INDEX\n}\n","'use strict'\n\nconst { version } = require('./package.json')\nconst { EventEmitter } = require('events')\nconst { Worker } = require('worker_threads')\nconst { join } = require('path')\nconst { pathToFileURL } = require('url')\nconst { wait } = require('./lib/wait')\nconst {\n  WRITE_INDEX,\n  READ_INDEX,\n  SEQ_INDEX\n} = require('./lib/indexes')\nconst buffer = require('buffer')\nconst assert = require('assert')\n\nconst kImpl = Symbol('kImpl')\n\n// Maximum pending buffered data before forcing a synchronous drain\nconst MAX_STRING = buffer.constants.MAX_STRING_LENGTH\n\nfunction noop () {}\n\nfunction updateState (stream, fn) {\n  Atomics.add(stream[kImpl].state, SEQ_INDEX, 1)\n  fn()\n  Atomics.add(stream[kImpl].state, SEQ_INDEX, 1)\n  Atomics.notify(stream[kImpl].state, SEQ_INDEX)\n}\n\nfunction resetIndexes (stream) {\n  updateState(stream, () => {\n    Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n    Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n  })\n}\n\nclass FakeWeakRef {\n  constructor (value) {\n    this._value = value\n  }\n\n  deref () {\n    return this._value\n  }\n}\n\nclass FakeFinalizationRegistry {\n  register () {}\n\n  unregister () {}\n}\n\n// Currently using FinalizationRegistry with code coverage breaks the world\n// Ref: https://github.com/nodejs/node/issues/49344\nconst FinalizationRegistry = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry\nconst WeakRef = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef\n\nconst registry = new FinalizationRegistry((worker) => {\n  if (worker.exited) {\n    return\n  }\n  worker.terminate()\n})\n\nfunction createWorker (stream, opts) {\n  const { filename, workerData } = opts\n\n  const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n  const toExecute = bundlerOverrides['thread-stream-worker'] || join(__dirname, 'lib', 'worker.js')\n\n  const worker = new Worker(toExecute, {\n    ...opts.workerOpts,\n    name: opts.workerOpts?.name || 'thread-stream',\n    trackUnmanagedFds: false,\n    workerData: {\n      filename: filename.indexOf('file://') === 0\n        ? filename\n        : pathToFileURL(filename).href,\n      dataBuf: stream[kImpl].dataBuf,\n      stateBuf: stream[kImpl].stateBuf,\n      workerData: {\n        $context: {\n          threadStreamVersion: version\n        },\n        ...workerData\n      }\n    }\n  })\n\n  // We keep a strong reference for now,\n  // we need to start writing first\n  worker.stream = new FakeWeakRef(stream)\n\n  worker.on('message', onWorkerMessage)\n  worker.on('exit', onWorkerExit)\n  registry.register(stream, worker)\n\n  return worker\n}\n\nfunction drain (stream) {\n  assert(!stream[kImpl].sync)\n  if (stream[kImpl].needDrain) {\n    stream[kImpl].needDrain = false\n    stream.emit('drain')\n  }\n}\n\nfunction nextFlush (stream) {\n  while (true) {\n    const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n    const leftover = stream[kImpl].data.length - writeIndex\n\n    if (leftover > 0) {\n      if (stream[kImpl].bufLen === 0) {\n        stream[kImpl].flushing = false\n\n        if (stream[kImpl].ending) {\n          end(stream)\n        } else if (stream[kImpl].needDrain) {\n          process.nextTick(drain, stream)\n        }\n\n        return\n      }\n\n      write(stream, leftover, noop)\n      continue\n    }\n\n    if (leftover === 0) {\n      if (writeIndex === 0 && stream[kImpl].bufLen === 0) {\n        // we had a flushSync in the meanwhile\n        return\n      }\n      waitForRead(stream, () => {\n        if (stream.destroyed) {\n          return\n        }\n\n        resetIndexes(stream)\n        nextFlush(stream)\n      })\n      return\n    }\n\n    // This should never happen\n    destroy(stream, new Error('overwritten'))\n    return\n  }\n}\n\nfunction onWorkerMessage (msg) {\n  const stream = this.stream.deref()\n  if (stream === undefined) {\n    this.exited = true\n    // Terminate the worker.\n    this.terminate()\n    return\n  }\n\n  // Node.js watch mode may send internal worker messages that do not\n  // participate in thread-stream's worker protocol.\n  if (msg?.code == null) {\n    return\n  }\n\n  switch (msg.code) {\n    case 'READY':\n      // Replace the FakeWeakRef with a\n      // proper one.\n      this.stream = new WeakRef(stream)\n\n      waitForRead(stream, () => {\n        stream[kImpl].ready = true\n        stream.emit('ready')\n      })\n      break\n    case 'ERROR':\n      destroy(stream, msg.err)\n      break\n    case 'EVENT':\n      if (Array.isArray(msg.args)) {\n        stream.emit(msg.name, ...msg.args)\n      } else {\n        stream.emit(msg.name, msg.args)\n      }\n      break\n    case 'FLUSHED': {\n      if (msg.context !== 'thread-stream') {\n        destroy(stream, new Error('this should not happen: ' + msg.code))\n        break\n      }\n\n      const cb = stream[kImpl].flushCallbacks.get(msg.id)\n      if (cb) {\n        stream[kImpl].flushCallbacks.delete(msg.id)\n        process.nextTick(cb)\n      }\n      break\n    }\n    case 'WARNING':\n      process.emitWarning(msg.err)\n      break\n    default:\n      destroy(stream, new Error('this should not happen: ' + msg.code))\n  }\n}\n\nfunction onWorkerExit (code) {\n  const stream = this.stream.deref()\n  if (stream === undefined) {\n    // Nothing to do, the worker already exit\n    return\n  }\n  registry.unregister(stream)\n  stream.worker.exited = true\n  stream.worker.off('exit', onWorkerExit)\n  destroy(stream, code !== 0 ? new Error('the worker thread exited') : null)\n}\n\nclass ThreadStream extends EventEmitter {\n  constructor (opts = {}) {\n    super()\n\n    if (opts.bufferSize < 4) {\n      throw new Error('bufferSize must at least fit a 4-byte utf-8 char')\n    }\n\n    this[kImpl] = {}\n    this[kImpl].stateBuf = new SharedArrayBuffer(128)\n    this[kImpl].state = new Int32Array(this[kImpl].stateBuf)\n    this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024)\n    this[kImpl].data = Buffer.from(this[kImpl].dataBuf)\n    this[kImpl].sync = opts.sync || false\n    this[kImpl].ending = false\n    this[kImpl].ended = false\n    this[kImpl].needDrain = false\n    this[kImpl].destroyed = false\n    this[kImpl].flushing = false\n    this[kImpl].ready = false\n    this[kImpl].finished = false\n    this[kImpl].errored = null\n    this[kImpl].closed = false\n    this[kImpl].buf = []\n    this[kImpl].bufHead = 0\n    this[kImpl].bufLen = 0\n    this[kImpl].flushCallbacks = new Map()\n    this[kImpl].nextFlushId = 0\n\n    // TODO (fix): Make private?\n    this.worker = createWorker(this, opts) // TODO (fix): make private\n    this.on('message', (message, transferList) => {\n      this.worker.postMessage(message, transferList)\n    })\n  }\n\n  write (data) {\n    const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data)\n    if (this[kImpl].destroyed) {\n      error(this, new Error('the worker has exited'))\n      return false\n    }\n\n    if (this[kImpl].ending) {\n      error(this, new Error('the worker is ending'))\n      return false\n    }\n\n    if (this[kImpl].flushing && this[kImpl].bufLen + dataBuf.length >= MAX_STRING) {\n      try {\n        writeSync(this)\n        this[kImpl].flushing = true\n      } catch (err) {\n        destroy(this, err)\n        return false\n      }\n    }\n\n    this[kImpl].buf.push(dataBuf)\n    this[kImpl].bufLen += dataBuf.length\n\n    if (this[kImpl].sync) {\n      try {\n        writeSync(this)\n        return true\n      } catch (err) {\n        destroy(this, err)\n        return false\n      }\n    }\n\n    if (!this[kImpl].flushing) {\n      this[kImpl].flushing = true\n      setImmediate(nextFlush, this)\n    }\n\n    this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].bufLen - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0\n    return !this[kImpl].needDrain\n  }\n\n  end () {\n    if (this[kImpl].destroyed) {\n      return\n    }\n\n    this[kImpl].ending = true\n    end(this)\n  }\n\n  flush (cb) {\n    cb = typeof cb === 'function' ? cb : noop\n\n    flushBuffer(this, (err) => {\n      if (err) {\n        process.nextTick(cb, err)\n        return\n      }\n\n      requestWorkerFlush(this, cb)\n    })\n  }\n\n  flushSync () {\n    if (this[kImpl].destroyed) {\n      return\n    }\n\n    writeSync(this)\n    flushSync(this)\n  }\n\n  unref () {\n    this.worker.unref()\n  }\n\n  ref () {\n    this.worker.ref()\n  }\n\n  get ready () {\n    return this[kImpl].ready\n  }\n\n  get destroyed () {\n    return this[kImpl].destroyed\n  }\n\n  get closed () {\n    return this[kImpl].closed\n  }\n\n  get writable () {\n    return !this[kImpl].destroyed && !this[kImpl].ending\n  }\n\n  get writableEnded () {\n    return this[kImpl].ending\n  }\n\n  get writableFinished () {\n    return this[kImpl].finished\n  }\n\n  get writableNeedDrain () {\n    return this[kImpl].needDrain\n  }\n\n  get writableObjectMode () {\n    return false\n  }\n\n  get writableErrored () {\n    return this[kImpl].errored\n  }\n}\n\nfunction flushBuffer (stream, cb) {\n  if (stream[kImpl].destroyed) {\n    process.nextTick(cb, new Error('the worker has exited'))\n    return\n  }\n\n  if (!stream[kImpl].sync && (stream[kImpl].flushing || stream[kImpl].bufLen > 0)) {\n    setImmediate(flushBuffer, stream, cb)\n    return\n  }\n\n  waitForRead(stream, cb)\n}\n\nfunction waitForRead (stream, cb) {\n  const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n  wait(stream[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {\n    if (err) {\n      destroy(stream, err)\n      cb(err)\n      return\n    }\n\n    if (res !== 'ok') {\n      waitForRead(stream, cb)\n      return\n    }\n\n    cb()\n  })\n}\n\nfunction requestWorkerFlush (stream, cb) {\n  if (stream[kImpl].destroyed) {\n    process.nextTick(cb, new Error('the worker has exited'))\n    return\n  }\n\n  if (!stream[kImpl].ready) {\n    const onReady = () => {\n      cleanup()\n      requestWorkerFlush(stream, cb)\n    }\n    const onClose = () => {\n      cleanup()\n      process.nextTick(cb, new Error('the worker has exited'))\n    }\n    const cleanup = () => {\n      stream.off('ready', onReady)\n      stream.off('close', onClose)\n    }\n\n    stream.once('ready', onReady)\n    stream.once('close', onClose)\n    return\n  }\n\n  const id = ++stream[kImpl].nextFlushId\n  stream[kImpl].flushCallbacks.set(id, cb)\n\n  try {\n    stream.worker.postMessage({\n      code: 'FLUSH',\n      context: 'thread-stream',\n      id\n    })\n  } catch (err) {\n    stream[kImpl].flushCallbacks.delete(id)\n    destroy(stream, err)\n    process.nextTick(cb, err)\n  }\n}\n\nfunction failPendingFlushCallbacks (stream, err) {\n  const callbacks = stream[kImpl].flushCallbacks\n  if (callbacks.size === 0) {\n    return\n  }\n\n  const flushErr = err || new Error('the worker has exited')\n\n  for (const cb of callbacks.values()) {\n    process.nextTick(cb, flushErr)\n  }\n  callbacks.clear()\n}\n\nfunction error (stream, err) {\n  setImmediate(() => {\n    stream.emit('error', err)\n  })\n}\n\nfunction destroy (stream, err) {\n  if (stream[kImpl].destroyed) {\n    return\n  }\n  stream[kImpl].destroyed = true\n  failPendingFlushCallbacks(stream, err)\n\n  if (err) {\n    stream[kImpl].errored = err\n    error(stream, err)\n  }\n\n  if (!stream.worker.exited) {\n    stream.worker.terminate()\n      .catch(() => {})\n      .then(() => {\n        stream[kImpl].closed = true\n        stream.emit('close')\n      })\n  } else {\n    setImmediate(() => {\n      stream[kImpl].closed = true\n      stream.emit('close')\n    })\n  }\n}\n\nfunction write (stream, maxBytes, cb) {\n  // data is smaller than the shared buffer length\n  const current = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n  let offset = current\n  let remaining = maxBytes\n\n  while (remaining > 0 && stream[kImpl].bufLen !== 0) {\n    const head = stream[kImpl].bufHead\n    const buf = stream[kImpl].buf[head]\n\n    if (buf.length <= remaining) {\n      buf.copy(stream[kImpl].data, offset)\n      offset += buf.length\n      remaining -= buf.length\n      stream[kImpl].bufLen -= buf.length\n      stream[kImpl].bufHead = head + 1\n\n      if (stream[kImpl].bufHead === stream[kImpl].buf.length) {\n        stream[kImpl].buf.length = 0\n        stream[kImpl].bufHead = 0\n      } else if (stream[kImpl].bufHead >= 1024 && stream[kImpl].bufHead * 2 >= stream[kImpl].buf.length) {\n        stream[kImpl].buf.splice(0, stream[kImpl].bufHead)\n        stream[kImpl].bufHead = 0\n      }\n      continue\n    }\n\n    buf.copy(stream[kImpl].data, offset, 0, remaining)\n    stream[kImpl].buf[head] = buf.subarray(remaining)\n    stream[kImpl].bufLen -= remaining\n    offset += remaining\n    remaining = 0\n  }\n\n  updateState(stream, () => {\n    Atomics.store(stream[kImpl].state, WRITE_INDEX, offset)\n  })\n  cb()\n  return true\n}\n\nfunction end (stream) {\n  if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {\n    return\n  }\n  stream[kImpl].ended = true\n\n  try {\n    stream.flushSync()\n\n    let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n    // process._rawDebug('writing index')\n    updateState(stream, () => {\n      Atomics.store(stream[kImpl].state, WRITE_INDEX, -1)\n    })\n    // process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`)\n\n    // Wait for the process to complete\n    let spins = 0\n    while (readIndex !== -1) {\n      // process._rawDebug(`read = ${read}`)\n      Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n      readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n      if (readIndex === -2) {\n        destroy(stream, new Error('end() failed'))\n        return\n      }\n\n      if (++spins === 10) {\n        destroy(stream, new Error('end() took too long (10s)'))\n        return\n      }\n    }\n\n    process.nextTick(() => {\n      stream[kImpl].finished = true\n      stream.emit('finish')\n    })\n  } catch (err) {\n    destroy(stream, err)\n  }\n  // process._rawDebug('end finished...')\n}\n\nfunction writeSync (stream) {\n  const cb = () => {\n    if (stream[kImpl].ending) {\n      end(stream)\n    } else if (stream[kImpl].needDrain) {\n      process.nextTick(drain, stream)\n    }\n  }\n  stream[kImpl].flushing = false\n\n  while (stream[kImpl].bufLen !== 0) {\n    const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n    const leftover = stream[kImpl].data.length - writeIndex\n    if (leftover === 0) {\n      flushSync(stream)\n      resetIndexes(stream)\n      continue\n    } else if (leftover < 0) {\n      // stream should never happen\n      throw new Error('overwritten')\n    }\n\n    write(stream, leftover, cb)\n  }\n}\n\nfunction flushSync (stream) {\n  if (stream[kImpl].flushing) {\n    throw new Error('unable to flush while flushing')\n  }\n\n  // process._rawDebug('flushSync started')\n\n  const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n\n  let spins = 0\n\n  // TODO handle deadlock\n  while (true) {\n    const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n    if (readIndex === -2) {\n      throw Error('_flushSync failed')\n    }\n\n    // process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`)\n    if (readIndex !== writeIndex) {\n      // TODO stream timeouts for some reason.\n      Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n    } else {\n      break\n    }\n\n    if (++spins === 10) {\n      throw new Error('_flushSync took too long (10s)')\n    }\n  }\n  // process._rawDebug('flushSync finished')\n}\n\nmodule.exports = ThreadStream\n","'use strict'\n\nconst { createRequire } = require('module')\nconst { existsSync } = require('node:fs')\nconst getCallers = require('./caller')\nconst { join, isAbsolute, sep } = require('node:path')\nconst { fileURLToPath } = require('node:url')\nconst sleep = require('atomic-sleep')\nconst onExit = require('on-exit-leak-free')\nconst ThreadStream = require('thread-stream')\n\nfunction setupOnExit (stream) {\n  // This is leak free, it does not leave event handlers\n  onExit.register(stream, autoEnd)\n  onExit.registerBeforeExit(stream, flush)\n\n  stream.on('close', function () {\n    onExit.unregister(stream)\n  })\n}\n\n// Check if preload flags exist in execArgv.\n// During preload phase (require.main undefined), we pass empty execArgv to prevent infinite worker spawning.\n// We don't try to filter and pass other flags because many (like --stack-trace-limit, --tls-cipher-list)\n// aren't valid for worker threads and would cause ERR_WORKER_INVALID_EXEC_ARGV.\nfunction hasPreloadFlags () {\n  const execArgv = process.execArgv\n  for (let i = 0; i < execArgv.length; i++) {\n    const arg = execArgv[i]\n    if (arg === '--import' || arg === '--require' || arg === '-r') {\n      return true\n    }\n    if (arg.startsWith('--import=') || arg.startsWith('--require=') || arg.startsWith('-r=')) {\n      return true\n    }\n  }\n  return false\n}\n\nfunction sanitizeNodeOptions (nodeOptions) {\n  const tokens = nodeOptions.match(/(?:[^\\s\"']+|\"[^\"]*\"|'[^']*')+/g)\n  if (!tokens) {\n    return nodeOptions\n  }\n\n  const sanitized = []\n  let changed = false\n\n  for (let i = 0; i < tokens.length; i++) {\n    const token = tokens[i]\n\n    if (token === '--require' || token === '-r' || token === '--import') {\n      const next = tokens[i + 1]\n      if (next && shouldDropPreload(next)) {\n        changed = true\n        i++\n        continue\n      }\n\n      sanitized.push(token)\n      if (next) {\n        sanitized.push(next)\n        i++\n      }\n      continue\n    }\n\n    if (token.startsWith('--require=') || token.startsWith('-r=') || token.startsWith('--import=')) {\n      const value = token.slice(token.indexOf('=') + 1)\n      if (shouldDropPreload(value)) {\n        changed = true\n        continue\n      }\n    }\n\n    sanitized.push(token)\n  }\n\n  return changed ? sanitized.join(' ') : nodeOptions\n}\n\nfunction shouldDropPreload (value) {\n  const unquoted = stripQuotes(value)\n  if (!unquoted) {\n    return false\n  }\n\n  let path = unquoted\n  if (path.startsWith('file://')) {\n    try {\n      path = fileURLToPath(path)\n    } catch {\n      return false\n    }\n  }\n\n  return isAbsolute(path) && !existsSync(path)\n}\n\nfunction stripQuotes (value) {\n  const first = value[0]\n  const last = value[value.length - 1]\n\n  if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n    return value.slice(1, -1)\n  }\n\n  return value\n}\n\nfunction buildStream (filename, workerData, workerOpts, sync, name) {\n  // When pino is loaded during a preload phase (via --import or --require),\n  // pass empty execArgv to prevent infinite spawning. Each worker would\n  // otherwise re-run the preload, creating another transport.\n  if (!workerOpts.execArgv && hasPreloadFlags() && require.main === undefined) {\n    workerOpts = {\n      ...workerOpts,\n      execArgv: []\n    }\n  }\n\n  if (!workerOpts.env && process.env.NODE_OPTIONS) {\n    const nodeOptions = sanitizeNodeOptions(process.env.NODE_OPTIONS)\n    if (nodeOptions !== process.env.NODE_OPTIONS) {\n      workerOpts = {\n        ...workerOpts,\n        env: {\n          ...process.env,\n          NODE_OPTIONS: nodeOptions\n        }\n      }\n    }\n  }\n\n  workerOpts = { ...workerOpts, name }\n\n  const stream = new ThreadStream({\n    filename,\n    workerData,\n    workerOpts,\n    sync\n  })\n\n  stream.on('ready', onReady)\n  stream.on('close', function () {\n    process.removeListener('exit', onExit)\n  })\n\n  process.on('exit', onExit)\n\n  function onReady () {\n    process.removeListener('exit', onExit)\n    stream.unref()\n\n    if (workerOpts.autoEnd !== false) {\n      setupOnExit(stream)\n    }\n  }\n\n  function onExit () {\n    /* istanbul ignore next */\n    if (stream.closed) {\n      return\n    }\n    stream.flushSync()\n    // Apparently there is a very sporadic race condition\n    // that in certain OS would prevent the messages to be flushed\n    // because the thread might not have been created still.\n    // Unfortunately we need to sleep(100) in this case.\n    sleep(100)\n    stream.end()\n  }\n\n  return stream\n}\n\nfunction autoEnd (stream) {\n  stream.ref()\n  stream.flushSync()\n  stream.end()\n  stream.once('close', function () {\n    stream.unref()\n  })\n}\n\nfunction flush (stream) {\n  stream.flushSync()\n}\n\nfunction transport (fullOptions) {\n  const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions\n\n  const options = {\n    ...fullOptions.options\n  }\n\n  // Backwards compatibility\n  const callers = typeof caller === 'string' ? [caller] : caller\n\n  // This will be eventually modified by bundlers\n  const bundlerOverrides = (typeof globalThis === 'object' &&\n    Object.prototype.hasOwnProperty.call(globalThis, '__bundlerPathsOverrides') &&\n    globalThis.__bundlerPathsOverrides &&\n    typeof globalThis.__bundlerPathsOverrides === 'object')\n    ? globalThis.__bundlerPathsOverrides\n    : Object.create(null)\n\n  let target = fullOptions.target\n\n  if (target && targets) {\n    throw new Error('only one of target or targets can be specified')\n  }\n\n  if (targets) {\n    target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n    options.targets = targets.filter(dest => dest.target).map((dest) => {\n      return {\n        ...dest,\n        target: fixTarget(dest.target)\n      }\n    })\n    options.pipelines = targets.filter(dest => dest.pipeline).map((dest) => {\n      return dest.pipeline.map((t) => {\n        return {\n          ...t,\n          level: dest.level, // duplicate the pipeline `level` property defined in the upper level\n          target: fixTarget(t.target)\n        }\n      })\n    })\n  } else if (pipeline) {\n    target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n    options.pipelines = [pipeline.map((dest) => {\n      return {\n        ...dest,\n        target: fixTarget(dest.target)\n      }\n    })]\n  }\n\n  if (levels) {\n    options.levels = levels\n  }\n\n  if (dedupe) {\n    options.dedupe = dedupe\n  }\n\n  options.pinoWillSendConfig = true\n\n  const name = (targets || pipeline) ? 'pino.transport' : target\n  return buildStream(fixTarget(target), options, worker, sync, name)\n\n  function fixTarget (origin) {\n    origin = bundlerOverrides[origin] || origin\n\n    if (isAbsolute(origin) || origin.indexOf('file://') === 0) {\n      return origin\n    }\n\n    if (origin === 'pino/file') {\n      return join(__dirname, '..', 'file.js')\n    }\n\n    let fixTarget\n\n    for (const filePath of callers) {\n      try {\n        const context = filePath === 'node:repl'\n          ? process.cwd() + sep\n          : filePath\n\n        fixTarget = createRequire(context).resolve(origin)\n        break\n      } catch (err) {\n        // Silent catch\n        continue\n      }\n    }\n\n    if (!fixTarget) {\n      throw new Error(`unable to determine transport target for \"${origin}\"`)\n    }\n\n    return fixTarget\n  }\n}\n\nmodule.exports = transport\n","'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst diagChan = require('node:diagnostics_channel')\nconst format = require('quick-format-unescaped')\nconst { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers')\nconst SonicBoom = require('sonic-boom')\nconst onExit = require('on-exit-leak-free')\nconst {\n  lsCacheSym,\n  chindingsSym,\n  writeSym,\n  serializersSym,\n  formatOptsSym,\n  endSym,\n  stringifiersSym,\n  stringifySym,\n  stringifySafeSym,\n  wildcardFirstSym,\n  nestedKeySym,\n  formattersSym,\n  messageKeySym,\n  errorKeySym,\n  nestedKeyStrSym,\n  msgPrefixSym\n} = require('./symbols')\nconst { isMainThread } = require('worker_threads')\nconst transport = require('./transport')\nconst [nodeMajor] = process.versions.node.split('.').map(v => Number(v))\n\nconst asJsonChan = diagChan.tracingChannel('pino_asJson')\n\n// JSON.stringify is faster in node 25+.\nconst asString = nodeMajor >= 25 ? str => JSON.stringify(str) : _asString\n\nfunction noop () {\n}\n\nfunction genLog (level, hook) {\n  if (!hook) return LOG\n\n  return function hookWrappedLog (...args) {\n    hook.call(this, args, LOG, level)\n  }\n\n  function LOG (o, ...n) {\n    if (typeof o === 'object') {\n      let msg = o\n      if (o !== null) {\n        if (o.method && o.headers && o.socket) {\n          o = mapHttpRequest(o)\n        } else if (typeof o.setHeader === 'function') {\n          o = mapHttpResponse(o)\n        }\n      }\n      let formatParams\n      if (msg === null && n.length === 0) {\n        formatParams = [null]\n      } else {\n        msg = n.shift()\n        formatParams = n\n      }\n      // We do not use a coercive check for `msg` as it is\n      // measurably slower than the explicit checks.\n      if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n        msg = this[msgPrefixSym] + msg\n      }\n      this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level)\n    } else {\n      let msg = o === undefined ? n.shift() : o\n\n      // We do not use a coercive check for `msg` as it is\n      // measurably slower than the explicit checks.\n      if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n        msg = this[msgPrefixSym] + msg\n      }\n      this[writeSym](null, format(msg, n, this[formatOptsSym]), level)\n    }\n  }\n}\n\n// magically escape strings for json\n// relying on their charCodeAt\n// everything below 32 needs JSON.stringify()\n// 34 and 92 happens all the time, so we\n// have a fast case for them\nfunction _asString (str) {\n  let result = ''\n  let last = 0\n  let found = false\n  let point = 255\n  const l = str.length\n  if (l > 100) {\n    return JSON.stringify(str)\n  }\n  for (var i = 0; i < l && point >= 32; i++) {\n    point = str.charCodeAt(i)\n    if (point === 34 || point === 92) {\n      result += str.slice(last, i) + '\\\\'\n      last = i\n      found = true\n    }\n  }\n  if (!found) {\n    result = str\n  } else {\n    result += str.slice(last)\n  }\n  return point < 32 ? JSON.stringify(str) : '\"' + result + '\"'\n}\n\n/**\n * `asJson` wraps `_asJson` in order to facilitate generating diagnostics.\n *\n * @param {object} obj The merging object passed to the log method.\n * @param {string} msg The log message passed to the log method.\n * @param {number} num The log level number.\n * @param {number} time The log time in milliseconds.\n *\n * @returns {string}\n */\nfunction asJson (obj, msg, num, time) {\n  if (asJsonChan.hasSubscribers === false) {\n    return _asJson.call(this, obj, msg, num, time)\n  }\n\n  const store = { instance: this, arguments }\n  return asJsonChan.traceSync(_asJson, store, this, obj, msg, num, time)\n}\n\n/**\n * `_asJson` parses all collected data and generates the finalized newline\n * delimited JSON string.\n *\n * @param {object} obj The merging object passed to the log method.\n * @param {string} msg The log message passed to the log method.\n * @param {number} num The log level number.\n * @param {number} time The log time in milliseconds.\n *\n * @returns {string} The finalized log string terminated with a newline.\n * @private\n */\nfunction _asJson (obj, msg, num, time) {\n  const stringify = this[stringifySym]\n  const stringifySafe = this[stringifySafeSym]\n  const stringifiers = this[stringifiersSym]\n  const end = this[endSym]\n  const chindings = this[chindingsSym]\n  const serializers = this[serializersSym]\n  const formatters = this[formattersSym]\n  const messageKey = this[messageKeySym]\n  const errorKey = this[errorKeySym]\n  let data = this[lsCacheSym][num] + time\n\n  // we need the child bindings added to the output first so instance logged\n  // objects can take precedence when JSON.parse-ing the resulting log line\n  data = data + chindings\n\n  let value\n  if (formatters.log) {\n    obj = formatters.log(obj)\n  }\n  const wildcardStringifier = stringifiers[wildcardFirstSym]\n  let propStr = ''\n  for (const key in obj) {\n    value = obj[key]\n    if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) {\n      if (serializers[key]) {\n        value = serializers[key](value)\n      } else if (key === errorKey && serializers.err) {\n        value = serializers.err(value)\n      }\n\n      const stringifier = stringifiers[key] || wildcardStringifier\n\n      switch (typeof value) {\n        case 'undefined':\n        case 'function':\n          continue\n        case 'number':\n          /* eslint no-fallthrough: \"off\" */\n          if (Number.isFinite(value) === false) {\n            value = null\n          }\n        // this case explicitly falls through to the next one\n        case 'boolean':\n          if (stringifier) value = stringifier(value)\n          break\n        case 'string':\n          value = (stringifier || asString)(value)\n          break\n        default:\n          value = (stringifier || stringify)(value, stringifySafe)\n      }\n      if (value === undefined) continue\n      const strKey = asString(key)\n      propStr += ',' + strKey + ':' + value\n    }\n  }\n\n  let msgStr = ''\n  if (msg !== undefined) {\n    value = serializers[messageKey] ? serializers[messageKey](msg) : msg\n    const stringifier = stringifiers[messageKey] || wildcardStringifier\n\n    switch (typeof value) {\n      case 'function':\n        break\n      case 'number':\n        if (Number.isFinite(value) === false) {\n          value = null\n        }\n      // this case explicitly falls through to the next one\n      case 'boolean':\n        if (stringifier) value = stringifier(value)\n        msgStr = ',\"' + messageKey + '\":' + value\n        break\n      case 'string':\n        value = (stringifier || asString)(value)\n        msgStr = ',\"' + messageKey + '\":' + value\n        break\n      default:\n        value = (stringifier || stringify)(value, stringifySafe)\n        msgStr = ',\"' + messageKey + '\":' + value\n    }\n  }\n\n  if (this[nestedKeySym] && propStr) {\n    // place all the obj properties under the specified key\n    // the nested key is already formatted from the constructor\n    return data + this[nestedKeyStrSym] + propStr.slice(1) + '}' + msgStr + end\n  } else {\n    return data + propStr + msgStr + end\n  }\n}\n\nfunction asChindings (instance, bindings) {\n  let value\n  let data = instance[chindingsSym]\n  const stringify = instance[stringifySym]\n  const stringifySafe = instance[stringifySafeSym]\n  const stringifiers = instance[stringifiersSym]\n  const wildcardStringifier = stringifiers[wildcardFirstSym]\n  const serializers = instance[serializersSym]\n  const formatter = instance[formattersSym].bindings\n  bindings = formatter(bindings)\n\n  for (const key in bindings) {\n    value = bindings[key]\n    const valid = (key.length < 5 || (key !== 'level' &&\n      key !== 'serializers' &&\n      key !== 'formatters' &&\n      key !== 'customLevels')) &&\n      bindings.hasOwnProperty(key) &&\n      value !== undefined\n    if (valid === true) {\n      value = serializers[key] ? serializers[key](value) : value\n      value = (stringifiers[key] || wildcardStringifier || stringify)(value, stringifySafe)\n      if (value === undefined) continue\n      data += ',\"' + key + '\":' + value\n    }\n  }\n  return data\n}\n\nfunction hasBeenTampered (stream) {\n  return stream.write !== stream.constructor.prototype.write\n}\n\nfunction buildSafeSonicBoom (opts) {\n  const stream = new SonicBoom(opts)\n  stream.on('error', filterBrokenPipe)\n  // If we are sync: false, we must flush on exit\n  if (!opts.sync && isMainThread) {\n    onExit.register(stream, autoEnd)\n\n    stream.on('close', function () {\n      onExit.unregister(stream)\n    })\n  }\n  return stream\n\n  function filterBrokenPipe (err) {\n    // Impossible to replicate across all operating systems\n    /* istanbul ignore next */\n    if (err.code === 'EPIPE') {\n      // If we get EPIPE, we should stop logging here\n      // however we have no control to the consumer of\n      // SonicBoom, so we just overwrite the write method\n      stream.write = noop\n      stream.end = noop\n      stream.flushSync = noop\n      stream.destroy = noop\n      return\n    }\n    stream.removeListener('error', filterBrokenPipe)\n    stream.emit('error', err)\n  }\n}\n\nfunction autoEnd (stream, eventName) {\n  // This check is needed only on some platforms\n  /* istanbul ignore next */\n  if (stream.destroyed) {\n    return\n  }\n\n  if (eventName === 'beforeExit') {\n    // We still have an event loop, let's use it\n    stream.flush()\n    stream.on('drain', function () {\n      stream.end()\n    })\n  } else {\n    // For some reason istanbul is not detecting this, but it's there\n    /* istanbul ignore next */\n    // We do not have an event loop, so flush synchronously\n    stream.flushSync()\n  }\n}\n\nfunction createArgsNormalizer (defaultOptions) {\n  return function normalizeArgs (instance, caller, opts = {}, stream) {\n    // support stream as a string\n    if (typeof opts === 'string') {\n      stream = buildSafeSonicBoom({ dest: opts })\n      opts = {}\n    } else if (typeof stream === 'string') {\n      if (opts && opts.transport) {\n        throw Error('only one of option.transport or stream can be specified')\n      }\n      stream = buildSafeSonicBoom({ dest: stream })\n    } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {\n      stream = opts\n      opts = {}\n    } else if (opts.transport) {\n      if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {\n        throw Error('option.transport do not allow stream, please pass to option directly. e.g. pino(transport)')\n      }\n      if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === 'function') {\n        throw Error('option.transport.targets do not allow custom level formatters')\n      }\n\n      let customLevels\n      if (opts.customLevels) {\n        customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels)\n      }\n      stream = transport({ caller, ...opts.transport, levels: customLevels })\n    }\n    opts = Object.assign({}, defaultOptions, opts)\n    opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers)\n    opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters)\n\n    if (opts.prettyPrint) {\n      throw new Error('prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)')\n    }\n\n    const { enabled, onChild } = opts\n    if (enabled === false) opts.level = 'silent'\n    if (!onChild) opts.onChild = noop\n    if (!stream) {\n      if (!hasBeenTampered(process.stdout)) {\n        // If process.stdout.fd is undefined, it means that we are running\n        // in a worker thread. Let's assume we are logging to file descriptor 1.\n        stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 })\n      } else {\n        stream = process.stdout\n      }\n    }\n    return { opts, stream }\n  }\n}\n\nfunction stringify (obj, stringifySafeFn) {\n  try {\n    return JSON.stringify(obj)\n  } catch (_) {\n    try {\n      const stringify = stringifySafeFn || this[stringifySafeSym]\n      return stringify(obj)\n    } catch (_) {\n      return '\"[unable to serialize, circular reference is too complex to analyze]\"'\n    }\n  }\n}\n\nfunction buildFormatters (level, bindings, log) {\n  return {\n    level,\n    bindings,\n    log\n  }\n}\n\n/**\n * Convert a string integer file descriptor to a proper native integer\n * file descriptor.\n *\n * @param {string} destination The file descriptor string to attempt to convert.\n *\n * @returns {Number}\n */\nfunction normalizeDestFileDescriptor (destination) {\n  const fd = Number(destination)\n  if (typeof destination === 'string' && Number.isFinite(fd)) {\n    return fd\n  }\n  // destination could be undefined if we are in a worker\n  if (destination === undefined) {\n    // This is stdout in UNIX systems\n    return 1\n  }\n  return destination\n}\n\nmodule.exports = {\n  noop,\n  buildSafeSonicBoom,\n  asChindings,\n  asJson,\n  genLog,\n  createArgsNormalizer,\n  stringify,\n  buildFormatters,\n  normalizeDestFileDescriptor\n}\n","/**\n * Represents default log level values\n *\n * @enum {number}\n */\nconst DEFAULT_LEVELS = {\n  trace: 10,\n  debug: 20,\n  info: 30,\n  warn: 40,\n  error: 50,\n  fatal: 60\n}\n\n/**\n * Represents sort order direction: `ascending` or `descending`\n *\n * @enum {string}\n */\nconst SORTING_ORDER = {\n  ASC: 'ASC',\n  DESC: 'DESC'\n}\n\nmodule.exports = {\n  DEFAULT_LEVELS,\n  SORTING_ORDER\n}\n","'use strict'\n/* eslint no-prototype-builtins: 0 */\nconst {\n  lsCacheSym,\n  levelValSym,\n  useOnlyCustomLevelsSym,\n  streamSym,\n  formattersSym,\n  hooksSym,\n  levelCompSym\n} = require('./symbols')\nconst { noop, genLog } = require('./tools')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./constants')\n\nconst levelMethods = {\n  fatal: (hook) => {\n    const logFatal = genLog(DEFAULT_LEVELS.fatal, hook)\n    return function (...args) {\n      const stream = this[streamSym]\n      logFatal.call(this, ...args)\n      if (typeof stream.flushSync === 'function') {\n        try {\n          stream.flushSync()\n        } catch (e) {\n          // https://github.com/pinojs/pino/pull/740#discussion_r346788313\n        }\n      }\n    }\n  },\n  error: (hook) => genLog(DEFAULT_LEVELS.error, hook),\n  warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook),\n  info: (hook) => genLog(DEFAULT_LEVELS.info, hook),\n  debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook),\n  trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook)\n}\n\nconst nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => {\n  o[DEFAULT_LEVELS[k]] = k\n  return o\n}, {})\n\nconst initialLsCache = Object.keys(nums).reduce((o, k) => {\n  o[k] = '{\"level\":' + Number(k)\n  return o\n}, {})\n\nfunction genLsCache (instance) {\n  const formatter = instance[formattersSym].level\n  const { labels } = instance.levels\n  const cache = {}\n  for (const label in labels) {\n    const level = formatter(labels[label], Number(label))\n    cache[label] = JSON.stringify(level).slice(0, -1)\n  }\n  instance[lsCacheSym] = cache\n  return instance\n}\n\nfunction isStandardLevel (level, useOnlyCustomLevels) {\n  if (useOnlyCustomLevels) {\n    return false\n  }\n\n  switch (level) {\n    case 'fatal':\n    case 'error':\n    case 'warn':\n    case 'info':\n    case 'debug':\n    case 'trace':\n      return true\n    default:\n      return false\n  }\n}\n\nfunction setLevel (level) {\n  const { labels, values } = this.levels\n  if (typeof level === 'number') {\n    if (labels[level] === undefined) throw Error('unknown level value' + level)\n    level = labels[level]\n  }\n  if (values[level] === undefined) throw Error('unknown level ' + level)\n  const preLevelVal = this[levelValSym]\n  const levelVal = this[levelValSym] = values[level]\n  const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]\n  const levelComparison = this[levelCompSym]\n  const hook = this[hooksSym].logMethod\n\n  for (const key in values) {\n    if (levelComparison(values[key], levelVal) === false) {\n      this[key] = noop\n      continue\n    }\n    this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook)\n  }\n\n  this.emit(\n    'level-change',\n    level,\n    levelVal,\n    labels[preLevelVal],\n    preLevelVal,\n    this\n  )\n}\n\nfunction getLevel (level) {\n  const { levels, levelVal } = this\n  // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833)\n  return (levels && levels.labels) ? levels.labels[levelVal] : ''\n}\n\nfunction isLevelEnabled (logLevel) {\n  const { values } = this.levels\n  const logLevelVal = values[logLevel]\n  return logLevelVal !== undefined && this[levelCompSym](logLevelVal, this[levelValSym])\n}\n\n/**\n * Determine if the given `current` level is enabled by comparing it\n * against the current threshold (`expected`).\n *\n * @param {SORTING_ORDER} direction comparison direction \"ASC\" or \"DESC\"\n * @param {number} current current log level number representation\n * @param {number} expected threshold value to compare with\n * @returns {boolean}\n */\nfunction compareLevel (direction, current, expected) {\n  if (direction === SORTING_ORDER.DESC) {\n    return current <= expected\n  }\n\n  return current >= expected\n}\n\n/**\n * Create a level comparison function based on `levelComparison`\n * it could a default function which compares levels either in \"ascending\" or \"descending\" order or custom comparison function\n *\n * @param {SORTING_ORDER | Function} levelComparison sort levels order direction or custom comparison function\n * @returns Function\n */\nfunction genLevelComparison (levelComparison) {\n  if (typeof levelComparison === 'string') {\n    return compareLevel.bind(null, levelComparison)\n  }\n\n  return levelComparison\n}\n\nfunction mappings (customLevels = null, useOnlyCustomLevels = false) {\n  const customNums = customLevels\n    /* eslint-disable */\n    ? Object.keys(customLevels).reduce((o, k) => {\n        o[customLevels[k]] = k\n        return o\n      }, {})\n    : null\n    /* eslint-enable */\n\n  const labels = Object.assign(\n    Object.create(Object.prototype, { Infinity: { value: 'silent' } }),\n    useOnlyCustomLevels ? null : nums,\n    customNums\n  )\n  const values = Object.assign(\n    Object.create(Object.prototype, { silent: { value: Infinity } }),\n    useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n    customLevels\n  )\n  return { labels, values }\n}\n\nfunction assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) {\n  if (typeof defaultLevel === 'number') {\n    const values = [].concat(\n      Object.keys(customLevels || {}).map(key => customLevels[key]),\n      useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),\n      Infinity\n    )\n    if (!values.includes(defaultLevel)) {\n      throw Error(`default level:${defaultLevel} must be included in custom levels`)\n    }\n    return\n  }\n\n  const labels = Object.assign(\n    Object.create(Object.prototype, { silent: { value: Infinity } }),\n    useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n    customLevels\n  )\n  if (!(defaultLevel in labels)) {\n    throw Error(`default level:${defaultLevel} must be included in custom levels`)\n  }\n}\n\nfunction assertNoLevelCollisions (levels, customLevels) {\n  const { labels, values } = levels\n  for (const k in customLevels) {\n    if (k in values) {\n      throw Error('levels cannot be overridden')\n    }\n    if (customLevels[k] in labels) {\n      throw Error('pre-existing level values cannot be used for new levels')\n    }\n  }\n}\n\n/**\n * Validates whether `levelComparison` is correct\n *\n * @throws Error\n * @param {SORTING_ORDER | Function} levelComparison - value to validate\n * @returns\n */\nfunction assertLevelComparison (levelComparison) {\n  if (typeof levelComparison === 'function') {\n    return\n  }\n\n  if (typeof levelComparison === 'string' && Object.values(SORTING_ORDER).includes(levelComparison)) {\n    return\n  }\n\n  throw new Error('Levels comparison should be one of \"ASC\", \"DESC\" or \"function\" type')\n}\n\nmodule.exports = {\n  initialLsCache,\n  genLsCache,\n  levelMethods,\n  getLevel,\n  setLevel,\n  isLevelEnabled,\n  mappings,\n  assertNoLevelCollisions,\n  assertDefaultLevelFound,\n  genLevelComparison,\n  assertLevelComparison\n}\n","'use strict'\n\nmodule.exports = { version: '10.3.1' }\n","'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst { EventEmitter } = require('node:events')\nconst {\n  lsCacheSym,\n  levelValSym,\n  setLevelSym,\n  getLevelSym,\n  chindingsSym,\n  mixinSym,\n  asJsonSym,\n  writeSym,\n  mixinMergeStrategySym,\n  timeSym,\n  timeSliceIndexSym,\n  streamSym,\n  serializersSym,\n  formattersSym,\n  errorKeySym,\n  messageKeySym,\n  useOnlyCustomLevelsSym,\n  needsMetadataGsym,\n  redactFmtSym,\n  stringifySym,\n  formatOptsSym,\n  stringifiersSym,\n  msgPrefixSym,\n  hooksSym\n} = require('./symbols')\nconst {\n  getLevel,\n  setLevel,\n  isLevelEnabled,\n  mappings,\n  initialLsCache,\n  genLsCache,\n  assertNoLevelCollisions\n} = require('./levels')\nconst {\n  asChindings,\n  asJson,\n  buildFormatters,\n  stringify,\n  noop\n} = require('./tools')\nconst {\n  version\n} = require('./meta')\nconst redaction = require('./redaction')\n\n// note: use of class is satirical\n// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127\nconst constructor = class Pino {}\nconst prototype = {\n  constructor,\n  child,\n  bindings,\n  setBindings,\n  flush,\n  isLevelEnabled,\n  version,\n  get level () { return this[getLevelSym]() },\n  set level (lvl) { this[setLevelSym](lvl) },\n  get levelVal () { return this[levelValSym] },\n  set levelVal (n) { throw Error('levelVal is read-only') },\n  get msgPrefix () { return this[msgPrefixSym] },\n  get [Symbol.toStringTag] () { return 'Pino' },\n  [lsCacheSym]: initialLsCache,\n  [writeSym]: write,\n  [asJsonSym]: asJson,\n  [getLevelSym]: getLevel,\n  [setLevelSym]: setLevel\n}\n\nObject.setPrototypeOf(prototype, EventEmitter.prototype)\n\n// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing\nmodule.exports = function () {\n  return Object.create(prototype)\n}\n\nconst resetChildingsFormatter = bindings => bindings\nfunction child (bindings, options) {\n  if (!bindings) {\n    throw Error('missing bindings for child Pino')\n  }\n  const serializers = this[serializersSym]\n  const formatters = this[formattersSym]\n  const instance = Object.create(this)\n\n  // If an `options` object was not supplied, we can improve\n  // the performance of child creation by skipping\n  // the checks for set options and simply return\n  // a baseline instance.\n  if (options == null) {\n    if (instance[formattersSym].bindings !== resetChildingsFormatter) {\n      instance[formattersSym] = buildFormatters(\n        formatters.level,\n        resetChildingsFormatter,\n        formatters.log\n      )\n    }\n\n    instance[chindingsSym] = asChindings(instance, bindings)\n\n    if (this.onChild !== noop) {\n      this.onChild(instance)\n    }\n\n    return instance\n  }\n\n  if (options.hasOwnProperty('serializers') === true) {\n    instance[serializersSym] = Object.create(null)\n\n    for (const k in serializers) {\n      instance[serializersSym][k] = serializers[k]\n    }\n    const parentSymbols = Object.getOwnPropertySymbols(serializers)\n    /* eslint no-var: off */\n    for (var i = 0; i < parentSymbols.length; i++) {\n      const ks = parentSymbols[i]\n      instance[serializersSym][ks] = serializers[ks]\n    }\n\n    for (const bk in options.serializers) {\n      instance[serializersSym][bk] = options.serializers[bk]\n    }\n    const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers)\n    for (var bi = 0; bi < bindingsSymbols.length; bi++) {\n      const bks = bindingsSymbols[bi]\n      instance[serializersSym][bks] = options.serializers[bks]\n    }\n  } else instance[serializersSym] = serializers\n  if (options.hasOwnProperty('formatters')) {\n    const { level, bindings: chindings, log } = options.formatters\n    instance[formattersSym] = buildFormatters(\n      level || formatters.level,\n      chindings || resetChildingsFormatter,\n      log || formatters.log\n    )\n  } else {\n    instance[formattersSym] = buildFormatters(\n      formatters.level,\n      resetChildingsFormatter,\n      formatters.log\n    )\n  }\n  if (options.hasOwnProperty('customLevels') === true) {\n    assertNoLevelCollisions(this.levels, options.customLevels)\n    instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym])\n    genLsCache(instance)\n  }\n\n  // redact must place before asChindings and only replace if exist\n  if ((typeof options.redact === 'object' && options.redact !== null) || Array.isArray(options.redact)) {\n    instance.redact = options.redact // replace redact directly\n    const stringifiers = redaction(instance.redact, stringify)\n    const formatOpts = { stringify: stringifiers[redactFmtSym] }\n    instance[stringifySym] = stringify\n    instance[stringifiersSym] = stringifiers\n    instance[formatOptsSym] = formatOpts\n  }\n\n  if (typeof options.msgPrefix === 'string') {\n    instance[msgPrefixSym] = (this[msgPrefixSym] || '') + options.msgPrefix\n  }\n\n  instance[chindingsSym] = asChindings(instance, bindings)\n  if ((options.level !== undefined && options.level !== this.level) || options.hasOwnProperty('customLevels')) {\n    const childLevel = options.level || this.level\n    instance[setLevelSym](childLevel)\n  }\n  this.onChild(instance)\n  return instance\n}\n\nfunction bindings () {\n  const chindings = this[chindingsSym]\n  const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,\"pid\":7068,\"hostname\":\"myMac\"\n  const bindingsFromJson = JSON.parse(chindingsJson)\n  delete bindingsFromJson.pid\n  delete bindingsFromJson.hostname\n  return bindingsFromJson\n}\n\nfunction setBindings (newBindings) {\n  const chindings = asChindings(this, newBindings)\n  this[chindingsSym] = chindings\n}\n\n/**\n * Default strategy for creating `mergeObject` from arguments and the result from `mixin()`.\n * Fields from `mergeObject` have higher priority in this strategy.\n *\n * @param {Object} mergeObject The object a user has supplied to the logging function.\n * @param {Object} mixinObject The result of the `mixin` method.\n * @return {Object}\n */\nfunction defaultMixinMergeStrategy (mergeObject, mixinObject) {\n  return Object.assign(mixinObject, mergeObject)\n}\n\nfunction write (_obj, msg, num) {\n  const t = this[timeSym]()\n  const mixin = this[mixinSym]\n  const errorKey = this[errorKeySym]\n  const messageKey = this[messageKeySym]\n  const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy\n  let obj\n  const streamWriteHook = this[hooksSym].streamWrite\n\n  if (_obj === undefined || _obj === null) {\n    obj = {}\n  } else if (_obj instanceof Error) {\n    obj = { [errorKey]: _obj }\n    if (msg === undefined) {\n      msg = _obj.message\n    }\n  } else {\n    obj = _obj\n    if (msg === undefined && _obj[messageKey] === undefined && _obj[errorKey]) {\n      msg = _obj[errorKey].message\n    }\n  }\n\n  if (mixin) {\n    obj = mixinMergeStrategy(obj, mixin(obj, num, this))\n  }\n\n  const s = this[asJsonSym](obj, msg, num, t)\n\n  const stream = this[streamSym]\n  if (stream[needsMetadataGsym] === true) {\n    stream.lastLevel = num\n    stream.lastObj = obj\n    stream.lastMsg = msg\n    stream.lastTime = t.slice(this[timeSliceIndexSym])\n    stream.lastLogger = this // for child loggers\n  }\n  stream.write(streamWriteHook ? streamWriteHook(s) : s)\n}\n\nfunction flush (cb) {\n  if (cb != null && typeof cb !== 'function') {\n    throw Error('callback must be a function')\n  }\n\n  const stream = this[streamSym]\n\n  if (typeof stream.flush === 'function') {\n    stream.flush(cb || noop)\n  } else if (cb) cb()\n}\n","'use strict'\n\nconst { hasOwnProperty } = Object.prototype\n\nconst stringify = configure()\n\n// @ts-expect-error\nstringify.configure = configure\n// @ts-expect-error\nstringify.stringify = stringify\n\n// @ts-expect-error\nstringify.default = stringify\n\n// @ts-expect-error used for named export\nexports.stringify = stringify\n// @ts-expect-error used for named export\nexports.configure = configure\n\nmodule.exports = stringify\n\n// eslint-disable-next-line no-control-regex\nconst strEscapeSequencesRegExp = /[\\u0000-\\u001f\\u0022\\u005c\\ud800-\\udfff]/\n\n// Escape C0 control characters, double quotes, the backslash and every code\n// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.\nfunction strEscape (str) {\n  // Some magic numbers that worked out fine while benchmarking with v8 8.0\n  if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {\n    return `\"${str}\"`\n  }\n  return JSON.stringify(str)\n}\n\nfunction sort (array, comparator) {\n  // Insertion sort is very efficient for small input sizes, but it has a bad\n  // worst case complexity. Thus, use native array sort for bigger values.\n  if (array.length > 2e2 || comparator) {\n    return array.sort(comparator)\n  }\n  for (let i = 1; i < array.length; i++) {\n    const currentValue = array[i]\n    let position = i\n    while (position !== 0 && array[position - 1] > currentValue) {\n      array[position] = array[position - 1]\n      position--\n    }\n    array[position] = currentValue\n  }\n  return array\n}\n\nconst typedArrayPrototypeGetSymbolToStringTag =\n  Object.getOwnPropertyDescriptor(\n    Object.getPrototypeOf(\n      Object.getPrototypeOf(\n        new Int8Array()\n      )\n    ),\n    Symbol.toStringTag\n  ).get\n\nfunction isTypedArrayWithEntries (value) {\n  return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0\n}\n\nfunction stringifyTypedArray (array, separator, maximumBreadth) {\n  if (array.length < maximumBreadth) {\n    maximumBreadth = array.length\n  }\n  const whitespace = separator === ',' ? '' : ' '\n  let res = `\"0\":${whitespace}${array[0]}`\n  for (let i = 1; i < maximumBreadth; i++) {\n    res += `${separator}\"${i}\":${whitespace}${array[i]}`\n  }\n  return res\n}\n\nfunction getCircularValueOption (options) {\n  if (hasOwnProperty.call(options, 'circularValue')) {\n    const circularValue = options.circularValue\n    if (typeof circularValue === 'string') {\n      return `\"${circularValue}\"`\n    }\n    if (circularValue == null) {\n      return circularValue\n    }\n    if (circularValue === Error || circularValue === TypeError) {\n      return {\n        toString () {\n          throw new TypeError('Converting circular structure to JSON')\n        }\n      }\n    }\n    throw new TypeError('The \"circularValue\" argument must be of type string or the value null or undefined')\n  }\n  return '\"[Circular]\"'\n}\n\nfunction getDeterministicOption (options) {\n  let value\n  if (hasOwnProperty.call(options, 'deterministic')) {\n    value = options.deterministic\n    if (typeof value !== 'boolean' && typeof value !== 'function') {\n      throw new TypeError('The \"deterministic\" argument must be of type boolean or comparator function')\n    }\n  }\n  return value === undefined ? true : value\n}\n\nfunction getBooleanOption (options, key) {\n  let value\n  if (hasOwnProperty.call(options, key)) {\n    value = options[key]\n    if (typeof value !== 'boolean') {\n      throw new TypeError(`The \"${key}\" argument must be of type boolean`)\n    }\n  }\n  return value === undefined ? true : value\n}\n\nfunction getPositiveIntegerOption (options, key) {\n  let value\n  if (hasOwnProperty.call(options, key)) {\n    value = options[key]\n    if (typeof value !== 'number') {\n      throw new TypeError(`The \"${key}\" argument must be of type number`)\n    }\n    if (!Number.isInteger(value)) {\n      throw new TypeError(`The \"${key}\" argument must be an integer`)\n    }\n    if (value < 1) {\n      throw new RangeError(`The \"${key}\" argument must be >= 1`)\n    }\n  }\n  return value === undefined ? Infinity : value\n}\n\nfunction getItemCount (number) {\n  if (number === 1) {\n    return '1 item'\n  }\n  return `${number} items`\n}\n\nfunction getUniqueReplacerSet (replacerArray) {\n  const replacerSet = new Set()\n  for (const value of replacerArray) {\n    if (typeof value === 'string' || typeof value === 'number') {\n      replacerSet.add(String(value))\n    }\n  }\n  return replacerSet\n}\n\nfunction getStrictOption (options) {\n  if (hasOwnProperty.call(options, 'strict')) {\n    const value = options.strict\n    if (typeof value !== 'boolean') {\n      throw new TypeError('The \"strict\" argument must be of type boolean')\n    }\n    if (value) {\n      return (value) => {\n        let message = `Object can not safely be stringified. Received type ${typeof value}`\n        if (typeof value !== 'function') message += ` (${value.toString()})`\n        throw new Error(message)\n      }\n    }\n  }\n}\n\nfunction configure (options) {\n  options = { ...options }\n  const fail = getStrictOption(options)\n  if (fail) {\n    if (options.bigint === undefined) {\n      options.bigint = false\n    }\n    if (!('circularValue' in options)) {\n      options.circularValue = Error\n    }\n  }\n  const circularValue = getCircularValueOption(options)\n  const bigint = getBooleanOption(options, 'bigint')\n  const deterministic = getDeterministicOption(options)\n  const comparator = typeof deterministic === 'function' ? deterministic : undefined\n  const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth')\n  const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth')\n\n  function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {\n    let value = parent[key]\n\n    if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n      value = value.toJSON(key)\n    }\n    value = replacer.call(parent, key, value)\n\n    switch (typeof value) {\n      case 'string':\n        return strEscape(value)\n      case 'object': {\n        if (value === null) {\n          return 'null'\n        }\n        if (stack.indexOf(value) !== -1) {\n          return circularValue\n        }\n\n        let res = ''\n        let join = ','\n        const originalIndentation = indentation\n\n        if (Array.isArray(value)) {\n          if (value.length === 0) {\n            return '[]'\n          }\n          if (maximumDepth < stack.length + 1) {\n            return '\"[Array]\"'\n          }\n          stack.push(value)\n          if (spacer !== '') {\n            indentation += spacer\n            res += `\\n${indentation}`\n            join = `,\\n${indentation}`\n          }\n          const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n          let i = 0\n          for (; i < maximumValuesToStringify - 1; i++) {\n            const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n            res += tmp !== undefined ? tmp : 'null'\n            res += join\n          }\n          const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n          res += tmp !== undefined ? tmp : 'null'\n          if (value.length - 1 > maximumBreadth) {\n            const removedKeys = value.length - maximumBreadth - 1\n            res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n          }\n          if (spacer !== '') {\n            res += `\\n${originalIndentation}`\n          }\n          stack.pop()\n          return `[${res}]`\n        }\n\n        let keys = Object.keys(value)\n        const keyLength = keys.length\n        if (keyLength === 0) {\n          return '{}'\n        }\n        if (maximumDepth < stack.length + 1) {\n          return '\"[Object]\"'\n        }\n        let whitespace = ''\n        let separator = ''\n        if (spacer !== '') {\n          indentation += spacer\n          join = `,\\n${indentation}`\n          whitespace = ' '\n        }\n        const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n        if (deterministic && !isTypedArrayWithEntries(value)) {\n          keys = sort(keys, comparator)\n        }\n        stack.push(value)\n        for (let i = 0; i < maximumPropertiesToStringify; i++) {\n          const key = keys[i]\n          const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation)\n          if (tmp !== undefined) {\n            res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n            separator = join\n          }\n        }\n        if (keyLength > maximumBreadth) {\n          const removedKeys = keyLength - maximumBreadth\n          res += `${separator}\"...\":${whitespace}\"${getItemCount(removedKeys)} not stringified\"`\n          separator = join\n        }\n        if (spacer !== '' && separator.length > 1) {\n          res = `\\n${indentation}${res}\\n${originalIndentation}`\n        }\n        stack.pop()\n        return `{${res}}`\n      }\n      case 'number':\n        return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n      case 'boolean':\n        return value === true ? 'true' : 'false'\n      case 'undefined':\n        return undefined\n      case 'bigint':\n        if (bigint) {\n          return String(value)\n        }\n        // fallthrough\n      default:\n        return fail ? fail(value) : undefined\n    }\n  }\n\n  function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {\n    if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n      value = value.toJSON(key)\n    }\n\n    switch (typeof value) {\n      case 'string':\n        return strEscape(value)\n      case 'object': {\n        if (value === null) {\n          return 'null'\n        }\n        if (stack.indexOf(value) !== -1) {\n          return circularValue\n        }\n\n        const originalIndentation = indentation\n        let res = ''\n        let join = ','\n\n        if (Array.isArray(value)) {\n          if (value.length === 0) {\n            return '[]'\n          }\n          if (maximumDepth < stack.length + 1) {\n            return '\"[Array]\"'\n          }\n          stack.push(value)\n          if (spacer !== '') {\n            indentation += spacer\n            res += `\\n${indentation}`\n            join = `,\\n${indentation}`\n          }\n          const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n          let i = 0\n          for (; i < maximumValuesToStringify - 1; i++) {\n            const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n            res += tmp !== undefined ? tmp : 'null'\n            res += join\n          }\n          const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n          res += tmp !== undefined ? tmp : 'null'\n          if (value.length - 1 > maximumBreadth) {\n            const removedKeys = value.length - maximumBreadth - 1\n            res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n          }\n          if (spacer !== '') {\n            res += `\\n${originalIndentation}`\n          }\n          stack.pop()\n          return `[${res}]`\n        }\n        stack.push(value)\n        let whitespace = ''\n        if (spacer !== '') {\n          indentation += spacer\n          join = `,\\n${indentation}`\n          whitespace = ' '\n        }\n        let separator = ''\n        for (const key of replacer) {\n          const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation)\n          if (tmp !== undefined) {\n            res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n            separator = join\n          }\n        }\n        if (spacer !== '' && separator.length > 1) {\n          res = `\\n${indentation}${res}\\n${originalIndentation}`\n        }\n        stack.pop()\n        return `{${res}}`\n      }\n      case 'number':\n        return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n      case 'boolean':\n        return value === true ? 'true' : 'false'\n      case 'undefined':\n        return undefined\n      case 'bigint':\n        if (bigint) {\n          return String(value)\n        }\n        // fallthrough\n      default:\n        return fail ? fail(value) : undefined\n    }\n  }\n\n  function stringifyIndent (key, value, stack, spacer, indentation) {\n    switch (typeof value) {\n      case 'string':\n        return strEscape(value)\n      case 'object': {\n        if (value === null) {\n          return 'null'\n        }\n        if (typeof value.toJSON === 'function') {\n          value = value.toJSON(key)\n          // Prevent calling `toJSON` again.\n          if (typeof value !== 'object') {\n            return stringifyIndent(key, value, stack, spacer, indentation)\n          }\n          if (value === null) {\n            return 'null'\n          }\n        }\n        if (stack.indexOf(value) !== -1) {\n          return circularValue\n        }\n        const originalIndentation = indentation\n\n        if (Array.isArray(value)) {\n          if (value.length === 0) {\n            return '[]'\n          }\n          if (maximumDepth < stack.length + 1) {\n            return '\"[Array]\"'\n          }\n          stack.push(value)\n          indentation += spacer\n          let res = `\\n${indentation}`\n          const join = `,\\n${indentation}`\n          const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n          let i = 0\n          for (; i < maximumValuesToStringify - 1; i++) {\n            const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n            res += tmp !== undefined ? tmp : 'null'\n            res += join\n          }\n          const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n          res += tmp !== undefined ? tmp : 'null'\n          if (value.length - 1 > maximumBreadth) {\n            const removedKeys = value.length - maximumBreadth - 1\n            res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n          }\n          res += `\\n${originalIndentation}`\n          stack.pop()\n          return `[${res}]`\n        }\n\n        let keys = Object.keys(value)\n        const keyLength = keys.length\n        if (keyLength === 0) {\n          return '{}'\n        }\n        if (maximumDepth < stack.length + 1) {\n          return '\"[Object]\"'\n        }\n        indentation += spacer\n        const join = `,\\n${indentation}`\n        let res = ''\n        let separator = ''\n        let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n        if (isTypedArrayWithEntries(value)) {\n          res += stringifyTypedArray(value, join, maximumBreadth)\n          keys = keys.slice(value.length)\n          maximumPropertiesToStringify -= value.length\n          separator = join\n        }\n        if (deterministic) {\n          keys = sort(keys, comparator)\n        }\n        stack.push(value)\n        for (let i = 0; i < maximumPropertiesToStringify; i++) {\n          const key = keys[i]\n          const tmp = stringifyIndent(key, value[key], stack, spacer, indentation)\n          if (tmp !== undefined) {\n            res += `${separator}${strEscape(key)}: ${tmp}`\n            separator = join\n          }\n        }\n        if (keyLength > maximumBreadth) {\n          const removedKeys = keyLength - maximumBreadth\n          res += `${separator}\"...\": \"${getItemCount(removedKeys)} not stringified\"`\n          separator = join\n        }\n        if (separator !== '') {\n          res = `\\n${indentation}${res}\\n${originalIndentation}`\n        }\n        stack.pop()\n        return `{${res}}`\n      }\n      case 'number':\n        return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n      case 'boolean':\n        return value === true ? 'true' : 'false'\n      case 'undefined':\n        return undefined\n      case 'bigint':\n        if (bigint) {\n          return String(value)\n        }\n        // fallthrough\n      default:\n        return fail ? fail(value) : undefined\n    }\n  }\n\n  function stringifySimple (key, value, stack) {\n    switch (typeof value) {\n      case 'string':\n        return strEscape(value)\n      case 'object': {\n        if (value === null) {\n          return 'null'\n        }\n        if (typeof value.toJSON === 'function') {\n          value = value.toJSON(key)\n          // Prevent calling `toJSON` again\n          if (typeof value !== 'object') {\n            return stringifySimple(key, value, stack)\n          }\n          if (value === null) {\n            return 'null'\n          }\n        }\n        if (stack.indexOf(value) !== -1) {\n          return circularValue\n        }\n\n        let res = ''\n\n        const hasLength = value.length !== undefined\n        if (hasLength && Array.isArray(value)) {\n          if (value.length === 0) {\n            return '[]'\n          }\n          if (maximumDepth < stack.length + 1) {\n            return '\"[Array]\"'\n          }\n          stack.push(value)\n          const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n          let i = 0\n          for (; i < maximumValuesToStringify - 1; i++) {\n            const tmp = stringifySimple(String(i), value[i], stack)\n            res += tmp !== undefined ? tmp : 'null'\n            res += ','\n          }\n          const tmp = stringifySimple(String(i), value[i], stack)\n          res += tmp !== undefined ? tmp : 'null'\n          if (value.length - 1 > maximumBreadth) {\n            const removedKeys = value.length - maximumBreadth - 1\n            res += `,\"... ${getItemCount(removedKeys)} not stringified\"`\n          }\n          stack.pop()\n          return `[${res}]`\n        }\n\n        let keys = Object.keys(value)\n        const keyLength = keys.length\n        if (keyLength === 0) {\n          return '{}'\n        }\n        if (maximumDepth < stack.length + 1) {\n          return '\"[Object]\"'\n        }\n        let separator = ''\n        let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n        if (hasLength && isTypedArrayWithEntries(value)) {\n          res += stringifyTypedArray(value, ',', maximumBreadth)\n          keys = keys.slice(value.length)\n          maximumPropertiesToStringify -= value.length\n          separator = ','\n        }\n        if (deterministic) {\n          keys = sort(keys, comparator)\n        }\n        stack.push(value)\n        for (let i = 0; i < maximumPropertiesToStringify; i++) {\n          const key = keys[i]\n          const tmp = stringifySimple(key, value[key], stack)\n          if (tmp !== undefined) {\n            res += `${separator}${strEscape(key)}:${tmp}`\n            separator = ','\n          }\n        }\n        if (keyLength > maximumBreadth) {\n          const removedKeys = keyLength - maximumBreadth\n          res += `${separator}\"...\":\"${getItemCount(removedKeys)} not stringified\"`\n        }\n        stack.pop()\n        return `{${res}}`\n      }\n      case 'number':\n        return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n      case 'boolean':\n        return value === true ? 'true' : 'false'\n      case 'undefined':\n        return undefined\n      case 'bigint':\n        if (bigint) {\n          return String(value)\n        }\n        // fallthrough\n      default:\n        return fail ? fail(value) : undefined\n    }\n  }\n\n  function stringify (value, replacer, space) {\n    if (arguments.length > 1) {\n      let spacer = ''\n      if (typeof space === 'number') {\n        spacer = ' '.repeat(Math.min(space, 10))\n      } else if (typeof space === 'string') {\n        spacer = space.slice(0, 10)\n      }\n      if (replacer != null) {\n        if (typeof replacer === 'function') {\n          return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')\n        }\n        if (Array.isArray(replacer)) {\n          return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')\n        }\n      }\n      if (spacer.length !== 0) {\n        return stringifyIndent('', value, [], spacer, '')\n      }\n    }\n    return stringifySimple('', value, [])\n  }\n\n  return stringify\n}\n","'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst { DEFAULT_LEVELS } = require('./constants')\n\nconst DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info\n\nfunction multistream (streamsArray, opts) {\n  streamsArray = streamsArray || []\n  opts = opts || { dedupe: false }\n\n  const streamLevels = Object.create(DEFAULT_LEVELS)\n  streamLevels.silent = Infinity\n  if (opts.levels && typeof opts.levels === 'object') {\n    Object.keys(opts.levels).forEach(i => {\n      streamLevels[i] = opts.levels[i]\n    })\n  }\n\n  const res = {\n    write,\n    add,\n    remove,\n    emit,\n    flushSync,\n    end,\n    minLevel: 0,\n    lastId: 0,\n    streams: [],\n    clone,\n    [metadata]: true,\n    streamLevels\n  }\n\n  if (Array.isArray(streamsArray)) {\n    streamsArray.forEach(add, res)\n  } else {\n    add.call(res, streamsArray)\n  }\n\n  // clean this object up\n  // or it will stay allocated forever\n  // as it is closed on the following closures\n  streamsArray = null\n\n  return res\n\n  // we can exit early because the streams are ordered by level\n  function write (data) {\n    let dest\n    const level = this.lastLevel\n    const { streams } = this\n    // for handling situation when several streams has the same level\n    let recordedLevel = 0\n    let stream\n\n    // if dedupe set to true we send logs to the stream with the highest level\n    // therefore, we have to change sorting order\n    for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {\n      dest = streams[i]\n      if (dest.level <= level) {\n        if (recordedLevel !== 0 && recordedLevel !== dest.level) {\n          break\n        }\n        stream = dest.stream\n        if (stream[metadata]) {\n          const { lastTime, lastMsg, lastObj, lastLogger } = this\n          stream.lastLevel = level\n          stream.lastTime = lastTime\n          stream.lastMsg = lastMsg\n          stream.lastObj = lastObj\n          stream.lastLogger = lastLogger\n        }\n        stream.write(data)\n        if (opts.dedupe) {\n          recordedLevel = dest.level\n        }\n      } else if (!opts.dedupe) {\n        break\n      }\n    }\n  }\n\n  function emit (...args) {\n    for (const { stream } of this.streams) {\n      if (typeof stream.emit === 'function') {\n        stream.emit(...args)\n      }\n    }\n  }\n\n  function flushSync () {\n    for (const { stream } of this.streams) {\n      if (typeof stream.flushSync === 'function') {\n        stream.flushSync()\n      }\n    }\n  }\n\n  function add (dest) {\n    if (!dest) {\n      return res\n    }\n\n    // Check that dest implements either StreamEntry or DestinationStream\n    const isStream = typeof dest.write === 'function' || dest.stream\n    const stream_ = dest.write ? dest : dest.stream\n    // This is necessary to provide a meaningful error message, otherwise it throws somewhere inside write()\n    if (!isStream) {\n      throw Error('stream object needs to implement either StreamEntry or DestinationStream interface')\n    }\n\n    const { streams, streamLevels } = this\n\n    let level\n    if (typeof dest.levelVal === 'number') {\n      level = dest.levelVal\n    } else if (typeof dest.level === 'string') {\n      level = streamLevels[dest.level]\n    } else if (typeof dest.level === 'number') {\n      level = dest.level\n    } else {\n      level = DEFAULT_INFO_LEVEL\n    }\n\n    const dest_ = {\n      stream: stream_,\n      level,\n      levelVal: undefined,\n      id: ++res.lastId\n    }\n\n    streams.unshift(dest_)\n    streams.sort(compareByLevel)\n\n    this.minLevel = streams[0].level\n\n    return res\n  }\n\n  function remove (id) {\n    const { streams } = this\n    const index = streams.findIndex(s => s.id === id)\n\n    if (index >= 0) {\n      streams.splice(index, 1)\n      streams.sort(compareByLevel)\n      this.minLevel = streams.length > 0 ? streams[0].level : -1\n    }\n\n    return res\n  }\n\n  function end () {\n    for (const { stream } of this.streams) {\n      if (typeof stream.flushSync === 'function') {\n        stream.flushSync()\n      }\n      stream.end()\n    }\n  }\n\n  function clone (level) {\n    const streams = new Array(this.streams.length)\n\n    for (let i = 0; i < streams.length; i++) {\n      streams[i] = {\n        level,\n        stream: this.streams[i].stream\n      }\n    }\n\n    return {\n      write,\n      add,\n      remove,\n      minLevel: level,\n      streams,\n      clone,\n      emit,\n      flushSync,\n      [metadata]: true\n    }\n  }\n}\n\nfunction compareByLevel (a, b) {\n  return a.level - b.level\n}\n\nfunction initLoopVar (length, dedupe) {\n  return dedupe ? length - 1 : 0\n}\n\nfunction adjustLoopVar (i, dedupe) {\n  return dedupe ? i - 1 : i + 1\n}\n\nfunction checkLoopVar (i, length, dedupe) {\n  return dedupe ? i >= 0 : i < length\n}\n\nmodule.exports = multistream\n","'use strict'\n\nconst os = require('node:os')\nconst stdSerializers = require('pino-std-serializers')\nconst caller = require('./lib/caller')\nconst redaction = require('./lib/redaction')\nconst time = require('./lib/time')\nconst proto = require('./lib/proto')\nconst symbols = require('./lib/symbols')\nconst { configure } = require('safe-stable-stringify')\nconst { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require('./lib/levels')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./lib/constants')\nconst {\n  createArgsNormalizer,\n  asChindings,\n  buildSafeSonicBoom,\n  buildFormatters,\n  stringify,\n  normalizeDestFileDescriptor,\n  noop\n} = require('./lib/tools')\nconst { version } = require('./lib/meta')\nconst {\n  chindingsSym,\n  redactFmtSym,\n  serializersSym,\n  timeSym,\n  timeSliceIndexSym,\n  streamSym,\n  stringifySym,\n  stringifySafeSym,\n  stringifiersSym,\n  setLevelSym,\n  endSym,\n  formatOptsSym,\n  messageKeySym,\n  errorKeySym,\n  nestedKeySym,\n  mixinSym,\n  levelCompSym,\n  useOnlyCustomLevelsSym,\n  formattersSym,\n  hooksSym,\n  nestedKeyStrSym,\n  mixinMergeStrategySym,\n  msgPrefixSym\n} = symbols\nconst { epochTime, nullTime } = time\nconst { pid } = process\nconst hostname = os.hostname()\nconst defaultErrorSerializer = stdSerializers.err\nconst defaultOptions = {\n  level: 'info',\n  levelComparison: SORTING_ORDER.ASC,\n  levels: DEFAULT_LEVELS,\n  messageKey: 'msg',\n  errorKey: 'err',\n  nestedKey: null,\n  enabled: true,\n  base: { pid, hostname },\n  serializers: Object.assign(Object.create(null), {\n    err: defaultErrorSerializer\n  }),\n  formatters: Object.assign(Object.create(null), {\n    bindings (bindings) {\n      return bindings\n    },\n    level (label, number) {\n      return { level: number }\n    }\n  }),\n  hooks: {\n    logMethod: undefined,\n    streamWrite: undefined\n  },\n  timestamp: epochTime,\n  name: undefined,\n  redact: null,\n  customLevels: null,\n  useOnlyCustomLevels: false,\n  depthLimit: 5,\n  edgeLimit: 100\n}\n\nconst normalize = createArgsNormalizer(defaultOptions)\n\nconst serializers = Object.assign(Object.create(null), stdSerializers)\n\nfunction pino (...args) {\n  const instance = {}\n  const { opts, stream } = normalize(instance, caller(), ...args)\n\n  if (opts.level && typeof opts.level === 'string' && DEFAULT_LEVELS[opts.level.toLowerCase()] !== undefined) opts.level = opts.level.toLowerCase()\n\n  const {\n    redact,\n    crlf,\n    serializers,\n    timestamp,\n    messageKey,\n    errorKey,\n    nestedKey,\n    base,\n    name,\n    level,\n    customLevels,\n    levelComparison,\n    mixin,\n    mixinMergeStrategy,\n    useOnlyCustomLevels,\n    formatters,\n    hooks,\n    depthLimit,\n    edgeLimit,\n    onChild,\n    msgPrefix\n  } = opts\n\n  const stringifySafe = configure({\n    maximumDepth: depthLimit,\n    maximumBreadth: edgeLimit\n  })\n\n  const allFormatters = buildFormatters(\n    formatters.level,\n    formatters.bindings,\n    formatters.log\n  )\n\n  const stringifyFn = stringify.bind({\n    [stringifySafeSym]: stringifySafe\n  })\n  const stringifiers = redact ? redaction(redact, stringifyFn) : {}\n  const formatOpts = redact\n    ? { stringify: stringifiers[redactFmtSym] }\n    : { stringify: stringifyFn }\n  const end = '}' + (crlf ? '\\r\\n' : '\\n')\n  const coreChindings = asChindings.bind(null, {\n    [chindingsSym]: '',\n    [serializersSym]: serializers,\n    [stringifiersSym]: stringifiers,\n    [stringifySym]: stringify,\n    [stringifySafeSym]: stringifySafe,\n    [formattersSym]: allFormatters\n  })\n\n  let chindings = ''\n  if (base !== null) {\n    if (name === undefined) {\n      chindings = coreChindings(base)\n    } else {\n      chindings = coreChindings(Object.assign({}, base, { name }))\n    }\n  }\n\n  const time = (timestamp instanceof Function)\n    ? timestamp\n    : (timestamp ? epochTime : nullTime)\n  const timeSliceIndex = time().indexOf(':') + 1\n\n  if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')\n  if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type \"${typeof mixin}\" - expected \"function\"`)\n  if (msgPrefix && typeof msgPrefix !== 'string') throw Error(`Unknown msgPrefix type \"${typeof msgPrefix}\" - expected \"string\"`)\n\n  assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)\n  const levels = mappings(customLevels, useOnlyCustomLevels)\n\n  if (typeof stream.emit === 'function') {\n    stream.emit('message', { code: 'PINO_CONFIG', config: { levels, messageKey, errorKey } })\n  }\n\n  assertLevelComparison(levelComparison)\n  const levelCompFunc = genLevelComparison(levelComparison)\n\n  Object.assign(instance, {\n    levels,\n    [levelCompSym]: levelCompFunc,\n    [useOnlyCustomLevelsSym]: useOnlyCustomLevels,\n    [streamSym]: stream,\n    [timeSym]: time,\n    [timeSliceIndexSym]: timeSliceIndex,\n    [stringifySym]: stringify,\n    [stringifySafeSym]: stringifySafe,\n    [stringifiersSym]: stringifiers,\n    [endSym]: end,\n    [formatOptsSym]: formatOpts,\n    [messageKeySym]: messageKey,\n    [errorKeySym]: errorKey,\n    [nestedKeySym]: nestedKey,\n    // protect against injection\n    [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : '',\n    [serializersSym]: serializers,\n    [mixinSym]: mixin,\n    [mixinMergeStrategySym]: mixinMergeStrategy,\n    [chindingsSym]: chindings,\n    [formattersSym]: allFormatters,\n    [hooksSym]: hooks,\n    silent: noop,\n    onChild,\n    [msgPrefixSym]: msgPrefix\n  })\n\n  Object.setPrototypeOf(instance, proto())\n\n  genLsCache(instance)\n\n  instance[setLevelSym](level)\n\n  return instance\n}\n\nmodule.exports = pino\n\nmodule.exports.destination = (dest = process.stdout.fd) => {\n  if (typeof dest === 'object') {\n    dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd)\n    return buildSafeSonicBoom(dest)\n  } else {\n    return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 })\n  }\n}\n\nmodule.exports.transport = require('./lib/transport')\nmodule.exports.multistream = require('./lib/multistream')\n\nmodule.exports.levels = mappings()\nmodule.exports.stdSerializers = serializers\nmodule.exports.stdTimeFunctions = Object.assign({}, time)\nmodule.exports.symbols = symbols\nmodule.exports.version = version\n\n// Enables default and name export with TypeScript and Babel\nmodule.exports.default = pino\nmodule.exports.pino = pino\n","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n  BINARY_TYPES,\n  CLOSE_TIMEOUT: 30000,\n  EMPTY_BUFFER: Buffer.alloc(0),\n  GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n  hasBlob,\n  kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n  kListener: Symbol('kListener'),\n  kStatusCode: Symbol('status-code'),\n  kWebSocket: Symbol('websocket'),\n  NOOP: () => {}\n};\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n  if (list.length === 0) return EMPTY_BUFFER;\n  if (list.length === 1) return list[0];\n\n  const target = Buffer.allocUnsafe(totalLength);\n  let offset = 0;\n\n  for (let i = 0; i < list.length; i++) {\n    const buf = list[i];\n    target.set(buf, offset);\n    offset += buf.length;\n  }\n\n  if (offset < totalLength) {\n    return new FastBuffer(target.buffer, target.byteOffset, offset);\n  }\n\n  return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n  for (let i = 0; i < length; i++) {\n    output[offset + i] = source[i] ^ mask[i & 3];\n  }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n  for (let i = 0; i < buffer.length; i++) {\n    buffer[i] ^= mask[i & 3];\n  }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n  if (buf.length === buf.buffer.byteLength) {\n    return buf.buffer;\n  }\n\n  return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n  toBuffer.readOnly = true;\n\n  if (Buffer.isBuffer(data)) return data;\n\n  let buf;\n\n  if (data instanceof ArrayBuffer) {\n    buf = new FastBuffer(data);\n  } else if (ArrayBuffer.isView(data)) {\n    buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n  } else {\n    buf = Buffer.from(data);\n    toBuffer.readOnly = false;\n  }\n\n  return buf;\n}\n\nmodule.exports = {\n  concat,\n  mask: _mask,\n  toArrayBuffer,\n  toBuffer,\n  unmask: _unmask\n};\n\n/* istanbul ignore else  */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n  try {\n    const bufferUtil = require('bufferutil');\n\n    module.exports.mask = function (source, mask, output, offset, length) {\n      if (length < 48) _mask(source, mask, output, offset, length);\n      else bufferUtil.mask(source, mask, output, offset, length);\n    };\n\n    module.exports.unmask = function (buffer, mask) {\n      if (buffer.length < 32) _unmask(buffer, mask);\n      else bufferUtil.unmask(buffer, mask);\n    };\n  } catch (e) {\n    // Continue regardless of the error.\n  }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n  /**\n   * Creates a new `Limiter`.\n   *\n   * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n   *     to run concurrently\n   */\n  constructor(concurrency) {\n    this[kDone] = () => {\n      this.pending--;\n      this[kRun]();\n    };\n    this.concurrency = concurrency || Infinity;\n    this.jobs = [];\n    this.pending = 0;\n  }\n\n  /**\n   * Adds a job to the queue.\n   *\n   * @param {Function} job The job to run\n   * @public\n   */\n  add(job) {\n    this.jobs.push(job);\n    this[kRun]();\n  }\n\n  /**\n   * Removes a job from the queue and runs it if possible.\n   *\n   * @private\n   */\n  [kRun]() {\n    if (this.pending === this.concurrency) return;\n\n    if (this.jobs.length) {\n      const job = this.jobs.shift();\n\n      this.pending++;\n      job(this[kDone]);\n    }\n  }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n  /**\n   * Creates a PerMessageDeflate instance.\n   *\n   * @param {Object} [options] Configuration options\n   * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n   *     for, or request, a custom client window size\n   * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n   *     acknowledge disabling of client context takeover\n   * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n   *     calls to zlib\n   * @param {Boolean} [options.isServer=false] Create the instance in either\n   *     server or client mode\n   * @param {Number} [options.maxPayload=0] The maximum allowed message length\n   * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n   *     use of a custom server window size\n   * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n   *     disabling of server context takeover\n   * @param {Number} [options.threshold=1024] Size (in bytes) below which\n   *     messages should not be compressed if context takeover is disabled\n   * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n   *     deflate\n   * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n   *     inflate\n   */\n  constructor(options) {\n    this._options = options || {};\n    this._threshold =\n      this._options.threshold !== undefined ? this._options.threshold : 1024;\n    this._maxPayload = this._options.maxPayload | 0;\n    this._isServer = !!this._options.isServer;\n    this._deflate = null;\n    this._inflate = null;\n\n    this.params = null;\n\n    if (!zlibLimiter) {\n      const concurrency =\n        this._options.concurrencyLimit !== undefined\n          ? this._options.concurrencyLimit\n          : 10;\n      zlibLimiter = new Limiter(concurrency);\n    }\n  }\n\n  /**\n   * @type {String}\n   */\n  static get extensionName() {\n    return 'permessage-deflate';\n  }\n\n  /**\n   * Create an extension negotiation offer.\n   *\n   * @return {Object} Extension parameters\n   * @public\n   */\n  offer() {\n    const params = {};\n\n    if (this._options.serverNoContextTakeover) {\n      params.server_no_context_takeover = true;\n    }\n    if (this._options.clientNoContextTakeover) {\n      params.client_no_context_takeover = true;\n    }\n    if (this._options.serverMaxWindowBits) {\n      params.server_max_window_bits = this._options.serverMaxWindowBits;\n    }\n    if (this._options.clientMaxWindowBits) {\n      params.client_max_window_bits = this._options.clientMaxWindowBits;\n    } else if (this._options.clientMaxWindowBits == null) {\n      params.client_max_window_bits = true;\n    }\n\n    return params;\n  }\n\n  /**\n   * Accept an extension negotiation offer/response.\n   *\n   * @param {Array} configurations The extension negotiation offers/reponse\n   * @return {Object} Accepted configuration\n   * @public\n   */\n  accept(configurations) {\n    configurations = this.normalizeParams(configurations);\n\n    this.params = this._isServer\n      ? this.acceptAsServer(configurations)\n      : this.acceptAsClient(configurations);\n\n    return this.params;\n  }\n\n  /**\n   * Releases all resources used by the extension.\n   *\n   * @public\n   */\n  cleanup() {\n    if (this._inflate) {\n      this._inflate.close();\n      this._inflate = null;\n    }\n\n    if (this._deflate) {\n      const callback = this._deflate[kCallback];\n\n      this._deflate.close();\n      this._deflate = null;\n\n      if (callback) {\n        callback(\n          new Error(\n            'The deflate stream was closed while data was being processed'\n          )\n        );\n      }\n    }\n  }\n\n  /**\n   *  Accept an extension negotiation offer.\n   *\n   * @param {Array} offers The extension negotiation offers\n   * @return {Object} Accepted configuration\n   * @private\n   */\n  acceptAsServer(offers) {\n    const opts = this._options;\n    const accepted = offers.find((params) => {\n      if (\n        (opts.serverNoContextTakeover === false &&\n          params.server_no_context_takeover) ||\n        (params.server_max_window_bits &&\n          (opts.serverMaxWindowBits === false ||\n            (typeof opts.serverMaxWindowBits === 'number' &&\n              opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n        (typeof opts.clientMaxWindowBits === 'number' &&\n          (typeof params.client_max_window_bits === 'number'\n            ? opts.clientMaxWindowBits > params.client_max_window_bits\n            : !params.client_max_window_bits))\n      ) {\n        return false;\n      }\n\n      return true;\n    });\n\n    if (!accepted) {\n      throw new Error('None of the extension offers can be accepted');\n    }\n\n    if (opts.serverNoContextTakeover) {\n      accepted.server_no_context_takeover = true;\n    }\n    if (opts.clientNoContextTakeover) {\n      accepted.client_no_context_takeover = true;\n    }\n    if (typeof opts.serverMaxWindowBits === 'number') {\n      accepted.server_max_window_bits = opts.serverMaxWindowBits;\n    }\n    if (typeof opts.clientMaxWindowBits === 'number') {\n      accepted.client_max_window_bits = opts.clientMaxWindowBits;\n    } else if (\n      accepted.client_max_window_bits === true ||\n      opts.clientMaxWindowBits === false\n    ) {\n      delete accepted.client_max_window_bits;\n    }\n\n    return accepted;\n  }\n\n  /**\n   * Accept the extension negotiation response.\n   *\n   * @param {Array} response The extension negotiation response\n   * @return {Object} Accepted configuration\n   * @private\n   */\n  acceptAsClient(response) {\n    const params = response[0];\n\n    if (\n      this._options.clientNoContextTakeover === false &&\n      params.client_no_context_takeover\n    ) {\n      throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n    }\n\n    if (!params.client_max_window_bits) {\n      if (typeof this._options.clientMaxWindowBits === 'number') {\n        params.client_max_window_bits = this._options.clientMaxWindowBits;\n      }\n    } else if (\n      this._options.clientMaxWindowBits === false ||\n      (typeof this._options.clientMaxWindowBits === 'number' &&\n        params.client_max_window_bits > this._options.clientMaxWindowBits)\n    ) {\n      throw new Error(\n        'Unexpected or invalid parameter \"client_max_window_bits\"'\n      );\n    }\n\n    return params;\n  }\n\n  /**\n   * Normalize parameters.\n   *\n   * @param {Array} configurations The extension negotiation offers/reponse\n   * @return {Array} The offers/response with normalized parameters\n   * @private\n   */\n  normalizeParams(configurations) {\n    configurations.forEach((params) => {\n      Object.keys(params).forEach((key) => {\n        let value = params[key];\n\n        if (value.length > 1) {\n          throw new Error(`Parameter \"${key}\" must have only a single value`);\n        }\n\n        value = value[0];\n\n        if (key === 'client_max_window_bits') {\n          if (value !== true) {\n            const num = +value;\n            if (!Number.isInteger(num) || num < 8 || num > 15) {\n              throw new TypeError(\n                `Invalid value for parameter \"${key}\": ${value}`\n              );\n            }\n            value = num;\n          } else if (!this._isServer) {\n            throw new TypeError(\n              `Invalid value for parameter \"${key}\": ${value}`\n            );\n          }\n        } else if (key === 'server_max_window_bits') {\n          const num = +value;\n          if (!Number.isInteger(num) || num < 8 || num > 15) {\n            throw new TypeError(\n              `Invalid value for parameter \"${key}\": ${value}`\n            );\n          }\n          value = num;\n        } else if (\n          key === 'client_no_context_takeover' ||\n          key === 'server_no_context_takeover'\n        ) {\n          if (value !== true) {\n            throw new TypeError(\n              `Invalid value for parameter \"${key}\": ${value}`\n            );\n          }\n        } else {\n          throw new Error(`Unknown parameter \"${key}\"`);\n        }\n\n        params[key] = value;\n      });\n    });\n\n    return configurations;\n  }\n\n  /**\n   * Decompress data. Concurrency limited.\n   *\n   * @param {Buffer} data Compressed data\n   * @param {Boolean} fin Specifies whether or not this is the last fragment\n   * @param {Function} callback Callback\n   * @public\n   */\n  decompress(data, fin, callback) {\n    zlibLimiter.add((done) => {\n      this._decompress(data, fin, (err, result) => {\n        done();\n        callback(err, result);\n      });\n    });\n  }\n\n  /**\n   * Compress data. Concurrency limited.\n   *\n   * @param {(Buffer|String)} data Data to compress\n   * @param {Boolean} fin Specifies whether or not this is the last fragment\n   * @param {Function} callback Callback\n   * @public\n   */\n  compress(data, fin, callback) {\n    zlibLimiter.add((done) => {\n      this._compress(data, fin, (err, result) => {\n        done();\n        callback(err, result);\n      });\n    });\n  }\n\n  /**\n   * Decompress data.\n   *\n   * @param {Buffer} data Compressed data\n   * @param {Boolean} fin Specifies whether or not this is the last fragment\n   * @param {Function} callback Callback\n   * @private\n   */\n  _decompress(data, fin, callback) {\n    const endpoint = this._isServer ? 'client' : 'server';\n\n    if (!this._inflate) {\n      const key = `${endpoint}_max_window_bits`;\n      const windowBits =\n        typeof this.params[key] !== 'number'\n          ? zlib.Z_DEFAULT_WINDOWBITS\n          : this.params[key];\n\n      this._inflate = zlib.createInflateRaw({\n        ...this._options.zlibInflateOptions,\n        windowBits\n      });\n      this._inflate[kPerMessageDeflate] = this;\n      this._inflate[kTotalLength] = 0;\n      this._inflate[kBuffers] = [];\n      this._inflate.on('error', inflateOnError);\n      this._inflate.on('data', inflateOnData);\n    }\n\n    this._inflate[kCallback] = callback;\n\n    this._inflate.write(data);\n    if (fin) this._inflate.write(TRAILER);\n\n    this._inflate.flush(() => {\n      const err = this._inflate[kError];\n\n      if (err) {\n        this._inflate.close();\n        this._inflate = null;\n        callback(err);\n        return;\n      }\n\n      const data = bufferUtil.concat(\n        this._inflate[kBuffers],\n        this._inflate[kTotalLength]\n      );\n\n      if (this._inflate._readableState.endEmitted) {\n        this._inflate.close();\n        this._inflate = null;\n      } else {\n        this._inflate[kTotalLength] = 0;\n        this._inflate[kBuffers] = [];\n\n        if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n          this._inflate.reset();\n        }\n      }\n\n      callback(null, data);\n    });\n  }\n\n  /**\n   * Compress data.\n   *\n   * @param {(Buffer|String)} data Data to compress\n   * @param {Boolean} fin Specifies whether or not this is the last fragment\n   * @param {Function} callback Callback\n   * @private\n   */\n  _compress(data, fin, callback) {\n    const endpoint = this._isServer ? 'server' : 'client';\n\n    if (!this._deflate) {\n      const key = `${endpoint}_max_window_bits`;\n      const windowBits =\n        typeof this.params[key] !== 'number'\n          ? zlib.Z_DEFAULT_WINDOWBITS\n          : this.params[key];\n\n      this._deflate = zlib.createDeflateRaw({\n        ...this._options.zlibDeflateOptions,\n        windowBits\n      });\n\n      this._deflate[kTotalLength] = 0;\n      this._deflate[kBuffers] = [];\n\n      this._deflate.on('data', deflateOnData);\n    }\n\n    this._deflate[kCallback] = callback;\n\n    this._deflate.write(data);\n    this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n      if (!this._deflate) {\n        //\n        // The deflate stream was closed while data was being processed.\n        //\n        return;\n      }\n\n      let data = bufferUtil.concat(\n        this._deflate[kBuffers],\n        this._deflate[kTotalLength]\n      );\n\n      if (fin) {\n        data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n      }\n\n      //\n      // Ensure that the callback will not be called again in\n      // `PerMessageDeflate#cleanup()`.\n      //\n      this._deflate[kCallback] = null;\n\n      this._deflate[kTotalLength] = 0;\n      this._deflate[kBuffers] = [];\n\n      if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n        this._deflate.reset();\n      }\n\n      callback(null, data);\n    });\n  }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n  this[kBuffers].push(chunk);\n  this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n  this[kTotalLength] += chunk.length;\n\n  if (\n    this[kPerMessageDeflate]._maxPayload < 1 ||\n    this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n  ) {\n    this[kBuffers].push(chunk);\n    return;\n  }\n\n  this[kError] = new RangeError('Max payload size exceeded');\n  this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n  this[kError][kStatusCode] = 1009;\n  this.removeListener('data', inflateOnData);\n\n  //\n  // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n  // fact that in Node.js versions prior to 13.10.0, the callback for\n  // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n  // `zlib.reset()` ensures that either the callback is invoked or an error is\n  // emitted.\n  //\n  this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n  //\n  // There is no need to call `Zlib#close()` as the handle is automatically\n  // closed when an error is emitted.\n  //\n  this[kPerMessageDeflate]._inflate = null;\n\n  if (this[kError]) {\n    this[kCallback](this[kError]);\n    return;\n  }\n\n  err[kStatusCode] = 1007;\n  this[kCallback](err);\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n  0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n  return (\n    (code >= 1000 &&\n      code <= 1014 &&\n      code !== 1004 &&\n      code !== 1005 &&\n      code !== 1006) ||\n    (code >= 3000 && code <= 4999)\n  );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n  const len = buf.length;\n  let i = 0;\n\n  while (i < len) {\n    if ((buf[i] & 0x80) === 0) {\n      // 0xxxxxxx\n      i++;\n    } else if ((buf[i] & 0xe0) === 0xc0) {\n      // 110xxxxx 10xxxxxx\n      if (\n        i + 1 === len ||\n        (buf[i + 1] & 0xc0) !== 0x80 ||\n        (buf[i] & 0xfe) === 0xc0 // Overlong\n      ) {\n        return false;\n      }\n\n      i += 2;\n    } else if ((buf[i] & 0xf0) === 0xe0) {\n      // 1110xxxx 10xxxxxx 10xxxxxx\n      if (\n        i + 2 >= len ||\n        (buf[i + 1] & 0xc0) !== 0x80 ||\n        (buf[i + 2] & 0xc0) !== 0x80 ||\n        (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n        (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n      ) {\n        return false;\n      }\n\n      i += 3;\n    } else if ((buf[i] & 0xf8) === 0xf0) {\n      // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n      if (\n        i + 3 >= len ||\n        (buf[i + 1] & 0xc0) !== 0x80 ||\n        (buf[i + 2] & 0xc0) !== 0x80 ||\n        (buf[i + 3] & 0xc0) !== 0x80 ||\n        (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n        (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n        buf[i] > 0xf4 // > U+10FFFF\n      ) {\n        return false;\n      }\n\n      i += 4;\n    } else {\n      return false;\n    }\n  }\n\n  return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n  return (\n    hasBlob &&\n    typeof value === 'object' &&\n    typeof value.arrayBuffer === 'function' &&\n    typeof value.type === 'string' &&\n    typeof value.stream === 'function' &&\n    (value[Symbol.toStringTag] === 'Blob' ||\n      value[Symbol.toStringTag] === 'File')\n  );\n}\n\nmodule.exports = {\n  isBlob,\n  isValidStatusCode,\n  isValidUTF8: _isValidUTF8,\n  tokenChars\n};\n\nif (isUtf8) {\n  module.exports.isValidUTF8 = function (buf) {\n    return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n  };\n} /* istanbul ignore else  */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n  try {\n    const isValidUTF8 = require('utf-8-validate');\n\n    module.exports.isValidUTF8 = function (buf) {\n      return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n    };\n  } catch (e) {\n    // Continue regardless of the error.\n  }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n  BINARY_TYPES,\n  EMPTY_BUFFER,\n  kStatusCode,\n  kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n  /**\n   * Creates a Receiver instance.\n   *\n   * @param {Object} [options] Options object\n   * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n   *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n   *     multiple times in the same tick\n   * @param {String} [options.binaryType=nodebuffer] The type for binary data\n   * @param {Object} [options.extensions] An object containing the negotiated\n   *     extensions\n   * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n   *     client or server mode\n   * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n   *     buffered data chunks\n   * @param {Number} [options.maxFragments=0] The maximum number of message\n   *     fragments\n   * @param {Number} [options.maxPayload=0] The maximum allowed message length\n   * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n   *     not to skip UTF-8 validation for text and close messages\n   */\n  constructor(options = {}) {\n    super();\n\n    this._allowSynchronousEvents =\n      options.allowSynchronousEvents !== undefined\n        ? options.allowSynchronousEvents\n        : true;\n    this._binaryType = options.binaryType || BINARY_TYPES[0];\n    this._extensions = options.extensions || {};\n    this._isServer = !!options.isServer;\n    this._maxBufferedChunks = options.maxBufferedChunks | 0;\n    this._maxFragments = options.maxFragments | 0;\n    this._maxPayload = options.maxPayload | 0;\n    this._skipUTF8Validation = !!options.skipUTF8Validation;\n    this[kWebSocket] = undefined;\n\n    this._bufferedBytes = 0;\n    this._buffers = [];\n\n    this._compressed = false;\n    this._payloadLength = 0;\n    this._mask = undefined;\n    this._fragmented = 0;\n    this._masked = false;\n    this._fin = false;\n    this._opcode = 0;\n\n    this._totalPayloadLength = 0;\n    this._messageLength = 0;\n    this._numFragments = 0;\n    this._fragments = [];\n\n    this._errored = false;\n    this._loop = false;\n    this._state = GET_INFO;\n  }\n\n  /**\n   * Implements `Writable.prototype._write()`.\n   *\n   * @param {Buffer} chunk The chunk of data to write\n   * @param {String} encoding The character encoding of `chunk`\n   * @param {Function} cb Callback\n   * @private\n   */\n  _write(chunk, encoding, cb) {\n    if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n    if (\n      this._maxBufferedChunks > 0 &&\n      this._buffers.length >= this._maxBufferedChunks\n    ) {\n      cb(\n        this.createError(\n          RangeError,\n          'Too many buffered chunks',\n          false,\n          1008,\n          'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n        )\n      );\n      return;\n    }\n\n    this._bufferedBytes += chunk.length;\n    this._buffers.push(chunk);\n    this.startLoop(cb);\n  }\n\n  /**\n   * Consumes `n` bytes from the buffered data.\n   *\n   * @param {Number} n The number of bytes to consume\n   * @return {Buffer} The consumed bytes\n   * @private\n   */\n  consume(n) {\n    this._bufferedBytes -= n;\n\n    if (n === this._buffers[0].length) return this._buffers.shift();\n\n    if (n < this._buffers[0].length) {\n      const buf = this._buffers[0];\n      this._buffers[0] = new FastBuffer(\n        buf.buffer,\n        buf.byteOffset + n,\n        buf.length - n\n      );\n\n      return new FastBuffer(buf.buffer, buf.byteOffset, n);\n    }\n\n    const dst = Buffer.allocUnsafe(n);\n\n    do {\n      const buf = this._buffers[0];\n      const offset = dst.length - n;\n\n      if (n >= buf.length) {\n        dst.set(this._buffers.shift(), offset);\n      } else {\n        dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n        this._buffers[0] = new FastBuffer(\n          buf.buffer,\n          buf.byteOffset + n,\n          buf.length - n\n        );\n      }\n\n      n -= buf.length;\n    } while (n > 0);\n\n    return dst;\n  }\n\n  /**\n   * Starts the parsing loop.\n   *\n   * @param {Function} cb Callback\n   * @private\n   */\n  startLoop(cb) {\n    this._loop = true;\n\n    do {\n      switch (this._state) {\n        case GET_INFO:\n          this.getInfo(cb);\n          break;\n        case GET_PAYLOAD_LENGTH_16:\n          this.getPayloadLength16(cb);\n          break;\n        case GET_PAYLOAD_LENGTH_64:\n          this.getPayloadLength64(cb);\n          break;\n        case GET_MASK:\n          this.getMask();\n          break;\n        case GET_DATA:\n          this.getData(cb);\n          break;\n        case INFLATING:\n        case DEFER_EVENT:\n          this._loop = false;\n          return;\n      }\n    } while (this._loop);\n\n    if (!this._errored) cb();\n  }\n\n  /**\n   * Reads the first two bytes of a frame.\n   *\n   * @param {Function} cb Callback\n   * @private\n   */\n  getInfo(cb) {\n    if (this._bufferedBytes < 2) {\n      this._loop = false;\n      return;\n    }\n\n    const buf = this.consume(2);\n\n    if ((buf[0] & 0x30) !== 0x00) {\n      const error = this.createError(\n        RangeError,\n        'RSV2 and RSV3 must be clear',\n        true,\n        1002,\n        'WS_ERR_UNEXPECTED_RSV_2_3'\n      );\n\n      cb(error);\n      return;\n    }\n\n    const compressed = (buf[0] & 0x40) === 0x40;\n\n    if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n      const error = this.createError(\n        RangeError,\n        'RSV1 must be clear',\n        true,\n        1002,\n        'WS_ERR_UNEXPECTED_RSV_1'\n      );\n\n      cb(error);\n      return;\n    }\n\n    this._fin = (buf[0] & 0x80) === 0x80;\n    this._opcode = buf[0] & 0x0f;\n    this._payloadLength = buf[1] & 0x7f;\n\n    if (this._opcode === 0x00) {\n      if (compressed) {\n        const error = this.createError(\n          RangeError,\n          'RSV1 must be clear',\n          true,\n          1002,\n          'WS_ERR_UNEXPECTED_RSV_1'\n        );\n\n        cb(error);\n        return;\n      }\n\n      if (!this._fragmented) {\n        const error = this.createError(\n          RangeError,\n          'invalid opcode 0',\n          true,\n          1002,\n          'WS_ERR_INVALID_OPCODE'\n        );\n\n        cb(error);\n        return;\n      }\n\n      this._opcode = this._fragmented;\n    } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n      if (this._fragmented) {\n        const error = this.createError(\n          RangeError,\n          `invalid opcode ${this._opcode}`,\n          true,\n          1002,\n          'WS_ERR_INVALID_OPCODE'\n        );\n\n        cb(error);\n        return;\n      }\n\n      this._compressed = compressed;\n    } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n      if (!this._fin) {\n        const error = this.createError(\n          RangeError,\n          'FIN must be set',\n          true,\n          1002,\n          'WS_ERR_EXPECTED_FIN'\n        );\n\n        cb(error);\n        return;\n      }\n\n      if (compressed) {\n        const error = this.createError(\n          RangeError,\n          'RSV1 must be clear',\n          true,\n          1002,\n          'WS_ERR_UNEXPECTED_RSV_1'\n        );\n\n        cb(error);\n        return;\n      }\n\n      if (\n        this._payloadLength > 0x7d ||\n        (this._opcode === 0x08 && this._payloadLength === 1)\n      ) {\n        const error = this.createError(\n          RangeError,\n          `invalid payload length ${this._payloadLength}`,\n          true,\n          1002,\n          'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n        );\n\n        cb(error);\n        return;\n      }\n    } else {\n      const error = this.createError(\n        RangeError,\n        `invalid opcode ${this._opcode}`,\n        true,\n        1002,\n        'WS_ERR_INVALID_OPCODE'\n      );\n\n      cb(error);\n      return;\n    }\n\n    if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n    this._masked = (buf[1] & 0x80) === 0x80;\n\n    if (this._isServer) {\n      if (!this._masked) {\n        const error = this.createError(\n          RangeError,\n          'MASK must be set',\n          true,\n          1002,\n          'WS_ERR_EXPECTED_MASK'\n        );\n\n        cb(error);\n        return;\n      }\n    } else if (this._masked) {\n      const error = this.createError(\n        RangeError,\n        'MASK must be clear',\n        true,\n        1002,\n        'WS_ERR_UNEXPECTED_MASK'\n      );\n\n      cb(error);\n      return;\n    }\n\n    if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n    else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n    else this.haveLength(cb);\n  }\n\n  /**\n   * Gets extended payload length (7+16).\n   *\n   * @param {Function} cb Callback\n   * @private\n   */\n  getPayloadLength16(cb) {\n    if (this._bufferedBytes < 2) {\n      this._loop = false;\n      return;\n    }\n\n    this._payloadLength = this.consume(2).readUInt16BE(0);\n    this.haveLength(cb);\n  }\n\n  /**\n   * Gets extended payload length (7+64).\n   *\n   * @param {Function} cb Callback\n   * @private\n   */\n  getPayloadLength64(cb) {\n    if (this._bufferedBytes < 8) {\n      this._loop = false;\n      return;\n    }\n\n    const buf = this.consume(8);\n    const num = buf.readUInt32BE(0);\n\n    //\n    // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n    // if payload length is greater than this number.\n    //\n    if (num > Math.pow(2, 53 - 32) - 1) {\n      const error = this.createError(\n        RangeError,\n        'Unsupported WebSocket frame: payload length > 2^53 - 1',\n        false,\n        1009,\n        'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n      );\n\n      cb(error);\n      return;\n    }\n\n    this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n    this.haveLength(cb);\n  }\n\n  /**\n   * Payload length has been read.\n   *\n   * @param {Function} cb Callback\n   * @private\n   */\n  haveLength(cb) {\n    if (this._payloadLength && this._opcode < 0x08) {\n      this._totalPayloadLength += this._payloadLength;\n      if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n        const error = this.createError(\n          RangeError,\n          'Max payload size exceeded',\n          false,\n          1009,\n          'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n        );\n\n        cb(error);\n        return;\n      }\n    }\n\n    if (this._masked) this._state = GET_MASK;\n    else this._state = GET_DATA;\n  }\n\n  /**\n   * Reads mask bytes.\n   *\n   * @private\n   */\n  getMask() {\n    if (this._bufferedBytes < 4) {\n      this._loop = false;\n      return;\n    }\n\n    this._mask = this.consume(4);\n    this._state = GET_DATA;\n  }\n\n  /**\n   * Reads data bytes.\n   *\n   * @param {Function} cb Callback\n   * @private\n   */\n  getData(cb) {\n    let data = EMPTY_BUFFER;\n\n    if (this._payloadLength) {\n      if (this._bufferedBytes < this._payloadLength) {\n        this._loop = false;\n        return;\n      }\n\n      data = this.consume(this._payloadLength);\n\n      if (\n        this._masked &&\n        (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n      ) {\n        unmask(data, this._mask);\n      }\n    }\n\n    if (this._opcode > 0x07) {\n      this.controlMessage(data, cb);\n      return;\n    }\n\n    if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {\n      const error = this.createError(\n        RangeError,\n        'Too many message fragments',\n        false,\n        1008,\n        'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n      );\n\n      cb(error);\n      return;\n    }\n\n    if (this._compressed) {\n      this._state = INFLATING;\n      this.decompress(data, cb);\n      return;\n    }\n\n    if (data.length) {\n      //\n      // This message is not compressed so its length is the sum of the payload\n      // length of all fragments.\n      //\n      this._messageLength = this._totalPayloadLength;\n      this._fragments.push(data);\n    }\n\n    this.dataMessage(cb);\n  }\n\n  /**\n   * Decompresses data.\n   *\n   * @param {Buffer} data Compressed data\n   * @param {Function} cb Callback\n   * @private\n   */\n  decompress(data, cb) {\n    const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n    perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n      if (err) return cb(err);\n\n      if (buf.length) {\n        this._messageLength += buf.length;\n        if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n          const error = this.createError(\n            RangeError,\n            'Max payload size exceeded',\n            false,\n            1009,\n            'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n          );\n\n          cb(error);\n          return;\n        }\n\n        this._fragments.push(buf);\n      }\n\n      this.dataMessage(cb);\n      if (this._state === GET_INFO) this.startLoop(cb);\n    });\n  }\n\n  /**\n   * Handles a data message.\n   *\n   * @param {Function} cb Callback\n   * @private\n   */\n  dataMessage(cb) {\n    if (!this._fin) {\n      this._state = GET_INFO;\n      return;\n    }\n\n    const messageLength = this._messageLength;\n    const fragments = this._fragments;\n\n    this._totalPayloadLength = 0;\n    this._messageLength = 0;\n    this._fragmented = 0;\n    this._numFragments = 0;\n    this._fragments = [];\n\n    if (this._opcode === 2) {\n      let data;\n\n      if (this._binaryType === 'nodebuffer') {\n        data = concat(fragments, messageLength);\n      } else if (this._binaryType === 'arraybuffer') {\n        data = toArrayBuffer(concat(fragments, messageLength));\n      } else if (this._binaryType === 'blob') {\n        data = new Blob(fragments);\n      } else {\n        data = fragments;\n      }\n\n      if (this._allowSynchronousEvents) {\n        this.emit('message', data, true);\n        this._state = GET_INFO;\n      } else {\n        this._state = DEFER_EVENT;\n        setImmediate(() => {\n          this.emit('message', data, true);\n          this._state = GET_INFO;\n          this.startLoop(cb);\n        });\n      }\n    } else {\n      const buf = concat(fragments, messageLength);\n\n      if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n        const error = this.createError(\n          Error,\n          'invalid UTF-8 sequence',\n          true,\n          1007,\n          'WS_ERR_INVALID_UTF8'\n        );\n\n        cb(error);\n        return;\n      }\n\n      if (this._state === INFLATING || this._allowSynchronousEvents) {\n        this.emit('message', buf, false);\n        this._state = GET_INFO;\n      } else {\n        this._state = DEFER_EVENT;\n        setImmediate(() => {\n          this.emit('message', buf, false);\n          this._state = GET_INFO;\n          this.startLoop(cb);\n        });\n      }\n    }\n  }\n\n  /**\n   * Handles a control message.\n   *\n   * @param {Buffer} data Data to handle\n   * @return {(Error|RangeError|undefined)} A possible error\n   * @private\n   */\n  controlMessage(data, cb) {\n    if (this._opcode === 0x08) {\n      if (data.length === 0) {\n        this._loop = false;\n        this.emit('conclude', 1005, EMPTY_BUFFER);\n        this.end();\n      } else {\n        const code = data.readUInt16BE(0);\n\n        if (!isValidStatusCode(code)) {\n          const error = this.createError(\n            RangeError,\n            `invalid status code ${code}`,\n            true,\n            1002,\n            'WS_ERR_INVALID_CLOSE_CODE'\n          );\n\n          cb(error);\n          return;\n        }\n\n        const buf = new FastBuffer(\n          data.buffer,\n          data.byteOffset + 2,\n          data.length - 2\n        );\n\n        if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n          const error = this.createError(\n            Error,\n            'invalid UTF-8 sequence',\n            true,\n            1007,\n            'WS_ERR_INVALID_UTF8'\n          );\n\n          cb(error);\n          return;\n        }\n\n        this._loop = false;\n        this.emit('conclude', code, buf);\n        this.end();\n      }\n\n      this._state = GET_INFO;\n      return;\n    }\n\n    if (this._allowSynchronousEvents) {\n      this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n      this._state = GET_INFO;\n    } else {\n      this._state = DEFER_EVENT;\n      setImmediate(() => {\n        this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n        this._state = GET_INFO;\n        this.startLoop(cb);\n      });\n    }\n  }\n\n  /**\n   * Builds an error object.\n   *\n   * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n   * @param {String} message The error message\n   * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n   *     `message`\n   * @param {Number} statusCode The status code\n   * @param {String} errorCode The exposed error code\n   * @return {(Error|RangeError)} The error\n   * @private\n   */\n  createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n    this._loop = false;\n    this._errored = true;\n\n    const err = new ErrorCtor(\n      prefix ? `Invalid WebSocket frame: ${message}` : message\n    );\n\n    Error.captureStackTrace(err, this.createError);\n    err.code = errorCode;\n    err[kStatusCode] = statusCode;\n    return err;\n  }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\nconst {\n  types: { isUint8Array }\n} = require('util');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n  /**\n   * Creates a Sender instance.\n   *\n   * @param {Duplex} socket The connection socket\n   * @param {Object} [extensions] An object containing the negotiated extensions\n   * @param {Function} [generateMask] The function used to generate the masking\n   *     key\n   */\n  constructor(socket, extensions, generateMask) {\n    this._extensions = extensions || {};\n\n    if (generateMask) {\n      this._generateMask = generateMask;\n      this._maskBuffer = Buffer.alloc(4);\n    }\n\n    this._socket = socket;\n\n    this._firstFragment = true;\n    this._compress = false;\n\n    this._bufferedBytes = 0;\n    this._queue = [];\n    this._state = DEFAULT;\n    this.onerror = NOOP;\n    this[kWebSocket] = undefined;\n  }\n\n  /**\n   * Frames a piece of data according to the HyBi WebSocket protocol.\n   *\n   * @param {(Buffer|String)} data The data to frame\n   * @param {Object} options Options object\n   * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n   *     FIN bit\n   * @param {Function} [options.generateMask] The function used to generate the\n   *     masking key\n   * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n   *     `data`\n   * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n   *     key\n   * @param {Number} options.opcode The opcode\n   * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n   *     modified\n   * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n   *     RSV1 bit\n   * @return {(Buffer|String)[]} The framed data\n   * @public\n   */\n  static frame(data, options) {\n    let mask;\n    let merge = false;\n    let offset = 2;\n    let skipMasking = false;\n\n    if (options.mask) {\n      mask = options.maskBuffer || maskBuffer;\n\n      if (options.generateMask) {\n        options.generateMask(mask);\n      } else {\n        if (randomPoolPointer === RANDOM_POOL_SIZE) {\n          /* istanbul ignore else  */\n          if (randomPool === undefined) {\n            //\n            // This is lazily initialized because server-sent frames must not\n            // be masked so it may never be used.\n            //\n            randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n          }\n\n          randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n          randomPoolPointer = 0;\n        }\n\n        mask[0] = randomPool[randomPoolPointer++];\n        mask[1] = randomPool[randomPoolPointer++];\n        mask[2] = randomPool[randomPoolPointer++];\n        mask[3] = randomPool[randomPoolPointer++];\n      }\n\n      skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n      offset = 6;\n    }\n\n    let dataLength;\n\n    if (typeof data === 'string') {\n      if (\n        (!options.mask || skipMasking) &&\n        options[kByteLength] !== undefined\n      ) {\n        dataLength = options[kByteLength];\n      } else {\n        data = Buffer.from(data);\n        dataLength = data.length;\n      }\n    } else {\n      dataLength = data.length;\n      merge = options.mask && options.readOnly && !skipMasking;\n    }\n\n    let payloadLength = dataLength;\n\n    if (dataLength >= 65536) {\n      offset += 8;\n      payloadLength = 127;\n    } else if (dataLength > 125) {\n      offset += 2;\n      payloadLength = 126;\n    }\n\n    const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n    target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n    if (options.rsv1) target[0] |= 0x40;\n\n    target[1] = payloadLength;\n\n    if (payloadLength === 126) {\n      target.writeUInt16BE(dataLength, 2);\n    } else if (payloadLength === 127) {\n      target[2] = target[3] = 0;\n      target.writeUIntBE(dataLength, 4, 6);\n    }\n\n    if (!options.mask) return [target, data];\n\n    target[1] |= 0x80;\n    target[offset - 4] = mask[0];\n    target[offset - 3] = mask[1];\n    target[offset - 2] = mask[2];\n    target[offset - 1] = mask[3];\n\n    if (skipMasking) return [target, data];\n\n    if (merge) {\n      applyMask(data, mask, target, offset, dataLength);\n      return [target];\n    }\n\n    applyMask(data, mask, data, 0, dataLength);\n    return [target, data];\n  }\n\n  /**\n   * Sends a close message to the other peer.\n   *\n   * @param {Number} [code] The status code component of the body\n   * @param {(String|Buffer)} [data] The message component of the body\n   * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n   * @param {Function} [cb] Callback\n   * @public\n   */\n  close(code, data, mask, cb) {\n    let buf;\n\n    if (code === undefined) {\n      buf = EMPTY_BUFFER;\n    } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n      throw new TypeError('First argument must be a valid error code number');\n    } else if (data === undefined || !data.length) {\n      buf = Buffer.allocUnsafe(2);\n      buf.writeUInt16BE(code, 0);\n    } else {\n      const length = Buffer.byteLength(data);\n\n      if (length > 123) {\n        throw new RangeError('The message must not be greater than 123 bytes');\n      }\n\n      buf = Buffer.allocUnsafe(2 + length);\n      buf.writeUInt16BE(code, 0);\n\n      if (typeof data === 'string') {\n        buf.write(data, 2);\n      } else if (isUint8Array(data)) {\n        buf.set(data, 2);\n      } else {\n        throw new TypeError('Second argument must be a string or a Uint8Array');\n      }\n    }\n\n    const options = {\n      [kByteLength]: buf.length,\n      fin: true,\n      generateMask: this._generateMask,\n      mask,\n      maskBuffer: this._maskBuffer,\n      opcode: 0x08,\n      readOnly: false,\n      rsv1: false\n    };\n\n    if (this._state !== DEFAULT) {\n      this.enqueue([this.dispatch, buf, false, options, cb]);\n    } else {\n      this.sendFrame(Sender.frame(buf, options), cb);\n    }\n  }\n\n  /**\n   * Sends a ping message to the other peer.\n   *\n   * @param {*} data The message to send\n   * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n   * @param {Function} [cb] Callback\n   * @public\n   */\n  ping(data, mask, cb) {\n    let byteLength;\n    let readOnly;\n\n    if (typeof data === 'string') {\n      byteLength = Buffer.byteLength(data);\n      readOnly = false;\n    } else if (isBlob(data)) {\n      byteLength = data.size;\n      readOnly = false;\n    } else {\n      data = toBuffer(data);\n      byteLength = data.length;\n      readOnly = toBuffer.readOnly;\n    }\n\n    if (byteLength > 125) {\n      throw new RangeError('The data size must not be greater than 125 bytes');\n    }\n\n    const options = {\n      [kByteLength]: byteLength,\n      fin: true,\n      generateMask: this._generateMask,\n      mask,\n      maskBuffer: this._maskBuffer,\n      opcode: 0x09,\n      readOnly,\n      rsv1: false\n    };\n\n    if (isBlob(data)) {\n      if (this._state !== DEFAULT) {\n        this.enqueue([this.getBlobData, data, false, options, cb]);\n      } else {\n        this.getBlobData(data, false, options, cb);\n      }\n    } else if (this._state !== DEFAULT) {\n      this.enqueue([this.dispatch, data, false, options, cb]);\n    } else {\n      this.sendFrame(Sender.frame(data, options), cb);\n    }\n  }\n\n  /**\n   * Sends a pong message to the other peer.\n   *\n   * @param {*} data The message to send\n   * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n   * @param {Function} [cb] Callback\n   * @public\n   */\n  pong(data, mask, cb) {\n    let byteLength;\n    let readOnly;\n\n    if (typeof data === 'string') {\n      byteLength = Buffer.byteLength(data);\n      readOnly = false;\n    } else if (isBlob(data)) {\n      byteLength = data.size;\n      readOnly = false;\n    } else {\n      data = toBuffer(data);\n      byteLength = data.length;\n      readOnly = toBuffer.readOnly;\n    }\n\n    if (byteLength > 125) {\n      throw new RangeError('The data size must not be greater than 125 bytes');\n    }\n\n    const options = {\n      [kByteLength]: byteLength,\n      fin: true,\n      generateMask: this._generateMask,\n      mask,\n      maskBuffer: this._maskBuffer,\n      opcode: 0x0a,\n      readOnly,\n      rsv1: false\n    };\n\n    if (isBlob(data)) {\n      if (this._state !== DEFAULT) {\n        this.enqueue([this.getBlobData, data, false, options, cb]);\n      } else {\n        this.getBlobData(data, false, options, cb);\n      }\n    } else if (this._state !== DEFAULT) {\n      this.enqueue([this.dispatch, data, false, options, cb]);\n    } else {\n      this.sendFrame(Sender.frame(data, options), cb);\n    }\n  }\n\n  /**\n   * Sends a data message to the other peer.\n   *\n   * @param {*} data The message to send\n   * @param {Object} options Options object\n   * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n   *     or text\n   * @param {Boolean} [options.compress=false] Specifies whether or not to\n   *     compress `data`\n   * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n   *     last one\n   * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n   *     `data`\n   * @param {Function} [cb] Callback\n   * @public\n   */\n  send(data, options, cb) {\n    const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n    let opcode = options.binary ? 2 : 1;\n    let rsv1 = options.compress;\n\n    let byteLength;\n    let readOnly;\n\n    if (typeof data === 'string') {\n      byteLength = Buffer.byteLength(data);\n      readOnly = false;\n    } else if (isBlob(data)) {\n      byteLength = data.size;\n      readOnly = false;\n    } else {\n      data = toBuffer(data);\n      byteLength = data.length;\n      readOnly = toBuffer.readOnly;\n    }\n\n    if (this._firstFragment) {\n      this._firstFragment = false;\n      if (\n        rsv1 &&\n        perMessageDeflate &&\n        perMessageDeflate.params[\n          perMessageDeflate._isServer\n            ? 'server_no_context_takeover'\n            : 'client_no_context_takeover'\n        ]\n      ) {\n        rsv1 = byteLength >= perMessageDeflate._threshold;\n      }\n      this._compress = rsv1;\n    } else {\n      rsv1 = false;\n      opcode = 0;\n    }\n\n    if (options.fin) this._firstFragment = true;\n\n    const opts = {\n      [kByteLength]: byteLength,\n      fin: options.fin,\n      generateMask: this._generateMask,\n      mask: options.mask,\n      maskBuffer: this._maskBuffer,\n      opcode,\n      readOnly,\n      rsv1\n    };\n\n    if (isBlob(data)) {\n      if (this._state !== DEFAULT) {\n        this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n      } else {\n        this.getBlobData(data, this._compress, opts, cb);\n      }\n    } else if (this._state !== DEFAULT) {\n      this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n    } else {\n      this.dispatch(data, this._compress, opts, cb);\n    }\n  }\n\n  /**\n   * Gets the contents of a blob as binary data.\n   *\n   * @param {Blob} blob The blob\n   * @param {Boolean} [compress=false] Specifies whether or not to compress\n   *     the data\n   * @param {Object} options Options object\n   * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n   *     FIN bit\n   * @param {Function} [options.generateMask] The function used to generate the\n   *     masking key\n   * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n   *     `data`\n   * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n   *     key\n   * @param {Number} options.opcode The opcode\n   * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n   *     modified\n   * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n   *     RSV1 bit\n   * @param {Function} [cb] Callback\n   * @private\n   */\n  getBlobData(blob, compress, options, cb) {\n    this._bufferedBytes += options[kByteLength];\n    this._state = GET_BLOB_DATA;\n\n    blob\n      .arrayBuffer()\n      .then((arrayBuffer) => {\n        if (this._socket.destroyed) {\n          const err = new Error(\n            'The socket was closed while the blob was being read'\n          );\n\n          //\n          // `callCallbacks` is called in the next tick to ensure that errors\n          // that might be thrown in the callbacks behave like errors thrown\n          // outside the promise chain.\n          //\n          process.nextTick(callCallbacks, this, err, cb);\n          return;\n        }\n\n        this._bufferedBytes -= options[kByteLength];\n        const data = toBuffer(arrayBuffer);\n\n        if (!compress) {\n          this._state = DEFAULT;\n          this.sendFrame(Sender.frame(data, options), cb);\n          this.dequeue();\n        } else {\n          this.dispatch(data, compress, options, cb);\n        }\n      })\n      .catch((err) => {\n        //\n        // `onError` is called in the next tick for the same reason that\n        // `callCallbacks` above is.\n        //\n        process.nextTick(onError, this, err, cb);\n      });\n  }\n\n  /**\n   * Dispatches a message.\n   *\n   * @param {(Buffer|String)} data The message to send\n   * @param {Boolean} [compress=false] Specifies whether or not to compress\n   *     `data`\n   * @param {Object} options Options object\n   * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n   *     FIN bit\n   * @param {Function} [options.generateMask] The function used to generate the\n   *     masking key\n   * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n   *     `data`\n   * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n   *     key\n   * @param {Number} options.opcode The opcode\n   * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n   *     modified\n   * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n   *     RSV1 bit\n   * @param {Function} [cb] Callback\n   * @private\n   */\n  dispatch(data, compress, options, cb) {\n    if (!compress) {\n      this.sendFrame(Sender.frame(data, options), cb);\n      return;\n    }\n\n    const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n    this._bufferedBytes += options[kByteLength];\n    this._state = DEFLATING;\n    perMessageDeflate.compress(data, options.fin, (_, buf) => {\n      if (this._socket.destroyed) {\n        const err = new Error(\n          'The socket was closed while data was being compressed'\n        );\n\n        callCallbacks(this, err, cb);\n        return;\n      }\n\n      this._bufferedBytes -= options[kByteLength];\n      this._state = DEFAULT;\n      options.readOnly = false;\n      this.sendFrame(Sender.frame(buf, options), cb);\n      this.dequeue();\n    });\n  }\n\n  /**\n   * Executes queued send operations.\n   *\n   * @private\n   */\n  dequeue() {\n    while (this._state === DEFAULT && this._queue.length) {\n      const params = this._queue.shift();\n\n      this._bufferedBytes -= params[3][kByteLength];\n      Reflect.apply(params[0], this, params.slice(1));\n    }\n  }\n\n  /**\n   * Enqueues a send operation.\n   *\n   * @param {Array} params Send operation parameters.\n   * @private\n   */\n  enqueue(params) {\n    this._bufferedBytes += params[3][kByteLength];\n    this._queue.push(params);\n  }\n\n  /**\n   * Sends a frame.\n   *\n   * @param {(Buffer | String)[]} list The frame to send\n   * @param {Function} [cb] Callback\n   * @private\n   */\n  sendFrame(list, cb) {\n    if (list.length === 2) {\n      this._socket.cork();\n      this._socket.write(list[0]);\n      this._socket.write(list[1], cb);\n      this._socket.uncork();\n    } else {\n      this._socket.write(list[0], cb);\n    }\n  }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n  if (typeof cb === 'function') cb(err);\n\n  for (let i = 0; i < sender._queue.length; i++) {\n    const params = sender._queue[i];\n    const callback = params[params.length - 1];\n\n    if (typeof callback === 'function') callback(err);\n  }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n  callCallbacks(sender, err, cb);\n  sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n  /**\n   * Create a new `Event`.\n   *\n   * @param {String} type The name of the event\n   * @throws {TypeError} If the `type` argument is not specified\n   */\n  constructor(type) {\n    this[kTarget] = null;\n    this[kType] = type;\n  }\n\n  /**\n   * @type {*}\n   */\n  get target() {\n    return this[kTarget];\n  }\n\n  /**\n   * @type {String}\n   */\n  get type() {\n    return this[kType];\n  }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n  /**\n   * Create a new `CloseEvent`.\n   *\n   * @param {String} type The name of the event\n   * @param {Object} [options] A dictionary object that allows for setting\n   *     attributes via object members of the same name\n   * @param {Number} [options.code=0] The status code explaining why the\n   *     connection was closed\n   * @param {String} [options.reason=''] A human-readable string explaining why\n   *     the connection was closed\n   * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n   *     connection was cleanly closed\n   */\n  constructor(type, options = {}) {\n    super(type);\n\n    this[kCode] = options.code === undefined ? 0 : options.code;\n    this[kReason] = options.reason === undefined ? '' : options.reason;\n    this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n  }\n\n  /**\n   * @type {Number}\n   */\n  get code() {\n    return this[kCode];\n  }\n\n  /**\n   * @type {String}\n   */\n  get reason() {\n    return this[kReason];\n  }\n\n  /**\n   * @type {Boolean}\n   */\n  get wasClean() {\n    return this[kWasClean];\n  }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n  /**\n   * Create a new `ErrorEvent`.\n   *\n   * @param {String} type The name of the event\n   * @param {Object} [options] A dictionary object that allows for setting\n   *     attributes via object members of the same name\n   * @param {*} [options.error=null] The error that generated this event\n   * @param {String} [options.message=''] The error message\n   */\n  constructor(type, options = {}) {\n    super(type);\n\n    this[kError] = options.error === undefined ? null : options.error;\n    this[kMessage] = options.message === undefined ? '' : options.message;\n  }\n\n  /**\n   * @type {*}\n   */\n  get error() {\n    return this[kError];\n  }\n\n  /**\n   * @type {String}\n   */\n  get message() {\n    return this[kMessage];\n  }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n  /**\n   * Create a new `MessageEvent`.\n   *\n   * @param {String} type The name of the event\n   * @param {Object} [options] A dictionary object that allows for setting\n   *     attributes via object members of the same name\n   * @param {*} [options.data=null] The message content\n   */\n  constructor(type, options = {}) {\n    super(type);\n\n    this[kData] = options.data === undefined ? null : options.data;\n  }\n\n  /**\n   * @type {*}\n   */\n  get data() {\n    return this[kData];\n  }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n  /**\n   * Register an event listener.\n   *\n   * @param {String} type A string representing the event type to listen for\n   * @param {(Function|Object)} handler The listener to add\n   * @param {Object} [options] An options object specifies characteristics about\n   *     the event listener\n   * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n   *     listener should be invoked at most once after being added. If `true`,\n   *     the listener would be automatically removed when invoked.\n   * @public\n   */\n  addEventListener(type, handler, options = {}) {\n    for (const listener of this.listeners(type)) {\n      if (\n        !options[kForOnEventAttribute] &&\n        listener[kListener] === handler &&\n        !listener[kForOnEventAttribute]\n      ) {\n        return;\n      }\n    }\n\n    let wrapper;\n\n    if (type === 'message') {\n      wrapper = function onMessage(data, isBinary) {\n        const event = new MessageEvent('message', {\n          data: isBinary ? data : data.toString()\n        });\n\n        event[kTarget] = this;\n        callListener(handler, this, event);\n      };\n    } else if (type === 'close') {\n      wrapper = function onClose(code, message) {\n        const event = new CloseEvent('close', {\n          code,\n          reason: message.toString(),\n          wasClean: this._closeFrameReceived && this._closeFrameSent\n        });\n\n        event[kTarget] = this;\n        callListener(handler, this, event);\n      };\n    } else if (type === 'error') {\n      wrapper = function onError(error) {\n        const event = new ErrorEvent('error', {\n          error,\n          message: error.message\n        });\n\n        event[kTarget] = this;\n        callListener(handler, this, event);\n      };\n    } else if (type === 'open') {\n      wrapper = function onOpen() {\n        const event = new Event('open');\n\n        event[kTarget] = this;\n        callListener(handler, this, event);\n      };\n    } else {\n      return;\n    }\n\n    wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n    wrapper[kListener] = handler;\n\n    if (options.once) {\n      this.once(type, wrapper);\n    } else {\n      this.on(type, wrapper);\n    }\n  },\n\n  /**\n   * Remove an event listener.\n   *\n   * @param {String} type A string representing the event type to remove\n   * @param {(Function|Object)} handler The listener to remove\n   * @public\n   */\n  removeEventListener(type, handler) {\n    for (const listener of this.listeners(type)) {\n      if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n        this.removeListener(type, listener);\n        break;\n      }\n    }\n  }\n};\n\nmodule.exports = {\n  CloseEvent,\n  ErrorEvent,\n  Event,\n  EventTarget,\n  MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n  if (typeof listener === 'object' && listener.handleEvent) {\n    listener.handleEvent.call(listener, event);\n  } else {\n    listener.call(thisArg, event);\n  }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n *     parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n  if (dest[name] === undefined) dest[name] = [elem];\n  else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n  const offers = Object.create(null);\n  let params = Object.create(null);\n  let mustUnescape = false;\n  let isEscaping = false;\n  let inQuotes = false;\n  let extensionName;\n  let paramName;\n  let start = -1;\n  let code = -1;\n  let end = -1;\n  let i = 0;\n\n  for (; i < header.length; i++) {\n    code = header.charCodeAt(i);\n\n    if (extensionName === undefined) {\n      if (end === -1 && tokenChars[code] === 1) {\n        if (start === -1) start = i;\n      } else if (\n        i !== 0 &&\n        (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n      ) {\n        if (end === -1 && start !== -1) end = i;\n      } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n        if (start === -1) {\n          throw new SyntaxError(`Unexpected character at index ${i}`);\n        }\n\n        if (end === -1) end = i;\n        const name = header.slice(start, end);\n        if (code === 0x2c) {\n          push(offers, name, params);\n          params = Object.create(null);\n        } else {\n          extensionName = name;\n        }\n\n        start = end = -1;\n      } else {\n        throw new SyntaxError(`Unexpected character at index ${i}`);\n      }\n    } else if (paramName === undefined) {\n      if (end === -1 && tokenChars[code] === 1) {\n        if (start === -1) start = i;\n      } else if (code === 0x20 || code === 0x09) {\n        if (end === -1 && start !== -1) end = i;\n      } else if (code === 0x3b || code === 0x2c) {\n        if (start === -1) {\n          throw new SyntaxError(`Unexpected character at index ${i}`);\n        }\n\n        if (end === -1) end = i;\n        push(params, header.slice(start, end), true);\n        if (code === 0x2c) {\n          push(offers, extensionName, params);\n          params = Object.create(null);\n          extensionName = undefined;\n        }\n\n        start = end = -1;\n      } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n        paramName = header.slice(start, i);\n        start = end = -1;\n      } else {\n        throw new SyntaxError(`Unexpected character at index ${i}`);\n      }\n    } else {\n      //\n      // The value of a quoted-string after unescaping must conform to the\n      // token ABNF, so only token characters are valid.\n      // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n      //\n      if (isEscaping) {\n        if (tokenChars[code] !== 1) {\n          throw new SyntaxError(`Unexpected character at index ${i}`);\n        }\n        if (start === -1) start = i;\n        else if (!mustUnescape) mustUnescape = true;\n        isEscaping = false;\n      } else if (inQuotes) {\n        if (tokenChars[code] === 1) {\n          if (start === -1) start = i;\n        } else if (code === 0x22 /* '\"' */ && start !== -1) {\n          inQuotes = false;\n          end = i;\n        } else if (code === 0x5c /* '\\' */) {\n          isEscaping = true;\n        } else {\n          throw new SyntaxError(`Unexpected character at index ${i}`);\n        }\n      } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n        inQuotes = true;\n      } else if (end === -1 && tokenChars[code] === 1) {\n        if (start === -1) start = i;\n      } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n        if (end === -1) end = i;\n      } else if (code === 0x3b || code === 0x2c) {\n        if (start === -1) {\n          throw new SyntaxError(`Unexpected character at index ${i}`);\n        }\n\n        if (end === -1) end = i;\n        let value = header.slice(start, end);\n        if (mustUnescape) {\n          value = value.replace(/\\\\/g, '');\n          mustUnescape = false;\n        }\n        push(params, paramName, value);\n        if (code === 0x2c) {\n          push(offers, extensionName, params);\n          params = Object.create(null);\n          extensionName = undefined;\n        }\n\n        paramName = undefined;\n        start = end = -1;\n      } else {\n        throw new SyntaxError(`Unexpected character at index ${i}`);\n      }\n    }\n  }\n\n  if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n    throw new SyntaxError('Unexpected end of input');\n  }\n\n  if (end === -1) end = i;\n  const token = header.slice(start, end);\n  if (extensionName === undefined) {\n    push(offers, token, params);\n  } else {\n    if (paramName === undefined) {\n      push(params, token, true);\n    } else if (mustUnescape) {\n      push(params, paramName, token.replace(/\\\\/g, ''));\n    } else {\n      push(params, paramName, token);\n    }\n    push(offers, extensionName, params);\n  }\n\n  return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n  return Object.keys(extensions)\n    .map((extension) => {\n      let configurations = extensions[extension];\n      if (!Array.isArray(configurations)) configurations = [configurations];\n      return configurations\n        .map((params) => {\n          return [extension]\n            .concat(\n              Object.keys(params).map((k) => {\n                let values = params[k];\n                if (!Array.isArray(values)) values = [values];\n                return values\n                  .map((v) => (v === true ? k : `${k}=${v}`))\n                  .join('; ');\n              })\n            )\n            .join('; ');\n        })\n        .join(', ');\n    })\n    .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n  BINARY_TYPES,\n  CLOSE_TIMEOUT,\n  EMPTY_BUFFER,\n  GUID,\n  kForOnEventAttribute,\n  kListener,\n  kStatusCode,\n  kWebSocket,\n  NOOP\n} = require('./constants');\nconst {\n  EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n  /**\n   * Create a new `WebSocket`.\n   *\n   * @param {(String|URL)} address The URL to which to connect\n   * @param {(String|String[])} [protocols] The subprotocols\n   * @param {Object} [options] Connection options\n   */\n  constructor(address, protocols, options) {\n    super();\n\n    this._binaryType = BINARY_TYPES[0];\n    this._closeCode = 1006;\n    this._closeFrameReceived = false;\n    this._closeFrameSent = false;\n    this._closeMessage = EMPTY_BUFFER;\n    this._closeTimer = null;\n    this._errorEmitted = false;\n    this._extensions = {};\n    this._paused = false;\n    this._protocol = '';\n    this._readyState = WebSocket.CONNECTING;\n    this._receiver = null;\n    this._sender = null;\n    this._socket = null;\n\n    if (address !== null) {\n      this._bufferedAmount = 0;\n      this._isServer = false;\n      this._redirects = 0;\n\n      if (protocols === undefined) {\n        protocols = [];\n      } else if (!Array.isArray(protocols)) {\n        if (typeof protocols === 'object' && protocols !== null) {\n          options = protocols;\n          protocols = [];\n        } else {\n          protocols = [protocols];\n        }\n      }\n\n      initAsClient(this, address, protocols, options);\n    } else {\n      this._autoPong = options.autoPong;\n      this._closeTimeout = options.closeTimeout;\n      this._isServer = true;\n    }\n  }\n\n  /**\n   * For historical reasons, the custom \"nodebuffer\" type is used by the default\n   * instead of \"blob\".\n   *\n   * @type {String}\n   */\n  get binaryType() {\n    return this._binaryType;\n  }\n\n  set binaryType(type) {\n    if (!BINARY_TYPES.includes(type)) return;\n\n    this._binaryType = type;\n\n    //\n    // Allow to change `binaryType` on the fly.\n    //\n    if (this._receiver) this._receiver._binaryType = type;\n  }\n\n  /**\n   * @type {Number}\n   */\n  get bufferedAmount() {\n    if (!this._socket) return this._bufferedAmount;\n\n    return this._socket._writableState.length + this._sender._bufferedBytes;\n  }\n\n  /**\n   * @type {String}\n   */\n  get extensions() {\n    return Object.keys(this._extensions).join();\n  }\n\n  /**\n   * @type {Boolean}\n   */\n  get isPaused() {\n    return this._paused;\n  }\n\n  /**\n   * @type {Function}\n   */\n  /* istanbul ignore next */\n  get onclose() {\n    return null;\n  }\n\n  /**\n   * @type {Function}\n   */\n  /* istanbul ignore next */\n  get onerror() {\n    return null;\n  }\n\n  /**\n   * @type {Function}\n   */\n  /* istanbul ignore next */\n  get onopen() {\n    return null;\n  }\n\n  /**\n   * @type {Function}\n   */\n  /* istanbul ignore next */\n  get onmessage() {\n    return null;\n  }\n\n  /**\n   * @type {String}\n   */\n  get protocol() {\n    return this._protocol;\n  }\n\n  /**\n   * @type {Number}\n   */\n  get readyState() {\n    return this._readyState;\n  }\n\n  /**\n   * @type {String}\n   */\n  get url() {\n    return this._url;\n  }\n\n  /**\n   * Set up the socket and the internal resources.\n   *\n   * @param {Duplex} socket The network socket between the server and client\n   * @param {Buffer} head The first packet of the upgraded stream\n   * @param {Object} options Options object\n   * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n   *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n   *     multiple times in the same tick\n   * @param {Function} [options.generateMask] The function used to generate the\n   *     masking key\n   * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n   *     buffered data chunks\n   * @param {Number} [options.maxFragments=0] The maximum number of message\n   *     fragments\n   * @param {Number} [options.maxPayload=0] The maximum allowed message size\n   * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n   *     not to skip UTF-8 validation for text and close messages\n   * @private\n   */\n  setSocket(socket, head, options) {\n    const receiver = new Receiver({\n      allowSynchronousEvents: options.allowSynchronousEvents,\n      binaryType: this.binaryType,\n      extensions: this._extensions,\n      isServer: this._isServer,\n      maxBufferedChunks: options.maxBufferedChunks,\n      maxFragments: options.maxFragments,\n      maxPayload: options.maxPayload,\n      skipUTF8Validation: options.skipUTF8Validation\n    });\n\n    const sender = new Sender(socket, this._extensions, options.generateMask);\n\n    this._receiver = receiver;\n    this._sender = sender;\n    this._socket = socket;\n\n    receiver[kWebSocket] = this;\n    sender[kWebSocket] = this;\n    socket[kWebSocket] = this;\n\n    receiver.on('conclude', receiverOnConclude);\n    receiver.on('drain', receiverOnDrain);\n    receiver.on('error', receiverOnError);\n    receiver.on('message', receiverOnMessage);\n    receiver.on('ping', receiverOnPing);\n    receiver.on('pong', receiverOnPong);\n\n    sender.onerror = senderOnError;\n\n    //\n    // These methods may not be available if `socket` is just a `Duplex`.\n    //\n    if (socket.setTimeout) socket.setTimeout(0);\n    if (socket.setNoDelay) socket.setNoDelay();\n\n    if (head.length > 0) socket.unshift(head);\n\n    socket.on('close', socketOnClose);\n    socket.on('data', socketOnData);\n    socket.on('end', socketOnEnd);\n    socket.on('error', socketOnError);\n\n    this._readyState = WebSocket.OPEN;\n    this.emit('open');\n  }\n\n  /**\n   * Emit the `'close'` event.\n   *\n   * @private\n   */\n  emitClose() {\n    if (!this._socket) {\n      this._readyState = WebSocket.CLOSED;\n      this.emit('close', this._closeCode, this._closeMessage);\n      return;\n    }\n\n    if (this._extensions[PerMessageDeflate.extensionName]) {\n      this._extensions[PerMessageDeflate.extensionName].cleanup();\n    }\n\n    this._receiver.removeAllListeners();\n    this._readyState = WebSocket.CLOSED;\n    this.emit('close', this._closeCode, this._closeMessage);\n  }\n\n  /**\n   * Start a closing handshake.\n   *\n   *          +----------+   +-----------+   +----------+\n   *     - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n   *    |     +----------+   +-----------+   +----------+     |\n   *          +----------+   +-----------+         |\n   * CLOSING  |ws.close()|<--|close frame|<--+-----+       CLOSING\n   *          +----------+   +-----------+   |\n   *    |           |                        |   +---+        |\n   *                +------------------------+-->|fin| - - - -\n   *    |         +---+                      |   +---+\n   *     - - - - -|fin|<---------------------+\n   *              +---+\n   *\n   * @param {Number} [code] Status code explaining why the connection is closing\n   * @param {(String|Buffer)} [data] The reason why the connection is\n   *     closing\n   * @public\n   */\n  close(code, data) {\n    if (this.readyState === WebSocket.CLOSED) return;\n    if (this.readyState === WebSocket.CONNECTING) {\n      const msg = 'WebSocket was closed before the connection was established';\n      abortHandshake(this, this._req, msg);\n      return;\n    }\n\n    if (this.readyState === WebSocket.CLOSING) {\n      if (\n        this._closeFrameSent &&\n        (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n      ) {\n        this._socket.end();\n      }\n\n      return;\n    }\n\n    this._readyState = WebSocket.CLOSING;\n    this._sender.close(code, data, !this._isServer, (err) => {\n      //\n      // This error is handled by the `'error'` listener on the socket. We only\n      // want to know if the close frame has been sent here.\n      //\n      if (err) return;\n\n      this._closeFrameSent = true;\n\n      if (\n        this._closeFrameReceived ||\n        this._receiver._writableState.errorEmitted\n      ) {\n        this._socket.end();\n      }\n    });\n\n    setCloseTimer(this);\n  }\n\n  /**\n   * Pause the socket.\n   *\n   * @public\n   */\n  pause() {\n    if (\n      this.readyState === WebSocket.CONNECTING ||\n      this.readyState === WebSocket.CLOSED\n    ) {\n      return;\n    }\n\n    this._paused = true;\n    this._socket.pause();\n  }\n\n  /**\n   * Send a ping.\n   *\n   * @param {*} [data] The data to send\n   * @param {Boolean} [mask] Indicates whether or not to mask `data`\n   * @param {Function} [cb] Callback which is executed when the ping is sent\n   * @public\n   */\n  ping(data, mask, cb) {\n    if (this.readyState === WebSocket.CONNECTING) {\n      throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n    }\n\n    if (typeof data === 'function') {\n      cb = data;\n      data = mask = undefined;\n    } else if (typeof mask === 'function') {\n      cb = mask;\n      mask = undefined;\n    }\n\n    if (typeof data === 'number') data = data.toString();\n\n    if (this.readyState !== WebSocket.OPEN) {\n      sendAfterClose(this, data, cb);\n      return;\n    }\n\n    if (mask === undefined) mask = !this._isServer;\n    this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n  }\n\n  /**\n   * Send a pong.\n   *\n   * @param {*} [data] The data to send\n   * @param {Boolean} [mask] Indicates whether or not to mask `data`\n   * @param {Function} [cb] Callback which is executed when the pong is sent\n   * @public\n   */\n  pong(data, mask, cb) {\n    if (this.readyState === WebSocket.CONNECTING) {\n      throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n    }\n\n    if (typeof data === 'function') {\n      cb = data;\n      data = mask = undefined;\n    } else if (typeof mask === 'function') {\n      cb = mask;\n      mask = undefined;\n    }\n\n    if (typeof data === 'number') data = data.toString();\n\n    if (this.readyState !== WebSocket.OPEN) {\n      sendAfterClose(this, data, cb);\n      return;\n    }\n\n    if (mask === undefined) mask = !this._isServer;\n    this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n  }\n\n  /**\n   * Resume the socket.\n   *\n   * @public\n   */\n  resume() {\n    if (\n      this.readyState === WebSocket.CONNECTING ||\n      this.readyState === WebSocket.CLOSED\n    ) {\n      return;\n    }\n\n    this._paused = false;\n    if (!this._receiver._writableState.needDrain) this._socket.resume();\n  }\n\n  /**\n   * Send a data message.\n   *\n   * @param {*} data The message to send\n   * @param {Object} [options] Options object\n   * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n   *     text\n   * @param {Boolean} [options.compress] Specifies whether or not to compress\n   *     `data`\n   * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n   *     last one\n   * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n   * @param {Function} [cb] Callback which is executed when data is written out\n   * @public\n   */\n  send(data, options, cb) {\n    if (this.readyState === WebSocket.CONNECTING) {\n      throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n    }\n\n    if (typeof options === 'function') {\n      cb = options;\n      options = {};\n    }\n\n    if (typeof data === 'number') data = data.toString();\n\n    if (this.readyState !== WebSocket.OPEN) {\n      sendAfterClose(this, data, cb);\n      return;\n    }\n\n    const opts = {\n      binary: typeof data !== 'string',\n      mask: !this._isServer,\n      compress: true,\n      fin: true,\n      ...options\n    };\n\n    if (!this._extensions[PerMessageDeflate.extensionName]) {\n      opts.compress = false;\n    }\n\n    this._sender.send(data || EMPTY_BUFFER, opts, cb);\n  }\n\n  /**\n   * Forcibly close the connection.\n   *\n   * @public\n   */\n  terminate() {\n    if (this.readyState === WebSocket.CLOSED) return;\n    if (this.readyState === WebSocket.CONNECTING) {\n      const msg = 'WebSocket was closed before the connection was established';\n      abortHandshake(this, this._req, msg);\n      return;\n    }\n\n    if (this._socket) {\n      this._readyState = WebSocket.CLOSING;\n      this._socket.destroy();\n    }\n  }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n  enumerable: true,\n  value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n  enumerable: true,\n  value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n  enumerable: true,\n  value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n  enumerable: true,\n  value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n  enumerable: true,\n  value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n  enumerable: true,\n  value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n  enumerable: true,\n  value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n  enumerable: true,\n  value: readyStates.indexOf('CLOSED')\n});\n\n[\n  'binaryType',\n  'bufferedAmount',\n  'extensions',\n  'isPaused',\n  'protocol',\n  'readyState',\n  'url'\n].forEach((property) => {\n  Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n  Object.defineProperty(WebSocket.prototype, `on${method}`, {\n    enumerable: true,\n    get() {\n      for (const listener of this.listeners(method)) {\n        if (listener[kForOnEventAttribute]) return listener[kListener];\n      }\n\n      return null;\n    },\n    set(handler) {\n      for (const listener of this.listeners(method)) {\n        if (listener[kForOnEventAttribute]) {\n          this.removeListener(method, listener);\n          break;\n        }\n      }\n\n      if (typeof handler !== 'function') return;\n\n      this.addEventListener(method, handler, {\n        [kForOnEventAttribute]: true\n      });\n    }\n  });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n *     of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n *     times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n *     automatically send a pong in response to a ping\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n *     for the closing handshake to finish after `websocket.close()` is called\n * @param {Function} [options.finishRequest] A function which can be used to\n *     customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n *     redirects\n * @param {Function} [options.generateMask] The function used to generate the\n *     masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n *     handshake request\n * @param {Number} [options.maxBufferedChunks=262144] The maximum number of\n *     buffered data chunks\n * @param {Number} [options.maxFragments=16384] The maximum number of message\n *     fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n *     size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n *     allowed\n * @param {String} [options.origin] Value of the `Origin` or\n *     `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n *     permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n *     `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n *     not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n  const opts = {\n    allowSynchronousEvents: true,\n    autoPong: true,\n    closeTimeout: CLOSE_TIMEOUT,\n    protocolVersion: protocolVersions[1],\n    maxBufferedChunks: 256 * 1024,\n    maxFragments: 16 * 1024,\n    maxPayload: 100 * 1024 * 1024,\n    skipUTF8Validation: false,\n    perMessageDeflate: true,\n    followRedirects: false,\n    maxRedirects: 10,\n    ...options,\n    socketPath: undefined,\n    hostname: undefined,\n    protocol: undefined,\n    timeout: undefined,\n    method: 'GET',\n    host: undefined,\n    path: undefined,\n    port: undefined\n  };\n\n  websocket._autoPong = opts.autoPong;\n  websocket._closeTimeout = opts.closeTimeout;\n\n  if (!protocolVersions.includes(opts.protocolVersion)) {\n    throw new RangeError(\n      `Unsupported protocol version: ${opts.protocolVersion} ` +\n        `(supported versions: ${protocolVersions.join(', ')})`\n    );\n  }\n\n  let parsedUrl;\n\n  if (address instanceof URL) {\n    parsedUrl = address;\n  } else {\n    try {\n      parsedUrl = new URL(address);\n    } catch {\n      throw new SyntaxError(`Invalid URL: ${address}`);\n    }\n  }\n\n  if (parsedUrl.protocol === 'http:') {\n    parsedUrl.protocol = 'ws:';\n  } else if (parsedUrl.protocol === 'https:') {\n    parsedUrl.protocol = 'wss:';\n  }\n\n  websocket._url = parsedUrl.href;\n\n  const isSecure = parsedUrl.protocol === 'wss:';\n  const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n  let invalidUrlMessage;\n\n  if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n    invalidUrlMessage =\n      'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n      '\"http:\", \"https:\", or \"ws+unix:\"';\n  } else if (isIpcUrl && !parsedUrl.pathname) {\n    invalidUrlMessage = \"The URL's pathname is empty\";\n  } else if (parsedUrl.hash) {\n    invalidUrlMessage = 'The URL contains a fragment identifier';\n  }\n\n  if (invalidUrlMessage) {\n    const err = new SyntaxError(invalidUrlMessage);\n\n    if (websocket._redirects === 0) {\n      throw err;\n    } else {\n      emitErrorAndClose(websocket, err);\n      return;\n    }\n  }\n\n  const defaultPort = isSecure ? 443 : 80;\n  const key = randomBytes(16).toString('base64');\n  const request = isSecure ? https.request : http.request;\n  const protocolSet = new Set();\n  let perMessageDeflate;\n\n  opts.createConnection =\n    opts.createConnection || (isSecure ? tlsConnect : netConnect);\n  opts.defaultPort = opts.defaultPort || defaultPort;\n  opts.port = parsedUrl.port || defaultPort;\n  opts.host = parsedUrl.hostname.startsWith('[')\n    ? parsedUrl.hostname.slice(1, -1)\n    : parsedUrl.hostname;\n  opts.headers = {\n    ...opts.headers,\n    'Sec-WebSocket-Version': opts.protocolVersion,\n    'Sec-WebSocket-Key': key,\n    Connection: 'Upgrade',\n    Upgrade: 'websocket'\n  };\n  opts.path = parsedUrl.pathname + parsedUrl.search;\n  opts.timeout = opts.handshakeTimeout;\n\n  if (opts.perMessageDeflate) {\n    perMessageDeflate = new PerMessageDeflate({\n      ...opts.perMessageDeflate,\n      isServer: false,\n      maxPayload: opts.maxPayload\n    });\n    opts.headers['Sec-WebSocket-Extensions'] = format({\n      [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n    });\n  }\n  if (protocols.length) {\n    for (const protocol of protocols) {\n      if (\n        typeof protocol !== 'string' ||\n        !subprotocolRegex.test(protocol) ||\n        protocolSet.has(protocol)\n      ) {\n        throw new SyntaxError(\n          'An invalid or duplicated subprotocol was specified'\n        );\n      }\n\n      protocolSet.add(protocol);\n    }\n\n    opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n  }\n  if (opts.origin) {\n    if (opts.protocolVersion < 13) {\n      opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n    } else {\n      opts.headers.Origin = opts.origin;\n    }\n  }\n  if (parsedUrl.username || parsedUrl.password) {\n    opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n  }\n\n  if (isIpcUrl) {\n    const parts = opts.path.split(':');\n\n    opts.socketPath = parts[0];\n    opts.path = parts[1];\n  }\n\n  let req;\n\n  if (opts.followRedirects) {\n    if (websocket._redirects === 0) {\n      websocket._originalIpc = isIpcUrl;\n      websocket._originalSecure = isSecure;\n      websocket._originalHostOrSocketPath = isIpcUrl\n        ? opts.socketPath\n        : parsedUrl.host;\n\n      const headers = options && options.headers;\n\n      //\n      // Shallow copy the user provided options so that headers can be changed\n      // without mutating the original object.\n      //\n      options = { ...options, headers: {} };\n\n      if (headers) {\n        for (const [key, value] of Object.entries(headers)) {\n          options.headers[key.toLowerCase()] = value;\n        }\n      }\n    } else if (websocket.listenerCount('redirect') === 0) {\n      const isSameHost = isIpcUrl\n        ? websocket._originalIpc\n          ? opts.socketPath === websocket._originalHostOrSocketPath\n          : false\n        : websocket._originalIpc\n          ? false\n          : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n      if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n        //\n        // Match curl 7.77.0 behavior and drop the following headers. These\n        // headers are also dropped when following a redirect to a subdomain.\n        //\n        delete opts.headers.authorization;\n        delete opts.headers.cookie;\n\n        if (!isSameHost) delete opts.headers.host;\n\n        opts.auth = undefined;\n      }\n    }\n\n    //\n    // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n    // If the `Authorization` header is set, then there is nothing to do as it\n    // will take precedence.\n    //\n    if (opts.auth && !options.headers.authorization) {\n      options.headers.authorization =\n        'Basic ' + Buffer.from(opts.auth).toString('base64');\n    }\n\n    req = websocket._req = request(opts);\n\n    if (websocket._redirects) {\n      //\n      // Unlike what is done for the `'upgrade'` event, no early exit is\n      // triggered here if the user calls `websocket.close()` or\n      // `websocket.terminate()` from a listener of the `'redirect'` event. This\n      // is because the user can also call `request.destroy()` with an error\n      // before calling `websocket.close()` or `websocket.terminate()` and this\n      // would result in an error being emitted on the `request` object with no\n      // `'error'` event listeners attached.\n      //\n      websocket.emit('redirect', websocket.url, req);\n    }\n  } else {\n    req = websocket._req = request(opts);\n  }\n\n  if (opts.timeout) {\n    req.on('timeout', () => {\n      abortHandshake(websocket, req, 'Opening handshake has timed out');\n    });\n  }\n\n  req.on('error', (err) => {\n    if (req === null || req[kAborted]) return;\n\n    req = websocket._req = null;\n    emitErrorAndClose(websocket, err);\n  });\n\n  req.on('response', (res) => {\n    const location = res.headers.location;\n    const statusCode = res.statusCode;\n\n    if (\n      location &&\n      opts.followRedirects &&\n      statusCode >= 300 &&\n      statusCode < 400\n    ) {\n      if (++websocket._redirects > opts.maxRedirects) {\n        abortHandshake(websocket, req, 'Maximum redirects exceeded');\n        return;\n      }\n\n      req.abort();\n\n      let addr;\n\n      try {\n        addr = new URL(location, address);\n      } catch (e) {\n        const err = new SyntaxError(`Invalid URL: ${location}`);\n        emitErrorAndClose(websocket, err);\n        return;\n      }\n\n      initAsClient(websocket, addr, protocols, options);\n    } else if (!websocket.emit('unexpected-response', req, res)) {\n      abortHandshake(\n        websocket,\n        req,\n        `Unexpected server response: ${res.statusCode}`\n      );\n    }\n  });\n\n  req.on('upgrade', (res, socket, head) => {\n    websocket.emit('upgrade', res);\n\n    //\n    // The user may have closed the connection from a listener of the\n    // `'upgrade'` event.\n    //\n    if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n    req = websocket._req = null;\n\n    const upgrade = res.headers.upgrade;\n\n    if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n      abortHandshake(websocket, socket, 'Invalid Upgrade header');\n      return;\n    }\n\n    const digest = createHash('sha1')\n      .update(key + GUID)\n      .digest('base64');\n\n    if (res.headers['sec-websocket-accept'] !== digest) {\n      abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n      return;\n    }\n\n    const serverProt = res.headers['sec-websocket-protocol'];\n    let protError;\n\n    if (serverProt !== undefined) {\n      if (!protocolSet.size) {\n        protError = 'Server sent a subprotocol but none was requested';\n      } else if (!protocolSet.has(serverProt)) {\n        protError = 'Server sent an invalid subprotocol';\n      }\n    } else if (protocolSet.size) {\n      protError = 'Server sent no subprotocol';\n    }\n\n    if (protError) {\n      abortHandshake(websocket, socket, protError);\n      return;\n    }\n\n    if (serverProt) websocket._protocol = serverProt;\n\n    const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n    if (secWebSocketExtensions !== undefined) {\n      if (!perMessageDeflate) {\n        const message =\n          'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n          'was requested';\n        abortHandshake(websocket, socket, message);\n        return;\n      }\n\n      let extensions;\n\n      try {\n        extensions = parse(secWebSocketExtensions);\n      } catch (err) {\n        const message = 'Invalid Sec-WebSocket-Extensions header';\n        abortHandshake(websocket, socket, message);\n        return;\n      }\n\n      const extensionNames = Object.keys(extensions);\n\n      if (\n        extensionNames.length !== 1 ||\n        extensionNames[0] !== PerMessageDeflate.extensionName\n      ) {\n        const message = 'Server indicated an extension that was not requested';\n        abortHandshake(websocket, socket, message);\n        return;\n      }\n\n      try {\n        perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n      } catch (err) {\n        const message = 'Invalid Sec-WebSocket-Extensions header';\n        abortHandshake(websocket, socket, message);\n        return;\n      }\n\n      websocket._extensions[PerMessageDeflate.extensionName] =\n        perMessageDeflate;\n    }\n\n    websocket.setSocket(socket, head, {\n      allowSynchronousEvents: opts.allowSynchronousEvents,\n      generateMask: opts.generateMask,\n      maxBufferedChunks: opts.maxBufferedChunks,\n      maxFragments: opts.maxFragments,\n      maxPayload: opts.maxPayload,\n      skipUTF8Validation: opts.skipUTF8Validation\n    });\n  });\n\n  if (opts.finishRequest) {\n    opts.finishRequest(req, websocket);\n  } else {\n    req.end();\n  }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n  websocket._readyState = WebSocket.CLOSING;\n  //\n  // The following assignment is practically useless and is done only for\n  // consistency.\n  //\n  websocket._errorEmitted = true;\n  websocket.emit('error', err);\n  websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n  options.path = options.socketPath;\n  return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n  options.path = undefined;\n\n  if (!options.servername && options.servername !== '') {\n    options.servername = net.isIP(options.host) ? '' : options.host;\n  }\n\n  return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n *     abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n  websocket._readyState = WebSocket.CLOSING;\n\n  const err = new Error(message);\n  Error.captureStackTrace(err, abortHandshake);\n\n  if (stream.setHeader) {\n    stream[kAborted] = true;\n    stream.abort();\n\n    if (stream.socket && !stream.socket.destroyed) {\n      //\n      // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n      // called after the request completed. See\n      // https://github.com/websockets/ws/issues/1869.\n      //\n      stream.socket.destroy();\n    }\n\n    process.nextTick(emitErrorAndClose, websocket, err);\n  } else {\n    stream.destroy(err);\n    stream.once('error', websocket.emit.bind(websocket, 'error'));\n    stream.once('close', websocket.emitClose.bind(websocket));\n  }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n  if (data) {\n    const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n    //\n    // The `_bufferedAmount` property is used only when the peer is a client and\n    // the opening handshake fails. Under these circumstances, in fact, the\n    // `setSocket()` method is not called, so the `_socket` and `_sender`\n    // properties are set to `null`.\n    //\n    if (websocket._socket) websocket._sender._bufferedBytes += length;\n    else websocket._bufferedAmount += length;\n  }\n\n  if (cb) {\n    const err = new Error(\n      `WebSocket is not open: readyState ${websocket.readyState} ` +\n        `(${readyStates[websocket.readyState]})`\n    );\n    process.nextTick(cb, err);\n  }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n  const websocket = this[kWebSocket];\n\n  websocket._closeFrameReceived = true;\n  websocket._closeMessage = reason;\n  websocket._closeCode = code;\n\n  if (websocket._socket[kWebSocket] === undefined) return;\n\n  websocket._socket.removeListener('data', socketOnData);\n  process.nextTick(resume, websocket._socket);\n\n  if (code === 1005) websocket.close();\n  else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n  const websocket = this[kWebSocket];\n\n  if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n  const websocket = this[kWebSocket];\n\n  if (websocket._socket[kWebSocket] !== undefined) {\n    websocket._socket.removeListener('data', socketOnData);\n\n    //\n    // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n    // https://github.com/websockets/ws/issues/1940.\n    //\n    process.nextTick(resume, websocket._socket);\n\n    websocket.close(err[kStatusCode]);\n  }\n\n  if (!websocket._errorEmitted) {\n    websocket._errorEmitted = true;\n    websocket.emit('error', err);\n  }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n  this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n  this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n  const websocket = this[kWebSocket];\n\n  if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n  websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n  this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n  stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n  const websocket = this[kWebSocket];\n\n  if (websocket.readyState === WebSocket.CLOSED) return;\n  if (websocket.readyState === WebSocket.OPEN) {\n    websocket._readyState = WebSocket.CLOSING;\n    setCloseTimer(websocket);\n  }\n\n  //\n  // `socket.end()` is used instead of `socket.destroy()` to allow the other\n  // peer to finish sending queued data. There is no need to set a timer here\n  // because `CLOSING` means that it is already set or not needed.\n  //\n  this._socket.end();\n\n  if (!websocket._errorEmitted) {\n    websocket._errorEmitted = true;\n    websocket.emit('error', err);\n  }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n  websocket._closeTimer = setTimeout(\n    websocket._socket.destroy.bind(websocket._socket),\n    websocket._closeTimeout\n  );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n  const websocket = this[kWebSocket];\n\n  this.removeListener('close', socketOnClose);\n  this.removeListener('data', socketOnData);\n  this.removeListener('end', socketOnEnd);\n\n  websocket._readyState = WebSocket.CLOSING;\n\n  //\n  // The close frame might not have been received or the `'end'` event emitted,\n  // for example, if the socket was destroyed due to an error. Ensure that the\n  // `receiver` stream is closed after writing any remaining buffered data to\n  // it. If the readable side of the socket is in flowing mode then there is no\n  // buffered data as everything has been already written. If instead, the\n  // socket is paused, any possible buffered data will be read as a single\n  // chunk.\n  //\n  if (\n    !this._readableState.endEmitted &&\n    !websocket._closeFrameReceived &&\n    !websocket._receiver._writableState.errorEmitted &&\n    this._readableState.length !== 0\n  ) {\n    const chunk = this.read(this._readableState.length);\n\n    websocket._receiver.write(chunk);\n  }\n\n  websocket._receiver.end();\n\n  this[kWebSocket] = undefined;\n\n  clearTimeout(websocket._closeTimer);\n\n  if (\n    websocket._receiver._writableState.finished ||\n    websocket._receiver._writableState.errorEmitted\n  ) {\n    websocket.emitClose();\n  } else {\n    websocket._receiver.on('error', receiverOnFinish);\n    websocket._receiver.on('finish', receiverOnFinish);\n  }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n  if (!this[kWebSocket]._receiver.write(chunk)) {\n    this.pause();\n  }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n  const websocket = this[kWebSocket];\n\n  websocket._readyState = WebSocket.CLOSING;\n  websocket._receiver.end();\n  this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n  const websocket = this[kWebSocket];\n\n  this.removeListener('error', socketOnError);\n  this.on('error', NOOP);\n\n  if (websocket) {\n    websocket._readyState = WebSocket.CLOSING;\n    this.destroy();\n  }\n}\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n  stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n  if (!this.destroyed && this._writableState.finished) {\n    this.destroy();\n  }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n  this.removeListener('error', duplexOnError);\n  this.destroy();\n  if (this.listenerCount('error') === 0) {\n    // Do not suppress the throwing behavior.\n    this.emit('error', err);\n  }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n  let terminateOnDestroy = true;\n\n  const duplex = new Duplex({\n    ...options,\n    autoDestroy: false,\n    emitClose: false,\n    objectMode: false,\n    writableObjectMode: false\n  });\n\n  ws.on('message', function message(msg, isBinary) {\n    const data =\n      !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n    if (!duplex.push(data)) ws.pause();\n  });\n\n  ws.once('error', function error(err) {\n    if (duplex.destroyed) return;\n\n    // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n    //\n    // - If the `'error'` event is emitted before the `'open'` event, then\n    //   `ws.terminate()` is a noop as no socket is assigned.\n    // - Otherwise, the error is re-emitted by the listener of the `'error'`\n    //   event of the `Receiver` object. The listener already closes the\n    //   connection by calling `ws.close()`. This allows a close frame to be\n    //   sent to the other peer. If `ws.terminate()` is called right after this,\n    //   then the close frame might not be sent.\n    terminateOnDestroy = false;\n    duplex.destroy(err);\n  });\n\n  ws.once('close', function close() {\n    if (duplex.destroyed) return;\n\n    duplex.push(null);\n  });\n\n  duplex._destroy = function (err, callback) {\n    if (ws.readyState === ws.CLOSED) {\n      callback(err);\n      process.nextTick(emitClose, duplex);\n      return;\n    }\n\n    let called = false;\n\n    ws.once('error', function error(err) {\n      called = true;\n      callback(err);\n    });\n\n    ws.once('close', function close() {\n      if (!called) callback(err);\n      process.nextTick(emitClose, duplex);\n    });\n\n    if (terminateOnDestroy) ws.terminate();\n  };\n\n  duplex._final = function (callback) {\n    if (ws.readyState === ws.CONNECTING) {\n      ws.once('open', function open() {\n        duplex._final(callback);\n      });\n      return;\n    }\n\n    // If the value of the `_socket` property is `null` it means that `ws` is a\n    // client websocket and the handshake failed. In fact, when this happens, a\n    // socket is never assigned to the websocket. Wait for the `'error'` event\n    // that will be emitted by the websocket.\n    if (ws._socket === null) return;\n\n    if (ws._socket._writableState.finished) {\n      callback();\n      if (duplex._readableState.endEmitted) duplex.destroy();\n    } else {\n      ws._socket.once('finish', function finish() {\n        // `duplex` is not destroyed here because the `'end'` event will be\n        // emitted on `duplex` after this `'finish'` event. The EOF signaling\n        // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n        callback();\n      });\n      ws.close();\n    }\n  };\n\n  duplex._read = function () {\n    if (ws.isPaused) ws.resume();\n  };\n\n  duplex._write = function (chunk, encoding, callback) {\n    if (ws.readyState === ws.CONNECTING) {\n      ws.once('open', function open() {\n        duplex._write(chunk, encoding, callback);\n      });\n      return;\n    }\n\n    ws.send(chunk, callback);\n  };\n\n  duplex.on('end', duplexOnEnd);\n  duplex.on('error', duplexOnError);\n  return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n  const protocols = new Set();\n  let start = -1;\n  let end = -1;\n  let i = 0;\n\n  for (i; i < header.length; i++) {\n    const code = header.charCodeAt(i);\n\n    if (end === -1 && tokenChars[code] === 1) {\n      if (start === -1) start = i;\n    } else if (\n      i !== 0 &&\n      (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n    ) {\n      if (end === -1 && start !== -1) end = i;\n    } else if (code === 0x2c /* ',' */) {\n      if (start === -1) {\n        throw new SyntaxError(`Unexpected character at index ${i}`);\n      }\n\n      if (end === -1) end = i;\n\n      const protocol = header.slice(start, end);\n\n      if (protocols.has(protocol)) {\n        throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n      }\n\n      protocols.add(protocol);\n      start = end = -1;\n    } else {\n      throw new SyntaxError(`Unexpected character at index ${i}`);\n    }\n  }\n\n  if (start === -1 || end !== -1) {\n    throw new SyntaxError('Unexpected end of input');\n  }\n\n  const protocol = header.slice(start, i);\n\n  if (protocols.has(protocol)) {\n    throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n  }\n\n  protocols.add(protocol);\n  return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n  /**\n   * Create a `WebSocketServer` instance.\n   *\n   * @param {Object} options Configuration options\n   * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n   *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n   *     multiple times in the same tick\n   * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n   *     automatically send a pong in response to a ping\n   * @param {Number} [options.backlog=511] The maximum length of the queue of\n   *     pending connections\n   * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n   *     track clients\n   * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to\n   *     wait for the closing handshake to finish after `websocket.close()` is\n   *     called\n   * @param {Function} [options.handleProtocols] A hook to handle protocols\n   * @param {String} [options.host] The hostname where to bind the server\n   * @param {Number} [options.maxBufferedChunks=262144] The maximum number of\n   *     buffered data chunks\n   * @param {Number} [options.maxFragments=16384] The maximum number of message\n   *     fragments\n   * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n   *     size\n   * @param {Boolean} [options.noServer=false] Enable no server mode\n   * @param {String} [options.path] Accept only connections matching this path\n   * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n   *     permessage-deflate\n   * @param {Number} [options.port] The port where to bind the server\n   * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n   *     server to use\n   * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n   *     not to skip UTF-8 validation for text and close messages\n   * @param {Function} [options.verifyClient] A hook to reject connections\n   * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n   *     class to use. It must be the `WebSocket` class or class that extends it\n   * @param {Function} [callback] A listener for the `listening` event\n   */\n  constructor(options, callback) {\n    super();\n\n    options = {\n      allowSynchronousEvents: true,\n      autoPong: true,\n      maxBufferedChunks: 256 * 1024,\n      maxFragments: 16 * 1024,\n      maxPayload: 100 * 1024 * 1024,\n      skipUTF8Validation: false,\n      perMessageDeflate: false,\n      handleProtocols: null,\n      clientTracking: true,\n      closeTimeout: CLOSE_TIMEOUT,\n      verifyClient: null,\n      noServer: false,\n      backlog: null, // use default (511 as implemented in net.js)\n      server: null,\n      host: null,\n      path: null,\n      port: null,\n      WebSocket,\n      ...options\n    };\n\n    if (\n      (options.port == null && !options.server && !options.noServer) ||\n      (options.port != null && (options.server || options.noServer)) ||\n      (options.server && options.noServer)\n    ) {\n      throw new TypeError(\n        'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n          'must be specified'\n      );\n    }\n\n    if (options.port != null) {\n      this._server = http.createServer((req, res) => {\n        const body = http.STATUS_CODES[426];\n\n        res.writeHead(426, {\n          'Content-Length': body.length,\n          'Content-Type': 'text/plain'\n        });\n        res.end(body);\n      });\n      this._server.listen(\n        options.port,\n        options.host,\n        options.backlog,\n        callback\n      );\n    } else if (options.server) {\n      this._server = options.server;\n    }\n\n    if (this._server) {\n      const emitConnection = this.emit.bind(this, 'connection');\n\n      this._removeListeners = addListeners(this._server, {\n        listening: this.emit.bind(this, 'listening'),\n        error: this.emit.bind(this, 'error'),\n        upgrade: (req, socket, head) => {\n          this.handleUpgrade(req, socket, head, emitConnection);\n        }\n      });\n    }\n\n    if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n    if (options.clientTracking) {\n      this.clients = new Set();\n      this._shouldEmitClose = false;\n    }\n\n    this.options = options;\n    this._state = RUNNING;\n  }\n\n  /**\n   * Returns the bound address, the address family name, and port of the server\n   * as reported by the operating system if listening on an IP socket.\n   * If the server is listening on a pipe or UNIX domain socket, the name is\n   * returned as a string.\n   *\n   * @return {(Object|String|null)} The address of the server\n   * @public\n   */\n  address() {\n    if (this.options.noServer) {\n      throw new Error('The server is operating in \"noServer\" mode');\n    }\n\n    if (!this._server) return null;\n    return this._server.address();\n  }\n\n  /**\n   * Stop the server from accepting new connections and emit the `'close'` event\n   * when all existing connections are closed.\n   *\n   * @param {Function} [cb] A one-time listener for the `'close'` event\n   * @public\n   */\n  close(cb) {\n    if (this._state === CLOSED) {\n      if (cb) {\n        this.once('close', () => {\n          cb(new Error('The server is not running'));\n        });\n      }\n\n      process.nextTick(emitClose, this);\n      return;\n    }\n\n    if (cb) this.once('close', cb);\n\n    if (this._state === CLOSING) return;\n    this._state = CLOSING;\n\n    if (this.options.noServer || this.options.server) {\n      if (this._server) {\n        this._removeListeners();\n        this._removeListeners = this._server = null;\n      }\n\n      if (this.clients) {\n        if (!this.clients.size) {\n          process.nextTick(emitClose, this);\n        } else {\n          this._shouldEmitClose = true;\n        }\n      } else {\n        process.nextTick(emitClose, this);\n      }\n    } else {\n      const server = this._server;\n\n      this._removeListeners();\n      this._removeListeners = this._server = null;\n\n      //\n      // The HTTP/S server was created internally. Close it, and rely on its\n      // `'close'` event.\n      //\n      server.close(() => {\n        emitClose(this);\n      });\n    }\n  }\n\n  /**\n   * See if a given request should be handled by this server instance.\n   *\n   * @param {http.IncomingMessage} req Request object to inspect\n   * @return {Boolean} `true` if the request is valid, else `false`\n   * @public\n   */\n  shouldHandle(req) {\n    if (this.options.path) {\n      const index = req.url.indexOf('?');\n      const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n      if (pathname !== this.options.path) return false;\n    }\n\n    return true;\n  }\n\n  /**\n   * Handle a HTTP Upgrade request.\n   *\n   * @param {http.IncomingMessage} req The request object\n   * @param {Duplex} socket The network socket between the server and client\n   * @param {Buffer} head The first packet of the upgraded stream\n   * @param {Function} cb Callback\n   * @public\n   */\n  handleUpgrade(req, socket, head, cb) {\n    socket.on('error', socketOnError);\n\n    const key = req.headers['sec-websocket-key'];\n    const upgrade = req.headers.upgrade;\n    const version = +req.headers['sec-websocket-version'];\n\n    if (req.method !== 'GET') {\n      const message = 'Invalid HTTP method';\n      abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n      return;\n    }\n\n    if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n      const message = 'Invalid Upgrade header';\n      abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n      return;\n    }\n\n    if (key === undefined || !keyRegex.test(key)) {\n      const message = 'Missing or invalid Sec-WebSocket-Key header';\n      abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n      return;\n    }\n\n    if (version !== 13 && version !== 8) {\n      const message = 'Missing or invalid Sec-WebSocket-Version header';\n      abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n        'Sec-WebSocket-Version': '13, 8'\n      });\n      return;\n    }\n\n    if (!this.shouldHandle(req)) {\n      abortHandshake(socket, 400);\n      return;\n    }\n\n    const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n    let protocols = new Set();\n\n    if (secWebSocketProtocol !== undefined) {\n      try {\n        protocols = subprotocol.parse(secWebSocketProtocol);\n      } catch (err) {\n        const message = 'Invalid Sec-WebSocket-Protocol header';\n        abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n        return;\n      }\n    }\n\n    const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n    const extensions = {};\n\n    if (\n      this.options.perMessageDeflate &&\n      secWebSocketExtensions !== undefined\n    ) {\n      const perMessageDeflate = new PerMessageDeflate({\n        ...this.options.perMessageDeflate,\n        isServer: true,\n        maxPayload: this.options.maxPayload\n      });\n\n      try {\n        const offers = extension.parse(secWebSocketExtensions);\n\n        if (offers[PerMessageDeflate.extensionName]) {\n          perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n          extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n        }\n      } catch (err) {\n        const message =\n          'Invalid or unacceptable Sec-WebSocket-Extensions header';\n        abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n        return;\n      }\n    }\n\n    //\n    // Optionally call external client verification handler.\n    //\n    if (this.options.verifyClient) {\n      const info = {\n        origin:\n          req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n        secure: !!(req.socket.authorized || req.socket.encrypted),\n        req\n      };\n\n      if (this.options.verifyClient.length === 2) {\n        this.options.verifyClient(info, (verified, code, message, headers) => {\n          if (!verified) {\n            return abortHandshake(socket, code || 401, message, headers);\n          }\n\n          this.completeUpgrade(\n            extensions,\n            key,\n            protocols,\n            req,\n            socket,\n            head,\n            cb\n          );\n        });\n        return;\n      }\n\n      if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n    }\n\n    this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n  }\n\n  /**\n   * Upgrade the connection to WebSocket.\n   *\n   * @param {Object} extensions The accepted extensions\n   * @param {String} key The value of the `Sec-WebSocket-Key` header\n   * @param {Set} protocols The subprotocols\n   * @param {http.IncomingMessage} req The request object\n   * @param {Duplex} socket The network socket between the server and client\n   * @param {Buffer} head The first packet of the upgraded stream\n   * @param {Function} cb Callback\n   * @throws {Error} If called more than once with the same socket\n   * @private\n   */\n  completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n    //\n    // Destroy the socket if the client has already sent a FIN packet.\n    //\n    if (!socket.readable || !socket.writable) return socket.destroy();\n\n    if (socket[kWebSocket]) {\n      throw new Error(\n        'server.handleUpgrade() was called more than once with the same ' +\n          'socket, possibly due to a misconfiguration'\n      );\n    }\n\n    if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n    const digest = createHash('sha1')\n      .update(key + GUID)\n      .digest('base64');\n\n    const headers = [\n      'HTTP/1.1 101 Switching Protocols',\n      'Upgrade: websocket',\n      'Connection: Upgrade',\n      `Sec-WebSocket-Accept: ${digest}`\n    ];\n\n    const ws = new this.options.WebSocket(null, undefined, this.options);\n\n    if (protocols.size) {\n      //\n      // Optionally call external protocol selection handler.\n      //\n      const protocol = this.options.handleProtocols\n        ? this.options.handleProtocols(protocols, req)\n        : protocols.values().next().value;\n\n      if (protocol) {\n        headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n        ws._protocol = protocol;\n      }\n    }\n\n    if (extensions[PerMessageDeflate.extensionName]) {\n      const params = extensions[PerMessageDeflate.extensionName].params;\n      const value = extension.format({\n        [PerMessageDeflate.extensionName]: [params]\n      });\n      headers.push(`Sec-WebSocket-Extensions: ${value}`);\n      ws._extensions = extensions;\n    }\n\n    //\n    // Allow external modification/inspection of handshake headers.\n    //\n    this.emit('headers', headers, req);\n\n    socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n    socket.removeListener('error', socketOnError);\n\n    ws.setSocket(socket, head, {\n      allowSynchronousEvents: this.options.allowSynchronousEvents,\n      maxBufferedChunks: this.options.maxBufferedChunks,\n      maxFragments: this.options.maxFragments,\n      maxPayload: this.options.maxPayload,\n      skipUTF8Validation: this.options.skipUTF8Validation\n    });\n\n    if (this.clients) {\n      this.clients.add(ws);\n      ws.on('close', () => {\n        this.clients.delete(ws);\n\n        if (this._shouldEmitClose && !this.clients.size) {\n          process.nextTick(emitClose, this);\n        }\n      });\n    }\n\n    cb(ws, req);\n  }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of <event, listener>\n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.<String, Function>} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n *     called\n * @private\n */\nfunction addListeners(server, map) {\n  for (const event of Object.keys(map)) server.on(event, map[event]);\n\n  return function removeListeners() {\n    for (const event of Object.keys(map)) {\n      server.removeListener(event, map[event]);\n    }\n  };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n  server._state = CLOSED;\n  server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n  this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n  //\n  // The socket is writable unless the user destroyed or ended it before calling\n  // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n  // error. Handling this does not make much sense as the worst that can happen\n  // is that some of the data written by the user might be discarded due to the\n  // call to `socket.end()` below, which triggers an `'error'` event that in\n  // turn causes the socket to be destroyed.\n  //\n  message = message || http.STATUS_CODES[code];\n  headers = {\n    Connection: 'close',\n    'Content-Type': 'text/html',\n    'Content-Length': Buffer.byteLength(message),\n    ...headers\n  };\n\n  socket.once('finish', socket.destroy);\n\n  socket.end(\n    `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n      Object.keys(headers)\n        .map((h) => `${h}: ${headers[h]}`)\n        .join('\\r\\n') +\n      '\\r\\n\\r\\n' +\n      message\n  );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n  server,\n  req,\n  socket,\n  code,\n  message,\n  headers\n) {\n  if (server.listenerCount('wsClientError')) {\n    const err = new Error(message);\n    Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n    server.emit('wsClientError', err, socket, req);\n  } else {\n    abortHandshake(socket, code, message, headers);\n  }\n}\n","import createWebSocketStream from './lib/stream.js';\nimport extension from './lib/extension.js';\nimport PerMessageDeflate from './lib/permessage-deflate.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport subprotocol from './lib/subprotocol.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport {\n  createWebSocketStream,\n  extension,\n  PerMessageDeflate,\n  Receiver,\n  Sender,\n  subprotocol,\n  WebSocket,\n  WebSocketServer\n};\n\nexport default WebSocket;\n","'use strict'\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n  'major',\n  'premajor',\n  'minor',\n  'preminor',\n  'patch',\n  'prepatch',\n  'prerelease',\n]\n\nmodule.exports = {\n  MAX_LENGTH,\n  MAX_SAFE_COMPONENT_LENGTH,\n  MAX_SAFE_BUILD_LENGTH,\n  MAX_SAFE_INTEGER,\n  RELEASE_TYPES,\n  SEMVER_SPEC_VERSION,\n  FLAG_INCLUDE_PRERELEASE: 0b001,\n  FLAG_LOOSE: 0b010,\n}\n","'use strict'\n\nconst debug = (\n  typeof process === 'object' &&\n  process.env &&\n  process.env.NODE_DEBUG &&\n  /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n  : () => {}\n\nmodule.exports = debug\n","'use strict'\n\nconst {\n  MAX_SAFE_COMPONENT_LENGTH,\n  MAX_SAFE_BUILD_LENGTH,\n  MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n  ['\\\\s', 1],\n  ['\\\\d', MAX_LENGTH],\n  [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n  for (const [token, max] of safeRegexReplacements) {\n    value = value\n      .split(`${token}*`).join(`${token}{0,${max}}`)\n      .split(`${token}+`).join(`${token}{1,${max}}`)\n  }\n  return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n  const safe = makeSafeRegex(value)\n  const index = R++\n  debug(name, index, value)\n  t[name] = index\n  src[index] = value\n  safeSrc[index] = safe\n  re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n  safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n                   `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n                   `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n                        `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n                        `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n// Non-numeric identifiers include numeric identifiers but can be longer.\n// Therefore non-numeric identifiers must go first.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]\n}|${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups.  The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n  src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n  src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifier, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n                   `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n                   `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n                   `(?:${src[t.PRERELEASE]})?${\n                     src[t.BUILD]}?` +\n                   `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n                        `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n                        `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n                        `(?:${src[t.PRERELEASELOOSE]})?${\n                          src[t.BUILD]}?` +\n                        `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n              '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n              `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n              `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n              `(?:${src[t.PRERELEASE]})?` +\n              `(?:${src[t.BUILD]})?` +\n              `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n                   `\\\\s+-\\\\s+` +\n                   `(${src[t.XRANGEPLAIN]})` +\n                   `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n                        `\\\\s+-\\\\s+` +\n                        `(${src[t.XRANGEPLAINLOOSE]})` +\n                        `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n","'use strict'\n\n// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n  if (!options) {\n    return emptyOpts\n  }\n\n  if (typeof options !== 'object') {\n    return looseOption\n  }\n\n  return options\n}\nmodule.exports = parseOptions\n","'use strict'\n\nconst numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n  if (typeof a === 'number' && typeof b === 'number') {\n    return a === b ? 0 : a < b ? -1 : 1\n  }\n\n  const anum = numeric.test(a)\n  const bnum = numeric.test(b)\n\n  if (anum && bnum) {\n    a = +a\n    b = +b\n  }\n\n  return a === b ? 0\n    : (anum && !bnum) ? -1\n    : (bnum && !anum) ? 1\n    : a < b ? -1\n    : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n  compareIdentifiers,\n  rcompareIdentifiers,\n}\n","'use strict'\n\nconst debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\n\nconst isPrereleaseIdentifier = (prerelease, identifier) => {\n  const identifiers = identifier.split('.')\n  if (identifiers.length > prerelease.length) {\n    return false\n  }\n\n  for (let i = 0; i < identifiers.length; i++) {\n    if (compareIdentifiers(prerelease[i], identifiers[i]) !== 0) {\n      return false\n    }\n  }\n\n  return true\n}\n\nclass SemVer {\n  constructor (version, options) {\n    options = parseOptions(options)\n\n    if (version instanceof SemVer) {\n      if (version.loose === !!options.loose &&\n        version.includePrerelease === !!options.includePrerelease) {\n        return version\n      } else {\n        version = version.version\n      }\n    } else if (typeof version !== 'string') {\n      throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n    }\n\n    if (version.length > MAX_LENGTH) {\n      throw new TypeError(\n        `version is longer than ${MAX_LENGTH} characters`\n      )\n    }\n\n    debug('SemVer', version, options)\n    this.options = options\n    this.loose = !!options.loose\n    // this isn't actually relevant for versions, but keep it so that we\n    // don't run into trouble passing this.options around.\n    this.includePrerelease = !!options.includePrerelease\n\n    const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n    if (!m) {\n      throw new TypeError(`Invalid Version: ${version}`)\n    }\n\n    this.raw = version\n\n    // these are actually numbers\n    this.major = +m[1]\n    this.minor = +m[2]\n    this.patch = +m[3]\n\n    if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n      throw new TypeError('Invalid major version')\n    }\n\n    if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n      throw new TypeError('Invalid minor version')\n    }\n\n    if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n      throw new TypeError('Invalid patch version')\n    }\n\n    // numberify any prerelease numeric ids\n    if (!m[4]) {\n      this.prerelease = []\n    } else {\n      this.prerelease = m[4].split('.').map((id) => {\n        if (/^[0-9]+$/.test(id)) {\n          const num = +id\n          if (num >= 0 && num < MAX_SAFE_INTEGER) {\n            return num\n          }\n        }\n        return id\n      })\n    }\n\n    this.build = m[5] ? m[5].split('.') : []\n    this.format()\n  }\n\n  format () {\n    this.version = `${this.major}.${this.minor}.${this.patch}`\n    if (this.prerelease.length) {\n      this.version += `-${this.prerelease.join('.')}`\n    }\n    return this.version\n  }\n\n  toString () {\n    return this.version\n  }\n\n  compare (other) {\n    debug('SemVer.compare', this.version, this.options, other)\n    if (!(other instanceof SemVer)) {\n      if (typeof other === 'string' && other === this.version) {\n        return 0\n      }\n      other = new SemVer(other, this.options)\n    }\n\n    if (other.version === this.version) {\n      return 0\n    }\n\n    return this.compareMain(other) || this.comparePre(other)\n  }\n\n  compareMain (other) {\n    if (!(other instanceof SemVer)) {\n      other = new SemVer(other, this.options)\n    }\n\n    if (this.major < other.major) {\n      return -1\n    }\n    if (this.major > other.major) {\n      return 1\n    }\n    if (this.minor < other.minor) {\n      return -1\n    }\n    if (this.minor > other.minor) {\n      return 1\n    }\n    if (this.patch < other.patch) {\n      return -1\n    }\n    if (this.patch > other.patch) {\n      return 1\n    }\n    return 0\n  }\n\n  comparePre (other) {\n    if (!(other instanceof SemVer)) {\n      other = new SemVer(other, this.options)\n    }\n\n    // NOT having a prerelease is > having one\n    if (this.prerelease.length && !other.prerelease.length) {\n      return -1\n    } else if (!this.prerelease.length && other.prerelease.length) {\n      return 1\n    } else if (!this.prerelease.length && !other.prerelease.length) {\n      return 0\n    }\n\n    let i = 0\n    do {\n      const a = this.prerelease[i]\n      const b = other.prerelease[i]\n      debug('prerelease compare', i, a, b)\n      if (a === undefined && b === undefined) {\n        return 0\n      } else if (b === undefined) {\n        return 1\n      } else if (a === undefined) {\n        return -1\n      } else if (a === b) {\n        continue\n      } else {\n        return compareIdentifiers(a, b)\n      }\n    } while (++i)\n  }\n\n  compareBuild (other) {\n    if (!(other instanceof SemVer)) {\n      other = new SemVer(other, this.options)\n    }\n\n    let i = 0\n    do {\n      const a = this.build[i]\n      const b = other.build[i]\n      debug('build compare', i, a, b)\n      if (a === undefined && b === undefined) {\n        return 0\n      } else if (b === undefined) {\n        return 1\n      } else if (a === undefined) {\n        return -1\n      } else if (a === b) {\n        continue\n      } else {\n        return compareIdentifiers(a, b)\n      }\n    } while (++i)\n  }\n\n  // preminor will bump the version up to the next minor release, and immediately\n  // down to pre-release. premajor and prepatch work the same way.\n  inc (release, identifier, identifierBase) {\n    if (release.startsWith('pre')) {\n      if (!identifier && identifierBase === false) {\n        throw new Error('invalid increment argument: identifier is empty')\n      }\n      // Avoid an invalid semver results\n      if (identifier) {\n        const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])\n        if (!match || match[1] !== identifier) {\n          throw new Error(`invalid identifier: ${identifier}`)\n        }\n      }\n    }\n\n    switch (release) {\n      case 'premajor':\n        this.prerelease.length = 0\n        this.patch = 0\n        this.minor = 0\n        this.major++\n        this.inc('pre', identifier, identifierBase)\n        break\n      case 'preminor':\n        this.prerelease.length = 0\n        this.patch = 0\n        this.minor++\n        this.inc('pre', identifier, identifierBase)\n        break\n      case 'prepatch':\n        // If this is already a prerelease, it will bump to the next version\n        // drop any prereleases that might already exist, since they are not\n        // relevant at this point.\n        this.prerelease.length = 0\n        this.inc('patch', identifier, identifierBase)\n        this.inc('pre', identifier, identifierBase)\n        break\n      // If the input is a non-prerelease version, this acts the same as\n      // prepatch.\n      case 'prerelease':\n        if (this.prerelease.length === 0) {\n          this.inc('patch', identifier, identifierBase)\n        }\n        this.inc('pre', identifier, identifierBase)\n        break\n      case 'release':\n        if (this.prerelease.length === 0) {\n          throw new Error(`version ${this.raw} is not a prerelease`)\n        }\n        this.prerelease.length = 0\n        break\n\n      case 'major':\n        // If this is a pre-major version, bump up to the same major version.\n        // Otherwise increment major.\n        // 1.0.0-5 bumps to 1.0.0\n        // 1.1.0 bumps to 2.0.0\n        if (\n          this.minor !== 0 ||\n          this.patch !== 0 ||\n          this.prerelease.length === 0\n        ) {\n          this.major++\n        }\n        this.minor = 0\n        this.patch = 0\n        this.prerelease = []\n        break\n      case 'minor':\n        // If this is a pre-minor version, bump up to the same minor version.\n        // Otherwise increment minor.\n        // 1.2.0-5 bumps to 1.2.0\n        // 1.2.1 bumps to 1.3.0\n        if (this.patch !== 0 || this.prerelease.length === 0) {\n          this.minor++\n        }\n        this.patch = 0\n        this.prerelease = []\n        break\n      case 'patch':\n        // If this is not a pre-release version, it will increment the patch.\n        // If it is a pre-release it will bump up to the same patch version.\n        // 1.2.0-5 patches to 1.2.0\n        // 1.2.0 patches to 1.2.1\n        if (this.prerelease.length === 0) {\n          this.patch++\n        }\n        this.prerelease = []\n        break\n      // This probably shouldn't be used publicly.\n      // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n      case 'pre': {\n        const base = Number(identifierBase) ? 1 : 0\n\n        if (this.prerelease.length === 0) {\n          this.prerelease = [base]\n        } else {\n          let i = this.prerelease.length\n          while (--i >= 0) {\n            if (typeof this.prerelease[i] === 'number') {\n              this.prerelease[i]++\n              i = -2\n            }\n          }\n          if (i === -1) {\n            // didn't increment anything\n            if (identifier === this.prerelease.join('.') && identifierBase === false) {\n              throw new Error('invalid increment argument: identifier already exists')\n            }\n            this.prerelease.push(base)\n          }\n        }\n        if (identifier) {\n          // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n          // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n          let prerelease = [identifier, base]\n          if (identifierBase === false) {\n            prerelease = [identifier]\n          }\n          if (isPrereleaseIdentifier(this.prerelease, identifier)) {\n            const prereleaseBase = this.prerelease[identifier.split('.').length]\n            if (isNaN(prereleaseBase)) {\n              this.prerelease = prerelease\n            }\n          } else {\n            this.prerelease = prerelease\n          }\n        }\n        break\n      }\n      default:\n        throw new Error(`invalid increment argument: ${release}`)\n    }\n    this.raw = this.format()\n    if (this.build.length) {\n      this.raw += `+${this.build.join('.')}`\n    }\n    return this\n  }\n}\n\nmodule.exports = SemVer\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n  if (version instanceof SemVer) {\n    return version\n  }\n  try {\n    return new SemVer(version, options)\n  } catch (er) {\n    if (!throwErrors) {\n      return null\n    }\n    throw er\n  }\n}\n\nmodule.exports = parse\n","'use strict'\n\nconst parse = require('./parse')\nconst valid = (version, options) => {\n  const v = parse(version, options)\n  return v ? v.version : null\n}\nmodule.exports = valid\n","'use strict'\n\nconst parse = require('./parse')\nconst clean = (version, options) => {\n  const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n  return s ? s.version : null\n}\nmodule.exports = clean\n","'use strict'\n\nconst SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n  if (typeof (options) === 'string') {\n    identifierBase = identifier\n    identifier = options\n    options = undefined\n  }\n\n  try {\n    return new SemVer(\n      version instanceof SemVer ? version.version : version,\n      options\n    ).inc(release, identifier, identifierBase).version\n  } catch (er) {\n    return null\n  }\n}\nmodule.exports = inc\n","'use strict'\n\nconst parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n  const v1 = parse(version1, null, true)\n  const v2 = parse(version2, null, true)\n  const comparison = v1.compare(v2)\n\n  if (comparison === 0) {\n    return null\n  }\n\n  const v1Higher = comparison > 0\n  const highVersion = v1Higher ? v1 : v2\n  const lowVersion = v1Higher ? v2 : v1\n  const highHasPre = !!highVersion.prerelease.length\n  const lowHasPre = !!lowVersion.prerelease.length\n\n  if (lowHasPre && !highHasPre) {\n    // Going from prerelease -> no prerelease requires some special casing\n\n    // If the low version has only a major, then it will always be a major\n    // Some examples:\n    // 1.0.0-1 -> 1.0.0\n    // 1.0.0-1 -> 1.1.1\n    // 1.0.0-1 -> 2.0.0\n    if (!lowVersion.patch && !lowVersion.minor) {\n      return 'major'\n    }\n\n    // If the main part has no difference\n    if (lowVersion.compareMain(highVersion) === 0) {\n      if (lowVersion.minor && !lowVersion.patch) {\n        return 'minor'\n      }\n      return 'patch'\n    }\n  }\n\n  // add the `pre` prefix if we are going to a prerelease version\n  const prefix = highHasPre ? 'pre' : ''\n\n  if (v1.major !== v2.major) {\n    return prefix + 'major'\n  }\n\n  if (v1.minor !== v2.minor) {\n    return prefix + 'minor'\n  }\n\n  if (v1.patch !== v2.patch) {\n    return prefix + 'patch'\n  }\n\n  // high and low are prereleases\n  return 'prerelease'\n}\n\nmodule.exports = diff\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n","'use strict'\n\nconst parse = require('./parse')\nconst prerelease = (version, options) => {\n  const parsed = parse(version, options)\n  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n  new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n","'use strict'\n\nconst compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n","'use strict'\n\nconst compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n  const versionA = new SemVer(a, loose)\n  const versionB = new SemVer(b, loose)\n  return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n","'use strict'\n\nconst compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n","'use strict'\n\nconst compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n","'use strict'\n\nconst compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n","'use strict'\n\nconst compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n","'use strict'\n\nconst compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n","'use strict'\n\nconst compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n","'use strict'\n\nconst compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n","'use strict'\n\nconst compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n","'use strict'\n\nconst eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n  switch (op) {\n    case '===':\n      if (typeof a === 'object') {\n        a = a.version\n      }\n      if (typeof b === 'object') {\n        b = b.version\n      }\n      return a === b\n\n    case '!==':\n      if (typeof a === 'object') {\n        a = a.version\n      }\n      if (typeof b === 'object') {\n        b = b.version\n      }\n      return a !== b\n\n    case '':\n    case '=':\n    case '==':\n      return eq(a, b, loose)\n\n    case '!=':\n      return neq(a, b, loose)\n\n    case '>':\n      return gt(a, b, loose)\n\n    case '>=':\n      return gte(a, b, loose)\n\n    case '<':\n      return lt(a, b, loose)\n\n    case '<=':\n      return lte(a, b, loose)\n\n    default:\n      throw new TypeError(`Invalid operator: ${op}`)\n  }\n}\nmodule.exports = cmp\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n  if (version instanceof SemVer) {\n    return version\n  }\n\n  if (typeof version === 'number') {\n    version = String(version)\n  }\n\n  if (typeof version !== 'string') {\n    return null\n  }\n\n  options = options || {}\n\n  let match = null\n  if (!options.rtl) {\n    match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n  } else {\n    // Find the right-most coercible string that does not share\n    // a terminus with a more left-ward coercible string.\n    // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n    // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n    //\n    // Walk through the string checking with a /g regexp\n    // Manually set the index so as to pick up overlapping matches.\n    // Stop when we get a match that ends at the string end, since no\n    // coercible string can be more right-ward without the same terminus.\n    const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n    let next\n    while ((next = coerceRtlRegex.exec(version)) &&\n        (!match || match.index + match[0].length !== version.length)\n    ) {\n      if (!match ||\n            next.index + next[0].length !== match.index + match[0].length) {\n        match = next\n      }\n      coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n    }\n    // leave it in a clean state\n    coerceRtlRegex.lastIndex = -1\n  }\n\n  if (match === null) {\n    return null\n  }\n\n  const major = match[2]\n  const minor = match[3] || '0'\n  const patch = match[4] || '0'\n  const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n  const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n  return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n","'use strict'\n\nconst parse = require('./parse')\nconst constants = require('../internal/constants')\nconst SemVer = require('../classes/semver')\n\nconst truncate = (version, truncation, options) => {\n  if (!constants.RELEASE_TYPES.includes(truncation)) {\n    return null\n  }\n\n  const clonedVersion = cloneInputVersion(version, options)\n  return clonedVersion && doTruncation(clonedVersion, truncation)\n}\n\nconst cloneInputVersion = (version, options) => {\n  const versionStringToParse = (\n    version instanceof SemVer ? version.version : version\n  )\n\n  return parse(versionStringToParse, options)\n}\n\nconst doTruncation = (version, truncation) => {\n  if (isPrerelease(truncation)) {\n    return version.version\n  }\n\n  version.prerelease = []\n\n  switch (truncation) {\n    case 'major':\n      version.minor = 0\n      version.patch = 0\n      break\n    case 'minor':\n      version.patch = 0\n      break\n  }\n\n  return version.format()\n}\n\nconst isPrerelease = (type) => {\n  return type.startsWith('pre')\n}\n\nmodule.exports = truncate\n","'use strict'\n\nclass LRUCache {\n  constructor () {\n    this.max = 1000\n    this.map = new Map()\n  }\n\n  get (key) {\n    const value = this.map.get(key)\n    if (value === undefined) {\n      return undefined\n    } else {\n      // Remove the key from the map and add it to the end\n      this.map.delete(key)\n      this.map.set(key, value)\n      return value\n    }\n  }\n\n  delete (key) {\n    return this.map.delete(key)\n  }\n\n  set (key, value) {\n    const deleted = this.delete(key)\n\n    if (!deleted && value !== undefined) {\n      // If cache is full, delete the least recently used item\n      if (this.map.size >= this.max) {\n        const firstKey = this.map.keys().next().value\n        this.delete(firstKey)\n      }\n\n      this.map.set(key, value)\n    }\n\n    return this\n  }\n}\n\nmodule.exports = LRUCache\n","'use strict'\n\nconst SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n  constructor (range, options) {\n    options = parseOptions(options)\n\n    if (range instanceof Range) {\n      if (\n        range.loose === !!options.loose &&\n        range.includePrerelease === !!options.includePrerelease\n      ) {\n        return range\n      } else {\n        return new Range(range.raw, options)\n      }\n    }\n\n    if (range instanceof Comparator) {\n      // just put it in the set and return\n      this.raw = range.value\n      this.set = [[range]]\n      this.formatted = undefined\n      return this\n    }\n\n    this.options = options\n    this.loose = !!options.loose\n    this.includePrerelease = !!options.includePrerelease\n\n    // First reduce all whitespace as much as possible so we do not have to rely\n    // on potentially slow regexes like \\s*. This is then stored and used for\n    // future error messages as well.\n    this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n    // First, split on ||\n    this.set = this.raw\n      .split('||')\n      // map the range to a 2d array of comparators\n      .map(r => this.parseRange(r.trim()))\n      // throw out any comparator lists that are empty\n      // this generally means that it was not a valid range, which is allowed\n      // in loose mode, but will still throw if the WHOLE range is invalid.\n      .filter(c => c.length)\n\n    if (!this.set.length) {\n      throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n    }\n\n    // if we have any that are not the null set, throw out null sets.\n    if (this.set.length > 1) {\n      // keep the first one, in case they're all null sets\n      const first = this.set[0]\n      this.set = this.set.filter(c => !isNullSet(c[0]))\n      if (this.set.length === 0) {\n        this.set = [first]\n      } else if (this.set.length > 1) {\n        // if we have any that are *, then the range is just *\n        for (const c of this.set) {\n          if (c.length === 1 && isAny(c[0])) {\n            this.set = [c]\n            break\n          }\n        }\n      }\n    }\n\n    this.formatted = undefined\n  }\n\n  get range () {\n    if (this.formatted === undefined) {\n      this.formatted = ''\n      for (let i = 0; i < this.set.length; i++) {\n        if (i > 0) {\n          this.formatted += '||'\n        }\n        const comps = this.set[i]\n        for (let k = 0; k < comps.length; k++) {\n          if (k > 0) {\n            this.formatted += ' '\n          }\n          this.formatted += comps[k].toString().trim()\n        }\n      }\n    }\n    return this.formatted\n  }\n\n  format () {\n    return this.range\n  }\n\n  toString () {\n    return this.range\n  }\n\n  parseRange (range) {\n    // strip build metadata so it can't bleed into the version\n    range = range.replace(BUILDSTRIPRE, '')\n\n    // memoize range parsing for performance.\n    // this is a very hot path, and fully deterministic.\n    const memoOpts =\n      (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n      (this.options.loose && FLAG_LOOSE)\n    const memoKey = memoOpts + ':' + range\n    const cached = cache.get(memoKey)\n    if (cached) {\n      return cached\n    }\n\n    const loose = this.options.loose\n    // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n    const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n    range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n    debug('hyphen replace', range)\n\n    // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n    range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n    debug('comparator trim', range)\n\n    // `~ 1.2.3` => `~1.2.3`\n    range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n    debug('tilde trim', range)\n\n    // `^ 1.2.3` => `^1.2.3`\n    range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n    debug('caret trim', range)\n\n    // At this point, the range is completely trimmed and\n    // ready to be split into comparators.\n\n    let rangeList = range\n      .split(' ')\n      .map(comp => parseComparator(comp, this.options))\n      .join(' ')\n      .split(/\\s+/)\n      // >=0.0.0 is equivalent to *\n      .map(comp => replaceGTE0(comp, this.options))\n\n    if (loose) {\n      // in loose mode, throw out any that are not valid comparators\n      rangeList = rangeList.filter(comp => {\n        debug('loose invalid filter', comp, this.options)\n        return !!comp.match(re[t.COMPARATORLOOSE])\n      })\n    }\n    debug('range list', rangeList)\n\n    // if any comparators are the null set, then replace with JUST null set\n    // if more than one comparator, remove any * comparators\n    // also, don't include the same comparator more than once\n    const rangeMap = new Map()\n    const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n    for (const comp of comparators) {\n      if (isNullSet(comp)) {\n        return [comp]\n      }\n      rangeMap.set(comp.value, comp)\n    }\n    if (rangeMap.size > 1 && rangeMap.has('')) {\n      rangeMap.delete('')\n    }\n\n    const result = [...rangeMap.values()]\n    cache.set(memoKey, result)\n    return result\n  }\n\n  intersects (range, options) {\n    if (!(range instanceof Range)) {\n      throw new TypeError('a Range is required')\n    }\n\n    return this.set.some((thisComparators) => {\n      return (\n        isSatisfiable(thisComparators, options) &&\n        range.set.some((rangeComparators) => {\n          return (\n            isSatisfiable(rangeComparators, options) &&\n            thisComparators.every((thisComparator) => {\n              return rangeComparators.every((rangeComparator) => {\n                return thisComparator.intersects(rangeComparator, options)\n              })\n            })\n          )\n        })\n      )\n    })\n  }\n\n  // if ANY of the sets match ALL of its comparators, then pass\n  test (version) {\n    if (!version) {\n      return false\n    }\n\n    if (typeof version === 'string') {\n      try {\n        version = new SemVer(version, this.options)\n      } catch (er) {\n        return false\n      }\n    }\n\n    for (let i = 0; i < this.set.length; i++) {\n      if (testSet(this.set[i], version, this.options)) {\n        return true\n      }\n    }\n    return false\n  }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n  safeRe: re,\n  src,\n  t,\n  comparatorTrimReplace,\n  tildeTrimReplace,\n  caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\n// unbounded global build-metadata stripper used by parseRange\nconst BUILDSTRIPRE = new RegExp(src[t.BUILD], 'g')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n  let result = true\n  const remainingComparators = comparators.slice()\n  let testComparator = remainingComparators.pop()\n\n  while (result && remainingComparators.length) {\n    result = remainingComparators.every((otherComparator) => {\n      return testComparator.intersects(otherComparator, options)\n    })\n\n    testComparator = remainingComparators.pop()\n  }\n\n  return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n  comp = comp.replace(re[t.BUILD], '')\n  debug('comp', comp, options)\n  comp = replaceCarets(comp, options)\n  debug('caret', comp)\n  comp = replaceTildes(comp, options)\n  debug('tildes', comp)\n  comp = replaceXRanges(comp, options)\n  debug('xrange', comp)\n  comp = replaceStars(comp, options)\n  debug('stars', comp)\n  return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\nconst invalidXRangeOrder = (M, m, p) => (\n  (isX(M) && !isX(m)) ||\n  (isX(m) && p && !isX(p))\n)\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n  return comp\n    .trim()\n    .split(/\\s+/)\n    .map((c) => replaceTilde(c, options))\n    .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n  const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n  // if we're including prereleases in the match, then the lower bound is\n  // -0, the lowest possible prerelease value, just like x-ranges and carets.\n  // this keeps `~1.2` equivalent to the `1.2.x` x-range it's documented as.\n  const z = options.includePrerelease ? '-0' : ''\n  return comp.replace(r, (_, M, m, p, pr) => {\n    debug('tilde', comp, _, M, m, p, pr)\n    let ret\n\n    if (isX(M)) {\n      ret = ''\n    } else if (isX(m)) {\n      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n    } else if (isX(p)) {\n      // ~1.2 == >=1.2.0 <1.3.0-0\n      ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n    } else if (pr) {\n      debug('replaceTilde pr', pr)\n      ret = `>=${M}.${m}.${p}-${pr\n      } <${M}.${+m + 1}.0-0`\n    } else {\n      // ~1.2.3 == >=1.2.3 <1.3.0-0\n      ret = `>=${M}.${m}.${p\n      } <${M}.${+m + 1}.0-0`\n    }\n\n    debug('tilde return', ret)\n    return ret\n  })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n  return comp\n    .trim()\n    .split(/\\s+/)\n    .map((c) => replaceCaret(c, options))\n    .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n  debug('caret', comp, options)\n  const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n  const z = options.includePrerelease ? '-0' : ''\n  return comp.replace(r, (_, M, m, p, pr) => {\n    debug('caret', comp, _, M, m, p, pr)\n    let ret\n\n    if (isX(M)) {\n      ret = ''\n    } else if (isX(m)) {\n      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n    } else if (isX(p)) {\n      if (M === '0') {\n        ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n      } else {\n        ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n      }\n    } else if (pr) {\n      debug('replaceCaret pr', pr)\n      if (M === '0') {\n        if (m === '0') {\n          ret = `>=${M}.${m}.${p}-${pr\n          } <${M}.${m}.${+p + 1}-0`\n        } else {\n          ret = `>=${M}.${m}.${p}-${pr\n          } <${M}.${+m + 1}.0-0`\n        }\n      } else {\n        ret = `>=${M}.${m}.${p}-${pr\n        } <${+M + 1}.0.0-0`\n      }\n    } else {\n      debug('no pr')\n      if (M === '0') {\n        if (m === '0') {\n          ret = `>=${M}.${m}.${p\n          } <${M}.${m}.${+p + 1}-0`\n        } else {\n          ret = `>=${M}.${m}.${p\n          } <${M}.${+m + 1}.0-0`\n        }\n      } else {\n        ret = `>=${M}.${m}.${p\n        } <${+M + 1}.0.0-0`\n      }\n    }\n\n    debug('caret return', ret)\n    return ret\n  })\n}\n\nconst replaceXRanges = (comp, options) => {\n  debug('replaceXRanges', comp, options)\n  return comp\n    .split(/\\s+/)\n    .map((c) => replaceXRange(c, options))\n    .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n  comp = comp.trim()\n  const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n  return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n    debug('xRange', comp, ret, gtlt, M, m, p, pr)\n    if (invalidXRangeOrder(M, m, p)) {\n      return comp\n    }\n\n    const xM = isX(M)\n    const xm = xM || isX(m)\n    const xp = xm || isX(p)\n    const anyX = xp\n\n    if (gtlt === '=' && anyX) {\n      gtlt = ''\n    }\n\n    // if we're including prereleases in the match, then we need\n    // to fix this to -0, the lowest possible prerelease value\n    pr = options.includePrerelease ? '-0' : ''\n\n    if (xM) {\n      if (gtlt === '>' || gtlt === '<') {\n        // nothing is allowed\n        ret = '<0.0.0-0'\n      } else {\n        // nothing is forbidden\n        ret = '*'\n      }\n    } else if (gtlt && anyX) {\n      // we know patch is an x, because we have any x at all.\n      // replace X with 0\n      if (xm) {\n        m = 0\n      }\n      p = 0\n\n      if (gtlt === '>') {\n        // >1 => >=2.0.0\n        // >1.2 => >=1.3.0\n        gtlt = '>='\n        if (xm) {\n          M = +M + 1\n          m = 0\n          p = 0\n        } else {\n          m = +m + 1\n          p = 0\n        }\n      } else if (gtlt === '<=') {\n        // <=0.7.x is actually <0.8.0, since any 0.7.x should\n        // pass.  Similarly, <=7.x is actually <8.0.0, etc.\n        gtlt = '<'\n        if (xm) {\n          M = +M + 1\n        } else {\n          m = +m + 1\n        }\n      }\n\n      if (gtlt === '<') {\n        pr = '-0'\n      }\n\n      ret = `${gtlt + M}.${m}.${p}${pr}`\n    } else if (xm) {\n      ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n    } else if (xp) {\n      ret = `>=${M}.${m}.0${pr\n      } <${M}.${+m + 1}.0-0`\n    }\n\n    debug('xRange return', ret)\n\n    return ret\n  })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n  debug('replaceStars', comp, options)\n  // Looseness is ignored here.  star is always as loose as it gets!\n  return comp\n    .trim()\n    .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n  debug('replaceGTE0', comp, options)\n  return comp\n    .trim()\n    .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n  from, fM, fm, fp, fpr, fb,\n  to, tM, tm, tp, tpr) => {\n  if (isX(fM)) {\n    from = ''\n  } else if (isX(fm)) {\n    from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n  } else if (isX(fp)) {\n    from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n  } else if (fpr) {\n    from = `>=${from}`\n  } else {\n    from = `>=${from}${incPr ? '-0' : ''}`\n  }\n\n  if (isX(tM)) {\n    to = ''\n  } else if (isX(tm)) {\n    to = `<${+tM + 1}.0.0-0`\n  } else if (isX(tp)) {\n    to = `<${tM}.${+tm + 1}.0-0`\n  } else if (tpr) {\n    to = `<=${tM}.${tm}.${tp}-${tpr}`\n  } else if (incPr) {\n    to = `<${tM}.${tm}.${+tp + 1}-0`\n  } else {\n    to = `<=${to}`\n  }\n\n  return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n  for (let i = 0; i < set.length; i++) {\n    if (!set[i].test(version)) {\n      return false\n    }\n  }\n\n  if (version.prerelease.length && !options.includePrerelease) {\n    // Find the set of versions that are allowed to have prereleases\n    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n    // That should allow `1.2.3-pr.2` to pass.\n    // However, `1.2.4-alpha.notready` should NOT be allowed,\n    // even though it's within the range set by the comparators.\n    for (let i = 0; i < set.length; i++) {\n      debug(set[i].semver)\n      if (set[i].semver === Comparator.ANY) {\n        continue\n      }\n\n      if (set[i].semver.prerelease.length > 0) {\n        const allowed = set[i].semver\n        if (allowed.major === version.major &&\n            allowed.minor === version.minor &&\n            allowed.patch === version.patch) {\n          return true\n        }\n      }\n    }\n\n    // Version has a -pre, but it's not one of the ones we like.\n    return false\n  }\n\n  return true\n}\n","'use strict'\n\nconst ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n  static get ANY () {\n    return ANY\n  }\n\n  constructor (comp, options) {\n    options = parseOptions(options)\n\n    if (comp instanceof Comparator) {\n      if (comp.loose === !!options.loose) {\n        return comp\n      } else {\n        comp = comp.value\n      }\n    }\n\n    comp = comp.trim().split(/\\s+/).join(' ')\n    debug('comparator', comp, options)\n    this.options = options\n    this.loose = !!options.loose\n    this.parse(comp)\n\n    if (this.semver === ANY) {\n      this.value = ''\n    } else {\n      this.value = this.operator + this.semver.version\n    }\n\n    debug('comp', this)\n  }\n\n  parse (comp) {\n    const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n    const m = comp.match(r)\n\n    if (!m) {\n      throw new TypeError(`Invalid comparator: ${comp}`)\n    }\n\n    this.operator = m[1] !== undefined ? m[1] : ''\n    if (this.operator === '=') {\n      this.operator = ''\n    }\n\n    // if it literally is just '>' or '' then allow anything.\n    if (!m[2]) {\n      this.semver = ANY\n    } else {\n      this.semver = new SemVer(m[2], this.options.loose)\n    }\n  }\n\n  toString () {\n    return this.value\n  }\n\n  test (version) {\n    debug('Comparator.test', version, this.options.loose)\n\n    if (this.semver === ANY || version === ANY) {\n      return true\n    }\n\n    if (typeof version === 'string') {\n      try {\n        version = new SemVer(version, this.options)\n      } catch (er) {\n        return false\n      }\n    }\n\n    return cmp(version, this.operator, this.semver, this.options)\n  }\n\n  intersects (comp, options) {\n    if (!(comp instanceof Comparator)) {\n      throw new TypeError('a Comparator is required')\n    }\n\n    if (this.operator === '') {\n      if (this.value === '') {\n        return true\n      }\n      return new Range(comp.value, options).test(this.value)\n    } else if (comp.operator === '') {\n      if (comp.value === '') {\n        return true\n      }\n      return new Range(this.value, options).test(comp.semver)\n    }\n\n    options = parseOptions(options)\n\n    // Special cases where nothing can possibly be lower\n    if (options.includePrerelease &&\n      (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n      return false\n    }\n    if (!options.includePrerelease &&\n      (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n      return false\n    }\n\n    // Same direction increasing (> or >=)\n    if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n      return true\n    }\n    // Same direction decreasing (< or <=)\n    if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n      return true\n    }\n    // same SemVer and both sides are inclusive (<= or >=)\n    if (\n      (this.semver.version === comp.semver.version) &&\n      this.operator.includes('=') && comp.operator.includes('=')) {\n      return true\n    }\n    // opposite directions less than\n    if (cmp(this.semver, '<', comp.semver, options) &&\n      this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n      return true\n    }\n    // opposite directions greater than\n    if (cmp(this.semver, '>', comp.semver, options) &&\n      this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n      return true\n    }\n    return false\n  }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n","'use strict'\n\nconst Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n  try {\n    range = new Range(range, options)\n  } catch (er) {\n    return false\n  }\n  return range.test(version)\n}\nmodule.exports = satisfies\n","'use strict'\n\nconst Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n  new Range(range, options).set\n    .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n  let max = null\n  let maxSV = null\n  let rangeObj = null\n  try {\n    rangeObj = new Range(range, options)\n  } catch (er) {\n    return null\n  }\n  versions.forEach((v) => {\n    if (rangeObj.test(v)) {\n      // satisfies(v, range, options)\n      if (!max || maxSV.compare(v) === -1) {\n        // compare(max, v, true)\n        max = v\n        maxSV = new SemVer(max, options)\n      }\n    }\n  })\n  return max\n}\nmodule.exports = maxSatisfying\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n  let min = null\n  let minSV = null\n  let rangeObj = null\n  try {\n    rangeObj = new Range(range, options)\n  } catch (er) {\n    return null\n  }\n  versions.forEach((v) => {\n    if (rangeObj.test(v)) {\n      // satisfies(v, range, options)\n      if (!min || minSV.compare(v) === 1) {\n        // compare(min, v, true)\n        min = v\n        minSV = new SemVer(min, options)\n      }\n    }\n  })\n  return min\n}\nmodule.exports = minSatisfying\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n  range = new Range(range, loose)\n\n  let minver = new SemVer('0.0.0')\n  if (range.test(minver)) {\n    return minver\n  }\n\n  minver = new SemVer('0.0.0-0')\n  if (range.test(minver)) {\n    return minver\n  }\n\n  minver = null\n  for (let i = 0; i < range.set.length; ++i) {\n    const comparators = range.set[i]\n\n    let setMin = null\n    comparators.forEach((comparator) => {\n      // Clone to avoid manipulating the comparator's semver object.\n      const compver = new SemVer(comparator.semver.version)\n      switch (comparator.operator) {\n        case '>':\n          if (compver.prerelease.length === 0) {\n            compver.patch++\n          } else {\n            compver.prerelease.push(0)\n          }\n          compver.raw = compver.format()\n          /* fallthrough */\n        case '':\n        case '>=':\n          if (!setMin || gt(compver, setMin)) {\n            setMin = compver\n          }\n          break\n        case '<':\n        case '<=':\n          /* Ignore maximum versions */\n          break\n        /* istanbul ignore next */\n        default:\n          throw new Error(`Unexpected operation: ${comparator.operator}`)\n      }\n    })\n    if (setMin && (!minver || gt(minver, setMin))) {\n      minver = setMin\n    }\n  }\n\n  if (minver && range.test(minver)) {\n    return minver\n  }\n\n  return null\n}\nmodule.exports = minVersion\n","'use strict'\n\nconst Range = require('../classes/range')\nconst validRange = (range, options) => {\n  try {\n    // Return '*' instead of '' so that truthiness works.\n    // This will throw if it's invalid anyway\n    return new Range(range, options).range || '*'\n  } catch (er) {\n    return null\n  }\n}\nmodule.exports = validRange\n","'use strict'\n\nconst SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n  version = new SemVer(version, options)\n  range = new Range(range, options)\n\n  let gtfn, ltefn, ltfn, comp, ecomp\n  switch (hilo) {\n    case '>':\n      gtfn = gt\n      ltefn = lte\n      ltfn = lt\n      comp = '>'\n      ecomp = '>='\n      break\n    case '<':\n      gtfn = lt\n      ltefn = gte\n      ltfn = gt\n      comp = '<'\n      ecomp = '<='\n      break\n    default:\n      throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n  }\n\n  // If it satisfies the range it is not outside\n  if (satisfies(version, range, options)) {\n    return false\n  }\n\n  // From now on, variable terms are as if we're in \"gtr\" mode.\n  // but note that everything is flipped for the \"ltr\" function.\n\n  for (let i = 0; i < range.set.length; ++i) {\n    const comparators = range.set[i]\n\n    let high = null\n    let low = null\n\n    comparators.forEach((comparator) => {\n      if (comparator.semver === ANY) {\n        comparator = new Comparator('>=0.0.0')\n      }\n      high = high || comparator\n      low = low || comparator\n      if (gtfn(comparator.semver, high.semver, options)) {\n        high = comparator\n      } else if (ltfn(comparator.semver, low.semver, options)) {\n        low = comparator\n      }\n    })\n\n    // If the edge version comparator has a operator then our version\n    // isn't outside it\n    if (high.operator === comp || high.operator === ecomp) {\n      return false\n    }\n\n    // If the lowest version comparator has an operator and our version\n    // is less than it then it isn't higher than the range\n    if ((!low.operator || low.operator === comp) &&\n        ltefn(version, low.semver)) {\n      return false\n    } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n      return false\n    }\n  }\n  return true\n}\n\nmodule.exports = outside\n","'use strict'\n\n// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n","'use strict'\n\nconst outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n","'use strict'\n\nconst Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n  r1 = new Range(r1, options)\n  r2 = new Range(r2, options)\n  return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n","'use strict'\n\n// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n  const set = []\n  let first = null\n  let prev = null\n  const v = versions.sort((a, b) => compare(a, b, options))\n  for (const version of v) {\n    const included = satisfies(version, range, options)\n    if (included) {\n      prev = version\n      if (!first) {\n        first = version\n      }\n    } else {\n      if (prev) {\n        set.push([first, prev])\n      }\n      prev = null\n      first = null\n    }\n  }\n  if (first) {\n    set.push([first, null])\n  }\n\n  const ranges = []\n  for (const [min, max] of set) {\n    if (min === max) {\n      ranges.push(min)\n    } else if (!max && min === v[0]) {\n      ranges.push('*')\n    } else if (!max) {\n      ranges.push(`>=${min}`)\n    } else if (min === v[0]) {\n      ranges.push(`<=${max}`)\n    } else {\n      ranges.push(`${min} - ${max}`)\n    }\n  }\n  const simplified = ranges.join(' || ')\n  const original = typeof range.raw === 'string' ? range.raw : String(range)\n  return simplified.length < original.length ? simplified : range\n}\n","'use strict'\n\nconst Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n//   some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n//   - If C is only the ANY comparator, return true\n//   - Else if in prerelease mode, return false\n//   - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n//   - if in prerelease mode, return true\n//   - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n//   - If GT, and EQ does not satisfy GT, return true (null set)\n//   - If LT, and EQ does not satisfy LT, return true (null set)\n//   - If EQ satisfies every C, return true\n//   - Else return false\n// - If GT\n//   - If GT.semver is lower than any > or >= comp in C, return false\n//   - If GT is >=, and GT.semver does not satisfy every C, return false\n//   - If GT.semver has a prerelease, and not in prerelease mode\n//     - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n//   - If LT.semver is greater than any < or <= comp in C, return false\n//   - If LT is <=, and LT.semver does not satisfy every C, return false\n//   - If LT.semver has a prerelease, and not in prerelease mode\n//     - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n  if (sub === dom) {\n    return true\n  }\n\n  sub = new Range(sub, options)\n  dom = new Range(dom, options)\n  let sawNonNull = false\n\n  OUTER: for (const simpleSub of sub.set) {\n    for (const simpleDom of dom.set) {\n      const isSub = simpleSubset(simpleSub, simpleDom, options)\n      sawNonNull = sawNonNull || isSub !== null\n      if (isSub) {\n        continue OUTER\n      }\n    }\n    // the null set is a subset of everything, but null simple ranges in\n    // a complex range should be ignored.  so if we saw a non-null range,\n    // then we know this isn't a subset, but if EVERY simple range was null,\n    // then it is a subset.\n    if (sawNonNull) {\n      return false\n    }\n  }\n  return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n  if (sub === dom) {\n    return true\n  }\n\n  if (sub.length === 1 && sub[0].semver === ANY) {\n    if (dom.length === 1 && dom[0].semver === ANY) {\n      return true\n    } else if (options.includePrerelease) {\n      sub = minimumVersionWithPreRelease\n    } else {\n      sub = minimumVersion\n    }\n  }\n\n  if (dom.length === 1 && dom[0].semver === ANY) {\n    if (options.includePrerelease) {\n      return true\n    } else {\n      dom = minimumVersion\n    }\n  }\n\n  const eqSet = new Set()\n  let gt, lt\n  for (const c of sub) {\n    if (c.operator === '>' || c.operator === '>=') {\n      gt = higherGT(gt, c, options)\n    } else if (c.operator === '<' || c.operator === '<=') {\n      lt = lowerLT(lt, c, options)\n    } else {\n      eqSet.add(c.semver)\n    }\n  }\n\n  if (eqSet.size > 1) {\n    return null\n  }\n\n  let gtltComp\n  if (gt && lt) {\n    gtltComp = compare(gt.semver, lt.semver, options)\n    if (gtltComp > 0) {\n      return null\n    } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n      return null\n    }\n  }\n\n  // will iterate one or zero times\n  for (const eq of eqSet) {\n    if (gt && !satisfies(eq, String(gt), options)) {\n      return null\n    }\n\n    if (lt && !satisfies(eq, String(lt), options)) {\n      return null\n    }\n\n    for (const c of dom) {\n      if (!satisfies(eq, String(c), options)) {\n        return false\n      }\n    }\n\n    return true\n  }\n\n  let higher, lower\n  let hasDomLT, hasDomGT\n  // if the subset has a prerelease, we need a comparator in the superset\n  // with the same tuple and a prerelease, or it's not a subset\n  let needDomLTPre = lt &&\n    !options.includePrerelease &&\n    lt.semver.prerelease.length ? lt.semver : false\n  let needDomGTPre = gt &&\n    !options.includePrerelease &&\n    gt.semver.prerelease.length ? gt.semver : false\n  // exception: <1.2.3-0 is the same as <1.2.3\n  if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n      lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n    needDomLTPre = false\n  }\n\n  for (const c of dom) {\n    hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n    hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n    if (gt) {\n      if (needDomGTPre) {\n        if (c.semver.prerelease && c.semver.prerelease.length &&\n            c.semver.major === needDomGTPre.major &&\n            c.semver.minor === needDomGTPre.minor &&\n            c.semver.patch === needDomGTPre.patch) {\n          needDomGTPre = false\n        }\n      }\n      if (c.operator === '>' || c.operator === '>=') {\n        higher = higherGT(gt, c, options)\n        if (higher === c && higher !== gt) {\n          return false\n        }\n      } else if (gt.operator === '>=' && !c.test(gt.semver)) {\n        return false\n      }\n    }\n    if (lt) {\n      if (needDomLTPre) {\n        if (c.semver.prerelease && c.semver.prerelease.length &&\n            c.semver.major === needDomLTPre.major &&\n            c.semver.minor === needDomLTPre.minor &&\n            c.semver.patch === needDomLTPre.patch) {\n          needDomLTPre = false\n        }\n      }\n      if (c.operator === '<' || c.operator === '<=') {\n        lower = lowerLT(lt, c, options)\n        if (lower === c && lower !== lt) {\n          return false\n        }\n      } else if (lt.operator === '<=' && !c.test(lt.semver)) {\n        return false\n      }\n    }\n    if (!c.operator && (lt || gt) && gtltComp !== 0) {\n      return false\n    }\n  }\n\n  // if there was a < or >, and nothing in the dom, then must be false\n  // UNLESS it was limited by another range in the other direction.\n  // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n  if (gt && hasDomLT && !lt && gtltComp !== 0) {\n    return false\n  }\n\n  if (lt && hasDomGT && !gt && gtltComp !== 0) {\n    return false\n  }\n\n  // we needed a prerelease range in a specific tuple, but didn't get one\n  // then this isn't a subset.  eg >=1.2.3-pre is not a subset of >=1.0.0,\n  // because it includes prereleases in the 1.2.3 tuple\n  if (needDomGTPre || needDomLTPre) {\n    return false\n  }\n\n  return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n  if (!a) {\n    return b\n  }\n  const comp = compare(a.semver, b.semver, options)\n  return comp > 0 ? a\n    : comp < 0 ? b\n    : b.operator === '>' && a.operator === '>=' ? b\n    : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n  if (!a) {\n    return b\n  }\n  const comp = compare(a.semver, b.semver, options)\n  return comp < 0 ? a\n    : comp > 0 ? b\n    : b.operator === '<' && a.operator === '<=' ? b\n    : a\n}\n\nmodule.exports = subset\n","'use strict'\n\n// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst truncate = require('./functions/truncate')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n  parse,\n  valid,\n  clean,\n  inc,\n  diff,\n  major,\n  minor,\n  patch,\n  prerelease,\n  compare,\n  rcompare,\n  compareLoose,\n  compareBuild,\n  sort,\n  rsort,\n  gt,\n  lt,\n  eq,\n  neq,\n  gte,\n  lte,\n  cmp,\n  coerce,\n  truncate,\n  Comparator,\n  Range,\n  satisfies,\n  toComparators,\n  maxSatisfying,\n  minSatisfying,\n  minVersion,\n  validRange,\n  outside,\n  gtr,\n  ltr,\n  intersects,\n  simplifyRange,\n  subset,\n  SemVer,\n  re: internalRe.re,\n  src: internalRe.src,\n  tokens: internalRe.t,\n  SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n  RELEASE_TYPES: constants.RELEASE_TYPES,\n  compareIdentifiers: identifiers.compareIdentifiers,\n  rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n","module.exports = require('events')\n","module.exports = class FixedFIFO {\n  constructor (hwm) {\n    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')\n    this.buffer = new Array(hwm)\n    this.mask = hwm - 1\n    this.top = 0\n    this.btm = 0\n    this.next = null\n  }\n\n  clear () {\n    this.top = this.btm = 0\n    this.next = null\n    this.buffer.fill(undefined)\n  }\n\n  push (data) {\n    if (this.buffer[this.top] !== undefined) return false\n    this.buffer[this.top] = data\n    this.top = (this.top + 1) & this.mask\n    return true\n  }\n\n  shift () {\n    const last = this.buffer[this.btm]\n    if (last === undefined) return undefined\n    this.buffer[this.btm] = undefined\n    this.btm = (this.btm + 1) & this.mask\n    return last\n  }\n\n  peek () {\n    return this.buffer[this.btm]\n  }\n\n  isEmpty () {\n    return this.buffer[this.btm] === undefined\n  }\n}\n","const FixedFIFO = require('./fixed-size')\n\nmodule.exports = class FastFIFO {\n  constructor (hwm) {\n    this.hwm = hwm || 16\n    this.head = new FixedFIFO(this.hwm)\n    this.tail = this.head\n    this.length = 0\n  }\n\n  clear () {\n    this.head = this.tail\n    this.head.clear()\n    this.length = 0\n  }\n\n  push (val) {\n    this.length++\n    if (!this.head.push(val)) {\n      const prev = this.head\n      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)\n      this.head.push(val)\n    }\n  }\n\n  shift () {\n    if (this.length !== 0) this.length--\n    const val = this.tail.shift()\n    if (val === undefined && this.tail.next) {\n      const next = this.tail.next\n      this.tail.next = null\n      this.tail = next\n      return this.tail.shift()\n    }\n\n    return val\n  }\n\n  peek () {\n    const val = this.tail.peek()\n    if (val === undefined && this.tail.next) return this.tail.next.peek()\n    return val\n  }\n\n  isEmpty () {\n    return this.length === 0\n  }\n}\n","function isBuffer(value) {\n  return Buffer.isBuffer(value) || value instanceof Uint8Array\n}\n\nfunction isEncoding(encoding) {\n  return Buffer.isEncoding(encoding)\n}\n\nfunction alloc(size, fill, encoding) {\n  return Buffer.alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe(size) {\n  return Buffer.allocUnsafe(size)\n}\n\nfunction allocUnsafeSlow(size) {\n  return Buffer.allocUnsafeSlow(size)\n}\n\nfunction byteLength(string, encoding) {\n  return Buffer.byteLength(string, encoding)\n}\n\nfunction compare(a, b) {\n  return Buffer.compare(a, b)\n}\n\nfunction concat(buffers, totalLength) {\n  return Buffer.concat(buffers, totalLength)\n}\n\nfunction copy(source, target, targetStart, start, end) {\n  return toBuffer(source).copy(target, targetStart, start, end)\n}\n\nfunction equals(a, b) {\n  return toBuffer(a).equals(b)\n}\n\nfunction fill(buffer, value, offset, end, encoding) {\n  return toBuffer(buffer).fill(value, offset, end, encoding)\n}\n\nfunction from(value, encodingOrOffset, length) {\n  return Buffer.from(value, encodingOrOffset, length)\n}\n\nfunction includes(buffer, value, byteOffset, encoding) {\n  return toBuffer(buffer).includes(value, byteOffset, encoding)\n}\n\nfunction indexOf(buffer, value, byfeOffset, encoding) {\n  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)\n}\n\nfunction lastIndexOf(buffer, value, byteOffset, encoding) {\n  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)\n}\n\nfunction swap16(buffer) {\n  return toBuffer(buffer).swap16()\n}\n\nfunction swap32(buffer) {\n  return toBuffer(buffer).swap32()\n}\n\nfunction swap64(buffer) {\n  return toBuffer(buffer).swap64()\n}\n\nfunction toBuffer(buffer) {\n  if (Buffer.isBuffer(buffer)) return buffer\n  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n}\n\nfunction toString(buffer, encoding, start, end) {\n  return toBuffer(buffer).toString(encoding, start, end)\n}\n\nfunction write(buffer, string, offset, length, encoding) {\n  return toBuffer(buffer).write(string, offset, length, encoding)\n}\n\nfunction readDoubleBE(buffer, offset) {\n  return toBuffer(buffer).readDoubleBE(offset)\n}\n\nfunction readDoubleLE(buffer, offset) {\n  return toBuffer(buffer).readDoubleLE(offset)\n}\n\nfunction readFloatBE(buffer, offset) {\n  return toBuffer(buffer).readFloatBE(offset)\n}\n\nfunction readFloatLE(buffer, offset) {\n  return toBuffer(buffer).readFloatLE(offset)\n}\n\nfunction readInt32BE(buffer, offset) {\n  return toBuffer(buffer).readInt32BE(offset)\n}\n\nfunction readInt32LE(buffer, offset) {\n  return toBuffer(buffer).readInt32LE(offset)\n}\n\nfunction readUInt32BE(buffer, offset) {\n  return toBuffer(buffer).readUInt32BE(offset)\n}\n\nfunction readUInt32LE(buffer, offset) {\n  return toBuffer(buffer).readUInt32LE(offset)\n}\n\nfunction writeDoubleBE(buffer, value, offset) {\n  return toBuffer(buffer).writeDoubleBE(value, offset)\n}\n\nfunction writeDoubleLE(buffer, value, offset) {\n  return toBuffer(buffer).writeDoubleLE(value, offset)\n}\n\nfunction writeFloatBE(buffer, value, offset) {\n  return toBuffer(buffer).writeFloatBE(value, offset)\n}\n\nfunction writeFloatLE(buffer, value, offset) {\n  return toBuffer(buffer).writeFloatLE(value, offset)\n}\n\nfunction writeInt32BE(buffer, value, offset) {\n  return toBuffer(buffer).writeInt32BE(value, offset)\n}\n\nfunction writeInt32LE(buffer, value, offset) {\n  return toBuffer(buffer).writeInt32LE(value, offset)\n}\n\nfunction writeUInt32BE(buffer, value, offset) {\n  return toBuffer(buffer).writeUInt32BE(value, offset)\n}\n\nfunction writeUInt32LE(buffer, value, offset) {\n  return toBuffer(buffer).writeUInt32LE(value, offset)\n}\n\nmodule.exports = {\n  isBuffer,\n  isEncoding,\n  alloc,\n  allocUnsafe,\n  allocUnsafeSlow,\n  byteLength,\n  compare,\n  concat,\n  copy,\n  equals,\n  fill,\n  from,\n  includes,\n  indexOf,\n  lastIndexOf,\n  swap16,\n  swap32,\n  swap64,\n  toBuffer,\n  toString,\n  write,\n  readDoubleBE,\n  readDoubleLE,\n  readFloatBE,\n  readFloatLE,\n  readInt32BE,\n  readInt32LE,\n  readUInt32BE,\n  readUInt32LE,\n  writeDoubleBE,\n  writeDoubleLE,\n  writeFloatBE,\n  writeFloatLE,\n  writeInt32BE,\n  writeInt32LE,\n  writeUInt32BE,\n  writeUInt32LE\n}\n","const b4a = require('b4a')\n\nmodule.exports = class PassThroughDecoder {\n  constructor(encoding) {\n    this.encoding = encoding\n  }\n\n  get remaining() {\n    return 0\n  }\n\n  decode(data) {\n    return b4a.toString(data, this.encoding)\n  }\n\n  flush() {\n    return ''\n  }\n}\n","const b4a = require('b4a')\n\n/**\n * https://encoding.spec.whatwg.org/#utf-8-decoder\n */\nmodule.exports = class UTF8Decoder {\n  constructor() {\n    this._reset()\n  }\n\n  get remaining() {\n    return this.bytesSeen\n  }\n\n  decode(data) {\n    if (data.byteLength === 0) return ''\n\n    if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) {\n      this.bytesSeen = trailingBytesSeen(data)\n      return b4a.toString(data, 'utf8')\n    }\n\n    let result = ''\n    let start = 0\n\n    if (this.bytesNeeded > 0) {\n      while (start < data.byteLength) {\n        const byte = data[start]\n\n        if (byte < this.lowerBoundary || byte > this.upperBoundary) {\n          result += '\\ufffd'\n          this._reset()\n          break\n        }\n\n        this.lowerBoundary = 0x80\n        this.upperBoundary = 0xbf\n        this.codePoint = (this.codePoint << 6) | (byte & 0x3f)\n        this.bytesSeen++\n        start++\n\n        if (this.bytesSeen === this.bytesNeeded) {\n          result += String.fromCodePoint(this.codePoint)\n          this._reset()\n          break\n        }\n      }\n\n      if (this.bytesNeeded > 0) return result\n    }\n\n    const trailing = trailingIncomplete(data, start)\n    const end = data.byteLength - trailing\n\n    if (end > start) result += b4a.toString(data, 'utf8', start, end)\n\n    for (let i = end; i < data.byteLength; i++) {\n      const byte = data[i]\n\n      if (this.bytesNeeded === 0) {\n        if (byte <= 0x7f) {\n          this.bytesSeen = 0\n          result += String.fromCharCode(byte)\n        } else if (byte >= 0xc2 && byte <= 0xdf) {\n          this.bytesNeeded = 2\n          this.bytesSeen = 1\n          this.codePoint = byte & 0x1f\n        } else if (byte >= 0xe0 && byte <= 0xef) {\n          if (byte === 0xe0) this.lowerBoundary = 0xa0\n          else if (byte === 0xed) this.upperBoundary = 0x9f\n          this.bytesNeeded = 3\n          this.bytesSeen = 1\n          this.codePoint = byte & 0xf\n        } else if (byte >= 0xf0 && byte <= 0xf4) {\n          if (byte === 0xf0) this.lowerBoundary = 0x90\n          else if (byte === 0xf4) this.upperBoundary = 0x8f\n          this.bytesNeeded = 4\n          this.bytesSeen = 1\n          this.codePoint = byte & 0x7\n        } else {\n          this.bytesSeen = 1\n          result += '\\ufffd'\n        }\n\n        continue\n      }\n\n      if (byte < this.lowerBoundary || byte > this.upperBoundary) {\n        result += '\\ufffd'\n        i--\n        this._reset()\n\n        continue\n      }\n\n      this.lowerBoundary = 0x80\n      this.upperBoundary = 0xbf\n\n      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)\n      this.bytesSeen++\n\n      if (this.bytesSeen === this.bytesNeeded) {\n        result += String.fromCodePoint(this.codePoint)\n        this._reset()\n      }\n    }\n\n    return result\n  }\n\n  flush() {\n    const result = this.bytesNeeded > 0 ? '\\ufffd' : ''\n    this._reset()\n    return result\n  }\n\n  _reset() {\n    this.codePoint = 0\n    this.bytesNeeded = 0\n    this.bytesSeen = 0\n    this.lowerBoundary = 0x80\n    this.upperBoundary = 0xbf\n  }\n}\n\nfunction trailingIncomplete(data, start) {\n  const len = data.byteLength\n  if (len <= start) return 0\n\n  const limit = Math.max(start, len - 4)\n\n  let i = len - 1\n  while (i > limit && (data[i] & 0xc0) === 0x80) i--\n\n  if (i < start) return 0\n\n  const byte = data[i]\n\n  let needed\n  if (byte <= 0x7f) return 0\n  if (byte >= 0xc2 && byte <= 0xdf) needed = 2\n  else if (byte >= 0xe0 && byte <= 0xef) needed = 3\n  else if (byte >= 0xf0 && byte <= 0xf4) needed = 4\n  else return 0\n\n  const available = len - i\n  return available < needed ? available : 0\n}\n\nfunction trailingBytesSeen(data) {\n  const len = data.byteLength\n  if (len === 0) return 0\n\n  const last = data[len - 1]\n\n  if (last <= 0x7f) return 0\n  if ((last & 0xc0) !== 0x80) return 1\n\n  const limit = Math.max(0, len - 4)\n\n  let i = len - 2\n  while (i >= limit && (data[i] & 0xc0) === 0x80) i--\n\n  if (i < 0) return 1\n\n  const first = data[i]\n\n  let needed\n  if (first >= 0xc2 && first <= 0xdf) needed = 2\n  else if (first >= 0xe0 && first <= 0xef) needed = 3\n  else if (first >= 0xf0 && first <= 0xf4) needed = 4\n  else return 1\n\n  if (len - i !== needed) return 1\n\n  if (needed >= 3) {\n    const second = data[i + 1]\n    if (first === 0xe0 && second < 0xa0) return 1\n    if (first === 0xed && second > 0x9f) return 1\n    if (first === 0xf0 && second < 0x90) return 1\n    if (first === 0xf4 && second > 0x8f) return 1\n  }\n\n  return 0\n}\n","const PassThroughDecoder = require('./lib/pass-through-decoder')\nconst UTF8Decoder = require('./lib/utf8-decoder')\n\nmodule.exports = class TextDecoder {\n  constructor(encoding = 'utf8') {\n    this.encoding = normalizeEncoding(encoding)\n\n    switch (this.encoding) {\n      case 'utf8':\n        this.decoder = new UTF8Decoder()\n        break\n      case 'utf16le':\n      case 'base64':\n        throw new Error('Unsupported encoding: ' + this.encoding)\n      default:\n        this.decoder = new PassThroughDecoder(this.encoding)\n    }\n  }\n\n  get remaining() {\n    return this.decoder.remaining\n  }\n\n  push(data) {\n    if (typeof data === 'string') return data\n    return this.decoder.decode(data)\n  }\n\n  // For Node.js compatibility\n  write(data) {\n    return this.push(data)\n  }\n\n  end(data) {\n    let result = ''\n    if (data) result = this.push(data)\n    result += this.decoder.flush()\n    return result\n  }\n}\n\nfunction normalizeEncoding(encoding) {\n  encoding = encoding.toLowerCase()\n\n  switch (encoding) {\n    case 'utf8':\n    case 'utf-8':\n      return 'utf8'\n    case 'ucs2':\n    case 'ucs-2':\n    case 'utf16le':\n    case 'utf-16le':\n      return 'utf16le'\n    case 'latin1':\n    case 'binary':\n      return 'latin1'\n    case 'base64':\n    case 'ascii':\n    case 'hex':\n      return encoding\n    default:\n      throw new Error('Unknown encoding: ' + encoding)\n  }\n}\n","module.exports = class StreamError extends Error {\n  constructor(msg, code, fn = StreamError) {\n    super(msg)\n\n    this.code = code\n\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, fn)\n    }\n  }\n\n  static isStreamDestroyed(err) {\n    return err && err.code === 'STREAM_DESTROYED'\n  }\n\n  static isPrematureClose(err) {\n    return err && err.code === 'PREMATURE_CLOSE'\n  }\n\n  static isAborted(err) {\n    return err && err.code === 'ABORTED'\n  }\n\n  static isBadArgument(err) {\n    return err && err.code === 'BAD_ARGUMENT'\n  }\n\n  get name() {\n    return 'StreamError'\n  }\n\n  static STREAM_DESTROYED() {\n    return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED)\n  }\n\n  static PREMATURE_CLOSE(msg = 'Premature close') {\n    return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE)\n  }\n\n  static ABORTED() {\n    return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED)\n  }\n\n  static BAD_ARGUMENT(msg = 'Bad argument') {\n    return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT)\n  }\n}\n","const { EventEmitter } = require('events-universal')\nconst FIFO = require('fast-fifo')\nconst TextDecoder = require('text-decoder')\n\nconst StreamError = require('./lib/errors.js')\n\n// if we do a future major, expect queue microtask to be there always, for now a bit defensive\nconst qmt =\n  typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask\n\n// 29 bits used total (4 from shared, 14 from read, and 11 from write)\nconst MAX = (1 << 29) - 1\n\n// Shared state\nconst OPENING = 0b0001\nconst PREDESTROYING = 0b0010\nconst DESTROYING = 0b0100\nconst DESTROYED = 0b1000\n\nconst NOT_OPENING = MAX ^ OPENING\nconst NOT_PREDESTROYING = MAX ^ PREDESTROYING\n\n// Read state (4 bit offset from shared state)\nconst READ_ACTIVE = 0b00000000000001 << 4\nconst READ_UPDATING = 0b00000000000010 << 4\nconst READ_PRIMARY = 0b00000000000100 << 4\nconst READ_QUEUED = 0b00000000001000 << 4\nconst READ_RESUMED = 0b00000000010000 << 4\nconst READ_PIPE_DRAINED = 0b00000000100000 << 4\nconst READ_ENDING = 0b00000001000000 << 4\nconst READ_EMIT_DATA = 0b00000010000000 << 4\nconst READ_EMIT_READABLE = 0b00000100000000 << 4\nconst READ_EMITTED_READABLE = 0b00001000000000 << 4\nconst READ_DONE = 0b00010000000000 << 4\nconst READ_NEXT_TICK = 0b00100000000000 << 4\nconst READ_NEEDS_PUSH = 0b01000000000000 << 4\nconst READ_READ_AHEAD = 0b10000000000000 << 4\n\n// Combined read state\nconst READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED\nconst READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH\nconst READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE\nconst READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED\nconst READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD\n\nconst READ_NOT_ACTIVE = MAX ^ READ_ACTIVE\nconst READ_NON_PRIMARY = MAX ^ READ_PRIMARY\nconst READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)\nconst READ_PUSHED = MAX ^ READ_NEEDS_PUSH\nconst READ_PAUSED = MAX ^ READ_RESUMED\nconst READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)\nconst READ_NOT_ENDING = MAX ^ READ_ENDING\nconst READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING\nconst READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK\nconst READ_NOT_UPDATING = MAX ^ READ_UPDATING\nconst READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD\nconst READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD\n\n// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)\nconst WRITE_ACTIVE = 0b00000000001 << 18\nconst WRITE_UPDATING = 0b00000000010 << 18\nconst WRITE_PRIMARY = 0b00000000100 << 18\nconst WRITE_QUEUED = 0b00000001000 << 18\nconst WRITE_UNDRAINED = 0b00000010000 << 18\nconst WRITE_DONE = 0b00000100000 << 18\nconst WRITE_EMIT_DRAIN = 0b00001000000 << 18\nconst WRITE_NEXT_TICK = 0b00010000000 << 18\nconst WRITE_WRITING = 0b00100000000 << 18\nconst WRITE_FINISHING = 0b01000000000 << 18\nconst WRITE_CORKED = 0b10000000000 << 18\n\nconst WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)\nconst WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY\nconst WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)\nconst WRITE_DRAINED = MAX ^ WRITE_UNDRAINED\nconst WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED\nconst WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK\nconst WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING\nconst WRITE_NOT_CORKED = MAX ^ WRITE_CORKED\n\n// Combined shared state\nconst ACTIVE = READ_ACTIVE | WRITE_ACTIVE\nconst NOT_ACTIVE = MAX ^ ACTIVE\nconst DONE = READ_DONE | WRITE_DONE\nconst DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING\nconst OPEN_STATUS = DESTROY_STATUS | OPENING\nconst AUTO_DESTROY = DESTROY_STATUS | DONE\nconst NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY\nconst ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK\nconst TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE\nconst IS_OPENING = OPEN_STATUS | TICKING\n\n// Combined shared state and read state\nconst READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE\nconst READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED\nconst READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED\nconst READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE\nconst SHOULD_NOT_READ =\n  OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD\nconst READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE\nconst READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY\nconst READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING\n\n// Combined write state\nconst WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE\nconst WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED\nconst WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE\nconst WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE\nconst WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED\nconst WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE\nconst WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING\nconst WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE\nconst WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE\nconst WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY\nconst WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS\n\nconst asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')\n\nclass WritableState {\n  constructor(\n    stream,\n    { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}\n  ) {\n    this.stream = stream\n    this.queue = new FIFO()\n    this.highWaterMark = highWaterMark\n    this.buffered = 0\n    this.error = null\n    this.pipeline = null\n    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr\n    this.byteLength = byteLengthWritable || byteLength || defaultByteLength\n    this.map = mapWritable || map\n    this.afterWrite = afterWrite.bind(this)\n    this.afterUpdateNextTick = updateWriteNT.bind(this)\n  }\n\n  get ending() {\n    return (this.stream._duplexState & WRITE_FINISHING) !== 0\n  }\n\n  get ended() {\n    return (this.stream._duplexState & WRITE_DONE) !== 0\n  }\n\n  push(data) {\n    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false\n    if (this.map !== null) data = this.map(data)\n\n    this.buffered += this.byteLength(data)\n    this.queue.push(data)\n\n    if (this.buffered < this.highWaterMark) {\n      this.stream._duplexState |= WRITE_QUEUED\n      return true\n    }\n\n    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED\n    return false\n  }\n\n  shift() {\n    const data = this.queue.shift()\n\n    this.buffered -= this.byteLength(data)\n    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED\n\n    return data\n  }\n\n  end(data) {\n    if (typeof data === 'function') {\n      this.stream.once('finish', data)\n    } else if (data !== undefined && data !== null) {\n      this.push(data)\n    }\n\n    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY\n  }\n\n  autoBatch(data, cb) {\n    const buffer = []\n    const stream = this.stream\n\n    buffer.push(data)\n    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {\n      buffer.push(stream._writableState.shift())\n    }\n\n    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)\n    stream._writev(buffer, cb)\n  }\n\n  update() {\n    const stream = this.stream\n\n    stream._duplexState |= WRITE_UPDATING\n\n    do {\n      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {\n        const data = this.shift()\n        stream._duplexState |= WRITE_ACTIVE_AND_WRITING\n        stream._write(data, this.afterWrite)\n      }\n\n      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()\n    } while (this.continueUpdate() === true)\n\n    stream._duplexState &= WRITE_NOT_UPDATING\n  }\n\n  updateNonPrimary() {\n    const stream = this.stream\n\n    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {\n      stream._duplexState = stream._duplexState | WRITE_ACTIVE\n      stream._final(afterFinal.bind(this))\n      return\n    }\n\n    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {\n      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {\n        stream._duplexState |= ACTIVE\n        stream._destroy(afterDestroy.bind(this))\n      }\n      return\n    }\n\n    if ((stream._duplexState & IS_OPENING) === OPENING) {\n      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING\n      stream._open(afterOpen.bind(this))\n    }\n  }\n\n  continueUpdate() {\n    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false\n    this.stream._duplexState &= WRITE_NOT_NEXT_TICK\n    return true\n  }\n\n  updateCallback() {\n    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) {\n      this.update()\n    } else {\n      this.updateNextTick()\n    }\n  }\n\n  updateNextTick() {\n    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return\n    this.stream._duplexState |= WRITE_NEXT_TICK\n    if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick)\n  }\n}\n\nclass ReadableState {\n  constructor(\n    stream,\n    { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}\n  ) {\n    this.stream = stream\n    this.queue = new FIFO()\n    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark\n    this.buffered = 0\n    this.readAhead = highWaterMark > 0\n    this.error = null\n    this.pipeline = null\n    this.byteLength = byteLengthReadable || byteLength || defaultByteLength\n    this.map = mapReadable || map\n    this.pipeTo = null\n    this.afterRead = afterRead.bind(this)\n    this.afterUpdateNextTick = updateReadNT.bind(this)\n  }\n\n  get ending() {\n    return (this.stream._duplexState & READ_ENDING) !== 0\n  }\n\n  get ended() {\n    return (this.stream._duplexState & READ_DONE) !== 0\n  }\n\n  pipe(pipeTo, cb) {\n    if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination')\n    if (typeof cb !== 'function') cb = null\n\n    this.stream._duplexState |= READ_PIPE_DRAINED\n    this.pipeTo = pipeTo\n    this.pipeline = new Pipeline(this.stream, pipeTo, cb)\n\n    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes\n\n    if (isStreamx(pipeTo)) {\n      pipeTo._writableState.pipeline = this.pipeline\n      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes\n      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself\n    } else {\n      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)\n      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg\n      pipeTo.on('error', onerror)\n      pipeTo.on('close', onclose)\n      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))\n    }\n\n    pipeTo.on('drain', afterDrain.bind(this))\n    this.stream.emit('piping', pipeTo)\n    pipeTo.emit('pipe', this.stream)\n  }\n\n  push(data) {\n    const stream = this.stream\n\n    if (data === null) {\n      this.highWaterMark = 0\n      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED\n      return false\n    }\n\n    if (this.map !== null) {\n      data = this.map(data)\n      if (data === null) {\n        stream._duplexState &= READ_PUSHED\n        return this.buffered < this.highWaterMark\n      }\n    }\n\n    this.buffered += this.byteLength(data)\n    this.queue.push(data)\n\n    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED\n\n    return this.buffered < this.highWaterMark\n  }\n\n  shift() {\n    const data = this.queue.shift()\n\n    this.buffered -= this.byteLength(data)\n    if (this.buffered === 0) {\n      this.stream._duplexState &= READ_NOT_QUEUED\n    }\n\n    return data\n  }\n\n  unshift(data) {\n    const pending = [this.map !== null ? this.map(data) : data]\n    while (this.buffered > 0) pending.push(this.shift())\n\n    for (let i = 0; i < pending.length - 1; i++) {\n      const data = pending[i]\n      this.buffered += this.byteLength(data)\n      this.queue.push(data)\n    }\n\n    this.push(pending[pending.length - 1])\n  }\n\n  read() {\n    const stream = this.stream\n\n    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {\n      const data = this.shift()\n\n      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {\n        stream._duplexState &= READ_PIPE_NOT_DRAINED\n      }\n\n      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {\n        stream.emit('data', data)\n      }\n\n      return data\n    }\n\n    if (this.readAhead === false) {\n      stream._duplexState |= READ_READ_AHEAD\n      this.updateNextTick()\n    }\n\n    return null\n  }\n\n  drain() {\n    const stream = this.stream\n\n    while (\n      (stream._duplexState & READ_STATUS) === READ_QUEUED &&\n      (stream._duplexState & READ_FLOWING) !== 0\n    ) {\n      const data = this.shift()\n\n      if (this.pipeTo !== null && this.pipeTo.write(data) === false) {\n        stream._duplexState &= READ_PIPE_NOT_DRAINED\n      }\n\n      if ((stream._duplexState & READ_EMIT_DATA) !== 0) {\n        stream.emit('data', data)\n      }\n    }\n  }\n\n  update() {\n    const stream = this.stream\n\n    stream._duplexState |= READ_UPDATING\n\n    do {\n      this.drain()\n\n      while (\n        this.buffered < this.highWaterMark &&\n        (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD\n      ) {\n        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH\n        stream._read(this.afterRead)\n        this.drain()\n      }\n\n      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {\n        stream._duplexState |= READ_EMITTED_READABLE\n        stream.emit('readable')\n      }\n\n      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) {\n        this.updateNonPrimary()\n      }\n    } while (this.continueUpdate() === true)\n\n    stream._duplexState &= READ_NOT_UPDATING\n  }\n\n  updateNonPrimary() {\n    const stream = this.stream\n\n    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {\n      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING\n      stream.emit('end')\n\n      if ((stream._duplexState & AUTO_DESTROY) === DONE) {\n        stream._duplexState |= DESTROYING\n      }\n\n      if (this.pipeTo !== null) {\n        this.pipeTo.end()\n      }\n    }\n\n    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {\n      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {\n        stream._duplexState |= ACTIVE\n        stream._destroy(afterDestroy.bind(this))\n      }\n      return\n    }\n\n    if ((stream._duplexState & IS_OPENING) === OPENING) {\n      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING\n      stream._open(afterOpen.bind(this))\n    }\n  }\n\n  continueUpdate() {\n    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false\n    this.stream._duplexState &= READ_NOT_NEXT_TICK\n    return true\n  }\n\n  updateCallback() {\n    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) {\n      this.update()\n    } else {\n      this.updateNextTick()\n    }\n  }\n\n  updateNextTickIfOpen() {\n    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return\n    this.stream._duplexState |= READ_NEXT_TICK\n    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)\n  }\n\n  updateNextTick() {\n    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return\n    this.stream._duplexState |= READ_NEXT_TICK\n    if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick)\n  }\n}\n\nclass TransformState {\n  constructor(stream) {\n    this.data = null\n    this.afterTransform = afterTransform.bind(stream)\n    this.afterFinal = null\n  }\n}\n\nclass Pipeline {\n  constructor(src, dst, cb) {\n    this.from = src\n    this.to = dst\n    this.afterPipe = cb\n    this.error = null\n    this.pipeToFinished = false\n  }\n\n  finished() {\n    this.pipeToFinished = true\n  }\n\n  done(stream, err) {\n    if (err) this.error = err\n\n    if (stream === this.to) {\n      this.to = null\n\n      if (this.from !== null) {\n        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {\n          this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed'))\n        }\n        return\n      }\n    }\n\n    if (stream === this.from) {\n      this.from = null\n\n      if (this.to !== null) {\n        if ((stream._duplexState & READ_DONE) === 0) {\n          this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed'))\n        }\n        return\n      }\n    }\n\n    if (this.afterPipe !== null) this.afterPipe(this.error)\n    this.to = this.from = this.afterPipe = null\n  }\n}\n\nfunction afterDrain() {\n  this.stream._duplexState |= READ_PIPE_DRAINED\n  this.updateCallback()\n}\n\nfunction afterFinal(err) {\n  const stream = this.stream\n  if (err) stream.destroy(err)\n\n  if ((stream._duplexState & DESTROY_STATUS) === 0) {\n    stream._duplexState |= WRITE_DONE\n    stream.emit('finish')\n  }\n\n  if ((stream._duplexState & AUTO_DESTROY) === DONE) {\n    stream._duplexState |= DESTROYING\n  }\n\n  stream._duplexState &= WRITE_NOT_FINISHING\n\n  // no need to wait the extra tick here, so we short circuit that\n  if ((stream._duplexState & WRITE_UPDATING) === 0) {\n    this.update()\n  } else {\n    this.updateNextTick()\n  }\n}\n\nfunction afterDestroy(err) {\n  const stream = this.stream\n\n  if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error\n  if (err) stream.emit('error', err)\n\n  stream._duplexState |= DESTROYED\n  stream.emit('close')\n\n  const rs = stream._readableState\n  const ws = stream._writableState\n\n  if (rs !== null && rs.pipeline !== null) {\n    rs.pipeline.done(stream, err)\n  }\n\n  if (ws !== null) {\n    while (ws.drains !== null && ws.drains.length > 0) {\n      ws.drains.shift().resolve(false)\n    }\n\n    if (ws.pipeline !== null) {\n      ws.pipeline.done(stream, err)\n    }\n  }\n}\n\nfunction afterWrite(err) {\n  const stream = this.stream\n\n  if (err) stream.destroy(err)\n  stream._duplexState &= WRITE_NOT_ACTIVE\n\n  if (this.drains !== null) tickDrains(this.drains)\n\n  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {\n    stream._duplexState &= WRITE_DRAINED\n\n    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {\n      stream.emit('drain')\n    }\n  }\n\n  this.updateCallback()\n}\n\nfunction afterRead(err) {\n  if (err) this.stream.destroy(err)\n  this.stream._duplexState &= READ_NOT_ACTIVE\n\n  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) {\n    this.stream._duplexState &= READ_NO_READ_AHEAD\n  }\n\n  this.updateCallback()\n}\n\nfunction updateReadNT() {\n  if ((this.stream._duplexState & READ_UPDATING) === 0) {\n    this.stream._duplexState &= READ_NOT_NEXT_TICK\n    this.update()\n  }\n}\n\nfunction updateWriteNT() {\n  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {\n    this.stream._duplexState &= WRITE_NOT_NEXT_TICK\n    this.update()\n  }\n}\n\nfunction tickDrains(drains) {\n  for (let i = 0; i < drains.length; i++) {\n    // drains.writes are monotonic, so if one is 0 its always the first one\n    if (--drains[i].writes === 0) {\n      drains.shift().resolve(true)\n      i--\n    }\n  }\n}\n\nfunction afterOpen(err) {\n  const stream = this.stream\n\n  if (err) stream.destroy(err)\n\n  if ((stream._duplexState & DESTROYING) === 0) {\n    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) {\n      stream._duplexState |= READ_PRIMARY\n    }\n\n    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) {\n      stream._duplexState |= WRITE_PRIMARY\n    }\n\n    stream.emit('open')\n  }\n\n  stream._duplexState &= NOT_ACTIVE\n\n  if (stream._writableState !== null) {\n    stream._writableState.updateCallback()\n  }\n\n  if (stream._readableState !== null) {\n    stream._readableState.updateCallback()\n  }\n}\n\nfunction afterTransform(err, data) {\n  if (data !== undefined && data !== null) this.push(data)\n  this._writableState.afterWrite(err)\n}\n\nfunction newListener(name) {\n  if (this._readableState !== null) {\n    if (name === 'data') {\n      this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD\n      this._readableState.updateNextTick()\n    }\n    if (name === 'readable') {\n      this._duplexState |= READ_EMIT_READABLE\n      this._readableState.updateNextTick()\n    }\n  }\n\n  if (this._writableState !== null) {\n    if (name === 'drain') {\n      this._duplexState |= WRITE_EMIT_DRAIN\n      this._writableState.updateNextTick()\n    }\n  }\n}\n\nclass Stream extends EventEmitter {\n  constructor(opts) {\n    super()\n\n    this._duplexState = 0\n    this._readableState = null\n    this._writableState = null\n\n    if (opts) {\n      if (opts.open) this._open = opts.open\n      if (opts.destroy) this._destroy = opts.destroy\n      if (opts.predestroy) this._predestroy = opts.predestroy\n      if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this))\n    }\n\n    this.on('newListener', newListener)\n  }\n\n  _open(cb) {\n    cb(null)\n  }\n\n  _destroy(cb) {\n    cb(null)\n  }\n\n  _predestroy() {\n    // does nothing\n  }\n\n  get readable() {\n    return this._readableState !== null ? true : undefined\n  }\n\n  get writable() {\n    return this._writableState !== null ? true : undefined\n  }\n\n  get destroyed() {\n    return (this._duplexState & DESTROYED) !== 0\n  }\n\n  get destroying() {\n    return (this._duplexState & DESTROY_STATUS) !== 0\n  }\n\n  destroy(err) {\n    if ((this._duplexState & DESTROY_STATUS) === 0) {\n      if (!err) err = StreamError.STREAM_DESTROYED()\n      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY\n\n      if (this._readableState !== null) {\n        this._readableState.highWaterMark = 0\n        this._readableState.error = err\n      }\n\n      if (this._writableState !== null) {\n        this._writableState.highWaterMark = 0\n        this._writableState.error = err\n      }\n\n      this._duplexState |= PREDESTROYING\n      this._predestroy()\n      this._duplexState &= NOT_PREDESTROYING\n\n      if (this._readableState !== null) {\n        this._readableState.updateNextTick()\n      }\n\n      if (this._writableState !== null) {\n        this._writableState.updateNextTick()\n      }\n    }\n  }\n}\n\nclass Readable extends Stream {\n  constructor(opts) {\n    super(opts)\n\n    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD\n    this._readableState = new ReadableState(this, opts)\n\n    if (opts) {\n      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD\n      if (opts.read) this._read = opts.read\n      if (opts.eagerOpen) this._readableState.updateNextTick()\n      if (opts.encoding) this.setEncoding(opts.encoding)\n    }\n  }\n\n  static deferred(fn, opts) {\n    const out = new PassThrough(opts)\n\n    fn()\n      .then((src) => {\n        if (src === null) return out.end()\n        if (out.destroying) return\n        pipeline(src, out, noop)\n      })\n      .catch((err) => out.destroy(err))\n\n    return out\n  }\n\n  setEncoding(encoding) {\n    const dec = new TextDecoder(encoding)\n    const map = this._readableState.map || echo\n    this._readableState.map = mapOrSkip\n    return this\n\n    function mapOrSkip(data) {\n      const next = dec.push(data)\n      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)\n    }\n  }\n\n  _read(cb) {\n    cb(null)\n  }\n\n  pipe(dest, cb) {\n    this._readableState.updateNextTick()\n    this._readableState.pipe(dest, cb)\n    return dest\n  }\n\n  read() {\n    this._readableState.updateNextTick()\n    return this._readableState.read()\n  }\n\n  push(data) {\n    this._readableState.updateNextTickIfOpen()\n    return this._readableState.push(data)\n  }\n\n  unshift(data) {\n    this._readableState.updateNextTickIfOpen()\n    return this._readableState.unshift(data)\n  }\n\n  resume() {\n    this._duplexState |= READ_RESUMED_READ_AHEAD\n    this._readableState.updateNextTick()\n    return this\n  }\n\n  pause() {\n    this._duplexState &=\n      this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED\n    return this\n  }\n\n  static _fromAsyncIterator(ite, opts) {\n    let destroy\n\n    const rs = new Readable({\n      ...opts,\n      read(cb) {\n        ite.next().then(push).then(cb.bind(null, null)).catch(cb)\n      },\n      predestroy() {\n        destroy = ite.return()\n      },\n      destroy(cb) {\n        if (!destroy) return cb(null)\n        destroy.then(cb.bind(null, null)).catch(cb)\n      }\n    })\n\n    return rs\n\n    function push(data) {\n      if (data.done) rs.push(null)\n      else rs.push(data.value)\n    }\n  }\n\n  static from(data, opts) {\n    if (isReadStreamx(data)) return data\n    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)\n    if (!Array.isArray(data)) data = data === undefined ? [] : [data]\n\n    let i = 0\n    return new Readable({\n      ...opts,\n      read(cb) {\n        this.push(i === data.length ? null : data[i++])\n        cb(null)\n      }\n    })\n  }\n\n  static isBackpressured(rs) {\n    return (\n      (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 ||\n      rs._readableState.buffered >= rs._readableState.highWaterMark\n    )\n  }\n\n  static isPaused(rs) {\n    return (rs._duplexState & READ_RESUMED) === 0\n  }\n\n  [asyncIterator]() {\n    const stream = this\n\n    let error = null\n    let promiseResolve = null\n    let promiseReject = null\n\n    this.on('error', (err) => {\n      error = err\n    })\n    this.on('readable', onreadable)\n    this.on('close', onclose)\n\n    return {\n      [asyncIterator]() {\n        return this\n      },\n      next() {\n        return new Promise(function (resolve, reject) {\n          promiseResolve = resolve\n          promiseReject = reject\n          const data = stream.read()\n          if (data !== null) ondata(data)\n          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)\n        })\n      },\n      return() {\n        return destroy(null)\n      },\n      throw(err) {\n        return destroy(err)\n      }\n    }\n\n    function onreadable() {\n      if (promiseResolve !== null) ondata(stream.read())\n    }\n\n    function onclose() {\n      if (promiseResolve !== null) ondata(null)\n    }\n\n    function ondata(data) {\n      if (promiseReject === null) return\n      if (error) {\n        promiseReject(error)\n      } else if (data === null && (stream._duplexState & READ_DONE) === 0) {\n        promiseReject(StreamError.STREAM_DESTROYED())\n      } else {\n        promiseResolve({ value: data, done: data === null })\n      }\n      promiseReject = promiseResolve = null\n    }\n\n    function destroy(err) {\n      stream.destroy(err)\n      return new Promise((resolve, reject) => {\n        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })\n        stream.once('close', function () {\n          if (err) reject(err)\n          else resolve({ value: undefined, done: true })\n        })\n      })\n    }\n  }\n}\n\nclass Writable extends Stream {\n  constructor(opts) {\n    super(opts)\n\n    this._duplexState |= OPENING | READ_DONE\n    this._writableState = new WritableState(this, opts)\n\n    if (opts) {\n      if (opts.writev) this._writev = opts.writev\n      if (opts.write) this._write = opts.write\n      if (opts.final) this._final = opts.final\n      if (opts.eagerOpen) this._writableState.updateNextTick()\n    }\n  }\n\n  cork() {\n    this._duplexState |= WRITE_CORKED\n  }\n\n  uncork() {\n    this._duplexState &= WRITE_NOT_CORKED\n    this._writableState.updateNextTick()\n  }\n\n  _writev(batch, cb) {\n    cb(null)\n  }\n\n  _write(data, cb) {\n    this._writableState.autoBatch(data, cb)\n  }\n\n  _final(cb) {\n    cb(null)\n  }\n\n  static isBackpressured(ws) {\n    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0\n  }\n\n  static drained(ws) {\n    if (ws.destroyed) return Promise.resolve(false)\n\n    const state = ws._writableState\n    const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length\n    const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0)\n    if (writes === 0) return Promise.resolve(true)\n\n    if (state.drains === null) state.drains = []\n    return new Promise((resolve) => {\n      state.drains.push({ writes, resolve })\n    })\n  }\n\n  write(data) {\n    this._writableState.updateNextTick()\n    return this._writableState.push(data)\n  }\n\n  end(data) {\n    this._writableState.updateNextTick()\n    this._writableState.end(data)\n    return this\n  }\n}\n\nclass Duplex extends Readable {\n  // and Writable\n  constructor(opts) {\n    super(opts)\n\n    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)\n    this._writableState = new WritableState(this, opts)\n\n    if (opts) {\n      if (opts.writev) this._writev = opts.writev\n      if (opts.write) this._write = opts.write\n      if (opts.final) this._final = opts.final\n    }\n  }\n\n  cork() {\n    this._duplexState |= WRITE_CORKED\n  }\n\n  uncork() {\n    this._duplexState &= WRITE_NOT_CORKED\n    this._writableState.updateNextTick()\n  }\n\n  _writev(batch, cb) {\n    cb(null)\n  }\n\n  _write(data, cb) {\n    this._writableState.autoBatch(data, cb)\n  }\n\n  _final(cb) {\n    cb(null)\n  }\n\n  write(data) {\n    this._writableState.updateNextTick()\n    return this._writableState.push(data)\n  }\n\n  end(data) {\n    this._writableState.updateNextTick()\n    this._writableState.end(data)\n    return this\n  }\n}\n\nclass Transform extends Duplex {\n  constructor(opts) {\n    super(opts)\n    this._transformState = new TransformState(this)\n\n    if (opts) {\n      if (opts.transform) this._transform = opts.transform\n      if (opts.flush) this._flush = opts.flush\n    }\n  }\n\n  _write(data, cb) {\n    if (this._readableState.buffered >= this._readableState.highWaterMark) {\n      this._transformState.data = data\n    } else {\n      this._transform(data, this._transformState.afterTransform)\n    }\n  }\n\n  _read(cb) {\n    if (this._transformState.data !== null) {\n      const data = this._transformState.data\n      this._transformState.data = null\n      cb(null)\n      this._transform(data, this._transformState.afterTransform)\n    } else {\n      cb(null)\n    }\n  }\n\n  destroy(err) {\n    super.destroy(err)\n    if (this._transformState.data !== null) {\n      this._transformState.data = null\n      this._transformState.afterTransform()\n    }\n  }\n\n  _transform(data, cb) {\n    cb(null, data)\n  }\n\n  _flush(cb) {\n    cb(null)\n  }\n\n  _final(cb) {\n    this._transformState.afterFinal = cb\n    this._flush(transformAfterFlush.bind(this))\n  }\n}\n\nclass PassThrough extends Transform {}\n\nfunction transformAfterFlush(err, data) {\n  const cb = this._transformState.afterFinal\n  if (err) return cb(err)\n\n  if (data !== null && data !== undefined) this.push(data)\n  this.push(null)\n  cb(null)\n}\n\nfunction pipelinePromise(...streams) {\n  return new Promise((resolve, reject) => {\n    return pipeline(...streams, (err) => {\n      if (err) return reject(err)\n      resolve()\n    })\n  })\n}\n\nfunction pipeline(stream, ...streams) {\n  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]\n  const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null\n\n  if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams')\n\n  let src = all[0]\n  let dest = null\n  let error = null\n\n  for (let i = 1; i < all.length; i++) {\n    dest = all[i]\n\n    if (isStreamx(src)) {\n      src.pipe(dest, onerror)\n    } else {\n      errorHandle(src, true, i > 1, onerror)\n      src.pipe(dest)\n    }\n\n    src = dest\n  }\n\n  if (done) {\n    let fin = false\n\n    const autoDestroy =\n      isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)\n\n    dest.on('error', (err) => {\n      if (error === null) error = err\n    })\n\n    dest.on('finish', () => {\n      fin = true\n      if (!autoDestroy) done(error)\n    })\n\n    if (autoDestroy) {\n      dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE())))\n    }\n  }\n\n  return dest\n\n  function errorHandle(s, rd, wr, onerror) {\n    s.on('error', onerror)\n    s.on('close', onclose)\n\n    function onclose() {\n      if (rd && s._readableState && !s._readableState.ended) {\n        return onerror(StreamError.PREMATURE_CLOSE())\n      }\n      if (wr && s._writableState && !s._writableState.ended) {\n        return onerror(StreamError.PREMATURE_CLOSE())\n      }\n    }\n  }\n\n  function onerror(err) {\n    if (!err || error) return\n    error = err\n\n    for (const s of all) {\n      s.destroy(err)\n    }\n  }\n}\n\nfunction echo(s) {\n  return s\n}\n\nfunction isStream(stream) {\n  return !!stream._readableState || !!stream._writableState\n}\n\nfunction isStreamx(stream) {\n  return typeof stream._duplexState === 'number' && isStream(stream)\n}\n\nfunction isEnding(stream) {\n  return !!stream._readableState && stream._readableState.ending\n}\n\nfunction isEnded(stream) {\n  return !!stream._readableState && stream._readableState.ended\n}\n\nfunction isFinishing(stream) {\n  return !!stream._writableState && stream._writableState.ending\n}\n\nfunction isFinished(stream) {\n  return !!stream._writableState && stream._writableState.ended\n}\n\nfunction getStreamError(stream, opts = {}) {\n  const err =\n    (stream._readableState && stream._readableState.error) ||\n    (stream._writableState && stream._writableState.error)\n\n  // avoid implicit errors by default\n  return !opts.all && StreamError.isStreamDestroyed(err) ? null : err\n}\n\nfunction isReadStreamx(stream) {\n  return isStreamx(stream) && stream.readable\n}\n\nfunction isDisturbed(stream) {\n  return (\n    (stream._duplexState & OPENING) !== OPENING ||\n    (stream._duplexState & DESTROYING) === DESTROYING ||\n    (stream._duplexState & ACTIVE_OR_TICKING) !== 0\n  )\n}\n\nfunction isTypedArray(data) {\n  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'\n}\n\nfunction defaultByteLength(data) {\n  return isTypedArray(data) ? data.byteLength : 1024\n}\n\nfunction noop() {}\n\nfunction abort() {\n  this.destroy(StreamError.ABORTED())\n}\n\nfunction isWritev(s) {\n  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev\n}\n\nmodule.exports = {\n  pipeline,\n  pipelinePromise,\n  isStream,\n  isStreamx,\n  isEnding,\n  isEnded,\n  isFinishing,\n  isFinished,\n  isDisturbed,\n  getStreamError,\n  Stream,\n  Writable,\n  Readable,\n  Duplex,\n  Transform,\n  // Export PassThrough for compatibility with Node.js core's stream module\n  PassThrough\n}\n","const b4a = require('b4a')\n\nconst ZEROS = '0000000000000000000'\nconst SEVENS = '7777777777777777777'\nconst ZERO_OFFSET = '0'.charCodeAt(0)\nconst USTAR_MAGIC = b4a.from([0x75, 0x73, 0x74, 0x61, 0x72, 0x00]) // ustar\\x00\nconst USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET])\nconst GNU_MAGIC = b4a.from([0x75, 0x73, 0x74, 0x61, 0x72, 0x20]) // ustar\\x20\nconst GNU_VER = b4a.from([0x20, 0x00])\nconst MASK = 0o7777\nconst MAGIC_OFFSET = 257\nconst VERSION_OFFSET = 263\n\nexports.decodeLongPath = function decodeLongPath (buf, encoding) {\n  return decodeStr(buf, 0, buf.length, encoding)\n}\n\nexports.encodePax = function encodePax (opts) { // TODO: encode more stuff in pax\n  let result = ''\n  if (opts.name) result += addLength(' path=' + opts.name + '\\n')\n  if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\\n')\n  const pax = opts.pax\n  if (pax) {\n    for (const key in pax) {\n      result += addLength(' ' + key + '=' + pax[key] + '\\n')\n    }\n  }\n  return b4a.from(result)\n}\n\nexports.decodePax = function decodePax (buf) {\n  const result = {}\n\n  while (buf.length) {\n    let i = 0\n    while (i < buf.length && buf[i] !== 32) i++\n    const len = parseInt(b4a.toString(buf.subarray(0, i)), 10)\n    if (!len) return result\n\n    const b = b4a.toString(buf.subarray(i + 1, len - 1))\n    const keyIndex = b.indexOf('=')\n    if (keyIndex === -1) return result\n    result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n\n    buf = buf.subarray(len)\n  }\n\n  return result\n}\n\nexports.encode = function encode (opts) {\n  const buf = b4a.alloc(512)\n  let name = opts.name\n  let prefix = ''\n\n  if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/'\n  if (b4a.byteLength(name) !== name.length) return null // utf-8\n\n  while (b4a.byteLength(name) > 100) {\n    const i = name.indexOf('/')\n    if (i === -1) return null\n    prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i)\n    name = name.slice(i + 1)\n  }\n\n  if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null\n  if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null\n\n  b4a.write(buf, name)\n  b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100)\n  b4a.write(buf, encodeOct(opts.uid, 6), 108)\n  b4a.write(buf, encodeOct(opts.gid, 6), 116)\n  encodeSize(opts.size, buf, 124)\n  b4a.write(buf, encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n  buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n  if (opts.linkname) b4a.write(buf, opts.linkname, 157)\n\n  b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET)\n  b4a.copy(USTAR_VER, buf, VERSION_OFFSET)\n  if (opts.uname) b4a.write(buf, opts.uname, 265)\n  if (opts.gname) b4a.write(buf, opts.gname, 297)\n  b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329)\n  b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337)\n\n  if (prefix) b4a.write(buf, prefix, 345)\n\n  b4a.write(buf, encodeOct(cksum(buf), 6), 148)\n\n  return buf\n}\n\nexports.decode = function decode (buf, filenameEncoding, allowUnknownFormat) {\n  let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET\n\n  let name = decodeStr(buf, 0, 100, filenameEncoding)\n  const mode = decodeOct(buf, 100, 8)\n  const uid = decodeOct(buf, 108, 8)\n  const gid = decodeOct(buf, 116, 8)\n  const size = decodeOct(buf, 124, 12)\n  const mtime = decodeOct(buf, 136, 12)\n  const type = toType(typeflag)\n  const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding)\n  const uname = decodeStr(buf, 265, 32)\n  const gname = decodeStr(buf, 297, 32)\n  const devmajor = decodeOct(buf, 329, 8)\n  const devminor = decodeOct(buf, 337, 8)\n\n  const c = cksum(buf)\n\n  // checksum is still initial value if header was null.\n  if (c === 8 * 32) return null\n\n  // valid checksum\n  if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n\n  if (isUSTAR(buf)) {\n    // ustar (posix) format.\n    // prepend prefix, if present.\n    if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name\n  } else if (isGNU(buf)) {\n    // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n    // multi-volume tarballs.\n  } else {\n    if (!allowUnknownFormat) {\n      throw new Error('Invalid tar header: unknown format.')\n    }\n  }\n\n  // to support old tar versions that use trailing / to indicate dirs\n  if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5\n\n  return {\n    name,\n    mode,\n    uid,\n    gid,\n    size,\n    byteOffset: 0,\n    mtime: new Date(1000 * mtime),\n    type,\n    linkname,\n    uname,\n    gname,\n    devmajor,\n    devminor,\n    pax: null\n  }\n}\n\nfunction isUSTAR (buf) {\n  return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6))\n}\n\nfunction isGNU (buf) {\n  return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) &&\n    b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2))\n}\n\nfunction clamp (index, len, defaultValue) {\n  if (typeof index !== 'number') return defaultValue\n  index = ~~index // Coerce to integer.\n  if (index >= len) return len\n  if (index >= 0) return index\n  index += len\n  if (index >= 0) return index\n  return 0\n}\n\nfunction toType (flag) {\n  switch (flag) {\n    case 0:\n      return 'file'\n    case 1:\n      return 'link'\n    case 2:\n      return 'symlink'\n    case 3:\n      return 'character-device'\n    case 4:\n      return 'block-device'\n    case 5:\n      return 'directory'\n    case 6:\n      return 'fifo'\n    case 7:\n      return 'contiguous-file'\n    case 72:\n      return 'pax-header'\n    case 55:\n      return 'pax-global-header'\n    case 27:\n      return 'gnu-long-link-path'\n    case 28:\n    case 30:\n      return 'gnu-long-path'\n  }\n\n  return null\n}\n\nfunction toTypeflag (flag) {\n  switch (flag) {\n    case 'file':\n      return 0\n    case 'link':\n      return 1\n    case 'symlink':\n      return 2\n    case 'character-device':\n      return 3\n    case 'block-device':\n      return 4\n    case 'directory':\n      return 5\n    case 'fifo':\n      return 6\n    case 'contiguous-file':\n      return 7\n    case 'pax-header':\n      return 72\n  }\n\n  return 0\n}\n\nfunction indexOf (block, num, offset, end) {\n  for (; offset < end; offset++) {\n    if (block[offset] === num) return offset\n  }\n  return end\n}\n\nfunction cksum (block) {\n  let sum = 8 * 32\n  for (let i = 0; i < 148; i++) sum += block[i]\n  for (let j = 156; j < 512; j++) sum += block[j]\n  return sum\n}\n\nfunction encodeOct (val, n) {\n  val = val.toString(8)\n  if (val.length > n) return SEVENS.slice(0, n) + ' '\n  return ZEROS.slice(0, n - val.length) + val + ' '\n}\n\nfunction encodeSizeBin (num, buf, off) {\n  buf[off] = 0x80\n  for (let i = 11; i > 0; i--) {\n    buf[off + i] = num & 0xff\n    num = Math.floor(num / 0x100)\n  }\n}\n\nfunction encodeSize (num, buf, off) {\n  if (num.toString(8).length > 11) {\n    encodeSizeBin(num, buf, off)\n  } else {\n    b4a.write(buf, encodeOct(num, 11), off)\n  }\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf) {\n  // first byte MUST be either 80 or FF\n  // 80 for positive, FF for 2's comp\n  let positive\n  if (buf[0] === 0x80) positive = true\n  else if (buf[0] === 0xFF) positive = false\n  else return null\n\n  // build up a base-256 tuple from the least sig to the highest\n  const tuple = []\n  let i\n  for (i = buf.length - 1; i > 0; i--) {\n    const byte = buf[i]\n    if (positive) tuple.push(byte)\n    else tuple.push(0xFF - byte)\n  }\n\n  let sum = 0\n  const l = tuple.length\n  for (i = 0; i < l; i++) {\n    sum += tuple[i] * Math.pow(256, i)\n  }\n\n  return positive ? sum : -1 * sum\n}\n\nfunction decodeOct (val, offset, length) {\n  val = val.subarray(offset, offset + length)\n  offset = 0\n\n  // If prefixed with 0x80 then parse as a base-256 integer\n  if (val[offset] & 0x80) {\n    return parse256(val)\n  } else {\n    // Older versions of tar can prefix with spaces\n    while (offset < val.length && val[offset] === 32) offset++\n    const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n    while (offset < end && val[offset] === 0) offset++\n    if (end === offset) return 0\n    return parseInt(b4a.toString(val.subarray(offset, end)), 8)\n  }\n}\n\nfunction decodeStr (val, offset, length, encoding) {\n  return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding)\n}\n\nfunction addLength (str) {\n  const len = b4a.byteLength(str)\n  let digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n  if (len + digits >= Math.pow(10, digits)) digits++\n\n  return (len + digits) + str\n}\n","const { Writable, Readable, getStreamError } = require('streamx')\nconst FIFO = require('fast-fifo')\nconst b4a = require('b4a')\nconst headers = require('./headers')\n\nconst EMPTY = b4a.alloc(0)\nconst MAX_HEADER_SIZE = 4 * 1024 * 1024 // arbitrary big number\n\nclass BufferList {\n  constructor () {\n    this.buffered = 0\n    this.shifted = 0\n    this.queue = new FIFO()\n\n    this._offset = 0\n  }\n\n  push (buffer) {\n    this.buffered += buffer.byteLength\n    this.queue.push(buffer)\n  }\n\n  shiftFirst (size) {\n    return this.buffered === 0 ? null : this._next(size)\n  }\n\n  shift (size) {\n    if (size > this.buffered) return null\n    if (size === 0) return EMPTY\n\n    let chunk = this._next(size)\n\n    if (size === chunk.byteLength) return chunk // likely case\n\n    const chunks = [chunk]\n\n    while ((size -= chunk.byteLength) > 0) {\n      chunk = this._next(size)\n      chunks.push(chunk)\n    }\n\n    return b4a.concat(chunks)\n  }\n\n  _next (size) {\n    const buf = this.queue.peek()\n    const rem = buf.byteLength - this._offset\n\n    if (size >= rem) {\n      const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf\n      this.queue.shift()\n      this._offset = 0\n      this.buffered -= rem\n      this.shifted += rem\n      return sub\n    }\n\n    this.buffered -= size\n    this.shifted += size\n\n    return buf.subarray(this._offset, (this._offset += size))\n  }\n}\n\nclass Source extends Readable {\n  constructor (self, header, offset) {\n    super()\n\n    this.header = header\n    this.offset = offset\n\n    this._parent = self\n  }\n\n  _read (cb) {\n    if (this.header.size === 0) {\n      this.push(null)\n    }\n    if (this._parent._stream === this) {\n      this._parent._update()\n    }\n    cb(null)\n  }\n\n  _predestroy () {\n    this._parent.destroy(getStreamError(this))\n  }\n\n  _detach () {\n    if (this._parent._stream === this) {\n      this._parent._stream = null\n      this._parent._missing = overflow(this.header.size)\n      this._parent._update()\n    }\n  }\n\n  _destroy (cb) {\n    this._detach()\n    cb(null)\n  }\n}\n\nclass Extract extends Writable {\n  constructor (opts) {\n    super(opts)\n\n    if (!opts) opts = {}\n\n    this._buffer = new BufferList()\n    this._offset = 0\n    this._header = null\n    this._stream = null\n    this._missing = 0\n    this._longHeader = false\n    this._callback = noop\n    this._locked = false\n    this._finished = false\n    this._pax = null\n    this._paxGlobal = null\n    this._gnuLongPath = null\n    this._gnuLongLinkPath = null\n    this._filenameEncoding = opts.filenameEncoding || 'utf-8'\n    this._allowUnknownFormat = !!opts.allowUnknownFormat\n    this._unlockBound = this._unlock.bind(this)\n  }\n\n  _unlock (err) {\n    this._locked = false\n\n    if (err) {\n      this.destroy(err)\n      this._continueWrite(err)\n      return\n    }\n\n    this._update()\n  }\n\n  _consumeHeader () {\n    if (this._locked) return false\n\n    this._offset = this._buffer.shifted\n\n    try {\n      this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat)\n    } catch (err) {\n      this._continueWrite(err)\n      return false\n    }\n\n    if (!this._header) return true\n\n    this._header.byteOffset = this._buffer.shifted\n\n    switch (this._header.type) {\n      case 'gnu-long-path':\n      case 'gnu-long-link-path':\n      case 'pax-global-header':\n      case 'pax-header':\n        this._longHeader = true\n        this._missing = this._header.size\n        if (this._missing > MAX_HEADER_SIZE) {\n          this._continueWrite(new Error('Header exceeds max size'))\n          return false\n        }\n        return true\n    }\n\n    this._locked = true\n    this._applyLongHeaders()\n\n    if (!(this._header.size >= 0)) {\n      this._continueWrite(new Error('Invalid header'))\n      return false\n    }\n\n    if (this._header.size === 0 || this._header.type === 'directory') {\n      this.emit('entry', this._header, this._createStream(), this._unlockBound)\n      return true\n    }\n\n    this._stream = this._createStream()\n    this._missing = this._header.size\n\n    this.emit('entry', this._header, this._stream, this._unlockBound)\n    return true\n  }\n\n  _applyLongHeaders () {\n    if (this._gnuLongPath) {\n      this._header.name = this._gnuLongPath\n      this._gnuLongPath = null\n    }\n\n    if (this._gnuLongLinkPath) {\n      this._header.linkname = this._gnuLongLinkPath\n      this._gnuLongLinkPath = null\n    }\n\n    if (this._pax) {\n      if (this._pax.path) this._header.name = this._pax.path\n      if (this._pax.linkpath) this._header.linkname = this._pax.linkpath\n      if (this._pax.size) this._header.size = parseInt(this._pax.size, 10)\n      this._header.pax = this._pax\n      this._pax = null\n    }\n  }\n\n  _decodeLongHeader (buf) {\n    switch (this._header.type) {\n      case 'gnu-long-path':\n        this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding)\n        break\n      case 'gnu-long-link-path':\n        this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding)\n        break\n      case 'pax-global-header':\n        this._paxGlobal = headers.decodePax(buf)\n        break\n      case 'pax-header':\n        this._pax = this._paxGlobal === null\n          ? headers.decodePax(buf)\n          : Object.assign({}, this._paxGlobal, headers.decodePax(buf))\n        break\n    }\n  }\n\n  _consumeLongHeader () {\n    this._longHeader = false\n    this._missing = overflow(this._header.size)\n\n    const buf = this._buffer.shift(this._header.size)\n\n    try {\n      this._decodeLongHeader(buf)\n    } catch (err) {\n      this._continueWrite(err)\n      return false\n    }\n\n    return true\n  }\n\n  _consumeStream () {\n    const buf = this._buffer.shiftFirst(this._missing)\n    if (buf === null) return false\n\n    this._missing -= buf.byteLength\n    const drained = this._stream.push(buf)\n\n    if (this._missing === 0) {\n      this._stream.push(null)\n      if (drained) this._stream._detach()\n      return drained && this._locked === false\n    }\n\n    return drained\n  }\n\n  _createStream () {\n    return new Source(this, this._header, this._offset)\n  }\n\n  _update () {\n    while (this._buffer.buffered > 0 && !this.destroying) {\n      if (this._missing > 0) {\n        if (this._stream !== null) {\n          if (this._consumeStream() === false) return\n          continue\n        }\n\n        if (this._longHeader === true) {\n          if (this._missing > this._buffer.buffered) break\n          if (this._consumeLongHeader() === false) return false\n          continue\n        }\n\n        const ignore = this._buffer.shiftFirst(this._missing)\n        if (ignore !== null) this._missing -= ignore.byteLength\n        continue\n      }\n\n      if (this._buffer.buffered < 512) break\n      if (this._stream !== null || this._consumeHeader() === false) return\n    }\n\n    this._continueWrite(null)\n  }\n\n  _continueWrite (err) {\n    const cb = this._callback\n    this._callback = noop\n    cb(err)\n  }\n\n  _write (data, cb) {\n    this._callback = cb\n    this._buffer.push(data)\n    this._update()\n  }\n\n  _final (cb) {\n    this._finished = this._missing === 0 && this._buffer.buffered === 0\n    cb(this._finished ? null : new Error('Unexpected end of data'))\n  }\n\n  _predestroy () {\n    this._continueWrite(null)\n  }\n\n  _destroy (cb) {\n    if (this._stream) this._stream.destroy(getStreamError(this))\n    cb(null)\n  }\n\n  [Symbol.asyncIterator] () {\n    let error = null\n\n    let promiseResolve = null\n    let promiseReject = null\n\n    let entryStream = null\n    let entryCallback = null\n\n    const extract = this\n\n    this.on('entry', onentry)\n    this.on('error', (err) => { error = err })\n    this.on('close', onclose)\n\n    return {\n      [Symbol.asyncIterator] () {\n        return this\n      },\n      next () {\n        return new Promise(onnext)\n      },\n      return () {\n        return destroy(null)\n      },\n      throw (err) {\n        return destroy(err)\n      }\n    }\n\n    function consumeCallback (err) {\n      if (!entryCallback) return\n      const cb = entryCallback\n      entryCallback = null\n      cb(err)\n    }\n\n    function onnext (resolve, reject) {\n      if (error) {\n        return reject(error)\n      }\n\n      if (entryStream) {\n        resolve({ value: entryStream, done: false })\n        entryStream = null\n        return\n      }\n\n      promiseResolve = resolve\n      promiseReject = reject\n\n      consumeCallback(null)\n\n      if (extract._finished && promiseResolve) {\n        promiseResolve({ value: undefined, done: true })\n        promiseResolve = promiseReject = null\n      }\n    }\n\n    function onentry (header, stream, callback) {\n      entryCallback = callback\n      stream.on('error', noop) // no way around this due to tick sillyness\n\n      if (promiseResolve) {\n        promiseResolve({ value: stream, done: false })\n        promiseResolve = promiseReject = null\n      } else {\n        entryStream = stream\n      }\n    }\n\n    function onclose () {\n      consumeCallback(error)\n      if (!promiseResolve) return\n      if (error) promiseReject(error)\n      else promiseResolve({ value: undefined, done: true })\n      promiseResolve = promiseReject = null\n    }\n\n    function destroy (err) {\n      extract.destroy(err)\n      consumeCallback(err)\n      return new Promise((resolve, reject) => {\n        if (extract.destroyed) return resolve({ value: undefined, done: true })\n        extract.once('close', function () {\n          if (err) reject(err)\n          else resolve({ value: undefined, done: true })\n        })\n      })\n    }\n  }\n}\n\nmodule.exports = function extract (opts) {\n  return new Extract(opts)\n}\n\nfunction noop () {}\n\nfunction overflow (size) {\n  size &= 511\n  return size && 512 - size\n}\n","const constants = { // just for envs without fs\n  S_IFMT: 61440,\n  S_IFDIR: 16384,\n  S_IFCHR: 8192,\n  S_IFBLK: 24576,\n  S_IFIFO: 4096,\n  S_IFLNK: 40960\n}\n\ntry {\n  module.exports = require('fs').constants || constants\n} catch {\n  module.exports = constants\n}\n","const { Readable, Writable, getStreamError } = require('streamx')\nconst b4a = require('b4a')\n\nconst constants = require('./constants')\nconst headers = require('./headers')\n\nconst DMODE = 0o755\nconst FMODE = 0o644\n\nconst END_OF_TAR = b4a.alloc(1024)\n\nclass Sink extends Writable {\n  constructor (pack, header, callback) {\n    super({ mapWritable, eagerOpen: true })\n\n    this.written = 0\n    this.header = header\n\n    this._callback = callback\n    this._linkname = null\n    this._isLinkname = header.type === 'symlink' && !header.linkname\n    this._isVoid = header.type !== 'file' && header.type !== 'contiguous-file'\n    this._finished = false\n    this._pack = pack\n    this._openCallback = null\n\n    if (this._pack._stream === null) this._pack._stream = this\n    else this._pack._pending.push(this)\n  }\n\n  _open (cb) {\n    this._openCallback = cb\n    if (this._pack._stream === this) this._continueOpen()\n  }\n\n  _continuePack (err) {\n    if (this._callback === null) return\n\n    const callback = this._callback\n    this._callback = null\n\n    callback(err)\n  }\n\n  _continueOpen () {\n    if (this._pack._stream === null) this._pack._stream = this\n\n    const cb = this._openCallback\n    this._openCallback = null\n    if (cb === null) return\n\n    if (this._pack.destroying) return cb(new Error('pack stream destroyed'))\n    if (this._pack._finalized) return cb(new Error('pack stream is already finalized'))\n\n    this._pack._stream = this\n\n    if (!this._isLinkname) {\n      this._pack._encode(this.header)\n    }\n\n    if (this._isVoid) {\n      this._finish()\n      this._continuePack(null)\n    }\n\n    cb(null)\n  }\n\n  _write (data, cb) {\n    if (this._isLinkname) {\n      this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data\n      return cb(null)\n    }\n\n    if (this._isVoid) {\n      if (data.byteLength > 0) {\n        return cb(new Error('No body allowed for this entry'))\n      }\n      return cb()\n    }\n\n    this.written += data.byteLength\n    if (this._pack.push(data)) return cb()\n    this._pack._drain = cb\n  }\n\n  _finish () {\n    if (this._finished) return\n    this._finished = true\n\n    if (this._isLinkname) {\n      this.header.linkname = this._linkname ? b4a.toString(this._linkname, 'utf-8') : ''\n      this._pack._encode(this.header)\n    }\n\n    overflow(this._pack, this.header.size)\n\n    this._pack._done(this)\n  }\n\n  _final (cb) {\n    if (this.written !== this.header.size) { // corrupting tar\n      return cb(new Error('Size mismatch'))\n    }\n\n    this._finish()\n    cb(null)\n  }\n\n  _getError () {\n    return getStreamError(this) || new Error('tar entry destroyed')\n  }\n\n  _predestroy () {\n    this._pack.destroy(this._getError())\n  }\n\n  _destroy (cb) {\n    this._pack._done(this)\n\n    this._continuePack(this._finished ? null : this._getError())\n\n    cb()\n  }\n}\n\nclass Pack extends Readable {\n  constructor (opts) {\n    super(opts)\n    this._drain = noop\n    this._finalized = false\n    this._finalizing = false\n    this._pending = []\n    this._stream = null\n  }\n\n  entry (header, buffer, callback) {\n    if (this._finalized || this.destroying) throw new Error('already finalized or destroyed')\n\n    if (typeof buffer === 'function') {\n      callback = buffer\n      buffer = null\n    }\n\n    if (!callback) callback = noop\n\n    if (!header.size || header.type === 'symlink') header.size = 0\n    if (!header.type) header.type = modeToType(header.mode)\n    if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE\n    if (!header.uid) header.uid = 0\n    if (!header.gid) header.gid = 0\n    if (!header.mtime) header.mtime = new Date()\n\n    if (typeof buffer === 'string') buffer = b4a.from(buffer)\n\n    const sink = new Sink(this, header, callback)\n\n    if (b4a.isBuffer(buffer)) {\n      header.size = buffer.byteLength\n      sink.write(buffer)\n      sink.end()\n      return sink\n    }\n\n    if (sink._isVoid) {\n      return sink\n    }\n\n    return sink\n  }\n\n  finalize () {\n    if (this._stream || this._pending.length > 0) {\n      this._finalizing = true\n      return\n    }\n\n    if (this._finalized) return\n    this._finalized = true\n\n    this.push(END_OF_TAR)\n    this.push(null)\n  }\n\n  _done (stream) {\n    if (stream !== this._stream) return\n\n    this._stream = null\n\n    if (this._finalizing) this.finalize()\n    if (this._pending.length) this._pending.shift()._continueOpen()\n  }\n\n  _encode (header) {\n    if (!header.pax) {\n      const buf = headers.encode(header)\n      if (buf) {\n        this.push(buf)\n        return\n      }\n    }\n    this._encodePax(header)\n  }\n\n  _encodePax (header) {\n    const paxHeader = headers.encodePax({\n      name: header.name,\n      linkname: header.linkname,\n      pax: header.pax\n    })\n\n    const newHeader = {\n      name: 'PaxHeader',\n      mode: header.mode,\n      uid: header.uid,\n      gid: header.gid,\n      size: paxHeader.byteLength,\n      mtime: header.mtime,\n      type: 'pax-header',\n      linkname: header.linkname && 'PaxHeader',\n      uname: header.uname,\n      gname: header.gname,\n      devmajor: header.devmajor,\n      devminor: header.devminor\n    }\n\n    this.push(headers.encode(newHeader))\n    this.push(paxHeader)\n    overflow(this, paxHeader.byteLength)\n\n    newHeader.size = header.size\n    newHeader.type = header.type\n    this.push(headers.encode(newHeader))\n  }\n\n  _doDrain () {\n    const drain = this._drain\n    this._drain = noop\n    drain()\n  }\n\n  _predestroy () {\n    const err = getStreamError(this)\n\n    if (this._stream) this._stream.destroy(err)\n\n    while (this._pending.length) {\n      const stream = this._pending.shift()\n      stream.destroy(err)\n      stream._continueOpen()\n    }\n\n    this._doDrain()\n  }\n\n  _read (cb) {\n    this._doDrain()\n    cb()\n  }\n}\n\nmodule.exports = function pack (opts) {\n  return new Pack(opts)\n}\n\nfunction modeToType (mode) {\n  switch (mode & constants.S_IFMT) {\n    case constants.S_IFBLK: return 'block-device'\n    case constants.S_IFCHR: return 'character-device'\n    case constants.S_IFDIR: return 'directory'\n    case constants.S_IFIFO: return 'fifo'\n    case constants.S_IFLNK: return 'symlink'\n  }\n\n  return 'file'\n}\n\nfunction noop () {}\n\nfunction overflow (self, size) {\n  size &= 511\n  if (size) self.push(END_OF_TAR.subarray(0, 512 - size))\n}\n\nfunction mapWritable (buf) {\n  return b4a.isBuffer(buf) ? buf : b4a.from(buf)\n}\n","exports.extract = require('./extract')\nexports.pack = require('./pack')\n","import { createRequire } from \"node:module\";\nimport { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { AgentTraceEventSchema, ContextTreeAliasSchema, ContextTreeRepositorySchema, DirectImMessageDeliveryRequestSchema, MCP_GATEWAY_PATH, MCP_GATEWAY_PATH as MCP_GATEWAY_PATH$1, PROVIDER_PROXY_CHUNK_MAX_BYTES, PROVIDER_PROXY_HEADER_MAX_BYTES, PROVIDER_PROXY_INITIAL_CREDIT_BYTES, PROVIDER_PROXY_MAX_FRAME_BYTES, PROVIDER_PROXY_MAX_STREAMS_PER_EXECUTION, PROVIDER_PROXY_MAX_STREAM_OPENS_PER_CONNECTION, RUNNER_ACCEPTANCE_WORKER_STDIN_MAX_BYTES, RUNNER_CLOUD_DELIVERY_VERSION, RUNNER_CLOUD_TURN_WORKER_STDIN_MAX_BYTES, RUNNER_REUSE_VERSION, RUNNER_SESSION_COLLABORATION_VERSION, RUNNER_WORKSPACE_ARCHIVE_MAX_BYTES, RUNNER_WORKSPACE_PATH, RUNNER_WORKSPACE_TIMEOUT_MS, RUNNER_WORKSPACE_VERSION, RUNNER_WS_PROTOCOL_VERSION, RUNTIME_CAPABILITY, RUNTIME_CREDENTIAL_PROVIDERS, RUNTIME_DEFAULT_MAX_DURATION_MS, RUNTIME_EXECUTION_MAX_LIFETIME_MS, RUNTIME_FINAL_TEXT_MAX_BYTES, RUNTIME_MAX_FRAME_BYTES, RUNTIME_OUTGOING_REPLY_MAX_COUNT, RUNTIME_OUTGOING_REPLY_RAW_MAX_BYTES, RUNTIME_OUTGOING_REPLY_SNAPSHOT_MAX_BYTES, RUNTIME_OUTGOING_REPLY_TEXT_MAX_BYTES, RUNTIME_PROVIDER_ORIGIN_HEADER, RUNTIME_PROVIDER_PROXY_PATH, RUNTIME_PROXY_TICKET_TTL_MS, RUNTIME_TRACE_BATCH_MAX_EVENTS, RUNTIME_WEB_FETCH_PATH, RUNTIME_WEB_SEARCH_PATH, RunnerAcceptanceReportWireSchema, RunnerCloudSessionWorkerRequestSchema, RunnerCloudTurnWorkerRequestSchema, RunnerPiConfigInputSchema, RunnerServerFrameSchema, RunnerWorkspaceObjectSchema, RuntimeCredentialClientFrameSchema, RuntimeCredentialServerFrameSchema, RuntimeImOutboxContextSchema, RuntimeProviderProxyReadyFrameSchema, RuntimeProviderProxyServerFrameSchema, RuntimeUsageSchema, SessionMessageDeliveryRequestSchema, StructuredErrorCategorySchema, StructuredErrorPhaseSchema, StructuredErrorSchema, TurnFailureReasonSchema, TurnOutgoingReplyContentSchema, TurnOutgoingReplyMsgTypeSchema, TurnOutgoingReplySchema, TurnOutgoingReplySnapshotSchema, TurnReportRequestSchema, WEB_FETCH_RESPONSE_MAX_BYTES, WEB_FETCH_TIMEOUT_CAP_MS, WEB_GATEWAY_FETCH_PATH, WEB_GATEWAY_SEARCH_PATH, WEB_REQUEST_MAX_BYTES, WEB_SEARCH_RESPONSE_MAX_BYTES, WEB_SEARCH_TIMEOUT_CAP_MS, WEB_TIMEOUT_HEADER, WEB_TOOLS_PROTOCOL_VERSION, WEB_TOOL_ERROR_CODES, WebFetchResultSchema, WebGatewayFetchRequestSchema, WebGatewaySearchRequestSchema, WebSearchResultSchema, computeRuntimeImMessageSemanticHash, computeTurnResultHash, hashTuple, normalizeContextTrees, redactForLog, redactSensitive, runtimeFrameByteLength, serializeRunnerAcceptanceWorkerStdin, serializeRunnerCloudSessionWorkerStdin, serializeRunnerCloudTurnWorkerStdin } from \"@opentag/shared\";\nimport pino from \"pino\";\nimport { chmodSync, closeSync, constants, createReadStream, createWriteStream, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync, writeSync } from \"node:fs\";\nimport { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { access, chmod, copyFile, link, lstat, mkdir, mkdtemp, open, opendir, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from \"node:fs/promises\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { execFile, spawn } from \"node:child_process\";\nimport WebSocket from \"ws\";\nimport { once } from \"node:events\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport tls, { connect } from \"node:tls\";\nimport { promisify } from \"node:util\";\nimport { connect as connect$1, createServer as createServer$1, isIP } from \"node:net\";\nimport { fileURLToPath } from \"node:url\";\nimport semver from \"semver\";\nimport { Duplex, PassThrough } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { createGunzip, createGzip } from \"node:zlib\";\nimport { extract, pack } from \"tar-stream\";\nimport { constants as constants$1, createServer as createServer$2 } from \"node:http2\";\n//#region src/observability/rotating-file-stream.ts\nconst CLIENT_LOG_FILE_NAME = \"client.log\";\nconst CLIENT_LOG_MIN_RETENTION_MS = 6048e5;\nconst defaultOperations = {\n\tclose: closeSync,\n\tfileStatus: fstatSync,\n\tfchmod: fchmodSync,\n\tlstat: lstatSync,\n\tmakeDirectory: (path, mode) => mkdirSync(path, {\n\t\trecursive: true,\n\t\tmode\n\t}),\n\topen: openSync,\n\trename: renameSync,\n\tunlink: unlinkSync,\n\twrite: (fileDescriptor, buffer, offset, length) => writeSync(fileDescriptor, buffer, offset, length)\n};\nvar RotatingFileStream = class {\n\tdirectory;\n\tpath;\n\t#fallbackWrite;\n\t#maxBackups;\n\t#maxBytes;\n\t#minRetentionMs;\n\t#maxTotalBytes;\n\t#operations;\n\t#bytes = 0;\n\t#failed = false;\n\t#fileDescriptor;\n\tconstructor(directory, options = {}) {\n\t\tthis.directory = resolve(directory);\n\t\tthis.path = join(this.directory, CLIENT_LOG_FILE_NAME);\n\t\tthis.#fallbackWrite = options.fallbackWrite ?? ((chunk) => writeStringToFileDescriptor(2, chunk));\n\t\tthis.#operations = {\n\t\t\t...defaultOperations,\n\t\t\t...options.operations\n\t\t};\n\t\tthis.#maxBackups = options.maxBackups ?? 7;\n\t\tthis.#maxBytes = options.maxBytes ?? 10485760;\n\t\tthis.#minRetentionMs = options.minRetentionMs ?? 0;\n\t\tthis.#maxTotalBytes = options.maxTotalBytes ?? this.#maxBytes * this.#maxBackups;\n\t\tif (!Number.isSafeInteger(this.#maxTotalBytes) || this.#maxTotalBytes < 1) throw new Error(\"Client log total size ceiling must be a positive safe integer\");\n\t\tif (!Number.isSafeInteger(this.#maxBackups) || this.#maxBackups < 1) throw new Error(\"Client log backup count must be a positive safe integer\");\n\t\tif (!Number.isSafeInteger(this.#maxBytes) || this.#maxBytes < 1) throw new Error(\"Client log size limit must be a positive safe integer\");\n\t\tif (!Number.isSafeInteger(this.#minRetentionMs) || this.#minRetentionMs < 0) throw new Error(\"Client log retention floor must be a non-negative safe integer\");\n\t\tthis.#open();\n\t}\n\twrite(chunk) {\n\t\tif (this.#failed) return this.#writeFallback(chunk);\n\t\ttry {\n\t\t\tconst bytes = Buffer.from(chunk, \"utf8\");\n\t\t\tif (this.#bytes > 0 && this.#bytes + bytes.byteLength > this.#maxBytes) this.#rotate();\n\t\t\tif (this.#fileDescriptor === void 0) throw new Error(\"Client log file is unavailable\");\n\t\t\tthis.#writeFully(this.#fileDescriptor, bytes);\n\t\t\tthis.#bytes += bytes.byteLength;\n\t\t} catch {\n\t\t\tthis.#failover();\n\t\t\tthis.#writeFallback(chunk);\n\t\t}\n\t\treturn true;\n\t}\n\tclose() {\n\t\tif (this.#fileDescriptor === void 0) return;\n\t\ttry {\n\t\t\tthis.#operations.close(this.#fileDescriptor);\n\t\t} catch {}\n\t\tthis.#fileDescriptor = void 0;\n\t}\n\t#open() {\n\t\ttry {\n\t\t\tthis.#ensurePrivateDirectory();\n\t\t\tthis.#openLogFile();\n\t\t} catch {\n\t\t\tthis.#failover();\n\t\t}\n\t}\n\t#rotate() {\n\t\tthis.close();\n\t\tif (this.#minRetentionMs > 0) {\n\t\t\tthis.#rotateWithRetentionFloor();\n\t\t\tthis.#openLogFile();\n\t\t\treturn;\n\t\t}\n\t\tthis.#removeIfPresent(`${this.path}.${this.#maxBackups}`);\n\t\tfor (let index = this.#maxBackups - 1; index >= 1; index -= 1) this.#renameIfPresent(`${this.path}.${index}`, `${this.path}.${index + 1}`);\n\t\tthis.#renameIfPresent(this.path, `${this.path}.1`);\n\t\tthis.#openLogFile();\n\t}\n\t#rotateWithRetentionFloor() {\n\t\tconst cutoff = Date.now() - this.#minRetentionMs;\n\t\tthis.#pruneExpiredBackups(cutoff);\n\t\tlet highest = this.#highestBackupIndex();\n\t\tif (highest >= this.#maxBackups && this.#isBackupExpired(highest, cutoff)) {\n\t\t\tthis.#removeIfPresent(`${this.path}.${highest}`);\n\t\t\thighest -= 1;\n\t\t}\n\t\tfor (let index = highest; index >= 1; index -= 1) this.#renameIfPresent(`${this.path}.${index}`, `${this.path}.${index + 1}`);\n\t\tthis.#renameIfPresent(this.path, `${this.path}.1`);\n\t\tthis.#enforceStorageCeiling();\n\t}\n\t/**\n\t* Drop the oldest backups until the retained bytes fit the ceiling, even when they are younger\n\t* than the retention floor. The floor is a target, never a licence to grow without bound: a\n\t* high-volume day would otherwise add a full-size backup on every rotation for the whole window.\n\t*/\n\t#enforceStorageCeiling() {\n\t\tlet total = 0;\n\t\tconst highest = this.#highestBackupIndex();\n\t\tfor (let index = 1; index <= highest; index += 1) total += this.#backupSize(index);\n\t\tfor (let index = highest; index >= 1 && total > this.#maxTotalBytes; index -= 1) {\n\t\t\ttotal -= this.#backupSize(index);\n\t\t\tthis.#removeIfPresent(`${this.path}.${index}`);\n\t\t}\n\t}\n\t#backupSize(index) {\n\t\ttry {\n\t\t\treturn this.#operations.lstat(`${this.path}.${index}`).size;\n\t\t} catch {\n\t\t\treturn 0;\n\t\t}\n\t}\n\t#pruneExpiredBackups(cutoff) {\n\t\tconst highest = this.#highestBackupIndex();\n\t\tfor (let index = 1; index <= highest; index += 1) if (this.#isBackupExpired(index, cutoff)) this.#removeIfPresent(`${this.path}.${index}`);\n\t}\n\t#highestBackupIndex() {\n\t\tlet highest = 0;\n\t\tfor (let index = 1; index <= this.#maxBackups + 1e5; index += 1) try {\n\t\t\tconst status = this.#operations.lstat(`${this.path}.${index}`);\n\t\t\tif (!status.isFile() || status.isSymbolicLink()) throw new Error(\"Client log backup must be a regular file\");\n\t\t\thighest = index;\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") break;\n\t\t\tthrow error;\n\t\t}\n\t\treturn highest;\n\t}\n\t#isBackupExpired(index, cutoff) {\n\t\ttry {\n\t\t\treturn this.#operations.lstat(`${this.path}.${index}`).mtimeMs <= cutoff;\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return true;\n\t\t\tthrow error;\n\t\t}\n\t}\n\t#ensurePrivateDirectory() {\n\t\tthis.#operations.makeDirectory(this.directory, 448);\n\t\tconst pathStatus = this.#operations.lstat(this.directory);\n\t\tif (!pathStatus.isDirectory() || pathStatus.isSymbolicLink()) throw new Error(\"Client log directory must be a real directory\");\n\t\tconst fileDescriptor = this.#operations.open(this.directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW, 448);\n\t\ttry {\n\t\t\tif (!this.#operations.fileStatus(fileDescriptor).isDirectory()) throw new Error(\"Client log directory changed during open\");\n\t\t\tthis.#operations.fchmod(fileDescriptor, 448);\n\t\t} finally {\n\t\t\tthis.#operations.close(fileDescriptor);\n\t\t}\n\t}\n\t#openLogFile() {\n\t\ttry {\n\t\t\tconst pathStatus = this.#operations.lstat(this.path);\n\t\t\tif (!pathStatus.isFile() || pathStatus.isSymbolicLink()) throw new Error(\"Client log path must be a regular file\");\n\t\t} catch (error) {\n\t\t\tif (error.code !== \"ENOENT\") throw error;\n\t\t}\n\t\tconst fileDescriptor = this.#operations.open(this.path, constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_NOFOLLOW, 384);\n\t\ttry {\n\t\t\tconst openedStatus = this.#operations.fileStatus(fileDescriptor);\n\t\t\tif (!openedStatus.isFile()) throw new Error(\"Client log path changed during open\");\n\t\t\tthis.#operations.fchmod(fileDescriptor, 384);\n\t\t\tthis.#fileDescriptor = fileDescriptor;\n\t\t\tthis.#bytes = openedStatus.size;\n\t\t} catch (error) {\n\t\t\tthis.#operations.close(fileDescriptor);\n\t\t\tthrow error;\n\t\t}\n\t}\n\t#renameIfPresent(from, to) {\n\t\ttry {\n\t\t\tthis.#operations.rename(from, to);\n\t\t} catch (error) {\n\t\t\tif (error.code !== \"ENOENT\") throw error;\n\t\t}\n\t}\n\t#removeIfPresent(path) {\n\t\ttry {\n\t\t\tthis.#operations.unlink(path);\n\t\t} catch (error) {\n\t\t\tif (error.code !== \"ENOENT\") throw error;\n\t\t}\n\t}\n\t#failover() {\n\t\tthis.close();\n\t\tthis.#failed = true;\n\t}\n\t#writeFallback(chunk) {\n\t\ttry {\n\t\t\tthis.#fallbackWrite(chunk);\n\t\t} catch {}\n\t\treturn true;\n\t}\n\t#writeFully(fileDescriptor, buffer) {\n\t\tlet offset = 0;\n\t\twhile (offset < buffer.byteLength) {\n\t\t\tconst written = this.#operations.write(fileDescriptor, buffer, offset, buffer.byteLength - offset);\n\t\t\tif (!Number.isSafeInteger(written) || written <= 0 || written > buffer.byteLength - offset) throw new Error(\"Client log write returned an invalid byte count\");\n\t\t\toffset += written;\n\t\t}\n\t}\n};\nfunction writeStringToFileDescriptor(fileDescriptor, chunk) {\n\tconst buffer = Buffer.from(chunk, \"utf8\");\n\tlet offset = 0;\n\twhile (offset < buffer.byteLength) {\n\t\tconst written = writeSync(fileDescriptor, buffer, offset, buffer.byteLength - offset);\n\t\tif (!Number.isSafeInteger(written) || written <= 0 || written > buffer.byteLength - offset) throw new Error(\"Diagnostic write returned an invalid byte count\");\n\t\toffset += written;\n\t}\n}\n//#endregion\n//#region src/observability/logger.ts\nconst LOG_LEVELS = /* @__PURE__ */ new Set([\n\t\"trace\",\n\t\"debug\",\n\t\"info\",\n\t\"warn\",\n\t\"error\",\n\t\"fatal\",\n\t\"silent\"\n]);\nconst SENSITIVE_KEYS = [\n\t\"password\",\n\t\"token\",\n\t\"accessToken\",\n\t\"refreshToken\",\n\t\"jwt\",\n\t\"secret\",\n\t\"apiKey\",\n\t\"api_key\",\n\t\"credentials\",\n\t\"authorization\"\n];\nconst REDACT_PATHS = [\n\t...SENSITIVE_KEYS,\n\t...SENSITIVE_KEYS.map((key) => `*.${key}`),\n\t\"headers.authorization\",\n\t\"headers.cookie\",\n\t\"*.headers.authorization\",\n\t\"*.headers.cookie\"\n];\nlet serviceDirectory;\nlet serviceStream;\nlet serviceDestination;\nlet rootLogger;\nlet clientLoggerContext = {};\nfunction configureClientLoggerForService(logDirectory) {\n\tconst canonicalDirectory = resolve(logDirectory);\n\tif (serviceDirectory && serviceDirectory !== canonicalDirectory) throw new Error(\"The Client logger is already configured for a different log directory\");\n\tif (serviceDirectory) return;\n\tserviceDirectory = canonicalDirectory;\n\tserviceStream = void 0;\n\tserviceDestination = void 0;\n\trootLogger = void 0;\n}\nfunction configureClientLoggerContext(bindings) {\n\tclientLoggerContext = {\n\t\t...clientLoggerContext,\n\t\t...redactForLog(bindings)\n\t};\n\trootLogger = void 0;\n}\nfunction createLogger(module, options = {}) {\n\tif (options.destination === \"stderr\") return adapt(fixed(buildRoot(stderrDestination(), false)), { module });\n\tif (options.destination === \"file\") return adapt(fixed(buildRoot(fileDestination(), true)), { module });\n\tif (options.destination === \"dual\") return adapt(fixed(buildRoot(dualDestination(), true)), { module });\n\treturn adapt(root, { module });\n}\nfunction root() {\n\tif (rootLogger) return rootLogger;\n\trootLogger = buildRoot(fileDestination(), serviceDirectory !== void 0);\n\treturn rootLogger;\n}\nfunction buildRoot(destination, serviceMode) {\n\tconst configured = process.env.OPENTAG_LOG_LEVEL;\n\tconst validConfigured = configured && LOG_LEVELS.has(configured) ? configured : void 0;\n\tconst level = validConfigured ?? (configured ? \"info\" : process.env.NODE_ENV === \"test\" ? \"silent\" : serviceMode ? \"info\" : \"warn\");\n\tconst logger = pino({\n\t\tbase: Object.keys(clientLoggerContext).length > 0 ? clientLoggerContext : null,\n\t\tlevel,\n\t\tmessageKey: \"message\",\n\t\tredact: {\n\t\t\tpaths: REDACT_PATHS,\n\t\t\tcensor: \"[REDACTED]\"\n\t\t},\n\t\ttimestamp: pino.stdTimeFunctions.isoTime\n\t}, destination);\n\tif (configured && !validConfigured) logger.warn({ module: \"logger\" }, \"Invalid OPENTAG_LOG_LEVEL; using info\");\n\treturn logger;\n}\nfunction stderrDestination() {\n\treturn { write(chunk) {\n\t\ttry {\n\t\t\twriteStringToFileDescriptor(2, chunk);\n\t\t} catch {}\n\t} };\n}\nfunction fileDestination() {\n\tif (!serviceDirectory) return stderrDestination();\n\tif (serviceDestination) return serviceDestination;\n\tserviceDestination = { write(chunk) {\n\t\tgetServiceStream().write(chunk);\n\t} };\n\treturn serviceDestination;\n}\nfunction dualDestination() {\n\tif (!serviceDirectory) return stderrDestination();\n\tconst file = fileDestination();\n\treturn { write(chunk) {\n\t\tfile.write(chunk);\n\t\ttry {\n\t\t\twriteStringToFileDescriptor(2, chunk);\n\t\t} catch {}\n\t} };\n}\nfunction getServiceStream() {\n\tif (!serviceDirectory) throw new Error(\"The Client logger has no configured service directory\");\n\tserviceStream ??= new RotatingFileStream(serviceDirectory, { minRetentionMs: CLIENT_LOG_MIN_RETENTION_MS });\n\treturn serviceStream;\n}\nfunction fixed(logger) {\n\treturn () => logger;\n}\nfunction adapt(resolveLogger, bindings) {\n\tconst write = (method, fields, message) => safeWrite(() => {\n\t\tconst logger = resolveLogger();\n\t\tif (!logger.isLevelEnabled(method)) return;\n\t\tlogger[method](redactForLog({\n\t\t\t...bindings,\n\t\t\t...fields\n\t\t}), redactForLog(message));\n\t});\n\treturn {\n\t\tchild: (childBindings) => adapt(resolveLogger, {\n\t\t\t...bindings,\n\t\t\t...childBindings\n\t\t}),\n\t\tdebug: (fields, message) => write(\"debug\", fields, message),\n\t\terror: (fields, message) => write(\"error\", fields, message),\n\t\tinfo: (fields, message) => write(\"info\", fields, message),\n\t\twarn: (fields, message) => write(\"warn\", fields, message)\n\t};\n}\nfunction safeWrite(write) {\n\ttry {\n\t\twrite();\n\t} catch {}\n}\n//#endregion\n//#region src/agent-runtime/errors.ts\nvar AgentRuntimeError = class extends Error {\n\tcode;\n\tconstructor(code, message, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = \"AgentRuntimeError\";\n\t}\n};\nvar AgentProviderError = class extends Error {\n\tcode;\n\tconstructor(code, message, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = \"AgentProviderError\";\n\t}\n};\n//#endregion\n//#region src/agent-runtime/types.ts\nconst AGENT_RUNTIME_CONTRACT_VERSION = 2;\nconst AGENT_RUNTIME_BINDING_MAX_BYTES = 65536;\nconst AGENT_RUNTIME_DESCRIPTION_MAX_BYTES = 1024;\nconst AGENT_RUNTIME_ID_MAX_BYTES = 256;\nconst AGENT_RUNTIME_TEXT_MAX_BYTES = 1048576;\n//#endregion\n//#region src/agent-runtime/validation.ts\nfunction assertIdentifier(value, field) {\n\tif (typeof value !== \"string\" || value.trim().length === 0 || Buffer.byteLength(value, \"utf8\") > 256) throw new AgentRuntimeError(\"invalid_request\", `${field} must be a non-empty bounded string`);\n}\nfunction assertAgentInput(input) {\n\tif (!input || !Array.isArray(input.items) || input.items.length === 0) throw new AgentRuntimeError(\"invalid_request\", \"input must contain at least one item\");\n\tlet bytes = 0;\n\tfor (const item of input.items) {\n\t\tif (item?.type !== \"text\" || typeof item.text !== \"string\" || item.text.length === 0) throw new AgentRuntimeError(\"invalid_request\", \"input contains an invalid text item\");\n\t\tbytes += Buffer.byteLength(item.text, \"utf8\");\n\t}\n\tif (bytes > 1048576) throw new AgentRuntimeError(\"invalid_request\", \"input exceeds the text size limit\");\n}\nfunction assertSystemPrompt(value) {\n\tif (typeof value !== \"string\" || value.trim().length === 0 || Buffer.byteLength(value, \"utf8\") > 1048576) throw new AgentRuntimeError(\"configuration_invalid\", \"systemPrompt must be a non-empty bounded string\");\n}\nfunction assertDescription(value, field) {\n\tif (typeof value !== \"string\" || value.trim().length === 0 || Buffer.byteLength(value, \"utf8\") > 1024) throw new AgentRuntimeError(\"configuration_invalid\", `${field} must be a non-empty bounded string`);\n}\nfunction assertPromptRequest(request) {\n\tif (!request || typeof request !== \"object\") throw new AgentRuntimeError(\"invalid_request\", \"prompt request is required\");\n\tassertIdentifier(request.runId, \"runId\");\n\tassertAgentInput(request.input);\n\tif (request.signal?.aborted) throw new AgentRuntimeError(\"invalid_request\", \"the run signal is already aborted\");\n\tconst configuration = request.configuration;\n\tif (configuration?.model !== void 0) assertIdentifier(configuration.model, \"configuration.model\");\n\tif (configuration?.reasoningEffort !== void 0) assertIdentifier(configuration.reasoningEffort, \"configuration.reasoningEffort\");\n\tif (configuration?.provider !== void 0) assertJsonValue(configuration.provider, \"configuration.provider\");\n}\nfunction assertHostedTools(policy, hostedTools) {\n\tif (!hostedTools) {\n\t\tif (policy.tools.mode === \"provider-default\") return;\n\t\tthrow new AgentRuntimeError(\"configuration_invalid\", \"allow-list policy requires hosted tool definitions and a handler\");\n\t}\n\tif (typeof hostedTools.handler !== \"function\" || !Array.isArray(hostedTools.definitions)) throw new AgentRuntimeError(\"configuration_invalid\", \"hosted tool definitions and a handler are required\");\n\tconst allowed = /* @__PURE__ */ new Set();\n\tif (policy.tools.mode === \"allow-list\") for (const name of policy.tools.names) {\n\t\tassertToolName(name, \"policy.tools.names\");\n\t\tif (allowed.has(name)) throw new AgentRuntimeError(\"configuration_invalid\", \"tool allow-list contains duplicates\");\n\t\tallowed.add(name);\n\t}\n\tconst defined = /* @__PURE__ */ new Set();\n\tfor (const definition of hostedTools.definitions) {\n\t\tif (!definition || typeof definition !== \"object\") throw new AgentRuntimeError(\"configuration_invalid\", \"hosted tool definition is invalid\");\n\t\tassertToolName(definition.name, \"hostedTools.definitions.name\");\n\t\tif (defined.has(definition.name)) throw new AgentRuntimeError(\"configuration_invalid\", \"hosted tool definitions contain duplicates\");\n\t\tdefined.add(definition.name);\n\t\tif (definition.description !== void 0) assertDescription(definition.description, \"hostedTools.definitions.description\");\n\t\tassertJsonValue(definition.inputSchema, \"hostedTools.definitions.inputSchema\");\n\t\tassertToolInputSchema(definition.inputSchema);\n\t}\n\tif (policy.tools.mode === \"allow-list\" && (allowed.size !== defined.size || [...allowed].some((name) => !defined.has(name)))) throw new AgentRuntimeError(\"configuration_invalid\", \"hosted tool definitions must exactly match the tool allow-list\");\n}\nfunction assertBinding(binding, manifest) {\n\tif (!binding || typeof binding !== \"object\") throw new AgentRuntimeError(\"binding_incompatible\", \"binding is required\");\n\tif (binding.providerId !== manifest.providerId || binding.schemaVersion !== manifest.bindingSchemaVersion) throw new AgentRuntimeError(\"binding_incompatible\", \"binding provider or schema version is incompatible\");\n\tassertJsonValue(binding.payload, \"binding.payload\", \"binding_incompatible\");\n\tif (Buffer.byteLength(JSON.stringify(binding), \"utf8\") > 65536) throw new AgentRuntimeError(\"binding_incompatible\", \"binding exceeds the size limit\");\n}\nfunction assertJsonValue(value, field, code = \"invalid_request\") {\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst visit = (candidate) => {\n\t\tif (candidate === null || typeof candidate === \"string\" || typeof candidate === \"boolean\") return;\n\t\tif (typeof candidate === \"number\") {\n\t\t\tif (Number.isFinite(candidate)) return;\n\t\t\tthrow new AgentRuntimeError(code, `${field} must contain finite JSON numbers`);\n\t\t}\n\t\tif (typeof candidate !== \"object\") throw new AgentRuntimeError(code, `${field} must be JSON-compatible`);\n\t\tif (seen.has(candidate)) throw new AgentRuntimeError(code, `${field} must not contain cycles`);\n\t\tseen.add(candidate);\n\t\tif (Array.isArray(candidate)) {\n\t\t\tif (Reflect.ownKeys(candidate).some((key) => key !== \"length\" && (typeof key !== \"string\" || !/^(0|[1-9]\\d*)$/.test(key) || Number(key) >= candidate.length)) || candidate.length !== Object.keys(candidate).length) throw new AgentRuntimeError(code, `${field} must contain dense JSON arrays without custom properties`);\n\t\t\tfor (let index = 0; index < candidate.length; index += 1) {\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(candidate, String(index));\n\t\t\t\tif (!descriptor?.enumerable || !(\"value\" in descriptor)) throw new AgentRuntimeError(code, `${field} must contain enumerable data properties`);\n\t\t\t\tvisit(descriptor.value);\n\t\t\t}\n\t\t} else {\n\t\t\tconst prototype = Object.getPrototypeOf(candidate);\n\t\t\tif (prototype !== Object.prototype && prototype !== null) throw new AgentRuntimeError(code, `${field} must contain only plain JSON objects`);\n\t\t\tfor (const key of Reflect.ownKeys(candidate)) {\n\t\t\t\tif (typeof key !== \"string\") throw new AgentRuntimeError(code, `${field} must not contain symbol properties`);\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(candidate, key);\n\t\t\t\tif (!descriptor?.enumerable || !(\"value\" in descriptor)) throw new AgentRuntimeError(code, `${field} must contain enumerable data properties`);\n\t\t\t\tvisit(descriptor.value);\n\t\t\t}\n\t\t}\n\t\tseen.delete(candidate);\n\t};\n\tvisit(value);\n}\nfunction sameBinding(left, right) {\n\treturn left !== void 0 && sameJsonValue(left, right);\n}\nasync function runWithAbortSignal(operation, signal) {\n\tif (!signal) return operation();\n\tsignal.throwIfAborted();\n\tlet rejectAborted;\n\tconst aborted = new Promise((_resolve, reject) => {\n\t\trejectAborted = reject;\n\t});\n\tconst onAbort = () => rejectAborted(signal.reason);\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\ttry {\n\t\treturn await Promise.race([operation(signal), aborted]);\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\nfunction sameJsonValue(left, right) {\n\tif (left === right) return true;\n\tif (Array.isArray(left) || Array.isArray(right)) return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((value, index) => sameJsonValue(value, right[index]));\n\tif (left === null || right === null || typeof left !== \"object\" || typeof right !== \"object\") return false;\n\tconst leftObject = left;\n\tconst rightObject = right;\n\tconst leftKeys = Object.keys(leftObject);\n\tconst rightKeys = Object.keys(rightObject);\n\treturn leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.hasOwn(rightObject, key) && sameJsonValue(leftObject[key], rightObject[key]));\n}\nconst TOOL_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\nconst SCHEMA_PROPERTY_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;\nconst SCHEMA_KEYS = /* @__PURE__ */ new Set([\n\t\"additionalProperties\",\n\t\"description\",\n\t\"format\",\n\t\"items\",\n\t\"properties\",\n\t\"required\",\n\t\"type\"\n]);\nconst SCHEMA_TYPES = /* @__PURE__ */ new Set([\n\t\"array\",\n\t\"boolean\",\n\t\"integer\",\n\t\"null\",\n\t\"number\",\n\t\"object\",\n\t\"string\"\n]);\nfunction assertToolName(value, field) {\n\tif (typeof value !== \"string\" || !TOOL_NAME_PATTERN.test(value)) throw new AgentRuntimeError(\"configuration_invalid\", `${field} must use portable tool-name characters and start with a letter`);\n}\nfunction assertToolInputSchema(value) {\n\tif (!isRecord$6(value) || value.type !== \"object\") throw new AgentRuntimeError(\"configuration_invalid\", \"hosted tool input schema must be an object JSON Schema\");\n\tvalidateSchema(value, 0);\n}\nfunction validateSchema(schema, depth) {\n\tif (depth > 16 || Object.keys(schema).some((key) => !SCHEMA_KEYS.has(key))) invalidSchema();\n\tif (typeof schema.type !== \"string\" || !SCHEMA_TYPES.has(schema.type)) invalidSchema();\n\tif (schema.description !== void 0 && (typeof schema.description !== \"string\" || schema.description.length === 0)) invalidSchema();\n\tif (schema.format !== void 0 && (schema.type !== \"string\" || schema.format !== \"uuid\")) invalidSchema();\n\tif (schema.type === \"object\") {\n\t\tif (schema.items !== void 0 || schema.format !== void 0) invalidSchema();\n\t\tif (schema.additionalProperties !== void 0 && typeof schema.additionalProperties !== \"boolean\") invalidSchema();\n\t\tconst properties = schema.properties ?? {};\n\t\tif (!isRecord$6(properties)) invalidSchema();\n\t\tfor (const [name, property] of Object.entries(properties)) {\n\t\t\tif (!SCHEMA_PROPERTY_PATTERN.test(name) || !isRecord$6(property)) invalidSchema();\n\t\t\tvalidateSchema(property, depth + 1);\n\t\t}\n\t\tif (schema.required !== void 0) {\n\t\t\tif (!Array.isArray(schema.required)) invalidSchema();\n\t\t\tconst required = /* @__PURE__ */ new Set();\n\t\t\tfor (const name of schema.required) {\n\t\t\t\tif (typeof name !== \"string\" || required.has(name) || !Object.hasOwn(properties, name)) invalidSchema();\n\t\t\t\trequired.add(name);\n\t\t\t}\n\t\t}\n\t\treturn;\n\t}\n\tif (schema.properties !== void 0 || schema.required !== void 0 || schema.additionalProperties !== void 0) invalidSchema();\n\tif (schema.type === \"array\") {\n\t\tif (!isRecord$6(schema.items)) invalidSchema();\n\t\tvalidateSchema(schema.items, depth + 1);\n\t} else if (schema.items !== void 0) invalidSchema();\n}\nfunction isRecord$6(value) {\n\treturn !!value && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction invalidSchema() {\n\tthrow new AgentRuntimeError(\"configuration_invalid\", \"hosted tool input schema is not in the portable JSON Schema subset\");\n}\n//#endregion\n//#region src/agent-runtime/event-validator.ts\nconst TOOL_COMPLETION_STATUSES = /* @__PURE__ */ new Set([\n\t\"completed\",\n\t\"failed\",\n\t\"declined\"\n]);\nconst logger$6 = createLogger(\"agent-runtime-event-validator\");\n/**\n* Validates the provider-neutral event grammar for one Run. Provider adapters\n* remain responsible only for translating their wire protocol into this grammar.\n* Model turns are optional because some providers do not expose that boundary.\n*/\nvar AgentRunEventValidator = class {\n\t#activeMessages = /* @__PURE__ */ new Set();\n\t#activeModelTurns = /* @__PURE__ */ new Set();\n\t#activeTools = /* @__PURE__ */ new Map();\n\t#seenMessages = /* @__PURE__ */ new Set();\n\t#seenModelTurns = /* @__PURE__ */ new Set();\n\t#seenTools = /* @__PURE__ */ new Set();\n\taccept(event) {\n\t\ttry {\n\t\t\tthis.#accept(event);\n\t\t} catch (error) {\n\t\t\tif (error instanceof AgentProviderError) throw error;\n\t\t\tlogger$6.debug({\n\t\t\t\tcode: \"event_validation_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider event validation failed\");\n\t\t\tthrow protocolError$1(error instanceof Error ? error.message : \"provider emitted an invalid event\");\n\t\t}\n\t}\n\tassertSettled(result) {\n\t\tif (result.status !== \"completed\") return;\n\t\tif (this.#activeModelTurns.size > 0 || this.#activeMessages.size > 0 || this.#activeTools.size > 0) throw protocolError$1(\"provider completed a run with unfinished event lifecycles\");\n\t}\n\t#accept(event) {\n\t\tif (!event || typeof event !== \"object\" || typeof event.type !== \"string\") throw protocolError$1(\"provider emitted an invalid event\");\n\t\tswitch (event.type) {\n\t\t\tcase \"model_turn_started\":\n\t\t\t\tthis.#start(event.modelTurnId, \"modelTurnId\", this.#seenModelTurns, this.#activeModelTurns);\n\t\t\t\treturn;\n\t\t\tcase \"model_turn_completed\":\n\t\t\t\tthis.#complete(event.modelTurnId, \"modelTurnId\", this.#activeModelTurns);\n\t\t\t\treturn;\n\t\t\tcase \"message_started\":\n\t\t\t\tthis.#start(event.messageId, \"messageId\", this.#seenMessages, this.#activeMessages);\n\t\t\t\treturn;\n\t\t\tcase \"message_delta\":\n\t\t\t\tthis.#requireActive(event.messageId, \"messageId\", this.#activeMessages);\n\t\t\t\tassertText(event.delta, \"message delta\");\n\t\t\t\treturn;\n\t\t\tcase \"message_completed\":\n\t\t\t\tthis.#complete(event.messageId, \"messageId\", this.#activeMessages);\n\t\t\t\tassertText(event.text, \"message text\");\n\t\t\t\treturn;\n\t\t\tcase \"tool_started\":\n\t\t\t\tassertIdentifier(event.toolCallId, \"toolCallId\");\n\t\t\t\tassertIdentifier(event.name, \"tool name\");\n\t\t\t\tif (this.#seenTools.has(event.toolCallId)) throw protocolError$1(\"provider reused a toolCallId\");\n\t\t\t\tif (event.input !== void 0) assertJsonValue(event.input, \"tool input\");\n\t\t\t\tthis.#seenTools.add(event.toolCallId);\n\t\t\t\tthis.#activeTools.set(event.toolCallId, { name: event.name });\n\t\t\t\treturn;\n\t\t\tcase \"tool_updated\":\n\t\t\t\tthis.#requireTool(event.toolCallId);\n\t\t\t\tassertJsonValue(event.update, \"tool update\");\n\t\t\t\treturn;\n\t\t\tcase \"tool_completed\": {\n\t\t\t\tconst tool = this.#requireTool(event.toolCallId);\n\t\t\t\tassertIdentifier(event.name, \"tool name\");\n\t\t\t\tif (tool.name !== event.name) throw protocolError$1(\"provider changed a tool name during its lifecycle\");\n\t\t\t\tif (!TOOL_COMPLETION_STATUSES.has(event.status)) throw protocolError$1(\"provider emitted an invalid tool completion status\");\n\t\t\t\tif (event.output !== void 0) assertJsonValue(event.output, \"tool output\");\n\t\t\t\tthis.#activeTools.delete(event.toolCallId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"usage_updated\":\n\t\t\t\tassertUsage(event.usage);\n\t\t\t\treturn;\n\t\t\tcase \"provider_warning\":\n\t\t\t\tassertIdentifier(event.code, \"provider warning code\");\n\t\t\t\tassertText(event.message, \"provider warning message\");\n\t\t\t\treturn;\n\t\t\tcase \"provider_event\":\n\t\t\t\tassertIdentifier(event.providerId, \"provider event providerId\");\n\t\t\t\tif (!Number.isSafeInteger(event.schemaVersion) || event.schemaVersion < 1) throw protocolError$1(\"provider event schemaVersion must be a positive safe integer\");\n\t\t\t\tassertJsonValue(event.payload, \"provider event payload\");\n\t\t\t\treturn;\n\t\t\tdefault: throw protocolError$1(\"provider emitted an unknown event type\");\n\t\t}\n\t}\n\t#start(id, field, seen, active) {\n\t\tassertIdentifier(id, field);\n\t\tif (seen.has(id)) throw protocolError$1(`provider reused a ${field}`);\n\t\tseen.add(id);\n\t\tactive.add(id);\n\t}\n\t#complete(id, field, active) {\n\t\tthis.#requireActive(id, field, active);\n\t\tactive.delete(id);\n\t}\n\t#requireActive(id, field, active) {\n\t\tassertIdentifier(id, field);\n\t\tif (!active.has(id)) throw protocolError$1(`provider referenced an inactive ${field}`);\n\t}\n\t#requireTool(toolCallId) {\n\t\tassertIdentifier(toolCallId, \"toolCallId\");\n\t\tconst tool = this.#activeTools.get(toolCallId);\n\t\tif (!tool) throw protocolError$1(\"provider referenced an inactive toolCallId\");\n\t\treturn tool;\n\t}\n};\nfunction assertText(value, field) {\n\tif (typeof value !== \"string\" || Buffer.byteLength(value, \"utf8\") > 1048576) throw protocolError$1(`${field} must be bounded text`);\n}\nfunction assertUsage(usage) {\n\tif (!usage || typeof usage !== \"object\") throw protocolError$1(\"provider usage must be an object\");\n\tfor (const value of [\n\t\tusage.inputTokens,\n\t\tusage.cachedInputTokens,\n\t\tusage.outputTokens\n\t]) if (value !== void 0 && (!Number.isSafeInteger(value) || value < 0)) throw protocolError$1(\"provider usage must contain non-negative safe integers\");\n}\nfunction protocolError$1(message) {\n\treturn new AgentProviderError(\"provider_protocol_error\", message);\n}\n//#endregion\n//#region src/agent-runtime/base-agent-runtime.ts\nvar BaseAgentRuntime = class BaseAgentRuntime {\n\tmanifest;\n\tcapabilities;\n\t#eventSink;\n\t#queued = [];\n\t#knownRunIds = /* @__PURE__ */ new Set();\n\t#interactions = /* @__PURE__ */ new Map();\n\t#idleWaiters = /* @__PURE__ */ new Set();\n\t#phase = \"idle\";\n\t#active;\n\t#binding;\n\t#dispatchTail = Promise.resolve();\n\t#sinkFailure;\n\t#closePromise;\n\t#providerFailureClosing = false;\n\tstatic #logger = createLogger(\"agent-runtime\");\n\tconstructor(options) {\n\t\tthis.manifest = Object.freeze({ ...options.manifest });\n\t\tthis.capabilities = Object.freeze({ ...options.capabilities });\n\t\tthis.#eventSink = options.eventSink;\n\t\tif (options.binding) {\n\t\t\tassertBinding(options.binding, options.manifest);\n\t\t\tthis.#binding = snapshotBinding(options.binding);\n\t\t}\n\t}\n\tget state() {\n\t\treturn Object.freeze({\n\t\t\tphase: this.#phase,\n\t\t\t...this.#active ? { activeRunId: this.#active.request.runId } : {},\n\t\t\tqueuedRunCount: this.#queued.length\n\t\t});\n\t}\n\tget binding() {\n\t\treturn this.#binding;\n\t}\n\tasync prompt(request) {\n\t\tassertPromptRequest(request);\n\t\tthis.#assertOpen();\n\t\tif (this.#phase !== \"idle\" || this.#active || this.#queued.length > 0) throw new AgentRuntimeError(\"busy\", \"prompt requires an idle runtime\");\n\t\tconst record = this.#admit(request, \"active\");\n\t\tthis.#phase = \"running\";\n\t\tthis.#active = record;\n\t\tthis.#execute(record);\n\t\treturn record.promise;\n\t}\n\tasync followUp(request) {\n\t\tassertPromptRequest(request);\n\t\tthis.#assertOpen();\n\t\tif (this.#phase !== \"running\") throw new AgentRuntimeError(\"busy\", \"followUp requires an active run or follow-up chain\");\n\t\tconst record = this.#admit(request, \"queued\");\n\t\tthis.#queued.push(record);\n\t\trecord.admissionEvent = this.#dispatch({\n\t\t\ttype: \"run_queued\",\n\t\t\trunId: record.request.runId,\n\t\t\tposition: this.#queued.length\n\t\t});\n\t\trecord.admissionEvent.catch(() => void 0);\n\t\treturn record.promise;\n\t}\n\tasync steer(request) {\n\t\tthis.#assertOpen();\n\t\tif (this.capabilities.steer !== \"supported\") throw new AgentRuntimeError(\"unsupported_capability\", \"this runtime does not support steer\");\n\t\tif (!request || typeof request !== \"object\") throw new AgentRuntimeError(\"invalid_request\", \"steer request is required\");\n\t\tassertIdentifier(request.expectedRunId, \"expectedRunId\");\n\t\tassertAgentInput(request.input);\n\t\tconst snapshot = immutableSnapshot(request);\n\t\tconst active = this.#requireActive(snapshot.expectedRunId);\n\t\tawait this.steerProvider(snapshot);\n\t\tif (active.state !== \"active\" || this.#active !== active) throw new AgentRuntimeError(\"run_mismatch\", \"the active run completed before steer was accepted\");\n\t\tawait this.#dispatch({\n\t\t\ttype: \"input_accepted\",\n\t\t\trunId: active.request.runId,\n\t\t\tinput: snapshot.input\n\t\t});\n\t}\n\tasync respond(response) {\n\t\tthis.#assertOpen();\n\t\tif (this.capabilities.interactions !== \"supported\") throw new AgentRuntimeError(\"unsupported_capability\", \"this runtime does not support interactions\");\n\t\tif (!response || typeof response !== \"object\") throw new AgentRuntimeError(\"invalid_request\", \"interaction response is required\");\n\t\tassertIdentifier(response.expectedRunId, \"expectedRunId\");\n\t\tassertIdentifier(response.requestId, \"requestId\");\n\t\tif (response.value !== void 0) assertJsonValue(response.value, \"interaction.value\");\n\t\tconst snapshot = immutableSnapshot(response);\n\t\tconst active = this.#requireActive(snapshot.expectedRunId);\n\t\tconst interaction = this.#interactions.get(snapshot.requestId);\n\t\tif (!interaction || interaction.kind !== snapshot.kind) throw new AgentRuntimeError(\"interaction_not_found\", \"the interaction is unknown, expired, or has another kind\");\n\t\tawait this.respondProvider(snapshot);\n\t\tif (active.state !== \"active\" || this.#active !== active || !this.#interactions.delete(snapshot.requestId)) throw new AgentRuntimeError(\"interaction_not_found\", \"the interaction expired before the response was accepted\");\n\t\t/* v8 ignore next -- best-effort notification; sink rejections are handled by the ordered event pipeline. */\n\t\tthis.#dispatch({\n\t\t\ttype: \"interaction_resolved\",\n\t\t\trunId: active.request.runId,\n\t\t\trequestId: snapshot.requestId,\n\t\t\tdecision: snapshot.decision\n\t\t}).catch(() => void 0);\n\t}\n\tasync abort(request) {\n\t\tthis.#assertOpen();\n\t\tif (!request || typeof request !== \"object\") throw new AgentRuntimeError(\"invalid_request\", \"abort request is required\");\n\t\tassertIdentifier(request.expectedRunId, \"expectedRunId\");\n\t\tconst active = this.#requireActive(request.expectedRunId);\n\t\tawait this.#requestAbort(active, request.reason ?? \"run aborted\");\n\t}\n\twaitForIdle() {\n\t\tif (this.#phase === \"idle\" || this.#phase === \"closed\") return Promise.resolve();\n\t\treturn new Promise((resolve) => this.#idleWaiters.add(resolve));\n\t}\n\tclose() {\n\t\tif (this.#closePromise) return this.#closePromise;\n\t\tthis.#closePromise = this.#closeInternal();\n\t\treturn this.#closePromise;\n\t}\n\tsteerProvider(_request) {\n\t\treturn Promise.reject(new AgentRuntimeError(\"unsupported_capability\", \"this runtime does not support steer\"));\n\t}\n\trespondProvider(_response) {\n\t\treturn Promise.reject(new AgentRuntimeError(\"unsupported_capability\", \"this runtime does not support interactions\"));\n\t}\n\tabortProvider(_request) {\n\t\treturn Promise.resolve();\n\t}\n\tcloseForProviderFailure() {\n\t\tthis.#providerFailureClosing = true;\n\t\t/* v8 ignore next -- close resolves through the run-failure path; the suppression only guards double faults. */\n\t\tthis.close().catch(() => void 0);\n\t}\n\t#admit(request, state) {\n\t\tconst snapshot = snapshotPromptRequest(request);\n\t\tif (this.#knownRunIds.has(snapshot.runId)) throw new AgentRuntimeError(\"duplicate_run_id\", \"runId is already active or queued\");\n\t\tlet resolveResult;\n\t\tlet failExecution;\n\t\tconst promise = new Promise((resolve) => {\n\t\t\tresolveResult = resolve;\n\t\t});\n\t\tconst executionFailure = new Promise((_resolve, reject) => {\n\t\t\tfailExecution = reject;\n\t\t});\n\t\texecutionFailure.catch(() => void 0);\n\t\tconst record = {\n\t\t\trequest: snapshot,\n\t\t\tcontroller: new AbortController(),\n\t\t\texecutionFailure,\n\t\t\teventValidator: new AgentRunEventValidator(),\n\t\t\tfailExecution,\n\t\t\tpromise,\n\t\t\tresolve: resolveResult,\n\t\t\tstate\n\t\t};\n\t\tthis.#knownRunIds.add(snapshot.runId);\n\t\tif (snapshot.signal) {\n\t\t\tconst onAbort = () => {\n\t\t\t\t/* v8 ignore else -- an abort for a settled record is a no-op by design. */\n\t\t\t\tif (record.state === \"queued\") this.#cancelQueued(record, \"run signal aborted\");\n\t\t\t\telse if (record.state === \"active\") this.#requestAbort(record, \"run signal aborted\").catch(() => void 0);\n\t\t\t};\n\t\t\tsnapshot.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\trecord.signalCleanup = () => snapshot.signal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t\treturn record;\n\t}\n\tasync #execute(record) {\n\t\tif (record.admissionEvent) await record.admissionEvent;\n\t\tlet result;\n\t\ttry {\n\t\t\tawait this.#dispatch({\n\t\t\t\ttype: \"run_started\",\n\t\t\t\trunId: record.request.runId\n\t\t\t});\n\t\t\tconst providerExecution = Promise.resolve().then(() => this.executeRun(record.request, this.#context(record)));\n\t\t\tconst providerResult = await Promise.race([providerExecution, record.executionFailure]);\n\t\t\trecord.eventValidator.assertSettled(providerResult);\n\t\t\tresult = this.#providerResult(record.request.runId, providerResult);\n\t\t} catch (error) {\n\t\t\tresult = this.#resultForThrownError(record, error);\n\t\t}\n\t\trecord.state = \"settling\";\n\t\tthis.#interactions.clear();\n\t\tif (!this.#sinkFailure) try {\n\t\t\tawait this.#dispatch(this.#terminalEvent(result));\n\t\t} catch (error) {\n\t\t\tBaseAgentRuntime.#logger.debug({\n\t\t\t\tcode: \"terminal_event_delivery_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Agent Runtime terminal event delivery failed\");\n\t\t\tresult = this.#eventDeliveryFailure(record.request.runId, result);\n\t\t}\n\t\telse result = this.#eventDeliveryFailure(record.request.runId, result);\n\t\tthis.#settle(record, result);\n\t\tthis.#finishActive();\n\t}\n\t#context(record) {\n\t\tconst assertCurrent = () => {\n\t\t\tif (record.state !== \"active\" || this.#active !== record) throw new AgentRuntimeError(\"run_mismatch\", \"provider event does not belong to the active run\");\n\t\t};\n\t\treturn {\n\t\t\trunId: record.request.runId,\n\t\t\tsignal: record.controller.signal,\n\t\t\tclaimTerminal: () => {\n\t\t\t\tassertCurrent();\n\t\t\t\trecord.providerTerminalClaimed = true;\n\t\t\t},\n\t\t\temit: async (event) => {\n\t\t\t\tassertCurrent();\n\t\t\t\trecord.eventValidator.accept(event);\n\t\t\t\tawait this.#dispatch({\n\t\t\t\t\t...event,\n\t\t\t\t\trunId: record.request.runId\n\t\t\t\t});\n\t\t\t},\n\t\t\tupdateBinding: async (binding) => {\n\t\t\t\tassertCurrent();\n\t\t\t\tassertBinding(binding, this.manifest);\n\t\t\t\tif (sameBinding(this.#binding, binding)) return;\n\t\t\t\tconst snapshot = snapshotBinding(binding);\n\t\t\t\tthis.#binding = snapshot;\n\t\t\t\tawait this.#dispatch({\n\t\t\t\t\ttype: \"binding_changed\",\n\t\t\t\t\tbinding: snapshot,\n\t\t\t\t\trunId: record.request.runId\n\t\t\t\t});\n\t\t\t},\n\t\t\trequestInteraction: async (request) => {\n\t\t\t\tassertCurrent();\n\t\t\t\tif (this.capabilities.interactions !== \"supported\") throw new AgentRuntimeError(\"unsupported_capability\", \"provider requested an unsupported interaction\");\n\t\t\t\tassertIdentifier(request.requestId, \"interaction.requestId\");\n\t\t\t\tif (this.#interactions.has(request.requestId)) throw new AgentRuntimeError(\"invalid_request\", \"provider emitted a duplicate interaction requestId\");\n\t\t\t\tthis.#interactions.set(request.requestId, { kind: request.kind });\n\t\t\t\ttry {\n\t\t\t\t\tawait this.#dispatch({\n\t\t\t\t\t\ttype: \"interaction_requested\",\n\t\t\t\t\t\trunId: record.request.runId,\n\t\t\t\t\t\trequest\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.#interactions.delete(request.requestId);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tresolveInteraction: async (requestId, decision) => {\n\t\t\t\tassertCurrent();\n\t\t\t\tif (!this.#interactions.delete(requestId)) return;\n\t\t\t\tawait this.#dispatch({\n\t\t\t\t\ttype: \"interaction_resolved\",\n\t\t\t\t\trunId: record.request.runId,\n\t\t\t\t\trequestId,\n\t\t\t\t\tdecision\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\t}\n\t#providerResult(runId, result) {\n\t\tconst error = result.error ?? (result.status === \"failed\" ? {\n\t\t\tcode: \"provider_error\",\n\t\t\tmessage: \"provider run failed\"\n\t\t} : result.status === \"aborted\" ? {\n\t\t\tcode: \"run_aborted\",\n\t\t\tmessage: \"provider run was interrupted\"\n\t\t} : void 0);\n\t\treturn immutableSnapshot({\n\t\t\trunId,\n\t\t\tstatus: result.status,\n\t\t\toutput: result.output ?? [],\n\t\t\t...result.usage ? { usage: result.usage } : {},\n\t\t\t...this.#binding ? { binding: this.#binding } : {},\n\t\t\t...error ? { error } : {},\n\t\t\t...result.diagnostics !== void 0 ? { providerDiagnostics: result.diagnostics } : {}\n\t\t});\n\t}\n\t#resultForThrownError(record, error) {\n\t\tif (this.#sinkFailure) return this.#eventDeliveryFailure(record.request.runId);\n\t\tif (record.controller.signal.aborted) return immutableSnapshot({\n\t\t\trunId: record.request.runId,\n\t\t\tstatus: \"aborted\",\n\t\t\toutput: [],\n\t\t\t...this.#binding ? { binding: this.#binding } : {},\n\t\t\terror: {\n\t\t\t\tcode: \"run_aborted\",\n\t\t\t\tmessage: \"run was interrupted\"\n\t\t\t}\n\t\t});\n\t\tconst providerError = error instanceof AgentProviderError ? error : void 0;\n\t\treturn immutableSnapshot({\n\t\t\trunId: record.request.runId,\n\t\t\tstatus: \"failed\",\n\t\t\toutput: [],\n\t\t\t...this.#binding ? { binding: this.#binding } : {},\n\t\t\terror: {\n\t\t\t\tcode: providerError?.code ?? \"provider_error\",\n\t\t\t\tmessage: providerError?.message ?? (error instanceof Error ? error.message : \"provider run failed\")\n\t\t\t}\n\t\t});\n\t}\n\t#eventDeliveryFailure(runId, previous) {\n\t\treturn immutableSnapshot({\n\t\t\trunId,\n\t\t\tstatus: \"failed\",\n\t\t\toutput: previous?.output ?? [],\n\t\t\t...previous?.usage ? { usage: previous.usage } : {},\n\t\t\t...this.#binding ? { binding: this.#binding } : {},\n\t\t\terror: {\n\t\t\t\tcode: \"event_delivery_failed\",\n\t\t\t\tmessage: \"the ordered event sink rejected an event\"\n\t\t\t},\n\t\t\t...previous?.providerDiagnostics !== void 0 ? { providerDiagnostics: previous.providerDiagnostics } : {}\n\t\t});\n\t}\n\t#terminalEvent(result) {\n\t\treturn {\n\t\t\ttype: result.status === \"completed\" ? \"run_completed\" : result.status === \"failed\" ? \"run_failed\" : result.status === \"aborted\" ? \"run_aborted\" : \"run_cancelled\",\n\t\t\trunId: result.runId,\n\t\t\tresult\n\t\t};\n\t}\n\t#settle(record, result) {\n\t\trecord.state = \"settled\";\n\t\trecord.signalCleanup?.();\n\t\trecord.signalCleanup = void 0;\n\t\tthis.#knownRunIds.delete(record.request.runId);\n\t\trecord.resolve(immutableSnapshot(result));\n\t}\n\t#finishActive() {\n\t\tthis.#active = void 0;\n\t\tif (this.#phase === \"closing\" || this.#sinkFailure) return;\n\t\twhile (this.#queued.length > 0) {\n\t\t\tconst next = this.#queued.shift();\n\t\t\tnext.state = \"active\";\n\t\t\tthis.#active = next;\n\t\t\tthis.#execute(next);\n\t\t\treturn;\n\t\t}\n\t\tthis.#phase = \"idle\";\n\t\tthis.#resolveIdleWaiters();\n\t}\n\tasync #cancelQueued(record, message) {\n\t\tconst index = this.#queued.indexOf(record);\n\t\t/* v8 ignore next -- queue claims detach this listener; the guard defends a stale callback already in flight. */\n\t\tif (record.state !== \"queued\" || index < 0) return;\n\t\tthis.#queued.splice(index, 1);\n\t\tthis.#claimQueued(record);\n\t\tlet result = {\n\t\t\trunId: record.request.runId,\n\t\t\tstatus: \"cancelled\",\n\t\t\toutput: [],\n\t\t\t...this.#binding ? { binding: this.#binding } : {},\n\t\t\terror: {\n\t\t\t\tcode: \"run_cancelled\",\n\t\t\t\tmessage\n\t\t\t}\n\t\t};\n\t\t/* v8 ignore else -- a cancelled run only skips its terminal event after a sink failure already closed the runtime. */\n\t\tif (!this.#sinkFailure) try {\n\t\t\tawait record.admissionEvent;\n\t\t\tawait this.#dispatch(this.#terminalEvent(result));\n\t\t} catch (error) {\n\t\t\tBaseAgentRuntime.#logger.debug({\n\t\t\t\tcode: \"cancelled_event_delivery_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Agent Runtime cancelled event delivery failed\");\n\t\t\tresult = {\n\t\t\t\t...result,\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"event_delivery_failed\",\n\t\t\t\t\tmessage: \"the ordered event sink rejected an event\"\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tthis.#settle(record, result);\n\t}\n\t#requestAbort(record, reason) {\n\t\tif (record.abortPromise) return record.abortPromise;\n\t\trecord.abortPromise = this.abortProvider({\n\t\t\texpectedRunId: record.request.runId,\n\t\t\treason\n\t\t}).then(() => {\n\t\t\tif (!record.controller.signal.aborted) record.controller.abort(reason);\n\t\t}, (error) => {\n\t\t\tthis.#failAbort(record, error);\n\t\t\tthrow error;\n\t\t});\n\t\treturn record.abortPromise;\n\t}\n\t#failAbort(record, error) {\n\t\tif (record.state !== \"active\" || this.#active !== record || record.providerTerminalClaimed) return;\n\t\trecord.failExecution(new AgentProviderError(\"provider_error\", \"provider interrupt failed\", { cause: error }));\n\t\tthis.closeForProviderFailure();\n\t}\n\t#requireActive(expectedRunId) {\n\t\tconst active = this.#active;\n\t\tif (!active || active.request.runId !== expectedRunId || active.state !== \"active\") throw new AgentRuntimeError(\"run_mismatch\", \"expectedRunId does not match the active run\");\n\t\treturn active;\n\t}\n\t#assertOpen() {\n\t\tif (this.#phase === \"closing\" || this.#phase === \"closed\") throw new AgentRuntimeError(\"closed\", \"runtime is closing or closed\");\n\t}\n\t#dispatch(event) {\n\t\tif (this.#sinkFailure) return Promise.reject(this.#sinkFailure);\n\t\tconst snapshot = immutableSnapshot(event);\n\t\tconst delivery = this.#dispatchTail.then(async () => {\n\t\t\tif (this.#sinkFailure) throw this.#sinkFailure;\n\t\t\tawait this.#eventSink(snapshot);\n\t\t});\n\t\tthis.#dispatchTail = delivery.catch((error) => {\n\t\t\tBaseAgentRuntime.#logger.debug({\n\t\t\t\tcode: \"event_sink_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Agent Runtime event sink failed\");\n\t\t\tthis.#breakEventSink(error instanceof Error ? error : /* @__PURE__ */ new Error(\"event sink rejected an event\"));\n\t\t});\n\t\treturn delivery;\n\t}\n\t#breakEventSink(error) {\n\t\tif (this.#sinkFailure) return;\n\t\tthis.#sinkFailure = error;\n\t\tthis.#phase = \"closing\";\n\t\tif (this.#active && !this.#active.controller.signal.aborted) this.#active.controller.abort(\"event delivery failed\");\n\t\tconst queued = this.#queued.splice(0);\n\t\tfor (const record of queued) this.#settle(record, {\n\t\t\trunId: record.request.runId,\n\t\t\tstatus: \"cancelled\",\n\t\t\toutput: [],\n\t\t\t...this.#binding ? { binding: this.#binding } : {},\n\t\t\terror: {\n\t\t\t\tcode: \"event_delivery_failed\",\n\t\t\t\tmessage: \"the ordered event sink rejected an event\"\n\t\t\t}\n\t\t});\n\t\t/* v8 ignore next -- closing after a sink failure must not raise a second fault. */\n\t\tthis.close().catch((error) => {\n\t\t\tBaseAgentRuntime.#logger.debug({\n\t\t\t\tcode: \"close_after_sink_failure_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Agent Runtime close after sink failure failed\");\n\t\t});\n\t}\n\tasync #closeInternal() {\n\t\tthis.#phase = \"closing\";\n\t\tconst active = this.#active;\n\t\tconst queued = this.#queued.splice(0);\n\t\tfor (const record of queued) this.#claimQueued(record);\n\t\tif (active && !this.#providerFailureClosing && !active.controller.signal.aborted) active.controller.abort(\"runtime closing\");\n\t\tconst aborting = active && !this.#providerFailureClosing ? this.#requestAbort(active, \"runtime closing\").catch((error) => {\n\t\t\tBaseAgentRuntime.#logger.debug({\n\t\t\t\tcode: \"abort_during_close_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Agent Runtime abort during close failed\");\n\t\t}) : Promise.resolve();\n\t\tlet closeError;\n\t\tconst providerClosing = this.closeProvider().catch((error) => {\n\t\t\tcloseError = error;\n\t\t});\n\t\tlet queueSinkHealthy = !this.#sinkFailure;\n\t\tfor (const record of queued) {\n\t\t\tlet result = {\n\t\t\t\trunId: record.request.runId,\n\t\t\t\tstatus: \"cancelled\",\n\t\t\t\toutput: [],\n\t\t\t\t...this.#binding ? { binding: this.#binding } : {},\n\t\t\t\terror: {\n\t\t\t\t\tcode: queueSinkHealthy ? \"runtime_closed\" : \"event_delivery_failed\",\n\t\t\t\t\tmessage: queueSinkHealthy ? \"runtime closed before the queued run started\" : \"event delivery failed\"\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (queueSinkHealthy) try {\n\t\t\t\tawait record.admissionEvent;\n\t\t\t\tawait this.#dispatch(this.#terminalEvent(result));\n\t\t\t} catch (error) {\n\t\t\t\tBaseAgentRuntime.#logger.debug({\n\t\t\t\t\tcode: \"queued_event_delivery_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Agent Runtime queued event delivery failed\");\n\t\t\t\tqueueSinkHealthy = false;\n\t\t\t\tresult = {\n\t\t\t\t\t...result,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: \"event_delivery_failed\",\n\t\t\t\t\t\tmessage: \"the ordered event sink rejected an event\"\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t\tthis.#settle(record, result);\n\t\t}\n\t\tawait aborting;\n\t\tawait providerClosing;\n\t\tawait active?.promise;\n\t\tawait this.#dispatchTail;\n\t\tif (!this.#sinkFailure) await this.#dispatch({ type: \"runtime_closed\" }).catch((error) => {\n\t\t\tBaseAgentRuntime.#logger.debug({\n\t\t\t\tcode: \"runtime_closed_event_delivery_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Agent Runtime closed event delivery failed\");\n\t\t});\n\t\tthis.#phase = \"closed\";\n\t\tthis.#active = void 0;\n\t\tthis.#interactions.clear();\n\t\tthis.#resolveIdleWaiters();\n\t\tif (closeError) throw new AgentRuntimeError(\"close_failed\", \"provider resources could not be closed\", { cause: closeError });\n\t}\n\t#resolveIdleWaiters() {\n\t\tfor (const resolve of this.#idleWaiters) resolve();\n\t\tthis.#idleWaiters.clear();\n\t}\n\t#claimQueued(record) {\n\t\trecord.state = \"settling\";\n\t\trecord.signalCleanup?.();\n\t\trecord.signalCleanup = void 0;\n\t}\n};\nfunction snapshotPromptRequest(request) {\n\treturn Object.freeze({\n\t\trunId: request.runId,\n\t\tinput: immutableSnapshot(request.input),\n\t\t...request.configuration ? { configuration: immutableSnapshot(request.configuration) } : {},\n\t\t...request.signal ? { signal: request.signal } : {}\n\t});\n}\nfunction snapshotBinding(binding) {\n\treturn immutableSnapshot(binding);\n}\nfunction immutableSnapshot(value) {\n\tif (Array.isArray(value)) return Object.freeze(value.map((item) => immutableSnapshot(item)));\n\tif (value !== null && typeof value === \"object\") return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, immutableSnapshot(item)])));\n\treturn value;\n}\n//#endregion\n//#region src/storage/durable-file.ts\nvar RuntimeStorageError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = \"RuntimeStorageError\";\n\t}\n};\nasync function ensurePrivateDirectory(root, target) {\n\tconst rootPath = resolve(root);\n\tconst targetPath = resolve(target);\n\tassertWithin(rootPath, targetPath);\n\tawait ensureRootDirectory(rootPath);\n\tconst suffix = relative(rootPath, targetPath);\n\tlet current = rootPath;\n\tif (suffix) for (const segment of suffix.split(sep)) {\n\t\tcurrent = resolve(current, segment);\n\t\tawait ensureOneDirectory(current);\n\t}\n\tconst canonicalRoot = await realpath(rootPath);\n\tconst canonicalTarget = await realpath(targetPath);\n\tassertWithin(canonicalRoot, canonicalTarget);\n\treturn canonicalTarget;\n}\nasync function validatePrivateDirectory(root, target) {\n\tconst rootPath = resolve(root);\n\tconst targetPath = resolve(target);\n\tassertWithin(rootPath, targetPath);\n\tconst suffix = relative(rootPath, targetPath);\n\tlet current = rootPath;\n\tfor (const segment of suffix ? [\"\", ...suffix.split(sep)] : [\"\"]) {\n\t\tif (segment) current = resolve(current, segment);\n\t\ttry {\n\t\t\tawait assertRealDirectory(current);\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return false;\n\t\t\tthrow error;\n\t\t}\n\t}\n\tassertWithin(await realpath(rootPath), await realpath(targetPath));\n\treturn true;\n}\nasync function readSecureFile(path) {\n\tlet handle;\n\ttry {\n\t\tconst status = await lstat(path);\n\t\tif (!status.isFile() || status.isSymbolicLink()) throw new RuntimeStorageError(\"unsafe\", \"Runtime storage files must be regular files\");\n\t\thandle = await open(path, constants.O_RDONLY | noFollowFlag());\n\t\tif (!(await handle.stat()).isFile()) throw new RuntimeStorageError(\"unsafe\", \"Runtime storage file changed during open\");\n\t\treturn await handle.readFile(\"utf8\");\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return void 0;\n\t\tthrow error;\n\t} finally {\n\t\tawait handle?.close();\n\t}\n}\nasync function readDurableJson(path, validate) {\n\tconst content = await readSecureFile(path);\n\tif (content === void 0) return void 0;\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(content);\n\t} catch {\n\t\tthrow new RuntimeStorageError(\"invalid\", \"Runtime storage contains invalid JSON\");\n\t}\n\ttry {\n\t\treturn validate(parsed);\n\t} catch (error) {\n\t\tif (error instanceof RuntimeStorageError) throw error;\n\t\tthrow new RuntimeStorageError(\"invalid\", \"Runtime storage contains data that does not match its schema\");\n\t}\n}\nasync function writeDurableFile(path, content, mode = 384) {\n\tconst parent = dirname(path);\n\tawait assertRealDirectory(parent);\n\tawait assertReplaceableFile(path);\n\tconst temporary = resolve(parent, `.${randomUUID()}.tmp`);\n\tlet handle;\n\ttry {\n\t\thandle = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollowFlag(), 384);\n\t\tawait handle.writeFile(content, \"utf8\");\n\t\tawait handle.sync();\n\t\tawait handle.close();\n\t\thandle = void 0;\n\t\tawait rename(temporary, path);\n\t\tawait chmod(path, mode);\n\t\tawait syncDirectory(parent);\n\t} catch (error) {\n\t\tawait handle?.close();\n\t\tawait rm(temporary, { force: true });\n\t\tthrow error;\n\t}\n}\nasync function writeDurableJson(path, value) {\n\tawait writeDurableFile(path, `${JSON.stringify(value, void 0, 2)}\\n`, 384);\n}\nasync function removeDurableFile(path) {\n\tawait assertReplaceableFile(path);\n\tawait rm(path);\n\tawait syncDirectory(dirname(path));\n}\nasync function assertRealDirectory(path) {\n\tconst status = await lstat(path);\n\tif (!status.isDirectory() || status.isSymbolicLink()) throw new RuntimeStorageError(\"unsafe\", \"Runtime storage directories must be real directories\");\n}\nfunction assertWithin(root, target) {\n\tconst rootPath = resolve(root);\n\tconst targetPath = resolve(target);\n\tconst suffix = relative(rootPath, targetPath);\n\tif (suffix === \"\" || !suffix.startsWith(`..${sep}`) && suffix !== \"..\" && !isAbsolute(suffix)) return;\n\tthrow new RuntimeStorageError(\"unsafe\", \"Runtime storage path escaped its root\");\n}\nasync function ensureOneDirectory(path) {\n\ttry {\n\t\tawait mkdir(path, { mode: 448 });\n\t} catch (error) {\n\t\tif (error.code !== \"EEXIST\") throw error;\n\t}\n\tawait assertRealDirectory(path);\n\tawait chmod(path, 448);\n}\nasync function ensureRootDirectory(root) {\n\tconst missingSegments = [];\n\tlet existing = root;\n\tfor (;;) try {\n\t\tawait assertRealDirectory(existing);\n\t\tbreak;\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t\tconst parent = dirname(existing);\n\t\tif (parent === existing) throw error;\n\t\tmissingSegments.unshift(basename(existing));\n\t\texisting = parent;\n\t}\n\tlet current = existing;\n\tfor (const segment of missingSegments) {\n\t\tcurrent = resolve(current, segment);\n\t\tawait ensureOneDirectory(current);\n\t}\n\tawait ensureOneDirectory(root);\n}\nasync function assertReplaceableFile(path) {\n\ttry {\n\t\tconst status = await lstat(path);\n\t\tif (!status.isFile() || status.isSymbolicLink()) throw new RuntimeStorageError(\"unsafe\", \"Runtime storage destination must be a regular file\");\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t}\n}\nasync function syncDirectory(path) {\n\tconst directory = await open(path, constants.O_RDONLY | noFollowFlag());\n\ttry {\n\t\tawait directory.sync();\n\t} finally {\n\t\tawait directory.close();\n\t}\n}\nasync function syncDurableDirectory(path) {\n\tawait syncDirectory(path);\n}\nfunction noFollowFlag() {\n\treturn constants.O_NOFOLLOW ?? 0;\n}\n//#endregion\n//#region src/storage/home-layout.ts\nfunction resolveOpenTagHome(environment = process.env) {\n\treturn environment.OPENTAG_HOME ? resolve(environment.OPENTAG_HOME) : join(homedir(), \".opentag\");\n}\nfunction resolveOpenTagHomeLayout(home = resolveOpenTagHome()) {\n\tconst resolvedHome = resolve(home);\n\tconst config = join(resolvedHome, \"config\");\n\tconst data = join(resolvedHome, \"data\");\n\tconst runtime = join(data, \"runtime\");\n\tconst state = join(resolvedHome, \"state\");\n\treturn {\n\t\tconfig,\n\t\tcontextTreeBin: join(resolvedHome, \"context-tree\", \"bin\"),\n\t\tdaemonState: join(state, \"daemon\"),\n\t\tdata,\n\t\thome: resolvedHome,\n\t\tlogs: join(resolvedHome, \"logs\"),\n\t\truntime,\n\t\truntimeEffectiveSnapshots: join(runtime, \"effective-snapshots\"),\n\t\truntimeSessionBindings: join(runtime, \"session-bindings\"),\n\t\truntimeWorkspaceStates: join(runtime, \"workspace-states\"),\n\t\tserviceState: join(state, \"service\"),\n\t\tstate,\n\t\tworkspaces: join(data, \"workspaces\")\n\t};\n}\n//#endregion\n//#region src/runtime/runtime-credential-frames.ts\n/** Capability negotiation names offered/negotiated at version 1. */\nconst RUNTIME_CREDENTIAL_CAPABILITY = RUNTIME_CAPABILITY.runtimeCredential;\nconst RUNTIME_PROVIDER_PROXY_CAPABILITY = RUNTIME_CAPABILITY.providerProxy;\n/** The `web_tools_v1` negotiation: both ends speak the fixed web tools protocol at version 1. */\nconst RUNTIME_WEB_TOOLS_CAPABILITY = RUNTIME_CAPABILITY.webTools;\n/** Both ends speak the inbound MCP gateway contract at version 1. */\nconst RUNTIME_MCP_GATEWAY_CAPABILITY = RUNTIME_CAPABILITY.mcpGateway;\n/** Short aliases used across the Client runtime modules. */\nconst RUNTIME_PROXY_DATA_HEADER_MAX_BYTES = PROVIDER_PROXY_HEADER_MAX_BYTES;\nconst RUNTIME_PROXY_DATA_CHUNK_BYTES = PROVIDER_PROXY_CHUNK_MAX_BYTES;\nconst RUNTIME_PROXY_DATA_BINARY_FRAME_MAX_BYTES = PROVIDER_PROXY_MAX_FRAME_BYTES;\nconst RUNTIME_PROXY_DATA_INITIAL_CREDIT_BYTES = PROVIDER_PROXY_INITIAL_CREDIT_BYTES;\nconst RUNTIME_PROXY_DATA_MAX_STREAMS = PROVIDER_PROXY_MAX_STREAMS_PER_EXECUTION;\n/** Local aliases kept for the data-client and public barrel naming. */\nconst RuntimeProxyDataReadyFrameSchema = RuntimeProviderProxyReadyFrameSchema;\nconst RuntimeProxyDataServerFrameSchema = RuntimeProviderProxyServerFrameSchema;\nconst RUNTIME_PROXY_PROVIDERS = RUNTIME_CREDENTIAL_PROVIDERS;\n/** Parse one Server business frame; returns undefined for non-credential frames. */\nfunction parseRuntimeCredentialServerFrame(value) {\n\tconst parsed = RuntimeCredentialServerFrameSchema.safeParse(value);\n\treturn parsed.success ? parsed.data : void 0;\n}\n/**\n* Stable, secret-free reason for proxy/relay logs and error messages. Exception messages can\n* embed a capability, ticket, or local handle (upstream errors, WebSocket failures, fetch\n* bodies), so only the constructor name plus an optional short string `code` are retained.\n* Unknown thrown values are never stringified.\n*/\nfunction runtimeProxyErrorReason(error) {\n\tif (typeof error !== \"object\" || error === null) return \"UnknownError\";\n\tconst name = error.name;\n\tconst code = error.code;\n\tconst label = typeof name === \"string\" && name.length > 0 && name.length <= 64 ? name : \"Error\";\n\treturn typeof code === \"string\" && /^[A-Z][A-Z0-9_]{0,31}$/.test(code) ? `${label}:${code}` : label;\n}\n//#endregion\n//#region src/runtime/runtime-proxy-data-client.ts\n/** Controlled data-channel failure. `code` identifies the local cause; upstream codes stay in `message`. */\nvar RuntimeProxyDataError = class extends Error {\n\tcode;\n\tconstructor(code, message, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = \"RuntimeProxyDataError\";\n\t}\n};\nvar ProxyStream = class {\n\tstreamId;\n\tinboundGranted = 0;\n\tinboundReceived = 0;\n\trequestEnded = false;\n\tresponded = false;\n\tresponseEnded = false;\n\tsettled = false;\n\tsendCredit = {\n\t\tavailable: RUNTIME_PROXY_DATA_INITIAL_CREDIT_BYTES,\n\t\twaiters: []\n\t};\n\tinbound;\n\tresolveOpen;\n\trejectOpen;\n\topenTimer;\n\tconstructor(streamId) {\n\t\tthis.streamId = streamId;\n\t}\n};\n/**\n* Pull-based handoff between the socket reader and the response consumer. Credit is\n* granted only when a chunk is handed to the consumer, so a slow consumer applies\n* backpressure to the Server within the fixed initial window.\n*/\nvar StreamChunkQueue = class {\n\tonConsume;\n\tonCancel;\n\t#chunks = [];\n\t#error;\n\t#finished = false;\n\t#waiter;\n\tconstructor(onConsume, onCancel) {\n\t\tthis.onConsume = onConsume;\n\t\tthis.onCancel = onCancel;\n\t}\n\tpush(chunk) {\n\t\tif (this.#finished) return;\n\t\tif (this.#waiter) {\n\t\t\tconst waiter = this.#waiter;\n\t\t\tthis.#waiter = void 0;\n\t\t\tthis.onConsume(chunk.byteLength);\n\t\t\twaiter.resolve({\n\t\t\t\tdone: false,\n\t\t\t\tvalue: chunk\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthis.#chunks.push(chunk);\n\t}\n\tend() {\n\t\tif (this.#finished) return;\n\t\tthis.#finished = true;\n\t\tif (this.#waiter) {\n\t\t\tconst waiter = this.#waiter;\n\t\t\tthis.#waiter = void 0;\n\t\t\twaiter.resolve({\n\t\t\t\tdone: true,\n\t\t\t\tvalue: void 0\n\t\t\t});\n\t\t}\n\t}\n\tfail(error) {\n\t\tif (this.#finished) return;\n\t\tthis.#finished = true;\n\t\tthis.#error = error;\n\t\tif (this.#waiter) {\n\t\t\tconst waiter = this.#waiter;\n\t\t\tthis.#waiter = void 0;\n\t\t\twaiter.reject(error);\n\t\t}\n\t\tthis.#chunks = [];\n\t}\n\t[Symbol.asyncIterator]() {\n\t\tconst queue = this;\n\t\treturn {\n\t\t\tnext() {\n\t\t\t\tconst chunk = queue.#chunks.shift();\n\t\t\t\tif (chunk !== void 0) {\n\t\t\t\t\tqueue.onConsume(chunk.byteLength);\n\t\t\t\t\treturn Promise.resolve({\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: chunk\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (queue.#error) return Promise.reject(queue.#error);\n\t\t\t\tif (queue.#finished) return Promise.resolve({\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t});\n\t\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\t\tqueue.#waiter = {\n\t\t\t\t\t\tresolve,\n\t\t\t\t\t\treject\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t\t},\n\t\t\treturn() {\n\t\t\t\tqueue.onCancel?.();\n\t\t\t\tqueue.end();\n\t\t\t\treturn Promise.resolve({\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\t}\n};\n/**\n* Production client for the fixed binary streaming data protocol: one authenticated\n* WSS per execution, first frame `{type:\"auth\",ticket}`, JSON header frames bounded at\n* 16 KiB, binary frames `4-byte BE streamId || chunk` with chunks ≤ 64 KiB, 1 MiB\n* initial per-direction credit, at most 8 concurrent streams with a bounded open\n* queue, half-close via `end`, and `cancel`/`error`/connection loss rejecting every\n* pending promise. Writes are never replayed.\n*/\nvar RuntimeProxyDataConnection = class RuntimeProxyDataConnection {\n\t#logger;\n\t#maxQueuedOpens;\n\t#maxStreams;\n\t#tombstoneLimit;\n\t/** Bounded tombstones for genuinely locally-cancelled streams only. */\n\t#tombstones = /* @__PURE__ */ new Map();\n\t#openTimeoutMs;\n\t#openQueue = [];\n\t#socket;\n\t#streams = /* @__PURE__ */ new Map();\n\t#closePromise;\n\t#closed = false;\n\t#closeSocket;\n\t#nextStreamId = 1;\n\tconstructor(socket, options) {\n\t\tthis.#socket = socket;\n\t\tthis.#logger = options.logger ?? createLogger(\"runtime-proxy-data\");\n\t\tthis.#maxQueuedOpens = options.maxQueuedOpens ?? 64;\n\t\tthis.#maxStreams = options.maxStreams ?? RUNTIME_PROXY_DATA_MAX_STREAMS;\n\t\tthis.#tombstoneLimit = PROVIDER_PROXY_MAX_STREAM_OPENS_PER_CONNECTION;\n\t\tthis.#openTimeoutMs = options.openTimeoutMs ?? 3e4;\n\t\tthis.#closePromise = new Promise((resolve) => {\n\t\t\tthis.#closeSocket = resolve;\n\t\t});\n\t\tsocket.on(\"message\", (data, isBinary) => this.#handleMessage(data, isBinary));\n\t\tsocket.on(\"close\", () => this.#failAll(new RuntimeProxyDataError(\"connection_lost\", \"The data connection closed\")));\n\t\tsocket.on(\"error\", (error) => {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"data_socket_error\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Data connection socket error\");\n\t\t});\n\t}\n\tget closed() {\n\t\treturn this.#closed;\n\t}\n\tget activeStreamCount() {\n\t\treturn this.#streams.size;\n\t}\n\t/** Resolves once the connection is fully closed (by either side or a protocol violation). */\n\tsettled() {\n\t\treturn this.#closePromise;\n\t}\n\t/** Establish the connection and complete the ticket auth handshake. */\n\tstatic async connect(options) {\n\t\tif (options.url.includes(\"?\") || options.url.includes(\"#\")) throw new RuntimeProxyDataError(\"protocol_error\", \"The data endpoint URL must not carry query parameters\");\n\t\tconst socket = (options.webSocketFactory ?? ((url, socketOptions) => new WebSocket(url, socketOptions)))(options.url, {\n\t\t\tmaxPayload: RUNTIME_PROXY_DATA_BINARY_FRAME_MAX_BYTES,\n\t\t\tperMessageDeflate: false\n\t\t});\n\t\tconst handshakeTimeoutMs = options.handshakeTimeoutMs ?? 15e3;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet settled = false;\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tsocket.terminate();\n\t\t\t\treject(new RuntimeProxyDataError(\"auth_failed\", \"The data connection auth handshake timed out\"));\n\t\t\t}, handshakeTimeoutMs);\n\t\t\ttimer.unref();\n\t\t\tconst cleanup = () => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tsocket.removeAllListeners(\"message\");\n\t\t\t\tsocket.removeAllListeners(\"open\");\n\t\t\t\tsocket.removeAllListeners(\"error\");\n\t\t\t\tsocket.removeAllListeners(\"close\");\n\t\t\t};\n\t\t\tconst fail = (error, closeCode, reason) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\tif (closeCode !== void 0 && socket.readyState === WebSocket.OPEN) socket.close(closeCode, reason);\n\t\t\t\telse socket.terminate();\n\t\t\t\treject(error);\n\t\t\t};\n\t\t\tsocket.on(\"open\", () => {\n\t\t\t\tsocket.send(JSON.stringify({\n\t\t\t\t\ttype: \"auth\",\n\t\t\t\t\tticket: options.ticket\n\t\t\t\t}));\n\t\t\t});\n\t\t\tsocket.on(\"message\", (data, isBinary) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tif (isBinary) {\n\t\t\t\t\tfail(new RuntimeProxyDataError(\"protocol_error\", \"The data connection sent binary before ready\"), 1008, \"binary_before_ready\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlet frame;\n\t\t\t\ttry {\n\t\t\t\t\tframe = JSON.parse(rawDataToBuffer(data).toString(\"utf8\"));\n\t\t\t\t} catch {\n\t\t\t\t\tfail(new RuntimeProxyDataError(\"protocol_error\", \"The data connection sent an invalid auth reply\"), 1008, \"invalid_frame\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst ready = RuntimeProxyDataReadyFrameSchema.safeParse(frame);\n\t\t\t\tif (!ready.success || ready.data.executionId !== options.executionId) {\n\t\t\t\t\tfail(new RuntimeProxyDataError(\"auth_failed\", \"The data connection rejected the ticket\"), 1008, \"auth_rejected\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(new RuntimeProxyDataConnection(socket, options));\n\t\t\t});\n\t\t\tsocket.on(\"error\", () => {\n\t\t\t\tfail(new RuntimeProxyDataError(\"connection_lost\", \"The data connection failed during the handshake\"));\n\t\t\t});\n\t\t\tsocket.on(\"close\", () => {\n\t\t\t\tfail(new RuntimeProxyDataError(\"auth_failed\", \"The data connection closed before ready\"));\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Open one request/response stream. The response resolves with the status and\n\t* headers; its body is an async iterable that applies credit backpressure. Request\n\t* bodies stream concurrently with the response within the credit window.\n\t*/\n\topenStream(request) {\n\t\tif (this.#closed) return Promise.reject(new RuntimeProxyDataError(\"connection_closed\", \"The data connection is closed\"));\n\t\tif (request.signal?.aborted) return Promise.reject(new RuntimeProxyDataError(\"aborted\", \"The stream was aborted before it opened\"));\n\t\tif (this.#streams.size >= this.#maxStreams) {\n\t\t\tif (this.#openQueue.length >= this.#maxQueuedOpens) return Promise.reject(new RuntimeProxyDataError(\"queue_full\", \"The data connection stream queue is full\"));\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tconst queued = {\n\t\t\t\t\treject,\n\t\t\t\t\trequest,\n\t\t\t\t\tresolve\n\t\t\t\t};\n\t\t\t\trequest.signal?.addEventListener(\"abort\", () => {\n\t\t\t\t\tconst index = this.#openQueue.indexOf(queued);\n\t\t\t\t\tif (index >= 0) {\n\t\t\t\t\t\tthis.#openQueue.splice(index, 1);\n\t\t\t\t\t\treject(new RuntimeProxyDataError(\"aborted\", \"The queued stream was aborted\"));\n\t\t\t\t\t}\n\t\t\t\t}, { once: true });\n\t\t\t\tthis.#openQueue.push(queued);\n\t\t\t});\n\t\t}\n\t\treturn this.#startStream(request);\n\t}\n\t/** Cancel every stream and close the socket. Idempotent. */\n\tasync close() {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tconst error = new RuntimeProxyDataError(\"connection_closed\", \"The data connection is closed\");\n\t\tthis.#failQueued(error);\n\t\tfor (const stream of this.#streams.values()) {\n\t\t\tthis.#sendControl({\n\t\t\t\ttype: \"cancel\",\n\t\t\t\tstreamId: stream.streamId\n\t\t\t});\n\t\t\tthis.#failStream(stream, error);\n\t\t}\n\t\tconst socket = this.#socket;\n\t\tif (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) socket.close(1e3, \"execution_closed\");\n\t\telse this.#closeSocket();\n\t\tawait this.#closePromise;\n\t}\n\t#startStream(request) {\n\t\tconst streamId = this.#allocateStreamId();\n\t\tconst stream = new ProxyStream(streamId);\n\t\tstream.inbound = new StreamChunkQueue((bytes) => this.#grantInboundCredit(stream, bytes), () => this.#cancelStream(stream, \"consumer_closed\"));\n\t\tthis.#streams.set(streamId, stream);\n\t\tconst openPromise = new Promise((resolve, reject) => {\n\t\t\tstream.resolveOpen = (response) => {\n\t\t\t\tstream.resolveOpen = void 0;\n\t\t\t\tstream.rejectOpen = void 0;\n\t\t\t\tif (stream.openTimer) clearTimeout(stream.openTimer);\n\t\t\t\tstream.openTimer = void 0;\n\t\t\t\tresolve(response);\n\t\t\t};\n\t\t\tstream.rejectOpen = (error) => {\n\t\t\t\tstream.resolveOpen = void 0;\n\t\t\t\tstream.rejectOpen = void 0;\n\t\t\t\tif (stream.openTimer) clearTimeout(stream.openTimer);\n\t\t\t\tstream.openTimer = void 0;\n\t\t\t\treject(error);\n\t\t\t};\n\t\t});\n\t\tstream.openTimer = setTimeout(() => {\n\t\t\tstream.openTimer = void 0;\n\t\t\tthis.#cancelStream(stream, \"open_timeout\");\n\t\t\tstream.rejectOpen?.(new RuntimeProxyDataError(\"open_timeout\", \"The data stream did not produce a response in time\"));\n\t\t}, this.#openTimeoutMs);\n\t\tstream.openTimer.unref();\n\t\tconst onAbort = () => {\n\t\t\tthis.#cancelStream(stream, \"aborted\");\n\t\t\tstream.rejectOpen?.(new RuntimeProxyDataError(\"aborted\", \"The stream was aborted\"));\n\t\t};\n\t\trequest.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\topenPromise.then(() => request.signal?.removeEventListener(\"abort\", onAbort), () => request.signal?.removeEventListener(\"abort\", onAbort));\n\t\tif (!this.#sendControl({\n\t\t\ttype: \"open\",\n\t\t\tstreamId,\n\t\t\tcapability: request.capability,\n\t\t\tprovider: request.provider,\n\t\t\tbindingId: request.bindingId,\n\t\t\tmethod: request.method,\n\t\t\tpath: request.path,\n\t\t\theaders: { ...request.headers }\n\t\t})) {\n\t\t\tthis.#failStream(stream, new RuntimeProxyDataError(\"connection_closed\", \"The data connection is closed\"));\n\t\t\treturn openPromise;\n\t\t}\n\t\tthis.#pumpRequestBody(stream, request.body);\n\t\treturn openPromise;\n\t}\n\t#allocateStreamId() {\n\t\tfor (let attempts = 0; attempts < 4294967295; attempts += 1) {\n\t\t\tconst candidate = this.#nextStreamId;\n\t\t\tthis.#nextStreamId = this.#nextStreamId >= 4294967295 ? 1 : this.#nextStreamId + 1;\n\t\t\tif (!this.#streams.has(candidate) && !this.#tombstones.has(candidate)) return candidate;\n\t\t}\n\t\tthrow new RuntimeProxyDataError(\"too_many_streams\", \"The data connection exhausted stream identifiers\");\n\t}\n\tasync #pumpRequestBody(stream, body) {\n\t\tif (!body) {\n\t\t\tthis.#finishRequestSide(stream);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tfor await (const chunk of body) {\n\t\t\t\tconst buffer = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);\n\t\t\t\tif (!await this.#pumpChunk(stream, buffer)) return;\n\t\t\t}\n\t\t\tthis.#finishRequestSide(stream);\n\t\t} catch (error) {\n\t\t\tif (error instanceof RuntimeProxyDataError && error.code === \"connection_closed\") return;\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"request_body_pump_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Request body pump failed\");\n\t\t\tthis.#cancelStream(stream, \"request_body_failed\");\n\t\t}\n\t}\n\t/** Sends one body chunk within the credit window; `false` when the stream/connection ended. */\n\tasync #pumpChunk(stream, chunk) {\n\t\tlet buffer = chunk;\n\t\twhile (buffer.byteLength > 0) {\n\t\t\tif (stream.settled || this.#closed) return false;\n\t\t\tconst slice = buffer.subarray(0, RUNTIME_PROXY_DATA_CHUNK_BYTES);\n\t\t\tbuffer = buffer.subarray(slice.byteLength);\n\t\t\tawait this.#waitSendCredit(stream, slice.byteLength);\n\t\t\tif (stream.settled || this.#closed) return false;\n\t\t\tstream.sendCredit.available -= slice.byteLength;\n\t\t\tconst frame = new Uint8Array(4 + slice.byteLength);\n\t\t\tnew DataView(frame.buffer).setUint32(0, stream.streamId, false);\n\t\t\tframe.set(slice, 4);\n\t\t\tif (!await this.#sendBinary(frame)) return false;\n\t\t}\n\t\treturn true;\n\t}\n\t#finishRequestSide(stream) {\n\t\tif (stream.requestEnded || stream.settled) return;\n\t\tstream.requestEnded = true;\n\t\tthis.#sendControl({\n\t\t\ttype: \"end\",\n\t\t\tstreamId: stream.streamId\n\t\t});\n\t\tthis.#completeIfDone(stream);\n\t}\n\tasync #waitSendCredit(stream, bytes) {\n\t\twhile (!stream.settled && !this.#closed && stream.sendCredit.available < bytes) await new Promise((resolve) => {\n\t\t\tstream.sendCredit.waiters.push(resolve);\n\t\t});\n\t\tif (stream.settled || this.#closed) throw new RuntimeProxyDataError(\"connection_closed\", \"The data stream closed while waiting for credit\");\n\t}\n\t#grantInboundCredit(stream, bytes) {\n\t\tif (stream.settled || this.#closed) return;\n\t\tstream.inboundGranted += bytes;\n\t\tthis.#sendControl({\n\t\t\ttype: \"credit\",\n\t\t\tstreamId: stream.streamId,\n\t\t\tbytes\n\t\t});\n\t}\n\t#sendBinary(frame) {\n\t\tif (this.#closed || this.#socket.readyState !== WebSocket.OPEN) return Promise.resolve(false);\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.#socket.send(frame, (error) => {\n\t\t\t\tresolve(!error);\n\t\t\t});\n\t\t});\n\t}\n\t#sendControl(frame) {\n\t\tif (this.#closed || this.#socket.readyState !== WebSocket.OPEN) return false;\n\t\tconst serialized = JSON.stringify(frame);\n\t\tif (Buffer.byteLength(serialized, \"utf8\") > RUNTIME_PROXY_DATA_HEADER_MAX_BYTES) return false;\n\t\tthis.#socket.send(serialized);\n\t\treturn true;\n\t}\n\t#handleMessage(data, isBinary) {\n\t\tif (this.#closed) return;\n\t\tif (isBinary) {\n\t\t\tthis.#handleBinaryFrame(rawDataToBuffer(data));\n\t\t\treturn;\n\t\t}\n\t\tconst frame = this.#decodeHeaderFrame(rawDataToBuffer(data));\n\t\tif (!frame) return;\n\t\tconst stream = this.#streams.get(frame.streamId);\n\t\tif (!stream) {\n\t\t\tconst tombstone = this.#tombstones.get(frame.streamId);\n\t\t\tif (!tombstone) {\n\t\t\t\tthis.#protocolViolation(\"The data connection referenced an unknown stream\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#handleTombstonedFrame(tombstone, frame);\n\t\t\treturn;\n\t\t}\n\t\tthis.#handleStreamFrame(stream, frame);\n\t}\n\t/** Strictly decode one Server header frame; protocol violations close the connection. */\n\t#decodeHeaderFrame(buffer) {\n\t\tif (buffer.byteLength > RUNTIME_PROXY_DATA_HEADER_MAX_BYTES) {\n\t\t\tthis.#protocolViolation(\"The data connection sent an oversized header frame\");\n\t\t\treturn;\n\t\t}\n\t\tlet value;\n\t\ttry {\n\t\t\tvalue = JSON.parse(buffer.toString(\"utf8\"));\n\t\t} catch {\n\t\t\tthis.#protocolViolation(\"The data connection sent an invalid header frame\");\n\t\t\treturn;\n\t\t}\n\t\tconst parsed = RuntimeProxyDataServerFrameSchema.safeParse(value);\n\t\tif (!parsed.success) {\n\t\t\tthis.#protocolViolation(\"The data connection sent an unexpected frame\");\n\t\t\treturn;\n\t\t}\n\t\tif (parsed.data.type === \"ready\") {\n\t\t\tthis.#protocolViolation(\"The data connection sent an unexpected frame\");\n\t\t\treturn;\n\t\t}\n\t\treturn parsed.data;\n\t}\n\t/**\n\t* Genuinely locally-cancelled streams may still have in-flight upstream completion frames. They\n\t* are validated against the same size/credit bounds and exactly one terminal completion; any\n\t* frame after that, or for a normally completed stream, is a protocol violation.\n\t*/\n\t#handleTombstonedFrame(tombstone, frame) {\n\t\tif (tombstone.terminal) {\n\t\t\tthis.#protocolViolation(\"The data connection sent a frame after the stream completed\");\n\t\t\treturn;\n\t\t}\n\t\tswitch (frame.type) {\n\t\t\tcase \"response\":\n\t\t\t\tif (tombstone.responded) {\n\t\t\t\t\tthis.#protocolViolation(\"The data connection repeated a stream response\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttombstone.responded = true;\n\t\t\t\treturn;\n\t\t\tcase \"credit\":\n\t\t\t\ttombstone.sendCreditAvailable += frame.bytes;\n\t\t\t\tif (tombstone.sendCreditAvailable > RUNTIME_PROXY_DATA_INITIAL_CREDIT_BYTES) {\n\t\t\t\t\tthis.#protocolViolation(\"The data connection exceeded the stream credit window\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase \"end\":\n\t\t\tcase \"cancel\":\n\t\t\tcase \"error\":\n\t\t\t\ttombstone.terminal = true;\n\t\t\t\treturn;\n\t\t}\n\t}\n\t#handleStreamFrame(stream, frame) {\n\t\tswitch (frame.type) {\n\t\t\tcase \"response\":\n\t\t\t\tif (stream.resolveOpen === void 0) {\n\t\t\t\t\tthis.#protocolViolation(\"The data connection repeated a stream response\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstream.responded = true;\n\t\t\t\tstream.resolveOpen({\n\t\t\t\t\tbody: stream.inbound,\n\t\t\t\t\tcancel: (code) => this.#cancelStream(stream, code ?? \"consumer_cancelled\"),\n\t\t\t\t\theaders: frame.headers,\n\t\t\t\t\tstatus: frame.status\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"credit\":\n\t\t\t\tstream.sendCredit.available += frame.bytes;\n\t\t\t\tif (stream.sendCredit.available > RUNTIME_PROXY_DATA_INITIAL_CREDIT_BYTES) {\n\t\t\t\t\tthis.#protocolViolation(\"The data connection exceeded the stream credit window\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfor (const waiter of stream.sendCredit.waiters.splice(0)) waiter();\n\t\t\t\tbreak;\n\t\t\tcase \"end\":\n\t\t\t\tif (stream.responseEnded) {\n\t\t\t\t\tthis.#protocolViolation(\"The data connection repeated a stream end\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstream.responseEnded = true;\n\t\t\t\tstream.inbound.end();\n\t\t\t\tthis.#completeIfDone(stream);\n\t\t\t\tbreak;\n\t\t\tcase \"cancel\":\n\t\t\t\tthis.#failStream(stream, new RuntimeProxyDataError(\"stream_error\", `The data stream was cancelled: ${frame.code ?? \"cancelled\"}`));\n\t\t\t\tbreak;\n\t\t\tcase \"error\": this.#failStream(stream, new RuntimeProxyDataError(\"stream_error\", `The data stream failed: ${frame.code}`));\n\t\t}\n\t}\n\t#handleBinaryFrame(buffer) {\n\t\tif (buffer.byteLength < 5 || buffer.byteLength > RUNTIME_PROXY_DATA_BINARY_FRAME_MAX_BYTES) {\n\t\t\tthis.#protocolViolation(\"The data connection sent a malformed binary frame\");\n\t\t\treturn;\n\t\t}\n\t\tconst streamId = buffer.readUInt32BE(0);\n\t\tconst chunk = buffer.subarray(4);\n\t\tconst stream = this.#streams.get(streamId);\n\t\tif (!stream) {\n\t\t\tconst tombstone = this.#tombstones.get(streamId);\n\t\t\tif (!tombstone) {\n\t\t\t\tthis.#protocolViolation(\"The data connection sent data for an unknown stream\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (tombstone.terminal) {\n\t\t\t\tthis.#protocolViolation(\"The data connection sent data after the stream completed\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttombstone.inboundReceived += chunk.byteLength;\n\t\t\tif (tombstone.inboundReceived > RUNTIME_PROXY_DATA_INITIAL_CREDIT_BYTES + tombstone.inboundGranted) {\n\t\t\t\tthis.#protocolViolation(\"The data connection exceeded the inbound credit window\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (stream.responseEnded) {\n\t\t\tthis.#protocolViolation(\"The data connection sent data for an unknown stream\");\n\t\t\treturn;\n\t\t}\n\t\tstream.inboundReceived += chunk.byteLength;\n\t\tif (stream.inboundReceived > RUNTIME_PROXY_DATA_INITIAL_CREDIT_BYTES + stream.inboundGranted) {\n\t\t\tthis.#protocolViolation(\"The data connection exceeded the inbound credit window\");\n\t\t\treturn;\n\t\t}\n\t\tstream.inbound.push(chunk);\n\t}\n\t#completeIfDone(stream) {\n\t\tif (stream.settled) return;\n\t\tif (!stream.requestEnded || !stream.responseEnded) return;\n\t\tstream.settled = true;\n\t\tif (stream.openTimer) {\n\t\t\tclearTimeout(stream.openTimer);\n\t\t\tstream.openTimer = void 0;\n\t\t}\n\t\tstream.inbound.end();\n\t\tthis.#streams.delete(stream.streamId);\n\t\tthis.#drainOpenQueue();\n\t}\n\t/**\n\t* Bounded tombstones so a genuinely locally-cancelled stream can absorb the upstream completion\n\t* frames already in flight without tearing down a healthy connection. Normally completed streams\n\t* get no tombstone: over ordered WebSocket delivery nothing may follow their `end`.\n\t*/\n\t#rememberTombstone(stream) {\n\t\tthis.#tombstones.set(stream.streamId, {\n\t\t\tinboundGranted: stream.inboundGranted,\n\t\t\tinboundReceived: stream.inboundReceived,\n\t\t\tresponded: stream.responded,\n\t\t\tterminal: false,\n\t\t\tsendCreditAvailable: stream.sendCredit.available\n\t\t});\n\t\twhile (this.#tombstones.size > this.#tombstoneLimit) {\n\t\t\tconst oldest = this.#tombstones.keys().next().value;\n\t\t\tif (oldest === void 0) break;\n\t\t\tthis.#tombstones.delete(oldest);\n\t\t}\n\t}\n\t#cancelStream(stream, code) {\n\t\tif (stream.settled) return;\n\t\tthis.#sendControl({\n\t\t\ttype: \"cancel\",\n\t\t\tstreamId: stream.streamId,\n\t\t\tcode\n\t\t});\n\t\tthis.#failStream(stream, new RuntimeProxyDataError(\"aborted\", `The data stream was cancelled: ${code}`), true);\n\t}\n\t#failStream(stream, error, tombstone = false) {\n\t\tif (stream.settled) return;\n\t\tstream.settled = true;\n\t\tif (stream.openTimer) {\n\t\t\tclearTimeout(stream.openTimer);\n\t\t\tstream.openTimer = void 0;\n\t\t}\n\t\tfor (const waiter of stream.sendCredit.waiters.splice(0)) waiter();\n\t\tstream.inbound.fail(error);\n\t\tthis.#streams.delete(stream.streamId);\n\t\tif (tombstone) this.#rememberTombstone(stream);\n\t\tstream.rejectOpen?.(error);\n\t\tthis.#drainOpenQueue();\n\t}\n\t#drainOpenQueue() {\n\t\twhile (!this.#closed && this.#openQueue.length > 0 && this.#streams.size < this.#maxStreams) {\n\t\t\tconst queued = this.#openQueue.shift();\n\t\t\tif (!queued) return;\n\t\t\tif (queued.request.signal?.aborted) {\n\t\t\t\tqueued.reject(new RuntimeProxyDataError(\"aborted\", \"The queued stream was aborted\"));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.#startStream(queued.request).then(queued.resolve, queued.reject);\n\t\t}\n\t}\n\t#failQueued(error) {\n\t\tfor (const queued of this.#openQueue.splice(0)) queued.reject(error);\n\t}\n\t#protocolViolation(message) {\n\t\tthis.#logger.debug({ code: \"data_protocol_violation\" }, message);\n\t\tthis.#closed = true;\n\t\tconst error = new RuntimeProxyDataError(\"protocol_error\", message);\n\t\tthis.#failQueued(error);\n\t\tfor (const stream of [...this.#streams.values()]) this.#failStream(stream, error);\n\t\tthis.#socket.close(1008, \"protocol_violation\");\n\t\tthis.#closeSocket();\n\t}\n\t#failAll(error) {\n\t\tthis.#closed = true;\n\t\tthis.#failQueued(error);\n\t\tfor (const stream of [...this.#streams.values()]) this.#failStream(stream, error);\n\t\tthis.#closeSocket();\n\t}\n};\nfunction rawDataToBuffer(data) {\n\tif (Buffer.isBuffer(data)) return data;\n\tif (Array.isArray(data)) return Buffer.concat(data);\n\treturn Buffer.from(data);\n}\n//#endregion\n//#region src/runtime/runtime-credential-relay.ts\nconst DEFAULT_CONTROL_RESULT_TIMEOUT_MS = 1e4;\nconst DEFAULT_OPEN_BUDGET_MS = 15e3;\nconst DEFAULT_NOT_READY_RETRY_MS = 250;\nconst EXPIRY_MARGIN_MS = 250;\nconst RENEW_RETRY_MS = 5e3;\nconst RENEW_JITTER_MAX_MS = 2e3;\n/** Renewal rejections that only mean the owner is momentarily unavailable. */\nconst RENEW_RETRYABLE_CODES = /* @__PURE__ */ new Set([\"owner_unavailable\"]);\n/** Controlled trusted-Relay failure. Server rejection codes stay in `serverCode`. */\nvar RuntimeCredentialRelayError = class extends Error {\n\tcode;\n\tserverCode;\n\tconstructor(code, message, serverCode) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.serverCode = serverCode;\n\t\tthis.name = \"RuntimeCredentialRelayError\";\n\t}\n};\nconst defaultScheduler = { schedule(delayMs, callback) {\n\tconst timer = setTimeout(callback, Math.max(0, delayMs));\n\ttimer.unref();\n\treturn { cancel: () => clearTimeout(timer) };\n} };\nasync function defaultRuntimeProxyDataConnectionFactory(input) {\n\tconst url = new URL(input.path, input.serverUrl);\n\turl.protocol = url.protocol === \"https:\" ? \"wss:\" : \"ws:\";\n\treturn RuntimeProxyDataConnection.connect({\n\t\texecutionId: input.executionId,\n\t\tticket: input.ticket,\n\t\turl: url.toString()\n\t});\n}\n/**\n* Trusted per-execution Relay. Holds short-lived capabilities in memory only, renews\n* them at `refreshAfter` while the Sandbox-facing local handle stays constant, and\n* injects the newest capability into every data-channel stream. A local handle is a\n* random 256-bit value stored hash-only and bound to its execution/provider; it is\n* never forwarded upstream. Connection replacement or Server revocation closes the\n* whole execution; nothing is replayed or resurrected.\n*/\nvar RuntimeCredentialRelay = class RuntimeCredentialRelay {\n\t#abort = new AbortController();\n\t#connection;\n\t#controlResultTimeoutMs;\n\t#dataFactory;\n\t#jitter;\n\t#logger;\n\t#notReadyRetryMs;\n\t#now;\n\t#openBudgetMs;\n\t#pending = /* @__PURE__ */ new Map();\n\t#providerHandles = /* @__PURE__ */ new Map();\n\t#grants = /* @__PURE__ */ new Map();\n\t#randomBytes;\n\t#scheduler;\n\t#serverUrl;\n\t#unsubscribeBusiness;\n\t#unsubscribeState;\n\t#closed = false;\n\t#data;\n\t#executionId = \"\";\n\t#providers = [];\n\t#sessionCliProof;\n\t#services = [];\n\tconstructor(options) {\n\t\tthis.#connection = options.connection;\n\t\tthis.#controlResultTimeoutMs = options.controlResultTimeoutMs ?? DEFAULT_CONTROL_RESULT_TIMEOUT_MS;\n\t\tthis.#dataFactory = options.dataConnectionFactory ?? defaultRuntimeProxyDataConnectionFactory;\n\t\tthis.#jitter = options.jitter ?? Math.random;\n\t\tthis.#logger = options.logger ?? createLogger(\"runtime-credential-relay\");\n\t\tthis.#notReadyRetryMs = options.notReadyRetryMs ?? DEFAULT_NOT_READY_RETRY_MS;\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#openBudgetMs = options.openBudgetMs ?? DEFAULT_OPEN_BUDGET_MS;\n\t\tthis.#randomBytes = options.randomBytes ?? ((bytes) => randomBytes(bytes));\n\t\tthis.#scheduler = options.scheduler ?? defaultScheduler;\n\t\tthis.#serverUrl = options.serverUrl;\n\t\tthis.#unsubscribeBusiness = this.#connection.subscribeBusinessFrames((frame) => this.#handleFrame(frame));\n\t\tthis.#unsubscribeState = this.#connection.subscribeState((state) => {\n\t\t\tif (state !== \"registered\") this.#closeInternal(\"control_connection_lost\", false).catch(() => void 0);\n\t\t});\n\t}\n\tget closed() {\n\t\treturn this.#closed;\n\t}\n\tget executionId() {\n\t\treturn this.#executionId;\n\t}\n\tget providers() {\n\t\treturn this.#providers;\n\t}\n\t/** Platform services the Server granted this execution (e.g. `web` with exact scopes). */\n\tget services() {\n\t\treturn this.#services;\n\t}\n\t/**\n\t* E8 Cloud Session CLI proof from the execution-open result, retained in memory only. The\n\t* trusted Runner forwards it to the in-sandbox worker via stdin; it is never journaled, logged,\n\t* or archived, and it is dropped with the execution.\n\t*/\n\tget sessionCliProof() {\n\t\treturn this.#sessionCliProof;\n\t}\n\t/** Fires when the execution is revoked, closed, or loses its control/data connection. */\n\tget signal() {\n\t\treturn this.#abort.signal;\n\t}\n\t/**\n\t* Open a trusted execution: bounded `execution_not_ready` retry until Server custody\n\t* accepts, acquire every granted provider, then establish the data channel with a\n\t* single-use ticket. Any failure closes the partial execution before throwing.\n\t*/\n\tstatic async open(options, subject, signal) {\n\t\tconst relay = new RuntimeCredentialRelay(options);\n\t\ttry {\n\t\t\tawait relay.#openExecution(subject, signal);\n\t\t\tawait relay.#acquireProviders(signal);\n\t\t\tawait relay.#connectData(signal);\n\t\t\treturn relay;\n\t\t} catch (error) {\n\t\t\tawait relay.#closeInternal(\"open_failed\", true).catch(() => void 0);\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/** Plaintext local handle for CLI material assembly. Never leaves the Runner boundary. */\n\tlocalHandleFor(provider) {\n\t\tconst handle = this.#providerHandles.get(provider);\n\t\tif (!handle) throw new RuntimeCredentialRelayError(\"provider_unavailable\", `Provider is not open: ${provider}`);\n\t\treturn handle.value;\n\t}\n\t/** Hash-verified handle check for the loopback entry; the entry itself binds the execution. */\n\tverifyLocalHandle(provider, candidate) {\n\t\tconst handle = this.#providerHandles.get(provider);\n\t\tif (!handle || this.#closed) return false;\n\t\tconst candidateHash = createHash(\"sha256\").update(candidate, \"utf8\").digest();\n\t\tconst recorded = Buffer.from(handle.hash, \"hex\");\n\t\treturn recorded.length === candidateHash.length && timingSafeEqual(recorded, candidateHash);\n\t}\n\t/** CLI metadata for the provider, when an open execution/grant described it. */\n\tcliMetadataFor(provider) {\n\t\tconst grant = this.#grants.get(provider);\n\t\tif (grant) return grant.cli;\n\t\treturn this.#providers.find((candidate) => candidate.provider === provider)?.cli;\n\t}\n\t/**\n\t* Open one data stream with the current capability for the provider. Expired or\n\t* missing capability fails the stream; the local handle is never attached.\n\t*/\n\topenProviderStream(request) {\n\t\tif (this.#closed) return Promise.reject(new RuntimeCredentialRelayError(\"relay_closed\", \"The execution Relay is closed\"));\n\t\tconst grant = this.#grants.get(request.provider);\n\t\tconst data = this.#data;\n\t\tif (!grant || !data || grant.dead) return Promise.reject(new RuntimeCredentialRelayError(\"provider_unavailable\", `Provider is not open: ${request.provider}`));\n\t\tif (grant.expiresAtMs - EXPIRY_MARGIN_MS <= this.#now()) return Promise.reject(new RuntimeCredentialRelayError(\"capability_expired\", `Provider capability expired and has not renewed: ${request.provider}`));\n\t\treturn data.openStream({\n\t\t\tbindingId: grant.bindingId,\n\t\t\tcapability: grant.capability,\n\t\t\tprovider: request.provider,\n\t\t\tmethod: request.method,\n\t\t\tpath: request.path,\n\t\t\theaders: request.headers,\n\t\t\t...request.body ? { body: request.body } : {},\n\t\t\t...request.signal ? { signal: request.signal } : {}\n\t\t});\n\t}\n\t/** Close/release the execution: cancel renewals, close the data channel, then release. */\n\tasync close(reason) {\n\t\tawait this.#closeInternal(reason, true);\n\t}\n\tasync #openExecution(subject, signal) {\n\t\tconst deadline = this.#now() + this.#openBudgetMs;\n\t\tfor (;;) {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tconst result = await this.#controlRequest({\n\t\t\t\ttype: \"runtime:execution:open\",\n\t\t\t\tsessionId: subject.sessionId,\n\t\t\t\tagentId: subject.agentId,\n\t\t\t\tplacementGeneration: subject.placementGeneration,\n\t\t\t\trunId: subject.runId,\n\t\t\t\tsource: subject.source,\n\t\t\t\t...subject.sandbox ? { sandbox: subject.sandbox } : {},\n\t\t\t\t...subject.services && subject.services.length > 0 ? { services: [...subject.services] } : {}\n\t\t\t}, \"runtime:execution:result\", signal);\n\t\t\tif (result.status === \"succeeded\") {\n\t\t\t\tthis.#executionId = result.executionId;\n\t\t\t\tthis.#providers = result.providers;\n\t\t\t\tthis.#services = result.services ?? [];\n\t\t\t\tthis.#sessionCliProof = result.sessionCliProof;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result.code !== \"execution_not_ready\") throw new RuntimeCredentialRelayError(\"execution_rejected\", `The Server rejected the execution open: ${result.code}`, result.code);\n\t\t\tif (this.#now() + this.#notReadyRetryMs > deadline) throw new RuntimeCredentialRelayError(\"execution_not_ready\", \"The Server did not accept execution custody within the bounded open budget\", result.code);\n\t\t\tawait this.#wait(this.#notReadyRetryMs, signal);\n\t\t}\n\t}\n\tasync #acquireProviders(signal) {\n\t\tfor (const provider of this.#providers) {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tconst grant = await this.#acquireProvider(provider, signal);\n\t\t\tthis.#grants.set(provider.provider, grant);\n\t\t\tthis.#providerHandles.set(provider.provider, this.#newLocalHandle());\n\t\t\tthis.#scheduleRenewal(provider.provider);\n\t\t}\n\t}\n\tasync #acquireProvider(provider, signal) {\n\t\tconst result = await this.#controlRequest({\n\t\t\ttype: \"runtime:credential:acquire\",\n\t\t\texecutionId: this.#executionId,\n\t\t\tprovider: provider.provider,\n\t\t\tbindingId: provider.bindingId\n\t\t}, \"runtime:credential:result\", signal);\n\t\tif (result.status === \"rejected\") throw new RuntimeCredentialRelayError(\"acquire_failed\", `The Server rejected the credential acquire for ${provider.provider}: ${result.code}`, result.code);\n\t\treturn this.#grantState(provider.provider, provider.bindingId, result);\n\t}\n\t#grantState(provider, bindingId, result) {\n\t\tif (result.executionId !== this.#executionId || result.provider !== provider) throw new RuntimeCredentialRelayError(\"acquire_failed\", \"The credential result fence does not match the execution\");\n\t\treturn {\n\t\t\tbindingId: result.bindingId || bindingId,\n\t\t\tcapability: result.opaqueToken,\n\t\t\tcli: result.cli,\n\t\t\texpiresAtMs: Date.parse(result.expiresAt),\n\t\t\tgrantId: result.grantId,\n\t\t\trefreshAfterMs: Date.parse(result.refreshAfter),\n\t\t\tdead: false\n\t\t};\n\t}\n\t#scheduleRenewal(provider) {\n\t\tconst grant = this.#grants.get(provider);\n\t\tif (!grant || this.#closed) return;\n\t\tgrant.renewTimer?.cancel();\n\t\tconst jitterMs = Math.floor(this.#jitter() * RENEW_JITTER_MAX_MS);\n\t\tconst delay = Math.max(0, grant.refreshAfterMs - this.#now()) + jitterMs;\n\t\tgrant.renewTimer = this.#scheduler.schedule(delay, () => {\n\t\t\tthis.#renewProvider(provider).catch((error) => {\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tcode: \"credential_renew_failed\",\n\t\t\t\t\terror: runtimeProxyErrorReason(error),\n\t\t\t\t\tprovider\n\t\t\t\t}, \"Credential renewal failed\");\n\t\t\t});\n\t\t});\n\t}\n\tasync #renewProvider(provider) {\n\t\tconst grant = this.#grants.get(provider);\n\t\tif (!grant || grant.dead || this.#closed) return;\n\t\ttry {\n\t\t\tconst result = await this.#controlRequest({\n\t\t\t\ttype: \"runtime:credential:renew\",\n\t\t\t\texecutionId: this.#executionId,\n\t\t\t\tgrantId: grant.grantId\n\t\t\t}, \"runtime:credential:result\");\n\t\t\tif (result.status === \"rejected\") {\n\t\t\t\tthis.#renewRejected(provider, grant, result.code);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst next = this.#grantState(provider, grant.bindingId, result);\n\t\t\tthis.#grants.set(provider, next);\n\t\t\tthis.#scheduleRenewal(provider);\n\t\t} catch (error) {\n\t\t\tif (this.#closed || grant.dead) return;\n\t\t\tif (grant.expiresAtMs - EXPIRY_MARGIN_MS > this.#now() + RENEW_RETRY_MS) {\n\t\t\t\tgrant.renewTimer?.cancel();\n\t\t\t\tgrant.renewTimer = this.#scheduler.schedule(RENEW_RETRY_MS, () => {\n\t\t\t\t\tthis.#renewProvider(provider).catch(() => void 0);\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"credential_renew_expired\",\n\t\t\t\terror: runtimeProxyErrorReason(error),\n\t\t\t\tprovider\n\t\t\t}, \"Credential renewal could not complete before expiry\");\n\t\t}\n\t}\n\t#renewRejected(provider, grant, code) {\n\t\tif (RENEW_RETRYABLE_CODES.has(code) && grant.expiresAtMs - EXPIRY_MARGIN_MS > this.#now() + RENEW_RETRY_MS) {\n\t\t\tgrant.renewTimer?.cancel();\n\t\t\tgrant.renewTimer = this.#scheduler.schedule(RENEW_RETRY_MS, () => {\n\t\t\t\tthis.#renewProvider(provider).catch(() => void 0);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tgrant.dead = true;\n\t}\n\t/**\n\t* Fetch this execution's MCP gateway bearer.\n\t*\n\t* Its own request rather than a field on the open result, matching the proxy ticket: the open\n\t* result carries authorization statements, and every secret in this protocol is fetched. The URL\n\t* is never taken from the Server — only the fixed path is checked against the constant, and the\n\t* caller composes it against the origin it already pinned.\n\t*\n\t* Returns `undefined` rather than throwing when the Server refuses. A missing gateway costs the\n\t* Agent its MCP tools; it must not cost it the turn.\n\t*/\n\tasync acquireMcpGatewayToken(signal) {\n\t\tif (!this.#services.some((service) => service.service === \"mcp\" && service.scopes.includes(\"mcp:tools\"))) return void 0;\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this.#controlRequest({\n\t\t\t\ttype: \"runtime:mcp:gateway\",\n\t\t\t\texecutionId: this.#executionId\n\t\t\t}, \"runtime:mcp:gateway:result\", signal);\n\t\t} catch (error) {\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"mcp_gateway_token_failed\",\n\t\t\t\treason: runtimeProxyErrorReason(error)\n\t\t\t}, \"The MCP gateway token request failed\");\n\t\t\treturn;\n\t\t}\n\t\tif (result.status === \"rejected\") {\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"mcp_gateway_token_rejected\",\n\t\t\t\treason: result.code\n\t\t\t}, \"The Server refused an MCP gateway token\");\n\t\t\treturn;\n\t\t}\n\t\tif (result.executionId !== this.#executionId || result.path !== MCP_GATEWAY_PATH$1) {\n\t\t\tthis.#logger.warn({ code: \"mcp_gateway_token_fence_mismatch\" }, \"The MCP gateway token fence does not match\");\n\t\t\treturn;\n\t\t}\n\t\treturn {\n\t\t\ttoken: result.token,\n\t\t\texpiresAt: result.expiresAt\n\t\t};\n\t}\n\t/**\n\t* Fetch this execution's web gateway bearer, if the Server granted the `web` service.\n\t*\n\t* The mirrored twin of {@link RuntimeCredentialRelay.acquireMcpGatewayToken}: its own request, a\n\t* fence on the exact execution. A refusal, timeout, or peer that does not implement the frame\n\t* returns `undefined`; the Cloud turn owner then fails an execution whose web grant cannot be\n\t* fulfilled. The bearer is returned to the trusted parent only; it is never written to the\n\t* worker document, the journal, or a log.\n\t*/\n\tasync acquireWebGatewayToken(signal) {\n\t\tif (!this.#services.some((service) => service.service === \"web\" && service.scopes.length > 0)) return void 0;\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this.#controlRequest({\n\t\t\t\ttype: \"runtime:web:gateway\",\n\t\t\t\texecutionId: this.#executionId\n\t\t\t}, \"runtime:web:gateway:result\", signal);\n\t\t} catch (error) {\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"web_gateway_token_failed\",\n\t\t\t\treason: runtimeProxyErrorReason(error)\n\t\t\t}, \"The web gateway token request failed\");\n\t\t\treturn;\n\t\t}\n\t\tif (result.status === \"rejected\") {\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"web_gateway_token_rejected\",\n\t\t\t\treason: result.code\n\t\t\t}, \"The Server refused a web gateway token\");\n\t\t\treturn;\n\t\t}\n\t\tif (result.executionId !== this.#executionId) {\n\t\t\tthis.#logger.warn({ code: \"web_gateway_token_fence_mismatch\" }, \"The web gateway token fence does not match\");\n\t\t\treturn;\n\t\t}\n\t\treturn {\n\t\t\ttoken: result.token,\n\t\t\texpiresAt: result.expiresAt\n\t\t};\n\t}\n\tasync #connectData(signal) {\n\t\tsignal?.throwIfAborted();\n\t\tconst result = await this.#controlRequest({\n\t\t\ttype: \"runtime:proxy:ticket\",\n\t\t\texecutionId: this.#executionId\n\t\t}, \"runtime:proxy:ticket:result\", signal);\n\t\tif (result.status === \"rejected\") throw new RuntimeCredentialRelayError(\"ticket_failed\", `The Server rejected the data ticket request: ${result.code}`, result.code);\n\t\tif (result.executionId !== this.#executionId || result.path !== RUNTIME_PROVIDER_PROXY_PATH) throw new RuntimeCredentialRelayError(\"ticket_failed\", \"The data ticket result fence does not match the execution\");\n\t\tlet data;\n\t\ttry {\n\t\t\tdata = await this.#dataFactory({\n\t\t\t\texecutionId: this.#executionId,\n\t\t\t\tpath: result.path,\n\t\t\t\tserverUrl: this.#serverUrl,\n\t\t\t\tticket: result.ticket,\n\t\t\t\t...signal ? { signal } : {}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new RuntimeCredentialRelayError(\"data_connect_failed\", `The data connection could not be established: ${runtimeProxyErrorReason(error)}`);\n\t\t}\n\t\tthis.#data = data;\n\t\tdata.settled().then(() => {\n\t\t\tif (!this.#closed) this.#closeInternal(\"data_connection_lost\", false).catch(() => void 0);\n\t\t});\n\t}\n\t#newLocalHandle() {\n\t\tconst value = `otrh_${Buffer.from(this.#randomBytes(32)).toString(\"base64url\")}`;\n\t\treturn {\n\t\t\thash: createHash(\"sha256\").update(value, \"utf8\").digest(\"hex\"),\n\t\t\tvalue\n\t\t};\n\t}\n\t#controlRequest(frame, resultType, signal, options) {\n\t\tif (this.#closed && options?.allowWhileClosed !== true) return Promise.reject(new RuntimeCredentialRelayError(\"relay_closed\", \"The execution Relay is closed\"));\n\t\tif (signal?.aborted) return Promise.reject(new RuntimeCredentialRelayError(\"aborted\", \"The control request was aborted\"));\n\t\tconst requestId = randomUUID();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tthis.#pending.delete(requestId);\n\t\t\t\ttimer.cancel();\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new RuntimeCredentialRelayError(\"aborted\", \"The control request was aborted\"));\n\t\t\t};\n\t\t\tconst timer = this.#scheduler.schedule(this.#controlResultTimeoutMs, () => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new RuntimeCredentialRelayError(\"execution_timeout\", `The control result for ${resultType} timed out`));\n\t\t\t});\n\t\t\tthis.#pending.set(requestId, {\n\t\t\t\ttimer,\n\t\t\t\treject: (error) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t\tresolve: (value) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(value);\n\t\t\t\t}\n\t\t\t});\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tthis.#connection.send({\n\t\t\t\t...frame,\n\t\t\t\trequestId\n\t\t\t}, {\n\t\t\t\tpriority: \"result\",\n\t\t\t\tsignal\n\t\t\t}).catch((error) => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new RuntimeCredentialRelayError(\"relay_closed\", `The control request could not be sent: ${runtimeProxyErrorReason(error)}`));\n\t\t\t});\n\t\t});\n\t}\n\t#handleFrame(frame) {\n\t\tconst parsed = parseRuntimeCredentialServerFrame(frame);\n\t\tif (!parsed) return;\n\t\tif (parsed.type === \"runtime:credential:revoked\") {\n\t\t\tif (parsed.executionId === this.#executionId) this.#closeInternal(`revoked:${parsed.code}`, false).catch(() => void 0);\n\t\t\treturn;\n\t\t}\n\t\tconst requestId = \"requestId\" in parsed && typeof parsed.requestId === \"string\" ? parsed.requestId : void 0;\n\t\tif (!requestId) return;\n\t\tthis.#pending.get(requestId)?.resolve(parsed);\n\t}\n\t#wait(milliseconds, signal) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst onAbort = () => {\n\t\t\t\ttimer.cancel();\n\t\t\t\treject(new RuntimeCredentialRelayError(\"aborted\", \"The wait was aborted\"));\n\t\t\t};\n\t\t\tconst timer = this.#scheduler.schedule(milliseconds, () => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t});\n\t}\n\tasync #closeInternal(reason, release) {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tthis.#sessionCliProof = void 0;\n\t\tfor (const grant of this.#grants.values()) {\n\t\t\tgrant.dead = true;\n\t\t\tgrant.renewTimer?.cancel();\n\t\t}\n\t\tfor (const [requestId, pending] of this.#pending) {\n\t\t\tthis.#pending.delete(requestId);\n\t\t\tpending.timer.cancel();\n\t\t\tpending.reject(new RuntimeCredentialRelayError(\"relay_closed\", `The execution Relay is closing: ${reason}`));\n\t\t}\n\t\tthis.#abort.abort(new RuntimeCredentialRelayError(\"relay_closed\", `The execution Relay is closing: ${reason}`));\n\t\tconst data = this.#data;\n\t\tthis.#data = void 0;\n\t\tif (data) await data.close().catch(() => void 0);\n\t\tif (release && this.#executionId) await this.#controlRequest({\n\t\t\ttype: \"runtime:execution:close\",\n\t\t\texecutionId: this.#executionId\n\t\t}, \"runtime:execution:closed\", void 0, { allowWhileClosed: true }).catch((error) => {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"execution_close_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Execution close failed\");\n\t\t});\n\t\tthis.#unsubscribeBusiness();\n\t\tthis.#unsubscribeState();\n\t}\n};\n//#endregion\n//#region src/runtime/runtime-proxy-loopback-adapter.ts\nconst execFileAsync$3 = promisify(execFile);\n/**\n* Server-issued upload/download handle path. Handles keep the provider's fixed origin and\n* never embed platform tokens; the Server revalidates every use and resolves the native\n* upstream URL only in trusted memory.\n*/\nconst RUNTIME_PROXY_HANDLE_PATH_PREFIX = \"/__opentag__/handles/\";\n/** Fixed platform CONNECT allowlist; authentication and target policy are revalidated on the Server. */\nconst RUNTIME_PROXY_ALLOWED_CONNECT_HOSTS = [\n\t\"github.com\",\n\t\"api.github.com\",\n\t\"slack.com\",\n\t\"open.feishu.cn\",\n\t\"open.larksuite.com\"\n];\nconst CONNECT_HOST_PROVIDERS = {\n\t\"github.com\": \"github\",\n\t\"api.github.com\": \"github\",\n\t\"slack.com\": \"slack\",\n\t\"open.feishu.cn\": \"feishu\",\n\t\"open.larksuite.com\": \"feishu\"\n};\nconst FEISHU_TENANT_TOKEN_PATH = \"/open-apis/auth/v3/tenant_access_token/internal\";\nconst FEISHU_TENANT_TOKEN_RESPONSE_MAX_BYTES = 262144;\n/**\n* The native Slack CLI sends its `token` in a urlencoded form body by default. Only bounded\n* urlencoded bodies are inspected; multipart and file streams are never buffered.\n*/\nconst SLACK_FORM_TOKEN_MAX_BYTES = 65536;\nconst URLENCODED_FORM_CONTENT_TYPE = \"application/x-www-form-urlencoded\";\nconst REQUEST_HEADER_ALLOWLIST = /* @__PURE__ */ new Set([\n\t\"accept\",\n\t\"accept-encoding\",\n\t\"content-length\",\n\t\"content-type\",\n\t\"git-protocol\",\n\t\"user-agent\"\n]);\nconst RESPONSE_HEADER_DENYLIST = /* @__PURE__ */ new Set([\n\t\"connection\",\n\t\"keep-alive\",\n\t\"transfer-encoding\",\n\t\"upgrade\"\n]);\nvar RuntimeProxyLoopbackError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = \"RuntimeProxyLoopbackError\";\n\t}\n};\n/**\n* Per-execution loopback TLS adapter: a CONNECT proxy for git/gh/slack/lark-cli with a fixed\n* platform host allowlist plus a direct HTTPS endpoint for the Slack `--apihost` launcher.\n* It terminates TLS with an ephemeral execution-scoped CA, challenges credential-less Git\n* requests with 401, verifies the execution-local handle, and forwards requests through the\n* trusted Relay. Platform credentials never appear here; `Authorization`, `Cookie`, and\n* `Host` are never forwarded upstream. Server-issued handle URLs stay on the provider's\n* fixed origin (`<origin>/__opentag__/handles/<id>`) and are resolved Server-side.\n*/\nvar RuntimeProxyLoopbackAdapter = class RuntimeProxyLoopbackAdapter {\n\t#ca;\n\t#connectServer;\n\t#directServer;\n\t#executionId;\n\t#localHandleFor;\n\t#logger;\n\t#openStream;\n\t#sockets = /* @__PURE__ */ new Set();\n\t#verifyHandle;\n\t#closed = false;\n\t#connectPort = 0;\n\t#directPort = 0;\n\tconstructor(options, ca) {\n\t\tthis.#ca = ca;\n\t\tthis.#executionId = options.executionId;\n\t\tthis.#localHandleFor = options.localHandleFor;\n\t\tthis.#logger = options.logger ?? createLogger(\"runtime-proxy-loopback\");\n\t\tthis.#openStream = options.openStream;\n\t\tthis.#verifyHandle = options.verifyHandle;\n\t\tthis.#connectServer = http.createServer((_request, response) => {\n\t\t\tresponse.writeHead(403, { \"content-type\": \"text/plain\" });\n\t\t\tresponse.end();\n\t\t});\n\t\tthis.#directServer = https.createServer((request, response) => {\n\t\t\tthis.#handleDirectRequest(request, response);\n\t\t});\n\t}\n\t/** Loopback HTTP CONNECT endpoint for git/gh HTTPS_PROXY and lark-cli proxy config. */\n\tget connectProxyUrl() {\n\t\treturn `http://127.0.0.1:${this.#connectPort}`;\n\t}\n\t/** Loopback HTTPS endpoint the Slack launcher pins through `--apihost`. */\n\tget slackApiHost() {\n\t\treturn `https://127.0.0.1:${this.#directPort}`;\n\t}\n\t/** Execution-scoped CA public certificate path for CLI trust configuration. */\n\tget caCertPath() {\n\t\treturn this.#ca.certPath;\n\t}\n\tget executionId() {\n\t\treturn this.#executionId;\n\t}\n\tget closed() {\n\t\treturn this.#closed;\n\t}\n\tstatic async start(options) {\n\t\tconst generateCa = options.generateCa ?? generateExecutionCa;\n\t\tawait mkdir(options.materialDir, {\n\t\t\tmode: 448,\n\t\t\trecursive: true\n\t\t});\n\t\tawait chmod(options.materialDir, 448);\n\t\tconst ca = await generateCa(options.materialDir);\n\t\tconst adapter = new RuntimeProxyLoopbackAdapter(options, ca);\n\t\tawait adapter.#listen();\n\t\treturn adapter;\n\t}\n\tasync #listen() {\n\t\tconst cert = await readFile(this.#ca.certPath, \"utf8\");\n\t\tconst key = await readFile(this.#ca.keyPath, \"utf8\");\n\t\tconst secureContext = tls.createSecureContext({\n\t\t\tcert,\n\t\t\tkey\n\t\t});\n\t\tthis.#directServer.setSecureContext?.({\n\t\t\tcert,\n\t\t\tkey\n\t\t});\n\t\tconst inner = http.createServer((request, response) => {\n\t\t\tthis.#handleInnerRequest(request, response).catch((error) => {\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tcode: \"loopback_request_failed\",\n\t\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t\t}, \"Loopback request handling failed\");\n\t\t\t\tif (!response.headersSent) response.writeHead(502, { \"content-type\": \"text/plain\" });\n\t\t\t\tresponse.end();\n\t\t\t});\n\t\t});\n\t\tthis.#connectServer.on(\"connect\", (request, socket, head) => {\n\t\t\tthis.#handleConnect(request, socket, head, inner, secureContext);\n\t\t});\n\t\tfor (const server of [this.#connectServer, this.#directServer]) {\n\t\t\tserver.on(\"connection\", (socket) => this.#track(socket));\n\t\t\tserver.on(\"secureConnection\", (socket) => this.#track(socket));\n\t\t}\n\t\tinner.on(\"connection\", (socket) => this.#track(socket));\n\t\ttry {\n\t\t\tthis.#connectPort = await listenLoopback(this.#connectServer);\n\t\t\tthis.#directPort = await listenLoopback(this.#directServer);\n\t\t} catch (error) {\n\t\t\tthis.#connectServer.close();\n\t\t\tthis.#directServer.close();\n\t\t\tthrow new RuntimeProxyLoopbackError(\"listen_failed\", `The loopback adapter could not listen: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\t/** Stop both listeners and destroy every tunneled socket. Idempotent. */\n\tasync close() {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tfor (const socket of [...this.#sockets]) socket.destroy();\n\t\tawait Promise.all([this.#connectServer, this.#directServer].map((server) => new Promise((resolve) => {\n\t\t\tserver.close(() => resolve());\n\t\t\tserver.closeAllConnections?.();\n\t\t})));\n\t}\n\t#track(socket) {\n\t\tif (this.#closed) {\n\t\t\tsocket.destroy();\n\t\t\treturn;\n\t\t}\n\t\tthis.#sockets.add(socket);\n\t\tsocket.on(\"close\", () => this.#sockets.delete(socket));\n\t}\n\t#handleConnect(request, socket, head, inner, secureContext) {\n\t\tconst target = parseConnectTarget(request.url ?? \"\");\n\t\tif (!target || !RUNTIME_PROXY_ALLOWED_CONNECT_HOSTS.includes(target.host)) {\n\t\t\tsocket.end(\"HTTP/1.1 403 Forbidden\\r\\nConnection: close\\r\\n\\r\\n\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.#closed) {\n\t\t\tsocket.destroy();\n\t\t\treturn;\n\t\t}\n\t\tsocket.write(\"HTTP/1.1 200 Connection Established\\r\\n\\r\\n\");\n\t\tif (head.length > 0) socket.unshift(head);\n\t\tconst encrypted = new tls.TLSSocket(socket, {\n\t\t\tisServer: true,\n\t\t\tsecureContext\n\t\t});\n\t\tencrypted.on(\"error\", () => encrypted.destroy());\n\t\tencrypted.__opentagConnect = {\n\t\t\thost: target.host,\n\t\t\t...CONNECT_HOST_PROVIDERS[target.host] ? { provider: CONNECT_HOST_PROVIDERS[target.host] } : {}\n\t\t};\n\t\tthis.#track(encrypted);\n\t\tinner.emit(\"connection\", encrypted);\n\t}\n\tasync #handleDirectRequest(request, response) {\n\t\ttry {\n\t\t\tconst path = originRelativePath(request.url ?? \"\");\n\t\t\tif (!path) {\n\t\t\t\treplyText(response, 400, \"bad_request\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isHandlePath(path)) {\n\t\t\t\tawait this.#handleHandleRequest(\"slack\", request, response, path, \"slack.com\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.#handleProviderRequest(\"slack\", request, response, path, \"slack.com\");\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"loopback_slack_request_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Loopback Slack request handling failed\");\n\t\t\tif (!response.headersSent) response.writeHead(502, { \"content-type\": \"text/plain\" });\n\t\t\tresponse.end();\n\t\t}\n\t}\n\tasync #handleInnerRequest(request, response) {\n\t\tconst pending = request.socket.__opentagConnect;\n\t\tif (!pending?.provider) {\n\t\t\treplyText(response, 403, \"forbidden\");\n\t\t\treturn;\n\t\t}\n\t\tconst path = originRelativePath(request.url ?? \"\");\n\t\tif (!path) {\n\t\t\treplyText(response, 400, \"bad_request\");\n\t\t\treturn;\n\t\t}\n\t\tif (isHandlePath(path)) {\n\t\t\tawait this.#handleHandleRequest(pending.provider, request, response, path, pending.host);\n\t\t\treturn;\n\t\t}\n\t\tawait this.#handleProviderRequest(pending.provider, request, response, path, pending.host);\n\t}\n\t/** Ordinary provider request: execution-local handle verification, no upstream identity. */\n\tasync #handleProviderRequest(provider, request, response, path, originHost) {\n\t\tif (provider === \"feishu\" && isFeishuTenantTokenExchange(request.method, path)) {\n\t\t\tawait this.#handleFeishuTenantToken(request, response, path, originHost);\n\t\t\treturn;\n\t\t}\n\t\tconst authorization = await authorizeProviderRequest({\n\t\t\tprovider,\n\t\t\trequest,\n\t\t\tverifyHandle: this.#verifyHandle\n\t\t});\n\t\tif (!authorization.ok) {\n\t\t\tif (authorization.challenge) {\n\t\t\t\tresponse.writeHead(401, {\n\t\t\t\t\t\"www-authenticate\": \"Basic realm=\\\"OpenTag\\\"\",\n\t\t\t\t\t\"content-type\": \"text/plain\"\n\t\t\t\t});\n\t\t\t\tresponse.end(\"authentication required\\n\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treplyText(response, authorization.status, authorization.code);\n\t\t\treturn;\n\t\t}\n\t\tif (this.#closed) {\n\t\t\treplyText(response, 503, \"adapter_closed\");\n\t\t\treturn;\n\t\t}\n\t\tawait this.#forward(provider, request, response, path, originHost, authorization.override);\n\t}\n\t/**\n\t* Server-issued handle URL: the path embeds the Server handle and the Relay revalidates it\n\t* before the Server resolves the protected native URL in memory. No local handle is needed.\n\t*/\n\tasync #handleHandleRequest(provider, request, response, path, originHost) {\n\t\tif (this.#closed) {\n\t\t\treplyText(response, 503, \"adapter_closed\");\n\t\t\treturn;\n\t\t}\n\t\tawait this.#forward(provider, request, response, path, originHost);\n\t}\n\t/**\n\t* `lark-cli` obtains a tenant token through the fixed exchange endpoint. The Server answers\n\t* locally with a harmless placeholder (never the Runner capability); this adapter replaces\n\t* that placeholder with the execution-local handle so the native CLI keeps working and no\n\t* usable token ever reaches the Sandbox.\n\t*/\n\tasync #handleFeishuTenantToken(request, response, path, originHost) {\n\t\tconst localHandle = this.#localHandleFor?.(\"feishu\");\n\t\tif (!localHandle || this.#closed) {\n\t\t\tif (this.#closed) {\n\t\t\t\treplyText(response, 503, \"adapter_closed\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.#forward(\"feishu\", request, response, path, originHost);\n\t\t\treturn;\n\t\t}\n\t\tconst abort = new AbortController();\n\t\trequest.on(\"aborted\", () => abort.abort(/* @__PURE__ */ new Error(\"request aborted\")));\n\t\tresponse.on(\"close\", () => {\n\t\t\tif (!response.writableEnded) abort.abort(/* @__PURE__ */ new Error(\"response closed\"));\n\t\t});\n\t\tlet upstream;\n\t\ttry {\n\t\t\tupstream = await this.#openStream({\n\t\t\t\tprovider: \"feishu\",\n\t\t\t\tmethod: request.method ?? \"GET\",\n\t\t\t\tpath,\n\t\t\t\theaders: forwardedRequestHeaders(\"feishu\", request.headers, originHost),\n\t\t\t\tbody: request,\n\t\t\t\tsignal: abort.signal\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"loopback_stream_open_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Loopback stream open failed\");\n\t\t\treplyText(response, 503, \"upstream_unavailable\");\n\t\t\treturn;\n\t\t}\n\t\tconst chunks = [];\n\t\tlet total = 0;\n\t\tlet tooLarge = false;\n\t\ttry {\n\t\t\tfor await (const chunk of upstream.body) {\n\t\t\t\ttotal += chunk.byteLength;\n\t\t\t\tif (total > FEISHU_TENANT_TOKEN_RESPONSE_MAX_BYTES) {\n\t\t\t\t\ttooLarge = true;\n\t\t\t\t\tupstream.cancel?.(\"response_too_large\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tchunks.push(Buffer.from(chunk));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"loopback_stream_body_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Stream body failed\");\n\t\t\tresponse.destroy();\n\t\t\treturn;\n\t\t}\n\t\tif (tooLarge) {\n\t\t\treplyText(response, 502, \"upstream_response_too_large\");\n\t\t\treturn;\n\t\t}\n\t\tconst body = substituteFeishuTenantToken(Buffer.concat(chunks).toString(\"utf8\"), localHandle);\n\t\tconst rewritten = Buffer.from(body, \"utf8\");\n\t\tresponse.writeHead(upstream.status, {\n\t\t\t...filteredResponseHeaders(upstream.headers),\n\t\t\t\"content-length\": String(rewritten.byteLength)\n\t\t});\n\t\tresponse.end(rewritten);\n\t}\n\tasync #forward(provider, request, response, path, originHost, override) {\n\t\tconst abort = new AbortController();\n\t\trequest.on(\"aborted\", () => abort.abort(/* @__PURE__ */ new Error(\"request aborted\")));\n\t\tresponse.on(\"close\", () => {\n\t\t\tif (!response.writableEnded) abort.abort(/* @__PURE__ */ new Error(\"response closed\"));\n\t\t});\n\t\tlet upstream;\n\t\ttry {\n\t\t\tupstream = await this.#openStream({\n\t\t\t\tprovider,\n\t\t\t\tmethod: request.method ?? \"GET\",\n\t\t\t\tpath,\n\t\t\t\theaders: forwardedRequestHeaders(provider, override?.headers ?? request.headers, originHost),\n\t\t\t\tbody: override?.body ?? request,\n\t\t\t\tsignal: abort.signal\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"loopback_stream_open_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Loopback stream open failed\");\n\t\t\treplyText(response, 503, \"upstream_unavailable\");\n\t\t\treturn;\n\t\t}\n\t\tconst onAbort = () => upstream.cancel?.(\"client_aborted\");\n\t\tabort.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tresponse.writeHead(upstream.status, filteredResponseHeaders(upstream.headers));\n\t\ttry {\n\t\t\tfor await (const chunk of upstream.body) {\n\t\t\t\tif (response.writableEnded) break;\n\t\t\t\tif (!response.write(chunk)) await once(response, \"drain\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"loopback_stream_body_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Stream body failed\");\n\t\t\tupstream.cancel?.(\"consumer_error\");\n\t\t\tresponse.destroy();\n\t\t\treturn;\n\t\t} finally {\n\t\t\tabort.signal.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t\tresponse.end();\n\t}\n};\n/**\n* Ephemeral per-execution CA via the platform OpenSSL CLI (the checked-in probe method).\n* The same self-signed CA cert carries every allowlisted SAN and terminates loopback\n* TLS; only Sandbox CLI subprocesses trust it, never the system store. The key is\n* untrusted Sandbox-side material: it cannot issue capabilities or platform tokens.\n*/\nasync function generateExecutionCa(materialDir) {\n\tconst keyPath = join(materialDir, \"loopback-ca-key.pem\");\n\tconst certPath = join(materialDir, \"loopback-ca.pem\");\n\tconst subjectAltName = [\n\t\t\"DNS:github.com\",\n\t\t\"DNS:api.github.com\",\n\t\t\"DNS:slack.com\",\n\t\t\"DNS:open.feishu.cn\",\n\t\t\"DNS:open.larksuite.com\",\n\t\t\"DNS:localhost\",\n\t\t\"IP:127.0.0.1\"\n\t].join(\",\");\n\ttry {\n\t\tawait execFileAsync$3(\"openssl\", [\n\t\t\t\"req\",\n\t\t\t\"-x509\",\n\t\t\t\"-newkey\",\n\t\t\t\"rsa:2048\",\n\t\t\t\"-nodes\",\n\t\t\t\"-days\",\n\t\t\t\"2\",\n\t\t\t\"-subj\",\n\t\t\t\"/CN=OpenTag execution loopback CA\",\n\t\t\t\"-addext\",\n\t\t\t`subjectAltName=${subjectAltName}`,\n\t\t\t\"-addext\",\n\t\t\t\"basicConstraints=critical,CA:TRUE\",\n\t\t\t\"-keyout\",\n\t\t\tkeyPath,\n\t\t\t\"-out\",\n\t\t\tcertPath\n\t\t], { timeout: 3e4 });\n\t} catch (error) {\n\t\tthrow new RuntimeProxyLoopbackError(\"ca_generation_failed\", `The execution loopback CA could not be generated: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\tawait chmod(keyPath, 384);\n\tawait chmod(certPath, 420);\n\treturn {\n\t\tcertPath,\n\t\tkeyPath\n\t};\n}\nfunction parseConnectTarget(url) {\n\tconst match = /^([a-z0-9.-]+):(\\d+)$/i.exec(url.trim());\n\tif (!match || match[1] === void 0 || match[2] === void 0) return void 0;\n\tconst port = Number(match[2]);\n\tif (port !== 443) return void 0;\n\treturn {\n\t\thost: match[1].toLowerCase(),\n\t\tport\n\t};\n}\nfunction originRelativePath(url) {\n\tif (!url.startsWith(\"/\") || url.startsWith(\"//\")) return void 0;\n\treturn url;\n}\nfunction isHandlePath(path) {\n\treturn path.startsWith(RUNTIME_PROXY_HANDLE_PATH_PREFIX);\n}\nfunction isFeishuTenantTokenExchange(method, path) {\n\treturn method?.toUpperCase() === \"POST\" && path.split(\"?\", 1)[0] === FEISHU_TENANT_TOKEN_PATH;\n}\n/** Replace the Server placeholder with the execution-local handle; leave other bodies intact. */\nfunction substituteFeishuTenantToken(body, localHandle) {\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(body);\n\t} catch {\n\t\treturn body;\n\t}\n\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return body;\n\tconst record = parsed;\n\tif (typeof record.tenant_access_token !== \"string\") return body;\n\trecord.tenant_access_token = localHandle;\n\treturn JSON.stringify(record);\n}\n/**\n* Local handle authorization for one provider request. Git/GitHub keep the 401 challenge flow;\n* Slack accepts the handle from `Authorization` or from the native urlencoded form `token` field,\n* rejects conflicting or duplicated credentials before any upstream work, and scrubs the form\n* field so the local handle is never forwarded. Multipart/file streams are never buffered.\n*/\nasync function authorizeProviderRequest(input) {\n\tconst { provider, request, verifyHandle } = input;\n\tconst headerHandle = extractProviderHandle(provider, headerValue$1(request.headers.authorization));\n\tconst form = provider === \"slack\" ? await inspectSlackFormToken(request) : { kind: \"none\" };\n\tif (form.kind === \"invalid\") return form.reason === \"oversized\" ? {\n\t\tok: false,\n\t\tstatus: 413,\n\t\tcode: \"payload_too_large\"\n\t} : {\n\t\tok: false,\n\t\tstatus: 403,\n\t\tcode: \"invalid_credentials\"\n\t};\n\tconst formHandle = form.kind === \"body\" ? form.token : void 0;\n\tif (headerHandle && formHandle && headerHandle !== formHandle) return {\n\t\tok: false,\n\t\tstatus: 403,\n\t\tcode: \"conflicting_credentials\"\n\t};\n\tconst handle = headerHandle ?? formHandle;\n\tif (!handle) return provider === \"feishu\" ? { ok: true } : {\n\t\tok: false,\n\t\tstatus: 401,\n\t\tcode: \"authentication_required\",\n\t\tchallenge: true\n\t};\n\tif (!verifyHandle(provider, handle)) return {\n\t\tok: false,\n\t\tstatus: 403,\n\t\tcode: \"invalid_handle\"\n\t};\n\tif (form.kind !== \"body\") return { ok: true };\n\treturn {\n\t\tok: true,\n\t\toverride: {\n\t\t\tbody: singleChunkBody(form.body),\n\t\t\theaders: headersWithContentLength(request.headers, form.body.byteLength)\n\t\t}\n\t};\n}\nasync function inspectSlackFormToken(request) {\n\tif ((request.method ?? \"\").toUpperCase() !== \"POST\") return { kind: \"none\" };\n\tif (!isUrlEncodedForm(request.headers[\"content-type\"])) return { kind: \"none\" };\n\tconst declaredLength = Number(headerValue$1(request.headers[\"content-length\"]));\n\tif (Number.isFinite(declaredLength) && declaredLength > SLACK_FORM_TOKEN_MAX_BYTES) return {\n\t\tkind: \"invalid\",\n\t\treason: \"oversized\"\n\t};\n\tlet raw;\n\ttry {\n\t\traw = await readBoundedRequestBody(request, SLACK_FORM_TOKEN_MAX_BYTES);\n\t} catch {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\treason: \"oversized\"\n\t\t};\n\t}\n\tconst params = new URLSearchParams(raw.toString(\"utf8\"));\n\tconst tokens = params.getAll(\"token\").filter((token) => token.length > 0);\n\tif (tokens.length > 1) return {\n\t\tkind: \"invalid\",\n\t\treason: \"duplicate\"\n\t};\n\tparams.delete(\"token\");\n\tconst token = tokens[0];\n\tconst body = Buffer.from(params.toString(), \"utf8\");\n\treturn token === void 0 ? {\n\t\tkind: \"body\",\n\t\tbody\n\t} : {\n\t\tkind: \"body\",\n\t\tbody,\n\t\ttoken\n\t};\n}\nfunction isUrlEncodedForm(contentType) {\n\treturn headerValue$1(contentType)?.split(\";\", 1)[0]?.trim().toLowerCase() === URLENCODED_FORM_CONTENT_TYPE;\n}\n/** Reads at most `maxBytes` and fails closed when the peer lies about or omits the length. */\nasync function readBoundedRequestBody(request, maxBytes) {\n\tconst chunks = [];\n\tlet total = 0;\n\tfor await (const chunk of request) {\n\t\tconst buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n\t\ttotal += buffer.byteLength;\n\t\tif (total > maxBytes) throw new Error(\"The bounded request body exceeds its limit\");\n\t\tchunks.push(buffer);\n\t}\n\treturn Buffer.concat(chunks);\n}\nfunction singleChunkBody(buffer) {\n\treturn { async *[Symbol.asyncIterator]() {\n\t\tyield buffer;\n\t} };\n}\nfunction headersWithContentLength(headers, length) {\n\treturn {\n\t\t...headers,\n\t\t\"content-length\": String(length)\n\t};\n}\nfunction extractProviderHandle(provider, authorization) {\n\tif (!authorization) return void 0;\n\tconst schemes = provider === \"github\" ? [\n\t\t\"Basic \",\n\t\t\"token \",\n\t\t\"bearer \"\n\t] : [\"Bearer \", \"bearer \"];\n\tfor (const scheme of schemes) if (authorization.startsWith(scheme)) return decodeHandleValue(scheme, authorization.slice(scheme.length));\n}\nfunction decodeHandleValue(scheme, value) {\n\tif (scheme !== \"Basic \") return value.trim() || void 0;\n\tconst decoded = Buffer.from(value, \"base64\").toString(\"utf8\");\n\tconst separator = decoded.indexOf(\":\");\n\treturn separator < 0 ? void 0 : decoded.slice(separator + 1) || void 0;\n}\nfunction forwardedRequestHeaders(provider, headers, originHost) {\n\tconst filtered = {};\n\tfor (const [name, value] of Object.entries(headers)) {\n\t\tif (!REQUEST_HEADER_ALLOWLIST.has(name) || value === void 0) continue;\n\t\tfiltered[name] = Array.isArray(value) ? value.join(\", \") : value;\n\t}\n\tif (provider === \"github\") filtered[RUNTIME_PROVIDER_ORIGIN_HEADER] = originHost;\n\treturn filtered;\n}\nfunction filteredResponseHeaders(headers) {\n\tconst filtered = {};\n\tfor (const [name, value] of Object.entries(headers)) {\n\t\tif (RESPONSE_HEADER_DENYLIST.has(name.toLowerCase())) continue;\n\t\tfiltered[name] = value;\n\t}\n\treturn filtered;\n}\nfunction headerValue$1(value) {\n\tif (Array.isArray(value)) return value[0];\n\treturn value;\n}\nfunction replyText(response, status, body) {\n\tif (!response.headersSent) response.writeHead(status, { \"content-type\": \"text/plain\" });\n\tresponse.end(`${body}\\n`);\n}\nasync function listenLoopback(server) {\n\tawait new Promise((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(0, \"127.0.0.1\", () => {\n\t\t\tserver.removeListener(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\tconst address = server.address();\n\tif (address === null || typeof address !== \"object\") throw new RuntimeProxyLoopbackError(\"listen_failed\", \"The loopback adapter has no bound address\");\n\treturn address.port;\n}\n//#endregion\n//#region src/runtime/im-credential-environment-manager.ts\nconst GRANT_TIMEOUT_MS = 1e4;\nconst MANAGED_CREDENTIAL_ARTIFACT = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}(?:\\.sh|\\.ps1|-lark-config|-slack-config)|\\.[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\\.tmp)$/i;\nvar ImCredentialEnvironmentError = class extends Error {\n\tcode;\n\tconstructor(code) {\n\t\tsuper(\"The provider CLI credential environment is unavailable\");\n\t\tthis.code = code;\n\t\tthis.name = \"ImCredentialEnvironmentError\";\n\t}\n};\nvar ImCredentialEnvironmentManager = class {\n\t#connection;\n\t#exchangeFeishuToken;\n\t#platform;\n\t#home;\n\t#listArtifacts;\n\t#logger;\n\t#removePath;\n\t#root;\n\t#startupCleanup;\n\t#writeEnvironmentFile;\n\t#pending = /* @__PURE__ */ new Map();\n\t#activeSessions = /* @__PURE__ */ new Set();\n\t#activeSlackConfigDirs = /* @__PURE__ */ new Map();\n\t#unsubscribe;\n\t#closed = false;\n\tconstructor(options) {\n\t\tthis.#connection = options.connection;\n\t\tthis.#exchangeFeishuToken = options.exchangeFeishuToken ?? exchangeFeishuTenantToken;\n\t\tthis.#platform = options.platform ?? process.platform;\n\t\tthis.#listArtifacts = options.listArtifacts ?? listArtifacts;\n\t\tthis.#logger = options.logger ?? createLogger(\"im-credential-environment\");\n\t\tthis.#removePath = options.removePath ?? rm;\n\t\tthis.#writeEnvironmentFile = options.writeEnvironmentFile ?? writeDurableFile;\n\t\tconst layout = resolveOpenTagHomeLayout(options.home);\n\t\tthis.#home = layout.home;\n\t\tthis.#root = join(layout.runtime, \"provider-credentials\");\n\t\tthis.#unsubscribe = this.#connection.subscribeBusinessFrames((frame) => this.#handleFrame(frame));\n\t\tthis.#startupCleanup = this.#cleanupStaleArtifacts().then(() => void 0, (error) => credentialEnvironmentError(error, void 0, \"stale_cleanup_failed\"));\n\t}\n\tpathForSession(sessionId) {\n\t\treturn this.#artifactPath(`${sessionId}${this.#platform === \"win32\" ? \".ps1\" : \".sh\"}`);\n\t}\n\tactiveSlackConfigDirForSession(sessionId) {\n\t\treturn this.#activeSlackConfigDirs.get(sessionId);\n\t}\n\tasync prepare(request, signal) {\n\t\tif (this.#closed) throw new ImCredentialEnvironmentError(\"client_shutdown\");\n\t\ttry {\n\t\t\tconst startupFailure = await this.#startupCleanup;\n\t\t\tif (startupFailure) throw startupFailure;\n\t\t\tconst result = await this.#requestGrant(request, signal);\n\t\t\tif (result.status === \"rejected\") throw new ImCredentialEnvironmentError(result.code);\n\t\t\tthis.#activeSessions.add(request.sessionId);\n\t\t\tawait ensurePrivateDirectory(this.#home, this.#root);\n\t\t\tconst path = this.pathForSession(request.sessionId);\n\t\t\tif (result.grant.provider === \"feishu\") {\n\t\t\t\tconst environment = await this.#feishuEnvironment(request.sessionId, result.grant, signal);\n\t\t\t\tawait this.#writeEnvironmentFile(path, serializeEnvironment(environment, this.#platform), 384);\n\t\t\t\treturn {\n\t\t\t\t\tpath,\n\t\t\t\t\tprovider: result.grant.provider,\n\t\t\t\t\t...result.outboxContext ? { outboxContext: result.outboxContext } : {}\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst slack = await this.#slackEnvironment(request.sessionId, result.grant);\n\t\t\tawait this.#writeEnvironmentFile(path, serializeEnvironment(slack.environment, this.#platform), 384);\n\t\t\tthis.#activeSlackConfigDirs.set(request.sessionId, slack.configDir);\n\t\t\treturn {\n\t\t\t\tpath,\n\t\t\t\tprovider: result.grant.provider,\n\t\t\t\tslackConfigDir: slack.configDir,\n\t\t\t\t...result.outboxContext ? { outboxContext: result.outboxContext } : {}\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"credential_materialization_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider credential environment materialization failed\");\n\t\t\tawait this.cleanup(request.sessionId).catch((cleanupError) => {\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tcode: \"credential_cleanup_after_failure_failed\",\n\t\t\t\t\terror: String(cleanupError)\n\t\t\t\t}, \"Provider credential cleanup after materialization failure failed\");\n\t\t\t});\n\t\t\tthrow credentialEnvironmentError(error, signal, \"credential_materialization_failed\");\n\t\t}\n\t}\n\tasync cleanup(sessionId) {\n\t\tconst slackConfigDir = this.#slackConfigDirPath(sessionId);\n\t\tthis.#activeSlackConfigDirs.delete(sessionId);\n\t\tif ((await Promise.allSettled([\n\t\t\tthis.#removePath(this.pathForSession(sessionId), { force: true }),\n\t\t\tthis.#removePath(this.#larkConfigDirPath(sessionId), {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t}),\n\t\t\tthis.#removePath(slackConfigDir, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t})\n\t\t])).some((result) => result.status === \"rejected\")) {\n\t\t\tthis.#activeSessions.add(sessionId);\n\t\t\tthis.#diagnostic(\"IM_CREDENTIAL_CLEANUP_FAILED\");\n\t\t\tthrow new ImCredentialEnvironmentError(\"cleanup_failed\");\n\t\t}\n\t\tthis.#activeSessions.delete(sessionId);\n\t}\n\tasync close() {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tthis.#unsubscribe();\n\t\tfor (const [requestId, pending] of this.#pending) {\n\t\t\tclearTimeout(pending.timer);\n\t\t\tpending.reject(new ImCredentialEnvironmentError(\"client_shutdown\"));\n\t\t\tthis.#pending.delete(requestId);\n\t\t}\n\t\tconst startupFailure = await this.#startupCleanup;\n\t\tawait Promise.all([...this.#activeSessions].map((sessionId) => this.cleanup(sessionId)));\n\t\tif (startupFailure) throw startupFailure;\n\t}\n\tasync #cleanupStaleArtifacts() {\n\t\tlet artifacts;\n\t\ttry {\n\t\t\tartifacts = await this.#listArtifacts(this.#root);\n\t\t} catch (error) {\n\t\t\tthis.#diagnostic(\"IM_CREDENTIAL_STALE_SCAN_FAILED\");\n\t\t\tthrow credentialEnvironmentError(error, void 0, \"stale_cleanup_failed\");\n\t\t}\n\t\tif ((await Promise.allSettled(artifacts.filter((name) => MANAGED_CREDENTIAL_ARTIFACT.test(name)).map((name) => this.#removePath(join(this.#root, name), {\n\t\t\tforce: true,\n\t\t\t...name.endsWith(\"-lark-config\") || name.endsWith(\"-slack-config\") ? { recursive: true } : {}\n\t\t})))).some((result) => result.status === \"rejected\")) {\n\t\t\tthis.#diagnostic(\"IM_CREDENTIAL_STALE_CLEANUP_FAILED\");\n\t\t\tthrow new ImCredentialEnvironmentError(\"stale_cleanup_failed\");\n\t\t}\n\t}\n\t#diagnostic(code) {\n\t\tthis.#logger.warn({ code }, \"Provider credential environment cleanup failed\");\n\t}\n\tasync #slackEnvironment(sessionId, grant) {\n\t\tconst configDir = await ensurePrivateDirectory(this.#root, this.#slackConfigDirPath(sessionId));\n\t\treturn {\n\t\t\tconfigDir,\n\t\t\tenvironment: {\n\t\t\t\tSLACK_BOT_TOKEN: grant.botAccessToken,\n\t\t\t\tSLACK_USER_TOKEN: void 0,\n\t\t\t\tSLACK_APP_TOKEN: void 0,\n\t\t\t\tOPENTAG_SLACK_CONFIG_DIR: configDir,\n\t\t\t\tSLACK_CONFIG_DIR: configDir\n\t\t\t}\n\t\t};\n\t}\n\t#slackConfigDirPath(sessionId) {\n\t\treturn this.#artifactPath(`${sessionId}-slack-config`);\n\t}\n\t#larkConfigDirPath(sessionId) {\n\t\treturn this.#artifactPath(`${sessionId}-lark-config`);\n\t}\n\t#artifactPath(name) {\n\t\tconst path = join(this.#root, name);\n\t\tassertWithin(this.#root, path);\n\t\treturn path;\n\t}\n\tasync #feishuEnvironment(sessionId, grant, signal) {\n\t\tconst configDir = this.#larkConfigDirPath(sessionId);\n\t\tawait ensurePrivateDirectory(this.#root, configDir);\n\t\tconst tenantAccessToken = await this.#exchangeFeishuToken(grant, signal);\n\t\treturn {\n\t\t\tLARKSUITE_CLI_APP_ID: grant.appId,\n\t\t\tLARKSUITE_CLI_APP_SECRET: grant.appSecret,\n\t\t\tLARKSUITE_CLI_CONFIG_DIR: configDir,\n\t\t\tLARKSUITE_CLI_BRAND: grant.teamBrand,\n\t\t\tLARKSUITE_CLI_TENANT_ACCESS_TOKEN: tenantAccessToken,\n\t\t\tLARKSUITE_CLI_USER_ACCESS_TOKEN: void 0\n\t\t};\n\t}\n\t#requestGrant(request, signal) {\n\t\tif (signal?.aborted) return Promise.reject(new ImCredentialEnvironmentError(\"aborted\"));\n\t\tconst requestId = randomUUID();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tconst pending = this.#pending.get(requestId);\n\t\t\t\tif (pending) clearTimeout(pending.timer);\n\t\t\t\tthis.#pending.delete(requestId);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new ImCredentialEnvironmentError(\"aborted\"));\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new ImCredentialEnvironmentError(\"timeout\"));\n\t\t\t}, GRANT_TIMEOUT_MS);\n\t\t\ttimer.unref();\n\t\t\tthis.#pending.set(requestId, {\n\t\t\t\ttimer,\n\t\t\t\tresolve: (result) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(result);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tthis.#connection.send({\n\t\t\t\ttype: \"im:credential\",\n\t\t\t\trequestId,\n\t\t\t\tsessionId: request.sessionId,\n\t\t\t\tagentId: request.agentId,\n\t\t\t\tplacementGeneration: request.placementGeneration\n\t\t\t}, {\n\t\t\t\tpriority: \"result\",\n\t\t\t\tsignal\n\t\t\t}).catch((error) => {\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tcode: \"credential_result_send_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Provider credential result send failed\");\n\t\t\t\tcleanup();\n\t\t\t\treject(error instanceof Error ? error : new ImCredentialEnvironmentError(\"send_failed\"));\n\t\t\t});\n\t\t});\n\t}\n\t#handleFrame(frame) {\n\t\tif (frame.type !== \"im:credential:result\") return;\n\t\tconst result = frame;\n\t\tthis.#pending.get(result.requestId)?.resolve(result);\n\t}\n};\nasync function listArtifacts(root) {\n\ttry {\n\t\treturn await readdir(root);\n\t} catch (error) {\n\t\tif (isFileSystemError(error, \"ENOENT\")) return [];\n\t\tthrow error;\n\t}\n}\nfunction isFileSystemError(error, code) {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === code;\n}\nfunction credentialEnvironmentError(error, signal, fallbackCode) {\n\tif (error instanceof ImCredentialEnvironmentError) return error;\n\treturn new ImCredentialEnvironmentError(signal?.aborted ? \"aborted\" : fallbackCode);\n}\nasync function exchangeFeishuTenantToken(grant, signal) {\n\tconst origin = grant.teamBrand === \"lark\" ? \"https://open.larksuite.com\" : \"https://open.feishu.cn\";\n\tconst response = await fetch(`${origin}/open-apis/auth/v3/tenant_access_token/internal`, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"content-type\": \"application/json\" },\n\t\tbody: JSON.stringify({\n\t\t\tapp_id: grant.appId,\n\t\t\tapp_secret: grant.appSecret\n\t\t}),\n\t\tsignal\n\t});\n\tconst body = await response.json();\n\tif (!response.ok || body.code !== 0 || typeof body.tenant_access_token !== \"string\") throw new ImCredentialEnvironmentError(\"feishu_token_exchange_failed\");\n\treturn body.tenant_access_token;\n}\nfunction serializeEnvironment(environment, platform) {\n\tconst entries = Object.entries(environment);\n\tif (platform === \"win32\") return `${entries.map(([key, value]) => value === void 0 ? `Remove-Item Env:${key} -ErrorAction SilentlyContinue` : `$env:${key} = '${value.replaceAll(\"'\", \"''\")}'`).join(\"\\n\")}\\n`;\n\treturn `${entries.map(([key, value]) => value === void 0 ? `unset ${key}` : `export ${key}='${value.replaceAll(\"'\", \"'\\\"'\\\"'\")}'`).join(\"\\n\")}\\n`;\n}\n//#endregion\n//#region src/runtime/runtime-proxy-material.ts\nconst RUNTIME_PROXY_SHIM_MARKER = \"# opentag-runtime-proxy-shim: v1\";\nconst RUNTIME_PROXY_GIT_HELPER_MARKER = \"# opentag-runtime-proxy-git-helper: v1\";\nconst RUNTIME_PROXY_LAUNCHER_MARKER = \"# opentag-runtime-proxy-launcher: v1\";\nconst EXECUTION_MARKER_PREFIX = \"# opentag-execution: \";\nconst MANAGED_SESSION_DIR = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n/**\n* Execution-scoped routing inputs published to the Agent. They are deliberately not standard\n* tool variables: only the provider launchers translate them into the proxy/CA variables their\n* own CLI process needs, so the Agent's ordinary subprocesses keep public routing and the system\n* trust store. Neither value is a credential.\n*/\nconst RUNTIME_PROXY_PROVIDER_URL_KEY = \"OPENTAG_PROVIDER_PROXY_URL\";\nconst RUNTIME_PROXY_PROVIDER_CA_KEY = \"OPENTAG_PROVIDER_CA_PATH\";\n/** Parse the non-secret outbox context returned for an IM provider, when present. */\nfunction runtimeProxyOutboxContext(cli) {\n\tif (!cli || !(\"outboxContext\" in cli)) return void 0;\n\tconst outbox = cli.outboxContext;\n\tif (!outbox || typeof outbox !== \"object\") return void 0;\n\treturn outbox;\n}\n/** Loopback endpoints never go through the CONNECT proxy (Slack `--apihost`). */\nconst LOCAL_PROXY_BYPASS = \"127.0.0.1,localhost\";\n/**\n* Build the CLI environment for one execution. Sandbox-visible values only: the local\n* handle, loopback addresses, the public CA path, and non-secret CLI metadata. No\n* capability, platform token, App Secret, Bot Token, or machine token. No `GH_REPO`:\n* GitHub target resolution stays with cwd, `-R`, and the canonical remote path.\n*/\nfunction buildRuntimeProxyEnvironment(input) {\n\tconst environment = {\n\t\tOPENTAG_GITHUB_REPOSITORIES: void 0,\n\t\tGH_ENTERPRISE_TOKEN: void 0,\n\t\tGITHUB_ENTERPRISE_TOKEN: void 0,\n\t\tGITHUB_TOKEN: void 0,\n\t\tGIT_SSH: void 0,\n\t\tGIT_SSH_COMMAND: void 0,\n\t\tSSH_AGENT_PID: void 0,\n\t\tSSH_AUTH_SOCK: void 0\n\t};\n\tconst github = input.handles.get(\"github\");\n\tif (github !== void 0) {\n\t\tconst cli = input.cliMetadata(\"github\");\n\t\tconst repositories = cli?.provider === \"github\" ? cli.repositories : [];\n\t\tObject.assign(environment, {\n\t\t\tGH_TOKEN: github,\n\t\t\tOPENTAG_GITHUB_REPOSITORIES: JSON.stringify(repositories),\n\t\t\tGH_PROMPT_DISABLED: \"1\",\n\t\t\tGIT_CONFIG_COUNT: \"2\",\n\t\t\tGIT_CONFIG_KEY_0: \"credential.helper\",\n\t\t\tGIT_CONFIG_VALUE_0: \"\",\n\t\t\tGIT_CONFIG_KEY_1: \"credential.helper\",\n\t\t\tGIT_CONFIG_VALUE_1: `!sh '${input.layout.gitCredentialHelperPath}'`,\n\t\t\tGIT_CONFIG_GLOBAL: input.layout.gitConfigPath,\n\t\t\tGIT_CONFIG_NOSYSTEM: \"1\",\n\t\t\tGIT_TERMINAL_PROMPT: \"0\"\n\t\t});\n\t}\n\tconst feishu = input.handles.get(\"feishu\");\n\tif (feishu !== void 0) {\n\t\tconst cli = input.cliMetadata(\"feishu\");\n\t\tconst feishuCli = cli?.provider === \"feishu\" ? cli : void 0;\n\t\tObject.assign(environment, {\n\t\t\tLARKSUITE_CLI_APP_ID: feishuCli?.appId ?? \"\",\n\t\t\tLARKSUITE_CLI_APP_SECRET: void 0,\n\t\t\tLARKSUITE_CLI_BRAND: feishuCli?.teamBrand ?? \"feishu\",\n\t\t\tLARKSUITE_CLI_CA_PATH: input.adapterCaCertPath,\n\t\t\tLARKSUITE_CLI_CONFIG_DIR: input.layout.larkConfigDir,\n\t\t\tLARKSUITE_CLI_DEFAULT_AS: \"bot\",\n\t\t\tLARKSUITE_CLI_PROXY_ADDRESS: input.connectProxyUrl,\n\t\t\tLARKSUITE_CLI_PROXY_ENABLE: \"1\",\n\t\t\tLARKSUITE_CLI_STRICT_MODE: \"bot\",\n\t\t\tLARKSUITE_CLI_TENANT_ACCESS_TOKEN: feishu,\n\t\t\tLARKSUITE_CLI_USER_ACCESS_TOKEN: void 0\n\t\t});\n\t}\n\tconst slack = input.handles.get(\"slack\");\n\tif (slack !== void 0) Object.assign(environment, {\n\t\tOPENTAG_SLACK_CONFIG_DIR: input.layout.slackConfigDir,\n\t\tSLACK_APP_TOKEN: void 0,\n\t\tSLACK_BOT_TOKEN: slack,\n\t\tSLACK_CONFIG_DIR: input.layout.slackConfigDir,\n\t\tSLACK_USER_TOKEN: void 0\n\t});\n\tif (github !== void 0 || slack !== void 0) Object.assign(environment, {\n\t\t[RUNTIME_PROXY_PROVIDER_URL_KEY]: input.connectProxyUrl,\n\t\t[RUNTIME_PROXY_PROVIDER_CA_KEY]: input.adapterCaCertPath\n\t});\n\treturn environment;\n}\n/**\n* Translate the scoped routing inputs into the standard variables provider CLIs and\n* explicitly-sourced provider shells honor. Apply this only at a provider use site: the Agent\n* runtime's own environment must never carry a global proxy or a private CA.\n*/\nfunction providerRoutingEnvironment(environment) {\n\tconst proxyUrl = environment[RUNTIME_PROXY_PROVIDER_URL_KEY];\n\tconst caPath = environment[RUNTIME_PROXY_PROVIDER_CA_KEY];\n\tif (!proxyUrl || !caPath) return {};\n\treturn {\n\t\tCURL_CA_BUNDLE: caPath,\n\t\tHTTPS_PROXY: proxyUrl,\n\t\tNO_PROXY: LOCAL_PROXY_BYPASS,\n\t\tSSL_CERT_FILE: caPath,\n\t\thttps_proxy: proxyUrl,\n\t\tno_proxy: LOCAL_PROXY_BYPASS\n\t};\n}\n/**\n* The execution Git configuration referenced through `GIT_CONFIG_GLOBAL`. The empty general\n* `http.proxy` disables every ambient proxy variable for Git, so only the explicit github.com\n* entry is routed through the credential proxy; other hosts (for example a public GitLab clone)\n* connect directly and keep the system CA.\n*/\nfunction renderRuntimeProxyGitConfig(input) {\n\treturn `[http]\n\\tproxy = ${quoteGitConfigValue(\"\")}\n[http \"https://github.com\"]\n\\tproxy = ${quoteGitConfigValue(input.connectProxyUrl)}\n\\tsslCAInfo = ${quoteGitConfigValue(input.caCertPath)}\n`;\n}\nfunction quoteGitConfigValue(value) {\n\treturn /[\\s#\"';]/.test(value) ? `\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"\\\"\", \"\\\\\\\"\")}\"` : value;\n}\nfunction renderRuntimeProxyGitCredentialHelper(handle) {\n\treturn `#!/bin/sh\n${RUNTIME_PROXY_GIT_HELPER_MARKER}\n# OpenTag execution-local Git credential helper; do not edit.\naction=\"$1\"\n[ \"$action\" = \"get\" ] || exit 0\nhost=\"\"\nprotocol=\"\"\nwhile IFS= read -r line; do\n  case \"$line\" in\n    host=*) host=\\${line#host=} ;;\n    protocol=*) protocol=\\${line#protocol=} ;;\n  esac\n  [ -n \"$host\" ] && [ -n \"$protocol\" ] && break\ndone\nif [ \"$host\" = \"github.com\" ] && [ \"$protocol\" = \"https\" ]; then\n  printf 'username=x-access-token\\\\npassword=%s\\\\n' '${handle.replaceAll(\"'\", \"'\\\"'\\\"'\")}'\nfi\nexit 0\n`;\n}\nfunction renderRuntimeProxyShim(binary, environmentFilePath) {\n\treturn `#!/bin/sh\n${RUNTIME_PROXY_SHIM_MARKER} binary=${binary}\n# OpenTag execution-local shim: load the current proxy environment, then exec the real\n# binary with unchanged argv, cwd, stdin, stdout, stderr, signals, and exit status.\nself_dir=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)\nreal_binary=\"\"\nold_ifs=$IFS\nIFS=:\nfor path_dir in $PATH; do\n  [ \"$path_dir\" = \"$self_dir\" ] && continue\n  if [ -x \"$path_dir/${binary}\" ]; then\n    real_binary=\"$path_dir/${binary}\"\n    break\n  fi\ndone\nIFS=$old_ifs\nif [ -z \"$real_binary\" ]; then\n  echo \"opentag: ${binary} is unavailable on PATH\" >&2\n  exit 127\nfi\nif [ ! -r '${environmentFilePath.replaceAll(\"'\", \"'\\\"'\\\"'\")}' ]; then\n  echo \"opentag: the provider proxy environment is unavailable\" >&2\n  exit 1\nfi\n. '${environmentFilePath.replaceAll(\"'\", \"'\\\"'\\\"'\")}'\nexec \"$real_binary\" \"$@\"\n`;\n}\n/**\n* Shell lines that scope the credential proxy and its execution CA to the process that sources\n* them. They never change the caller's environment and are a no-op without both scoped inputs.\n*/\nfunction renderRuntimeProxyScopePreamble() {\n\treturn `if [ -n \"$OPENTAG_PROVIDER_PROXY_URL\" ] && [ -n \"$OPENTAG_PROVIDER_CA_PATH\" ]; then\n  HTTPS_PROXY=$OPENTAG_PROVIDER_PROXY_URL\n  https_proxy=$OPENTAG_PROVIDER_PROXY_URL\n  NO_PROXY=127.0.0.1,localhost\n  no_proxy=127.0.0.1,localhost\n  SSL_CERT_FILE=$OPENTAG_PROVIDER_CA_PATH\n  CURL_CA_BUNDLE=$OPENTAG_PROVIDER_CA_PATH\n  export HTTPS_PROXY https_proxy NO_PROXY no_proxy SSL_CERT_FILE CURL_CA_BUNDLE\nfi`;\n}\n/**\n* Sandbox-facing provider launcher: it resolves the real binary on PATH and scopes the credential\n* proxy plus its execution CA to exactly this CLI process. The Agent runtime environment itself\n* keeps public routing and the system trust store; only CLI invocations that need a platform\n* provider come through here (or through the pinned Slack launcher that also carries the scope).\n*/\nfunction renderRuntimeProxyProviderLauncher(binary) {\n\treturn `#!/bin/sh\n${RUNTIME_PROXY_LAUNCHER_MARKER} binary=${binary}\n# OpenTag execution-local provider launcher: scope the credential proxy and CA to this process,\n# then exec the real binary with unchanged argv, cwd, stdin, stdout, stderr, signals, and status.\nself_dir=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)\nreal_binary=\"\"\nold_ifs=$IFS\nIFS=:\nfor path_dir in $PATH; do\n  [ \"$path_dir\" = \"$self_dir\" ] && continue\n  if [ -x \"$path_dir/${binary}\" ]; then\n    real_binary=\"$path_dir/${binary}\"\n    break\n  fi\ndone\nIFS=$old_ifs\nif [ -z \"$real_binary\" ]; then\n  echo \"opentag: ${binary} is unavailable on PATH\" >&2\n  exit 127\nfi\n${renderRuntimeProxyScopePreamble()}\nexec \"$real_binary\" \"$@\"\n`;\n}\n/**\n* Per-Session proxy material store. The stable env file/manifest/shims point at the\n* current execution; every rotating secret-bearing artifact lives under\n* `executions/<executionId>/` so a stale cleanup cannot delete successor material.\n*/\nvar RuntimeProxyMaterialStore = class {\n\t#home;\n\t#root;\n\tconstructor(options) {\n\t\tconst layout = resolveOpenTagHomeLayout(options.home);\n\t\tthis.#home = layout.home;\n\t\tthis.#root = join(layout.runtime, \"provider-proxy\");\n\t}\n\tget root() {\n\t\treturn this.#root;\n\t}\n\tsessionDir(sessionId) {\n\t\treturn this.#within(this.#root, sessionId);\n\t}\n\t/** Stable per-Session env file path wired to `OPENTAG_PROVIDER_ENV_FILE`. */\n\tenvironmentFilePath(sessionId) {\n\t\treturn join(this.sessionDir(sessionId), \"current.sh\");\n\t}\n\tmanifestPath(sessionId) {\n\t\treturn join(this.sessionDir(sessionId), \"current.json\");\n\t}\n\tshimDir(sessionId) {\n\t\treturn join(this.sessionDir(sessionId), \"bin\");\n\t}\n\texecutionLayout(sessionId, executionId) {\n\t\tconst executionDir = this.#within(this.sessionDir(sessionId), \"executions\", executionId);\n\t\treturn {\n\t\t\tadapterCaCertPath: join(executionDir, \"loopback-ca.pem\"),\n\t\t\texecutionDir,\n\t\t\tgitConfigPath: join(executionDir, \"gitconfig\"),\n\t\t\tgitCredentialHelperPath: join(executionDir, \"git-credential-helper.sh\"),\n\t\t\tlarkConfigDir: join(executionDir, \"lark-config\"),\n\t\t\tslackConfigDir: join(executionDir, \"slack-config\")\n\t\t};\n\t}\n\t/**\n\t* Publish one execution's material atomically: per-execution artifacts first, then\n\t* the stable env file and manifest, then the git/gh shims.\n\t*/\n\tasync publish(input) {\n\t\tconst layout = this.executionLayout(input.sessionId, input.executionId);\n\t\tawait ensurePrivateDirectory(this.#home, layout.executionDir);\n\t\tawait mkdir(layout.larkConfigDir, {\n\t\t\tmode: 448,\n\t\t\trecursive: true\n\t\t});\n\t\tawait mkdir(layout.slackConfigDir, {\n\t\t\tmode: 448,\n\t\t\trecursive: true\n\t\t});\n\t\tconst github = input.handles.get(\"github\");\n\t\tconst routing = providerRoutingEnvironment(input.environment);\n\t\tif (github !== void 0) {\n\t\t\tif (routing.HTTPS_PROXY !== void 0 && routing.SSL_CERT_FILE !== void 0) await writeDurableFile(layout.gitConfigPath, renderRuntimeProxyGitConfig({\n\t\t\t\tcaCertPath: routing.SSL_CERT_FILE,\n\t\t\t\tconnectProxyUrl: routing.HTTPS_PROXY\n\t\t\t}), 384);\n\t\t\telse await writeDurableFile(layout.gitConfigPath, \"\", 384);\n\t\t\tawait writeDurableFile(layout.gitCredentialHelperPath, renderRuntimeProxyGitCredentialHelper(github), 448);\n\t\t\tawait chmod(layout.gitCredentialHelperPath, 448);\n\t\t}\n\t\tconst serialized = serializeEnvironment({\n\t\t\t...input.environment,\n\t\t\t...routing\n\t\t}, input.platform);\n\t\tconst marked = `${EXECUTION_MARKER_PREFIX}${input.executionId}\\n${serialized}`;\n\t\tawait writeDurableFile(this.environmentFilePath(input.sessionId), marked, 384);\n\t\tconst manifestEnvironment = Object.fromEntries(Object.entries(input.environment).map(([key, value]) => [key, value ?? null]));\n\t\tawait writeDurableFile(this.manifestPath(input.sessionId), `${JSON.stringify({\n\t\t\tschemaVersion: 1,\n\t\t\texecutionId: input.executionId,\n\t\t\tenvironment: manifestEnvironment\n\t\t}, void 0, 2)}\\n`, 384);\n\t\tconst shimDir = this.shimDir(input.sessionId);\n\t\tawait ensurePrivateDirectory(this.#home, shimDir);\n\t\tconst environmentFilePath = this.environmentFilePath(input.sessionId);\n\t\tfor (const binary of [\"git\", \"gh\"]) {\n\t\t\tconst shimPath = join(shimDir, binary);\n\t\t\tawait writeDurableFile(shimPath, renderRuntimeProxyShim(binary, environmentFilePath), 448);\n\t\t\tawait chmod(shimPath, 448);\n\t\t}\n\t\treturn layout;\n\t}\n\t/** Execution marker recorded in the stable env file; undefined when absent/foreign. */\n\tasync publishedExecution(sessionId) {\n\t\tlet content;\n\t\ttry {\n\t\t\tcontent = await readFile(this.environmentFilePath(sessionId), \"utf8\");\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return void 0;\n\t\t\tthrow error;\n\t\t}\n\t\tconst firstLine = content.split(\"\\n\", 1)[0] ?? \"\";\n\t\treturn firstLine.startsWith(EXECUTION_MARKER_PREFIX) ? firstLine.slice(21) : void 0;\n\t}\n\t/**\n\t* Exact-execution cleanup: remove the execution directory; remove the stable env\n\t* file and manifest only while they still belong to this execution.\n\t*/\n\tasync cleanupExecution(sessionId, executionId) {\n\t\tawait rm(this.executionLayout(sessionId, executionId).executionDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t\tif (await this.publishedExecution(sessionId).catch(() => void 0) !== executionId) return;\n\t\tawait rm(this.environmentFilePath(sessionId), { force: true });\n\t\tawait rm(this.manifestPath(sessionId), { force: true });\n\t}\n\t/** Remove every proxy artifact for the Session (Session stop / shutdown). */\n\tasync cleanupSession(sessionId) {\n\t\tawait rm(this.sessionDir(sessionId), {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n\t/** Startup sweep: remove every managed Session directory left by a previous run. */\n\tasync cleanupStale() {\n\t\tlet entries;\n\t\ttry {\n\t\t\tentries = await readdir(this.#root);\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return;\n\t\t\tthrow error;\n\t\t}\n\t\tawait Promise.all(entries.filter((entry) => MANAGED_SESSION_DIR.test(entry)).map((entry) => rm(join(this.#root, entry), {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t})));\n\t}\n\t#within(root, ...segments) {\n\t\tconst path = join(root, ...segments);\n\t\tassertWithin(this.#root, path);\n\t\treturn path;\n\t}\n};\n//#endregion\n//#region src/cloud-runtime/sandbox-entry.ts\n/** Trusted mount point for the read-only, per-execution public material directory. */\nconst CLOUD_EXECUTION_MOUNT = \"/run/opentag-execution\";\n/** Loopback CONNECT proxy the Sandbox CLI subprocesses use inside the container. */\nconst CLOUD_CONNECT_PROXY_PORT = 18080;\n/** Loopback HTTPS endpoint the Slack launcher pins through `--apihost` inside the container. */\nconst CLOUD_SLACK_API_PORT = 18443;\n/** Public CA certificate file name inside the read-only per-execution mount. */\nconst CLOUD_SANDBOX_CA_FILE = \"ca.pem\";\n/**\n* Sandbox-owned CA copy location. The mounted public CA is root-owned, and native CLIs such as\n* `lark-cli` refuse a CA that is not owned by the current Sandbox uid, so the entry program copies\n* the public certificate into its own 0700 tmpfs home as a 0600 file and rewrites every CA\n* environment path to that copy. Only the public certificate is copied; the CA private key never\n* leaves the trusted Runner.\n*/\nconst CLOUD_SANDBOX_CA_DESTINATION = \"/home/runner/.opentag/ca.pem\";\n/** Environment variables that may point at the mounted CA and must follow the Sandbox copy. */\nconst CLOUD_SANDBOX_CA_ENVIRONMENT_KEYS = [\n\t\"CURL_CA_BUNDLE\",\n\t\"GIT_SSL_CAINFO\",\n\t\"LARKSUITE_CLI_CA_PATH\",\n\t\"NODE_EXTRA_CA_CERTS\",\n\t\"OPENTAG_PROVIDER_CA_PATH\",\n\t\"SSL_CERT_FILE\"\n];\n/**\n* Generated ESM helper published next to `entry.mjs`. It runs as the Sandbox uid, so the copy is\n* owned by that uid and accepted by native CLIs; the read-only public mount is never mutated.\n*/\nconst CLOUD_SANDBOX_CA_PROGRAM = `\nimport {chmodSync, mkdirSync, readFileSync, writeFileSync} from 'node:fs';\nimport {dirname} from 'node:path';\nexport const SANDBOX_CA_ENVIRONMENT_KEYS=${JSON.stringify(CLOUD_SANDBOX_CA_ENVIRONMENT_KEYS)};\nexport function prepareSandboxCa({destination, environment, mount}) {\n  const source = mount + '/${CLOUD_SANDBOX_CA_FILE}';\n  const directory = dirname(destination);\n  mkdirSync(directory, {recursive: true, mode: 0o700});\n  chmodSync(directory, 0o700);\n  // Flag 'wx' never follows a pre-existing path, and the explicit chmod fixes the mode under any umask.\n  writeFileSync(destination, readFileSync(source), {flag: 'wx', mode: 0o600});\n  chmodSync(destination, 0o600);\n  const rewritten = {...environment};\n  for (const key of SANDBOX_CA_ENVIRONMENT_KEYS) {\n    if (rewritten[key] === source) rewritten[key] = destination;\n  }\n  return {destination, environment: rewritten};\n}\n`;\n/**\n* This program runs inside the untrusted container. It receives only local handles and public\n* CA material, forwards the two loopback endpoints to the per-execution Unix sockets mounted\n* from the trusted Runner, and executes exactly one native command with inherited stdio.\n*/\nconst CLOUD_SANDBOX_ENTRY_PROGRAM = `\nimport {createServer, connect} from 'node:net';\nimport {readFileSync, mkdirSync} from 'node:fs';\nimport {spawn} from 'node:child_process';\nimport {prepareSandboxCa} from './sandbox-ca.mjs';\nconst root='${CLOUD_EXECUTION_MOUNT}';\nconst manifest=JSON.parse(readFileSync(root+'/environment.json','utf8'));\nconst sockets=new Set();\nconst servers=[];\nfor(const [name,port] of [['connect',${CLOUD_CONNECT_PROXY_PORT}],['slack',${CLOUD_SLACK_API_PORT}]]) {\n  const server=createServer(client=>{\n    const upstream=connect(root+'/'+name+'.sock');\n    sockets.add(client);sockets.add(upstream);\n    const close=()=>{client.destroy();upstream.destroy();sockets.delete(client);sockets.delete(upstream);};\n    client.on('error',close);upstream.on('error',close);client.on('close',close);upstream.on('close',close);\n    client.pipe(upstream);upstream.pipe(client);\n  });\n  await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});\n  servers.push(server);\n}\nmkdirSync('/tmp/opentag/lark',{recursive:true,mode:0o700});\nmkdirSync('/tmp/opentag/slack',{recursive:true,mode:0o700});\nconst base={PATH:'${CLOUD_EXECUTION_MOUNT}/bin:/usr/local/bin:/opt/opentag/tools/bin:/usr/bin:/bin',HOME:'/home/runner',TMPDIR:'/tmp',LANG:'C.UTF-8',...manifest.environment};\nconst environment=prepareSandboxCa({destination:'${CLOUD_SANDBOX_CA_DESTINATION}',environment:base,mount:root}).environment;\nconst [command,...args]=process.argv.slice(2);\nif(!command)throw Error('A sandbox command is required');\nconst child=spawn(command,args,{env:environment,stdio:'inherit'});\nfor(const signal of ['SIGTERM','SIGINT']) process.on(signal,()=>child.kill(signal));\nconst code=await new Promise(resolve=>{child.once('error',()=>resolve(127));child.once('exit',code=>resolve(code??1));});\nfor(const socket of sockets)socket.destroy();\nfor(const server of servers)await new Promise(resolve=>server.close(resolve));\nprocess.exitCode=code;\n`;\n//#endregion\n//#region src/cloud-runtime/bridge-material.ts\nconst MAX_PROXY_SOCKETS = 64;\nconst SOCKET_PATH_MAX_BYTES$1 = 100;\nfunction createBridgeSocketResources() {\n\treturn {\n\t\tclosing: { value: false },\n\t\tservers: [],\n\t\tsockets: /* @__PURE__ */ new Set()\n\t};\n}\n/** Tear down every listener and in-flight bridged connection. */\nasync function closeBridgeSockets(resources) {\n\tresources.closing.value = true;\n\tfor (const socket of [...resources.sockets]) socket.destroy();\n\tresources.sockets.clear();\n\tawait Promise.all(resources.servers.map((server) => new Promise((done) => server.close(() => done()))));\n}\n/**\n* Publish the per-execution PUBLIC material (CA certificate, handles, CLI config) into\n* `publicDirectory` — the exact directory that becomes the read-only Sandbox mount. The\n* trusted CA private key and every handle secret stay in the adapter's private `materialDir`,\n* which callers must keep OUTSIDE `publicDirectory` (the native Runner mounts only this subtree).\n*/\nasync function publishExecutionMaterial(resources, publicDirectory, options) {\n\tconst { adapter, relay } = resources;\n\tconst published = publicDirectory;\n\tconst mount = options.publicMountPath ?? \"/run/opentag-execution\";\n\tawait mkdir(published, {\n\t\trecursive: true,\n\t\tmode: 493\n\t});\n\tawait chmod(published, 493);\n\tconst caFile = join(published, CLOUD_SANDBOX_CA_FILE);\n\tawait copyFile(adapter.caCertPath, caFile);\n\tawait chmod(caFile, 292);\n\tconst handles = new Map(relay.providers.map((entry) => [entry.provider, relay.localHandleFor(entry.provider)]));\n\tconst layout = {\n\t\tadapterCaCertPath: `${mount}/${CLOUD_SANDBOX_CA_FILE}`,\n\t\texecutionDir: mount,\n\t\tgitCredentialHelperPath: `${mount}/git-credential-helper`,\n\t\tgitConfigPath: `${mount}/gitconfig`,\n\t\tlarkConfigDir: \"/tmp/opentag/lark\",\n\t\tslackConfigDir: \"/tmp/opentag/slack\"\n\t};\n\tconst environment = buildRuntimeProxyEnvironment({\n\t\tadapterCaCertPath: layout.adapterCaCertPath,\n\t\tcliMetadata: (provider) => relay.cliMetadataFor(provider),\n\t\tconnectProxyUrl: `http://127.0.0.1:${CLOUD_CONNECT_PROXY_PORT}`,\n\t\thandles,\n\t\tlayout,\n\t\tslackApiHost: `https://127.0.0.1:${CLOUD_SLACK_API_PORT}`\n\t});\n\tconst routing = providerRoutingEnvironment(environment);\n\tawait writePublicFile(join(published, \"environment.json\"), JSON.stringify({\n\t\texecutionId: relay.executionId,\n\t\tenvironment\n\t}));\n\tif (options.includeEntryPrograms) {\n\t\tawait writePublicFile(join(published, \"entry.mjs\"), CLOUD_SANDBOX_ENTRY_PROGRAM);\n\t\tawait writePublicFile(join(published, \"sandbox-ca.mjs\"), CLOUD_SANDBOX_CA_PROGRAM);\n\t}\n\tawait writePublicFile(join(published, \"gitconfig\"), routing.HTTPS_PROXY !== void 0 && routing.SSL_CERT_FILE !== void 0 ? renderRuntimeProxyGitConfig({\n\t\tcaCertPath: routing.SSL_CERT_FILE,\n\t\tconnectProxyUrl: routing.HTTPS_PROXY\n\t}) : \"\");\n\tawait writePublicFile(join(published, \"git-credential-helper\"), renderRuntimeProxyGitCredentialHelper(handles.get(\"github\") ?? \"unavailable\"), 365);\n\tawait mkdir(join(published, \"bin\"), { mode: 493 });\n\tawait writePublicFile(join(published, \"bin\", \"slack\"), `#!/bin/sh\\n# OpenTag execution-local Slack launcher; do not edit.\\n${renderRuntimeProxyScopePreamble()}\\nexec /opt/opentag/tools/bin/slack --apihost https://127.0.0.1:${CLOUD_SLACK_API_PORT} \"$@\"\\n`, 365);\n\tawait writePublicFile(join(published, \"bin\", \"gh\"), renderRuntimeProxyProviderLauncher(\"gh\"), 365);\n\treturn published;\n}\n/**\n* Docker bridge only: listen on the two per-execution Unix sockets inside the published\n* directory and bridge each accepted connection to the trusted loopback adapter. The native\n* transport never calls this — no parent socket is ever mounted into the native Sandbox.\n*/\nasync function listenBridgeProxySockets(resources, adapter, publicDirectory) {\n\tawait listenProxySocket(resources, \"connect\", adapter.connectProxyUrl, join(publicDirectory, \"connect.sock\"));\n\tawait listenProxySocket(resources, \"slack\", adapter.slackApiHost, join(publicDirectory, \"slack.sock\"));\n}\nasync function listenProxySocket(resources, name, endpoint, socketPath) {\n\tconst target = new URL(endpoint);\n\tconst port = Number(target.port);\n\tif (!Number.isInteger(port) || port <= 0 || port > 65535) throw new Error(\"Invalid loopback endpoint\");\n\tif (Buffer.byteLength(socketPath) > SOCKET_PATH_MAX_BYTES$1) throw new Error(`The trusted ${name} socket path is too long`);\n\tconst server = createServer$1();\n\tserver.on(\"connection\", (client) => proxyLoopbackConnection(client, port, resources));\n\tresources.servers.push(server);\n\tserver.listen(socketPath);\n\tawait once(server, \"listening\");\n\tawait chmod(socketPath, 438);\n}\n/** Bridges one in-sandbox loopback connection to the trusted per-execution Unix socket. */\nfunction proxyLoopbackConnection(client, port, resources) {\n\tresources.sockets.add(client);\n\tclient.once(\"close\", () => resources.sockets.delete(client));\n\tif (resources.closing.value || resources.sockets.size > MAX_PROXY_SOCKETS) {\n\t\tclient.destroy();\n\t\treturn;\n\t}\n\tconst remote = connect$1({\n\t\thost: \"127.0.0.1\",\n\t\tport\n\t});\n\tresources.sockets.add(remote);\n\tconst close = () => {\n\t\tclient.destroy();\n\t\tremote.destroy();\n\t\tresources.sockets.delete(client);\n\t\tresources.sockets.delete(remote);\n\t};\n\tclient.once(\"error\", close);\n\tremote.once(\"error\", close);\n\tclient.once(\"close\", close);\n\tremote.once(\"close\", close);\n\tclient.pipe(remote);\n\tremote.pipe(client);\n}\nasync function writePublicFile(path, content, mode = 292) {\n\tawait writeFile(path, content, { mode });\n\tawait chmod(path, mode);\n}\n//#endregion\n//#region src/agent-runtime/environment.ts\n/** Compose all environment layers before giving Session tools first place on PATH. */\nfunction composeRuntimeEnvironment(environment, workspaceEnvironment, pathPrepend) {\n\tconst composed = {\n\t\t...environment,\n\t\t...workspaceEnvironment\n\t};\n\tconst current = composed.PATH;\n\tif (pathPrepend && current !== pathPrepend && !current?.startsWith(`${pathPrepend}${delimiter}`)) composed.PATH = current ? `${pathPrepend}${delimiter}${current}` : pathPrepend;\n\treturn composed;\n}\n//#endregion\n//#region src/providers/process-owner.ts\nconst WATCHDOG_SOURCE = `\nconst { spawn, spawnSync } = require(\"node:child_process\");\nconst command = process.argv[1];\nconst args = process.argv.slice(2);\nconst child = spawn(command, args, {\n  cwd: process.cwd(),\n  env: process.env,\n  stdio: [\"pipe\", \"pipe\", \"pipe\"],\n});\nlet stopping = false;\nconst stop = (signal = \"SIGTERM\") => {\n  if (stopping) return;\n  stopping = true;\n  if (process.platform === \"win32\") {\n    if (child.pid) spawnSync(\"taskkill\", [\"/pid\", String(child.pid), \"/T\", \"/F\"], { stdio: \"ignore\" });\n  } else {\n    try { process.kill(-process.pid, signal); } catch { child.kill(signal); }\n  }\n  const timer = setTimeout(() => {\n    if (process.platform !== \"win32\") {\n      try { process.kill(-process.pid, \"SIGKILL\"); } catch { child.kill(\"SIGKILL\"); }\n    }\n    process.exit(1);\n  }, 500);\n  timer.unref();\n};\nprocess.once(\"SIGINT\", () => stop(\"SIGINT\"));\nprocess.once(\"SIGTERM\", () => stop(\"SIGTERM\"));\nprocess.stdin.pipe(child.stdin);\nprocess.stdin.once(\"end\", () => stop());\nprocess.stdin.once(\"error\", () => stop());\nchild.stdout.pipe(process.stdout);\nchild.stderr.pipe(process.stderr);\nchild.once(\"error\", () => stop());\nchild.once(\"exit\", () => stop());\n`;\nfunction spawnWatchedProcess(command, args, options) {\n\treturn spawn(process.execPath, [\n\t\t\"-e\",\n\t\tWATCHDOG_SOURCE,\n\t\tcommand,\n\t\t...args\n\t], {\n\t\tcwd: options.cwd,\n\t\tdetached: options.detached,\n\t\tenv: options.env,\n\t\tstdio: \"pipe\"\n\t});\n}\nfunction signalWatchedProcess(child, signal) {\n\tif (!child.pid) return;\n\ttry {\n\t\t/* v8 ignore next -- the Windows process-tree branch is exercised only on Windows. */\n\t\tif (process.platform === \"win32\") child.kill(signal);\n\t\telse process.kill(-child.pid, signal);\n\t} catch {\n\t\tchild.kill(signal);\n\t}\n}\n//#endregion\n//#region src/providers/pi/rpc-wire.ts\nconst PI_RPC_MAX_LINE_BYTES = 8388608;\nconst PI_RPC_MAX_STDERR_BYTES = 65536;\nconst PI_RPC_REQUEST_TIMEOUT_MS = 6e4;\nconst utf8Decoder = new TextDecoder(\"utf-8\", { fatal: true });\nvar PiRpcError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = \"PiRpcError\";\n\t}\n};\nconst defaultSpawn = (command, args, options) => spawnWatchedProcess(command, args, options);\nvar PiRpcProcess = class {\n\t#child;\n\t#maxLineBytes;\n\t#maxStderrBytes;\n\t#requestTimeoutMs;\n\t#logger;\n\t#pending = /* @__PURE__ */ new Map();\n\t#listeners = /* @__PURE__ */ new Set();\n\t#exit;\n\t#resolveExit;\n\t#buffer = Buffer.alloc(0);\n\t#stderr = Buffer.alloc(0);\n\t#nextId = 1;\n\t#closed = false;\n\t#closing = false;\n\t#failure;\n\tconstructor(options) {\n\t\tthis.#maxLineBytes = options.maxLineBytes ?? 8388608;\n\t\tthis.#maxStderrBytes = options.maxStderrBytes ?? 65536;\n\t\tthis.#requestTimeoutMs = options.requestTimeoutMs ?? 6e4;\n\t\tthis.#logger = options.logger ?? createLogger(\"provider-pi\");\n\t\tif (!Number.isSafeInteger(this.#maxLineBytes) || this.#maxLineBytes < 1024) throw new Error(\"maxLineBytes must be a safe integer of at least 1024\");\n\t\tif (!Number.isSafeInteger(this.#maxStderrBytes) || this.#maxStderrBytes < 0) throw new Error(\"maxStderrBytes must be a non-negative safe integer\");\n\t\tif (!Number.isSafeInteger(this.#requestTimeoutMs) || this.#requestTimeoutMs < 1) throw new Error(\"requestTimeoutMs must be a positive safe integer\");\n\t\tthis.#exit = new Promise((resolve) => {\n\t\t\tthis.#resolveExit = resolve;\n\t\t});\n\t\ttry {\n\t\t\tthis.#child = (options.spawnProcess ?? defaultSpawn)(options.command ?? \"pi\", options.args, {\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tenv: options.env,\n\t\t\t\tdetached: process.platform !== \"win32\"\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"spawn_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Pi RPC process spawn failed\");\n\t\t\tthrow new PiRpcError(\"spawn\", error instanceof Error ? error.message : \"Pi could not be started\");\n\t\t}\n\t\tthis.#child.stdout.on(\"data\", (chunk) => this.#onStdout(chunk));\n\t\tthis.#child.stderr.on(\"data\", (chunk) => this.#onStderr(chunk));\n\t\tthis.#child.on(\"error\", (error) => {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"process_error\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Pi RPC process failed\");\n\t\t\tthis.#onChildError(error);\n\t\t});\n\t\tthis.#child.on(\"close\", () => this.#onExit());\n\t}\n\tget pid() {\n\t\treturn this.#child.pid;\n\t}\n\tsubscribe(listener) {\n\t\tthis.#listeners.add(listener);\n\t\treturn () => this.#listeners.delete(listener);\n\t}\n\trequest(command, signal) {\n\t\tif (this.#failure || this.#closed) return Promise.reject(this.#failure ?? new PiRpcError(\"exited\", \"Pi RPC is closed\"));\n\t\tif (signal?.aborted) return Promise.reject(new PiRpcError(\"aborted\", \"Pi RPC request was aborted\"));\n\t\tif (typeof command.type !== \"string\" || command.type.length === 0) return Promise.reject(new PiRpcError(\"protocol\", \"Pi RPC command has no type\"));\n\t\tconst commandType = command.type;\n\t\tconst id = `opentag-${this.#nextId}`;\n\t\tthis.#nextId += 1;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tconst pending = this.#pending.get(id);\n\t\t\t\t/* v8 ignore else -- cleanup only runs while its own pending entry is registered. */\n\t\t\t\tif (pending) clearTimeout(pending.timer);\n\t\t\t\tthis.#pending.delete(id);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new PiRpcError(\"aborted\", \"Pi RPC request was aborted\"));\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new PiRpcError(\"timeout\", `Pi RPC request timed out: ${commandType}`));\n\t\t\t}, this.#requestTimeoutMs);\n\t\t\ttimer.unref();\n\t\t\tthis.#pending.set(id, {\n\t\t\t\tcommand: commandType,\n\t\t\t\ttimer,\n\t\t\t\tresolve: (value) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tthis.#write({\n\t\t\t\t...command,\n\t\t\t\tid\n\t\t\t}).catch((error) => {\n\t\t\t\tthis.#pending.get(id)?.reject(error);\n\t\t\t});\n\t\t});\n\t}\n\tasync close(graceMs = 1e3) {\n\t\tif (this.#closed) return this.#exit;\n\t\tthis.#closing = true;\n\t\tthis.#closed = true;\n\t\tconst closingError = new PiRpcError(\"aborted\", \"Pi RPC is closing\");\n\t\tfor (const pending of [...this.#pending.values()]) pending.reject(closingError);\n\t\tthis.#child.stdin.end();\n\t\tsignalWatchedProcess(this.#child, \"SIGTERM\");\n\t\tif (await settlesWithin(this.#exit, graceMs)) return;\n\t\tsignalWatchedProcess(this.#child, \"SIGKILL\");\n\t\t/* v8 ignore else -- a process that survives SIGTERM in tests never exits before the SIGKILL deadline either. */\n\t\tif (!await settlesWithin(this.#exit, graceMs)) throw new PiRpcError(\"exited\", \"Pi RPC process tree did not exit\");\n\t}\n\tasync #write(message) {\n\t\tif (this.#failure || this.#closed || !this.#child.stdin.writable) throw this.#failure ?? new PiRpcError(\"write\", \"Pi RPC stdin is unavailable\");\n\t\tlet line;\n\t\ttry {\n\t\t\tline = `${JSON.stringify(message)}\\n`;\n\t\t} catch {\n\t\t\tthis.#logger.debug({ code: \"request_not_serializable\" }, \"Pi RPC request could not be serialized\");\n\t\t\tthrow new PiRpcError(\"protocol\", \"Pi RPC request is not JSON serializable\");\n\t\t}\n\t\tif (Buffer.byteLength(line, \"utf8\") > this.#maxLineBytes) throw new PiRpcError(\"protocol\", \"Pi RPC request exceeds the JSONL line limit\");\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tthis.#child.stdin.write(line, (error) => {\n\t\t\t\terror ? reject(new PiRpcError(\"write\", \"Pi RPC request could not be written\")) : resolve();\n\t\t\t});\n\t\t});\n\t}\n\t#onStdout(chunk) {\n\t\tif (this.#failure) return;\n\t\tthis.#buffer = Buffer.concat([this.#buffer, chunk]);\n\t\twhile (true) {\n\t\t\tconst newline = this.#buffer.indexOf(10);\n\t\t\tif (newline < 0) break;\n\t\t\tif (newline + 1 > this.#maxLineBytes) {\n\t\t\t\tthis.#fail(new PiRpcError(\"protocol\", \"Pi emitted an oversized JSONL line\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet raw;\n\t\t\ttry {\n\t\t\t\traw = utf8Decoder.decode(this.#buffer.subarray(0, newline)).replace(/\\r$/, \"\");\n\t\t\t} catch {\n\t\t\t\tthis.#logger.debug({ code: \"stdout_invalid_utf8\" }, \"Pi RPC protocol output was rejected\");\n\t\t\t\tthis.#fail(new PiRpcError(\"protocol\", \"Pi emitted invalid UTF-8\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#buffer = this.#buffer.subarray(newline + 1);\n\t\t\tif (raw.length === 0) continue;\n\t\t\tlet message;\n\t\t\ttry {\n\t\t\t\tmessage = JSON.parse(raw);\n\t\t\t} catch {\n\t\t\t\tthis.#logger.debug({ code: \"stdout_malformed_json\" }, \"Pi RPC protocol output was rejected\");\n\t\t\t\tthis.#fail(new PiRpcError(\"protocol\", \"Pi emitted malformed JSONL\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!isRecord$5(message)) {\n\t\t\t\tthis.#fail(new PiRpcError(\"protocol\", \"Pi emitted a non-object RPC message\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#onMessage(message);\n\t\t\tif (this.#failure) return;\n\t\t}\n\t\tif (this.#buffer.byteLength > this.#maxLineBytes) this.#fail(new PiRpcError(\"protocol\", \"Pi emitted an oversized JSONL line\"));\n\t}\n\t#onStderr(chunk) {\n\t\tif (this.#stderr.byteLength >= this.#maxStderrBytes) return;\n\t\tconst remaining = this.#maxStderrBytes - this.#stderr.byteLength;\n\t\tthis.#stderr = Buffer.concat([this.#stderr, chunk.subarray(0, remaining)]);\n\t}\n\t#onMessage(message) {\n\t\tif (message.type === \"response\") {\n\t\t\tconst id = message.id;\n\t\t\tif (typeof id !== \"string\") {\n\t\t\t\tthis.#fail(new PiRpcError(\"protocol\", \"Pi emitted a response without an ID\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst pending = this.#pending.get(id);\n\t\t\tif (!pending) {\n\t\t\t\tthis.#fail(new PiRpcError(\"protocol\", \"Pi emitted an unknown or duplicate response ID\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (message.command !== pending.command) {\n\t\t\t\tthis.#fail(new PiRpcError(\"protocol\", \"Pi response command does not match its request\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (message.success === true) {\n\t\t\t\tpending.resolve(message.data);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (message.success === false && typeof message.error === \"string\") {\n\t\t\t\tpending.reject(new PiRpcError(\"command\", `Pi rejected ${pending.command}: ${message.error}`));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#fail(new PiRpcError(\"protocol\", \"Pi emitted an invalid RPC response\"));\n\t\t\treturn;\n\t\t}\n\t\tif (typeof message.type !== \"string\") {\n\t\t\tthis.#fail(new PiRpcError(\"protocol\", \"Pi emitted an event without a type\"));\n\t\t\treturn;\n\t\t}\n\t\tfor (const listener of this.#listeners) try {\n\t\t\tlistener(message);\n\t\t} catch {\n\t\t\tthis.#logger.debug({ code: \"protocol_listener_failed\" }, \"Pi RPC protocol listener failed\");\n\t\t\tthis.#fail(new PiRpcError(\"protocol\", \"A Pi RPC listener rejected an event\"));\n\t\t\treturn;\n\t\t}\n\t}\n\t#onExit() {\n\t\tthis.#closed = true;\n\t\tthis.#resolveExit?.();\n\t\tthis.#resolveExit = void 0;\n\t\tif (this.#failure || this.#closing) return;\n\t\tconst error = this.#buffer.byteLength > 0 ? new PiRpcError(\"protocol\", \"Pi exited with a truncated JSONL line\") : new PiRpcError(\"exited\", this.#exitMessage());\n\t\tthis.#fail(error);\n\t}\n\t#onChildError(error) {\n\t\tthis.#fail(new PiRpcError(\"spawn\", error.message));\n\t\tthis.#closed = true;\n\t\tthis.#resolveExit?.();\n\t\tthis.#resolveExit = void 0;\n\t}\n\t#exitMessage() {\n\t\tconst stderr = this.#stderr.toString(\"utf8\").trim();\n\t\treturn stderr ? `Pi RPC exited: ${stderr}` : \"Pi RPC exited unexpectedly\";\n\t}\n\t#fail(error) {\n\t\tif (this.#failure) return;\n\t\tthis.#failure = error;\n\t\tfor (const pending of [...this.#pending.values()]) pending.reject(error);\n\t\tfor (const listener of this.#listeners) try {\n\t\t\tlistener({\n\t\t\t\ttype: \"opentag/process_error\",\n\t\t\t\terror\n\t\t\t});\n\t\t} catch {\n\t\t\tthis.#logger.debug({ code: \"process_error_listener_failed\" }, \"Pi process error listener failed\");\n\t\t}\n\t\tif (!this.#closed) {\n\t\t\tthis.#closing = true;\n\t\t\tsignalWatchedProcess(this.#child, \"SIGTERM\");\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (!this.#closed) signalWatchedProcess(this.#child, \"SIGKILL\");\n\t\t\t}, 1e3).unref();\n\t\t}\n\t}\n};\nasync function settlesWithin(promise, milliseconds) {\n\tlet timer;\n\tconst timeout = new Promise((resolve) => {\n\t\ttimer = setTimeout(() => resolve(false), milliseconds);\n\t\ttimer.unref();\n\t});\n\tconst settled = await Promise.race([promise.then(() => true), timeout]);\n\t/* v8 ignore else -- the timer is always armed before the race settles. */\n\tif (timer) clearTimeout(timer);\n\treturn settled;\n}\nfunction isRecord$5(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n//#endregion\n//#region src/providers/pi/agent-runtime.ts\nconst execFileAsync$2 = promisify(execFile);\nconst PI_BINDING_SCHEMA_VERSION = 1;\nconst PI_PROVIDER_ID = \"pi\";\nconst logger$5 = createLogger(\"provider-pi-runtime\");\nconst PI_MINIMUM_VERSION = [\n\t0,\n\t80,\n\t6\n];\nconst PI_THINKING_LEVELS = /* @__PURE__ */ new Set([\n\t\"off\",\n\t\"minimal\",\n\t\"low\",\n\t\"medium\",\n\t\"high\",\n\t\"xhigh\",\n\t\"max\"\n]);\nconst PI_READ_ONLY_TOOLS = [\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\"\n];\nconst PI_STOP_REASONS = /* @__PURE__ */ new Set([\n\t\"stop\",\n\t\"length\",\n\t\"toolUse\",\n\t\"error\",\n\t\"aborted\"\n]);\nconst PI_RESOURCE_DISABLE_ARGUMENTS = [\n\t\"--offline\",\n\t\"--no-extensions\",\n\t\"--no-skills\",\n\t\"--no-prompt-templates\",\n\t\"--no-themes\",\n\t\"--no-context-files\",\n\t\"--no-approve\"\n];\nconst PI_LIST_MODELS_COLUMNS = [\n\t\"provider\",\n\t\"model\",\n\t\"context\",\n\t\"max-out\",\n\t\"thinking\",\n\t\"images\"\n];\n/** Local Pi probes have always allowed 5s; native Cloud Run Pi startup measured ~6s. */\nconst PI_PROBE_DEFAULT_TIMEOUT_MS = 5e3;\n/** Upper bound on a configured probe budget so no caller can wait unbounded. */\nconst PI_PROBE_MAX_TIMEOUT_MS = 6e4;\nconst PI_AGENT_RUNTIME_MANIFEST = Object.freeze({\n\tproviderId: PI_PROVIDER_ID,\n\tdisplayName: \"Pi\",\n\tcontractVersion: 2,\n\tbindingSchemaVersion: PI_BINDING_SCHEMA_VERSION\n});\n/** Nonsecret endpoint descriptor consumed by the trusted extension artifact. */\nconst PI_WEB_TOOLS_SOCKET_ENV = \"OPENTAG_WEB_TOOLS_SOCKET\";\nconst PI_MCP_GATEWAY_EXTENSION = fileURLToPath(new URL(\"../../pi-extensions/mcp-gateway.ts\", import.meta.url));\nconst PI_MCP_GATEWAY_BUNDLED_EXTENSION = fileURLToPath(new URL(\"./pi-extensions/mcp-gateway.mjs\", import.meta.url));\nvar PiAgentRuntime = class extends BaseAgentRuntime {\n\t#mcpAdapterEntry;\n\t#sessionId;\n\t#policy;\n\t#configuration;\n\t#sessionDirectory;\n\t#skillArgs;\n\t#systemPrompt;\n\t#createClient;\n\t#tools = /* @__PURE__ */ new Map();\n\t#client;\n\t#unsubscribe;\n\t#context;\n\t#eventTail = Promise.resolve();\n\t#terminal;\n\t#promptAccepted;\n\t#providerFailure;\n\t#currentTurnId;\n\t#currentAssistant;\n\t#turnSequence = 0;\n\t#assistantSequence = 0;\n\t#lastText;\n\t#lastStopReason;\n\t#lastError;\n\t#model;\n\t#usage = {};\n\t#sessionExists;\n\t#sessionFileHash;\n\t#pendingSessionFileHash = \"\";\n\t#terminalClaimed = false;\n\t#compacting = false;\n\t#mcpEnabled = false;\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tmanifest: PI_AGENT_RUNTIME_MANIFEST,\n\t\t\tcapabilities: {\n\t\t\t\tsteer: \"supported\",\n\t\t\t\tinteractions: \"unsupported\"\n\t\t\t},\n\t\t\teventSink: options.eventSink,\n\t\t\tbinding: options.binding\n\t\t});\n\t\tconst binding = parsePiBinding(options.binding);\n\t\tthis.#sessionId = binding.sessionId;\n\t\tthis.#sessionFileHash = binding.sessionFileHash;\n\t\tthis.#policy = options.policy;\n\t\tthis.#mcpAdapterEntry = options.mcpAdapterEntry;\n\t\tthis.#configuration = options.configuration;\n\t\tthis.#sessionDirectory = options.sessionDirectory;\n\t\tthis.#skillArgs = (options.skillPaths ?? []).flatMap((path) => [\"--skill\", path]);\n\t\tthis.#systemPrompt = options.systemPrompt;\n\t\tthis.#createClient = options.createClient;\n\t\tthis.#sessionExists = options.resume;\n\t}\n\tasync executeRun(request, context) {\n\t\tthis.#resetRun(context);\n\t\tthis.#mcpEnabled = Boolean(parseProviderConfiguration(mergeConfiguration(this.#configuration, request.configuration)?.provider).mcpGateway);\n\t\tlet client;\n\t\tlet cleanupFailure;\n\t\tlet result;\n\t\ttry {\n\t\t\tclient = this.#createClient(this.#arguments(request), piExtensionEnvironment(request, this.#configuration, this.#mcpAdapterEntry));\n\t\t\tthis.#client = client;\n\t\t\tthis.#unsubscribe = client.subscribe((message) => this.#enqueue(message));\n\t\t\tconst state = requireRecord(await client.request({ type: \"get_state\" }, context.signal), \"Pi get_state returned invalid data\");\n\t\t\tawait this.#restoreSessionState(state, context);\n\t\t\tawait client.request({\n\t\t\t\ttype: \"prompt\",\n\t\t\t\tmessage: piInput(request)\n\t\t\t}, context.signal);\n\t\t\tthis.#promptAccepted?.resolve();\n\t\t\tconst terminal = await this.#terminal?.promise;\n\t\t\t/* v8 ignore next -- resetRun always creates the terminal before Provider I/O begins. */\n\t\t\tif (!terminal) throw protocolError(\"Pi run has no terminal state\");\n\t\t\tawait this.#eventTail;\n\t\t\tif (this.#providerFailure) throw this.#providerFailure;\n\t\t\tresult = this.#runResult(terminal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : /* @__PURE__ */ new Error(\"Pi run failed\");\n\t\t\tlogger$5.debug({\n\t\t\t\tcode: \"provider_run_failed\",\n\t\t\t\terror: failure.message\n\t\t\t}, \"Pi provider run failed\");\n\t\t\tthis.#promptAccepted?.reject(failure);\n\t\t\tconst causalFailure = this.#providerFailure ?? failure;\n\t\t\tif (!context.signal.aborted && isIrrecoverablePiFailure(causalFailure)) this.closeForProviderFailure();\n\t\t\tif (causalFailure instanceof AgentProviderError) throw causalFailure;\n\t\t\tthrow new AgentProviderError(causalFailure instanceof PiRpcError && causalFailure.code === \"protocol\" ? \"provider_protocol_error\" : \"provider_error\", causalFailure.message, { cause: causalFailure });\n\t\t} finally {\n\t\t\tcleanupFailure = await this.#cleanupRun(client);\n\t\t}\n\t\tif (cleanupFailure && result.status !== \"failed\") throw new AgentProviderError(\"provider_error\", cleanupFailure.message, { cause: cleanupFailure });\n\t\treturn result;\n\t}\n\tasync #restoreSessionState(state, context) {\n\t\tif (requireUuid(state.sessionId, \"Pi get_state sessionId\") !== this.#sessionId) throw protocolError(\"Pi opened another session\");\n\t\tconst sessionFile = requireAbsolutePath(state.sessionFile, \"Pi get_state sessionFile is not absolute\");\n\t\tconst messageCount = requireNonNegativeSafeInteger(state.messageCount, \"Pi get_state messageCount is invalid\");\n\t\tconst sessionFileHash = fingerprint(sessionFile);\n\t\tif (!this.#sessionExists && messageCount !== 0) throw protocolError(\"Pi create opened an existing conversation\");\n\t\tif (this.#sessionFileHash && this.#sessionFileHash !== sessionFileHash) throw protocolError(\"Pi opened another session file\");\n\t\tif (this.#sessionFileHash && messageCount === 0) throw protocolError(\"Pi session has no conversation history\");\n\t\tthis.#pendingSessionFileHash = sessionFileHash;\n\t\tthis.#sessionExists = true;\n\t\tthis.#model = parseModel(state.model);\n\t\tif (!this.#sessionFileHash && messageCount !== 0) await this.#materializeSession(context, sessionFileHash);\n\t}\n\tasync #materializeSession(context, sessionFileHash) {\n\t\tif (this.#sessionFileHash) return;\n\t\tawait context.updateBinding(piBinding(this.#sessionId, sessionFileHash));\n\t\tthis.#sessionFileHash = sessionFileHash;\n\t}\n\tasync #cleanupRun(client) {\n\t\tthis.#unsubscribe?.();\n\t\tthis.#unsubscribe = void 0;\n\t\tlet failure;\n\t\ttry {\n\t\t\tawait client?.close();\n\t\t} catch (error) {\n\t\t\tfailure = error instanceof Error ? error : /* @__PURE__ */ new Error(\"Pi provider close failed\");\n\t\t\tlogger$5.debug({\n\t\t\t\tcode: \"provider_close_failed\",\n\t\t\t\terror: failure.message\n\t\t\t}, \"Pi provider close failed\");\n\t\t}\n\t\tthis.#client = void 0;\n\t\tthis.#context = void 0;\n\t\tthis.#terminal = void 0;\n\t\tthis.#promptAccepted = void 0;\n\t\tthis.#currentTurnId = void 0;\n\t\tthis.#currentAssistant = void 0;\n\t\tthis.#tools.clear();\n\t\tif (failure) this.closeForProviderFailure();\n\t\treturn failure;\n\t}\n\tasync steerProvider(request) {\n\t\t/* v8 ignore next -- BaseAgentRuntime admits steer only while executeRun owns an active prompt. */\n\t\tif (!this.#promptAccepted) throw new AgentRuntimeError(\"run_mismatch\", \"there is no active Pi prompt\");\n\t\tawait this.#promptAccepted.promise;\n\t\tconst client = this.#client;\n\t\t/* v8 ignore next -- the client remains owned until the active Provider Run leaves executeRun. */\n\t\tif (!client) throw new AgentRuntimeError(\"run_mismatch\", \"there is no active Pi process\");\n\t\tawait client.request({\n\t\t\ttype: \"steer\",\n\t\t\tmessage: piItems(request.input.items)\n\t\t});\n\t}\n\tasync abortProvider(_request) {\n\t\tif (this.#terminalClaimed) return;\n\t\tconst client = this.#client;\n\t\tif (!client) return;\n\t\tif (!this.#compacting) try {\n\t\t\tawait client.request({ type: \"abort\" }, AbortSignal.timeout(2e3));\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof PiRpcError) || error.code !== \"aborted\" && error.code !== \"timeout\") throw error;\n\t\t}\n\t\tawait client.close();\n\t\tawait this.#eventTail;\n\t\tif (!this.#terminalClaimed) this.#terminal?.resolve({\n\t\t\tstatus: \"aborted\",\n\t\t\tstopReason: \"aborted\"\n\t\t});\n\t}\n\tasync closeProvider() {\n\t\tawait this.#client?.close();\n\t}\n\t#resetRun(context) {\n\t\tthis.#context = context;\n\t\tthis.#eventTail = Promise.resolve();\n\t\tthis.#terminal = deferred();\n\t\tthis.#promptAccepted = deferred();\n\t\tthis.#terminal.promise.catch(() => void 0);\n\t\tthis.#promptAccepted.promise.catch(() => void 0);\n\t\tthis.#providerFailure = void 0;\n\t\tthis.#currentTurnId = void 0;\n\t\tthis.#currentAssistant = void 0;\n\t\tthis.#turnSequence = 0;\n\t\tthis.#assistantSequence = 0;\n\t\tthis.#lastText = void 0;\n\t\tthis.#lastStopReason = void 0;\n\t\tthis.#lastError = void 0;\n\t\tthis.#model = void 0;\n\t\tthis.#usage = {};\n\t\tthis.#tools.clear();\n\t\tthis.#terminalClaimed = false;\n\t\tthis.#compacting = false;\n\t}\n\t#arguments(request) {\n\t\tconst configuration = mergeConfiguration(this.#configuration, request.configuration);\n\t\tconst provider = parseProviderConfiguration(configuration?.provider);\n\t\treturn [\n\t\t\t\"--mode\",\n\t\t\t\"rpc\",\n\t\t\t...PI_RESOURCE_DISABLE_ARGUMENTS,\n\t\t\t...this.#skillArgs,\n\t\t\t\"--session-id\",\n\t\t\tthis.#sessionId,\n\t\t\t...this.#sessionDirectory ? [\"--session-dir\", this.#sessionDirectory] : [],\n\t\t\t...piPolicyArguments(this.#policy),\n\t\t\t...configuration?.model ? [\"--model\", configuration.model] : [],\n\t\t\t...configuration?.reasoningEffort ? [\"--thinking\", configuration.reasoningEffort] : [],\n\t\t\t...provider.webTools ? [\"--extension\", provider.webTools.extensionPath] : [],\n\t\t\t...provider.mcpGateway ? [\"--extension\", import.meta.url.endsWith(\".mjs\") ? PI_MCP_GATEWAY_BUNDLED_EXTENSION : PI_MCP_GATEWAY_EXTENSION] : [],\n\t\t\t\"--append-system-prompt\",\n\t\t\tthis.#systemPrompt,\n\t\t\t...provider.sessionName ? [\"--name\", provider.sessionName] : []\n\t\t];\n\t}\n\t#enqueue(message) {\n\t\tthis.#claimTerminalAtIngress(message);\n\t\tif (message.type === \"compaction_start\") this.#compacting = true;\n\t\tif (message.type === \"compaction_end\") this.#compacting = false;\n\t\tconst next = this.#eventTail.then(async () => {\n\t\t\t/* v8 ignore next -- unsubscribe detaches the only event source before Run context cleanup. */\n\t\t\tif (!this.#context) return;\n\t\t\tawait this.#handleMessage(message);\n\t\t});\n\t\tthis.#eventTail = next.catch((error) => {\n\t\t\tthis.#failProvider(error instanceof Error ? error : protocolError(\"Pi event processing failed\"));\n\t\t});\n\t}\n\t#claimTerminalAtIngress(message) {\n\t\tif (message.type !== \"agent_settled\" || !this.#context) return;\n\t\tthis.#context.claimTerminal();\n\t\tthis.#terminalClaimed = true;\n\t}\n\tasync #handleMessage(message) {\n\t\tconst type = requireString$1(message.type, \"Pi event has no type\");\n\t\tif (type === \"opentag/process_error\") throw message.error instanceof Error ? message.error : new AgentProviderError(\"provider_error\", \"Pi process failed\");\n\t\tif (type === \"extension_ui_request\") return this.#handleExtensionUiRequest(message);\n\t\tif (type === \"agent_start\") return;\n\t\tif (type === \"turn_start\") {\n\t\t\tif (this.#currentTurnId) throw protocolError(\"Pi started overlapping turns\");\n\t\t\tthis.#turnSequence += 1;\n\t\t\tthis.#currentTurnId = `pi-turn-${this.#turnSequence}`;\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"model_turn_started\",\n\t\t\t\tmodelTurnId: this.#currentTurnId\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"turn_end\") {\n\t\t\tawait this.#endTurn();\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"message_start\") {\n\t\t\tthis.#requireActiveTurn(\"Pi started a message outside an active turn\");\n\t\t\tawait this.#startMessage(requireRecord(message.message, \"Pi message_start has no message\"));\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"message_update\") {\n\t\t\tthis.#requireActiveTurn(\"Pi updated a message outside an active turn\");\n\t\t\tawait this.#updateMessage(requireRecord(message.assistantMessageEvent, \"Pi message_update has no delta\"));\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"message_end\") {\n\t\t\tthis.#requireActiveTurn(\"Pi ended a message outside an active turn\");\n\t\t\tawait this.#endMessage(requireRecord(message.message, \"Pi message_end has no message\"));\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"tool_execution_start\") {\n\t\t\tthis.#requireActiveTurn(\"Pi started a tool outside an active turn\");\n\t\t\tawait this.#startTool(message);\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"tool_execution_update\") {\n\t\t\tthis.#requireActiveTurn(\"Pi updated a tool outside an active turn\");\n\t\t\tawait this.#updateTool(message);\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"tool_execution_end\") {\n\t\t\tthis.#requireActiveTurn(\"Pi ended a tool outside an active turn\");\n\t\t\tawait this.#endTool(message);\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"agent_end\") {\n\t\t\tawait this.#emitProviderEvent({\n\t\t\t\ttype,\n\t\t\t\twillRetry: message.willRetry === true\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"compaction_start\" || type === \"compaction_end\") {\n\t\t\tawait this.#handleCompaction(type, message);\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"agent_settled\") {\n\t\t\tthis.#settleAgent();\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"extension_error\") {\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"provider_warning\",\n\t\t\t\tcode: \"pi_extension_error\",\n\t\t\t\tmessage: typeof message.error === \"string\" ? message.error : \"Pi extension failed\"\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"auto_retry_start\") {\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"provider_warning\",\n\t\t\t\tcode: \"pi_auto_retry\",\n\t\t\t\tmessage: typeof message.errorMessage === \"string\" ? message.errorMessage : \"Pi is retrying the model request\"\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tawait this.#emitProviderEvent(message);\n\t}\n\tasync #handleExtensionUiRequest(message) {\n\t\tif (this.#mcpEnabled && (message.method === \"setStatus\" || message.method === \"setWidget\" || message.method === \"setTitle\")) return;\n\t\tif (this.#mcpEnabled && message.method === \"notify\") {\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"provider_warning\",\n\t\t\t\tcode: \"pi_mcp_notice\",\n\t\t\t\tmessage: \"Pi MCP adapter reported a notice\"\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthrow protocolError(\"Pi requested extension UI while extensions are disabled\");\n\t}\n\tasync #startMessage(message) {\n\t\tif (message.role !== \"assistant\") return;\n\t\tif (this.#currentAssistant) throw protocolError(\"Pi started overlapping assistant messages\");\n\t\tthis.#assistantSequence += 1;\n\t\tthis.#currentAssistant = {\n\t\t\tid: `pi-message-${this.#assistantSequence}`,\n\t\t\tblocks: /* @__PURE__ */ new Map()\n\t\t};\n\t}\n\t#requireActiveTurn(message) {\n\t\tif (!this.#currentTurnId) throw protocolError(message);\n\t}\n\tasync #updateMessage(update) {\n\t\tconst current = this.#currentAssistant;\n\t\tif (!current) throw protocolError(\"Pi emitted an assistant update without an active message\");\n\t\tconst type = requireString$1(update.type, \"Pi assistant update has no type\");\n\t\tif (type === \"text_start\") {\n\t\t\tconst index = requireIndex(update.contentIndex);\n\t\t\tif (current.blocks.has(index)) throw protocolError(\"Pi reused a text content index\");\n\t\t\tconst block = {\n\t\t\t\tid: `${current.id}:text:${index}`,\n\t\t\t\ttext: \"\",\n\t\t\t\tcompleted: false\n\t\t\t};\n\t\t\tcurrent.blocks.set(index, block);\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"message_started\",\n\t\t\t\tmessageId: block.id\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"text_delta\") {\n\t\t\tconst block = current.blocks.get(requireIndex(update.contentIndex));\n\t\t\tif (!block || block.completed) throw protocolError(\"Pi text delta has no active content block\");\n\t\t\tconst delta = requireString$1(update.delta, \"Pi text delta has no text\", true);\n\t\t\tblock.text += delta;\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"message_delta\",\n\t\t\t\tmessageId: block.id,\n\t\t\t\tdelta\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"text_end\") {\n\t\t\tconst block = current.blocks.get(requireIndex(update.contentIndex));\n\t\t\tif (!block || block.completed) throw protocolError(\"Pi text end has no active content block\");\n\t\t\tconst text = requireString$1(update.content, \"Pi text end has no text\", true);\n\t\t\tif (block.text !== text) throw protocolError(\"Pi text stream does not match its completed content\");\n\t\t\tblock.completed = true;\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"message_completed\",\n\t\t\t\tmessageId: block.id,\n\t\t\t\ttext\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"error\") {\n\t\t\tconst failedMessage = record(update.error) ?? record(update.partial);\n\t\t\t/* v8 ignore else -- Pi error updates always carry an errorMessage string. */\n\t\t\tif (typeof failedMessage?.errorMessage === \"string\") this.#lastError = failedMessage.errorMessage;\n\t\t\tawait this.#emitProviderEvent({\n\t\t\t\ttype: \"assistant_update\",\n\t\t\t\tupdateType: type\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"start\" || type === \"done\") {\n\t\t\tif (type === \"done\") requireStopReason(update.reason, \"Pi assistant done reason is invalid\");\n\t\t\tawait this.#emitProviderEvent({\n\t\t\t\ttype: \"assistant_update\",\n\t\t\t\tupdateType: type\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type.startsWith(\"thinking_\")) {\n\t\t\tconst contentIndex = requireIndex(update.contentIndex);\n\t\t\tif (type === \"thinking_delta\") requireString$1(update.delta, \"Pi thinking delta has no text\", true);\n\t\t\telse if (type === \"thinking_end\") requireString$1(update.content, \"Pi thinking end has no text\", true);\n\t\t\telse if (type !== \"thinking_start\") throw protocolError(\"Pi assistant thinking update is unsupported\");\n\t\t\tawait this.#emitProviderEvent({\n\t\t\t\ttype: \"assistant_update\",\n\t\t\t\tupdateType: type,\n\t\t\t\tcontentIndex\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type.startsWith(\"toolcall_\")) {\n\t\t\tconst contentIndex = requireIndex(update.contentIndex);\n\t\t\tif (type === \"toolcall_delta\") requireString$1(update.delta, \"Pi tool-call delta has no text\", true);\n\t\t\telse if (type === \"toolcall_end\") requireRecord(update.toolCall, \"Pi tool-call end has no tool call\");\n\t\t\telse if (type !== \"toolcall_start\") throw protocolError(\"Pi assistant tool-call update is unsupported\");\n\t\t\tawait this.#emitProviderEvent({\n\t\t\t\ttype: \"assistant_update\",\n\t\t\t\tupdateType: type,\n\t\t\t\tcontentIndex\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tthrow protocolError(\"Pi assistant update type is unsupported\");\n\t}\n\tasync #endMessage(message) {\n\t\tif (message.role !== \"assistant\") return;\n\t\tconst current = this.#currentAssistant;\n\t\tif (!current) throw protocolError(\"Pi ended an assistant message that was not active\");\n\t\tconst content = requireArray(message.content, \"Pi assistant content is invalid\");\n\t\tconst textParts = [];\n\t\tfor (let index = 0; index < content.length; index += 1) {\n\t\t\tconst item = requireRecord(content[index], \"Pi assistant content block is invalid\");\n\t\t\tif (item.type !== \"text\") continue;\n\t\t\tconst text = requireString$1(item.text, \"Pi assistant text block has no text\", true);\n\t\t\ttextParts.push(text);\n\t\t\tlet block = current.blocks.get(index);\n\t\t\tif (!block) {\n\t\t\t\tblock = {\n\t\t\t\t\tid: `${current.id}:text:${index}`,\n\t\t\t\t\ttext,\n\t\t\t\t\tcompleted: true\n\t\t\t\t};\n\t\t\t\tcurrent.blocks.set(index, block);\n\t\t\t\tawait this.#requireContext().emit({\n\t\t\t\t\ttype: \"message_started\",\n\t\t\t\t\tmessageId: block.id\n\t\t\t\t});\n\t\t\t\tif (text) await this.#requireContext().emit({\n\t\t\t\t\ttype: \"message_delta\",\n\t\t\t\t\tmessageId: block.id,\n\t\t\t\t\tdelta: text\n\t\t\t\t});\n\t\t\t\tawait this.#requireContext().emit({\n\t\t\t\t\ttype: \"message_completed\",\n\t\t\t\t\tmessageId: block.id,\n\t\t\t\t\ttext\n\t\t\t\t});\n\t\t\t} else if (!block.completed || block.text !== text) throw protocolError(\"Pi completed assistant content does not match its text stream\");\n\t\t}\n\t\tthis.#lastText = textParts.join(\"\\n\");\n\t\tthis.#lastStopReason = requireStopReason(message.stopReason, \"Pi assistant message has invalid stop reason\");\n\t\tif (typeof message.errorMessage === \"string\") this.#lastError = message.errorMessage;\n\t\tconst usage = parseUsage(message.usage);\n\t\tif (usage) {\n\t\t\tthis.#usage = addUsage(this.#usage, usage);\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"usage_updated\",\n\t\t\t\tusage: this.#usage\n\t\t\t});\n\t\t}\n\t\tthis.#currentAssistant = void 0;\n\t\tawait this.#materializeSession(this.#requireContext(), this.#pendingSessionFileHash);\n\t}\n\tasync #endTurn() {\n\t\tconst turnId = this.#currentTurnId;\n\t\tif (!turnId) throw protocolError(\"Pi ended a turn that was not active\");\n\t\tif (this.#currentAssistant || this.#tools.size > 0) throw protocolError(\"Pi ended a turn with unfinished child events\");\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"model_turn_completed\",\n\t\t\tmodelTurnId: turnId\n\t\t});\n\t\tthis.#currentTurnId = void 0;\n\t}\n\tasync #startTool(message) {\n\t\tconst toolCallId = requireString$1(message.toolCallId, \"Pi tool start has no toolCallId\");\n\t\tif (this.#tools.has(toolCallId)) throw protocolError(\"Pi reused an active toolCallId\");\n\t\tconst name = requireString$1(message.toolName, \"Pi tool start has no toolName\");\n\t\tthis.#tools.set(toolCallId, { name });\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"tool_started\",\n\t\t\ttoolCallId: piToolEventId(toolCallId),\n\t\t\tname,\n\t\t\t...message.args !== void 0 ? { input: toJsonValue(message.args) } : {}\n\t\t});\n\t}\n\tasync #updateTool(message) {\n\t\tconst toolCallId = requireString$1(message.toolCallId, \"Pi tool update has no toolCallId\");\n\t\tif (!this.#tools.has(toolCallId)) throw protocolError(\"Pi tool update has no active tool\");\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"tool_updated\",\n\t\t\ttoolCallId: piToolEventId(toolCallId),\n\t\t\tupdate: toJsonValue(message.partialResult ?? {})\n\t\t});\n\t}\n\tasync #endTool(message) {\n\t\tconst toolCallId = requireString$1(message.toolCallId, \"Pi tool end has no toolCallId\");\n\t\tconst tool = this.#tools.get(toolCallId);\n\t\tif (!tool) throw protocolError(\"Pi tool end has no active tool\");\n\t\tthis.#tools.delete(toolCallId);\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"tool_completed\",\n\t\t\ttoolCallId: piToolEventId(toolCallId),\n\t\t\tname: tool.name,\n\t\t\tstatus: message.isError === true ? \"failed\" : \"completed\",\n\t\t\t...message.result !== void 0 ? { output: toJsonValue(message.result) } : {}\n\t\t});\n\t}\n\t/**\n\t* Pi native auto-compaction runs INSIDE the same run: the events arrive between `agent_end`\n\t* and `agent_settled`, so they never resolve the terminal here — the run stays in progress\n\t* through the summary request, any recovery, and the continued agent loop, and only\n\t* `agent_settled` settles it. A successful `compaction_end` carries the summary request's usage\n\t* in `result.usage`; it is folded into the existing usage aggregate exactly once (the serial\n\t* event queue handles each event once, and Pi emits one end per compaction). A failed or\n\t* cancelled compaction (`result` absent, with or without a matching start — Pi reports an\n\t* already-attempted overflow recovery with an end event alone) is a diagnostic only: Pi owns\n\t* the retry/continue/fail decision, so the warning can neither falsely complete an interrupted\n\t* run nor falsely fail one whose business output already completed.\n\t*/\n\tasync #handleCompaction(type, message) {\n\t\tif (type === \"compaction_end\") {\n\t\t\tconst result = message.result === void 0 ? void 0 : requireRecord(message.result, \"Pi compaction_end result is invalid\");\n\t\t\tif (result === void 0) await this.#requireContext().emit({\n\t\t\t\ttype: \"provider_warning\",\n\t\t\t\tcode: message.aborted === true ? \"pi_compaction_aborted\" : \"pi_compaction_failed\",\n\t\t\t\tmessage: compactionDiagnostic(message)\n\t\t\t});\n\t\t\tawait this.#emitProviderEvent(message);\n\t\t\tif (result !== void 0) {\n\t\t\t\tconst usage = parseUsage(result.usage);\n\t\t\t\tif (usage) {\n\t\t\t\t\tthis.#usage = addUsage(this.#usage, usage);\n\t\t\t\t\tawait this.#requireContext().emit({\n\t\t\t\t\t\ttype: \"usage_updated\",\n\t\t\t\t\t\tusage: this.#usage\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tawait this.#emitProviderEvent(message);\n\t}\n\t#settleAgent() {\n\t\tif (this.#currentTurnId || this.#currentAssistant || this.#tools.size > 0) throw protocolError(\"Pi settled with unfinished protocol state\");\n\t\tconst stopReason = this.#lastStopReason;\n\t\tif (!stopReason) throw protocolError(\"Pi settled without an assistant result\");\n\t\tconst status = stopReason === \"stop\" ? \"completed\" : stopReason === \"aborted\" ? \"aborted\" : \"failed\";\n\t\tthis.#terminal?.resolve({\n\t\t\tstatus,\n\t\t\tstopReason,\n\t\t\t...this.#lastError ? { error: this.#lastError } : {}\n\t\t});\n\t}\n\t#runResult(terminal) {\n\t\tconst output = this.#lastText ? [{\n\t\t\ttype: \"text\",\n\t\t\ttext: this.#lastText\n\t\t}] : [];\n\t\tconst usage = hasUsage(this.#usage) ? this.#usage : void 0;\n\t\tconst diagnostics = {\n\t\t\tproviderSessionId: this.#sessionId,\n\t\t\tstopReason: terminal.stopReason,\n\t\t\t...this.#model ? { model: this.#model } : {}\n\t\t};\n\t\tif (terminal.status === \"completed\") return {\n\t\t\tstatus: \"completed\",\n\t\t\toutput,\n\t\t\t...usage ? { usage } : {},\n\t\t\tdiagnostics\n\t\t};\n\t\tif (terminal.status === \"aborted\") return {\n\t\t\tstatus: \"aborted\",\n\t\t\toutput,\n\t\t\t...usage ? { usage } : {},\n\t\t\terror: {\n\t\t\t\tcode: \"run_aborted\",\n\t\t\t\tmessage: terminal.error ?? \"Pi run was aborted\"\n\t\t\t},\n\t\t\tdiagnostics\n\t\t};\n\t\treturn {\n\t\t\tstatus: \"failed\",\n\t\t\toutput,\n\t\t\t...usage ? { usage } : {},\n\t\t\terror: {\n\t\t\t\tcode: \"provider_error\",\n\t\t\t\tmessage: terminal.error ?? piFailedStopMessage(terminal.stopReason)\n\t\t\t},\n\t\t\tdiagnostics\n\t\t};\n\t}\n\tasync #emitProviderEvent(payload) {\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"provider_event\",\n\t\t\tproviderId: PI_PROVIDER_ID,\n\t\t\tschemaVersion: 1,\n\t\t\tpayload: toJsonValue(payload)\n\t\t});\n\t}\n\t#requireContext() {\n\t\t/* v8 ignore next -- the serial event queue drops events after the active Run context is cleared. */\n\t\tif (!this.#context) throw protocolError(\"Pi event arrived without an active run\");\n\t\treturn this.#context;\n\t}\n\t#failProvider(error) {\n\t\t/* v8 ignore next -- the serial event queue records only the first causal Provider failure. */\n\t\tif (this.#providerFailure) return;\n\t\tthis.#providerFailure = error;\n\t\tthis.#terminal?.reject(error);\n\t\tthis.#promptAccepted?.reject(error);\n\t\t/* v8 ignore next -- client teardown during a provider failure must not raise a second fault. */\n\t\tthis.#client?.close().catch((closeError) => {\n\t\t\tlogger$5.debug({\n\t\t\t\tcode: \"provider_close_failed\",\n\t\t\t\terror: String(closeError)\n\t\t\t}, \"Pi provider close failed\");\n\t\t});\n\t\tthis.closeForProviderFailure();\n\t}\n};\nvar PiAgentRuntimeFactory = class {\n\t#mcpAdapterEntry;\n\tmanifest = PI_AGENT_RUNTIME_MANIFEST;\n\t#createSessionId;\n\t#createClient;\n\t#probeRunner;\n\t#sessionDirectory;\n\tconstructor(options = {}) {\n\t\tif (options.mcpAdapterEntry && !isAbsolute(options.mcpAdapterEntry)) throw new AgentRuntimeError(\"configuration_invalid\", \"Pi mcpAdapterEntry must be an absolute path\");\n\t\tthis.#mcpAdapterEntry = options.mcpAdapterEntry;\n\t\tthis.#createSessionId = options.createSessionId ?? randomUUID;\n\t\tconst environment = piAgentRuntimeEnvironment(options.process?.env ?? process.env);\n\t\tconst command = options.process?.command ?? \"pi\";\n\t\tconst prefix = options.process?.args ?? [];\n\t\tconst sessionDirectory = options.process?.sessionDirectory;\n\t\tif (sessionDirectory && !isAbsolute(sessionDirectory)) throw new AgentRuntimeError(\"configuration_invalid\", \"Pi sessionDirectory must be absolute\");\n\t\tthis.#sessionDirectory = sessionDirectory;\n\t\tconst probeTimeoutMs = options.process?.probeTimeoutMs;\n\t\tif (probeTimeoutMs !== void 0 && (!Number.isInteger(probeTimeoutMs) || probeTimeoutMs < 1 || probeTimeoutMs > PI_PROBE_MAX_TIMEOUT_MS)) throw new AgentRuntimeError(\"configuration_invalid\", `Pi probeTimeoutMs must be an integer between 1 and ${PI_PROBE_MAX_TIMEOUT_MS}`);\n\t\tthis.#createClient = options.createClient ?? ((cwd, args, workspaceEnvironment, pathPrepend) => new PiRpcProcess({\n\t\t\tcommand,\n\t\t\targs: [...prefix, ...args],\n\t\t\tcwd,\n\t\t\tenv: composeRuntimeEnvironment(environment, workspaceEnvironment, pathPrepend),\n\t\t\tmaxLineBytes: options.process?.maxLineBytes,\n\t\t\tmaxStderrBytes: options.process?.maxStderrBytes,\n\t\t\trequestTimeoutMs: options.process?.requestTimeoutMs,\n\t\t\tspawnProcess: options.process?.spawnProcess\n\t\t}));\n\t\tthis.#probeRunner = options.probeRunner ?? ((signal) => probePi(command, environment, signal, probeTimeoutMs));\n\t}\n\tasync probe(request) {\n\t\tconst issues = [];\n\t\ttry {\n\t\t\tvalidateConfiguration(request.configuration);\n\t\t} catch (error) {\n\t\t\tissues.push({\n\t\t\t\tcode: \"configuration_invalid\",\n\t\t\t\tmessage: error.message\n\t\t\t});\n\t\t}\n\t\tlet version;\n\t\ttry {\n\t\t\tconst result = await runWithAbortSignal(this.#probeRunner, request.signal);\n\t\t\tversion = result.version;\n\t\t\tif (!result.rpc) issues.push({\n\t\t\t\tcode: \"version_incompatible\",\n\t\t\t\tmessage: \"Pi RPC mode is unavailable\"\n\t\t\t});\n\t\t\tif (!result.credential) issues.push({\n\t\t\t\tcode: \"credential_missing\",\n\t\t\t\tmessage: \"Pi has no configured model credential\"\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (request.signal?.aborted) throw error;\n\t\t\tlogger$5.debug({\n\t\t\t\tcode: \"probe_execution_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Pi probe execution failed\");\n\t\t\tissues.push({\n\t\t\t\tcode: \"artifact_missing\",\n\t\t\t\tmessage: \"Pi CLI could not be executed\"\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tready: issues.length === 0,\n\t\t\t...version ? { version } : {},\n\t\t\tissues\n\t\t};\n\t}\n\tcreate(request) {\n\t\treturn this.#open(request, \"create\");\n\t}\n\tresume(request) {\n\t\treturn this.#open(request, \"resume\");\n\t}\n\tasync #open(request, mode) {\n\t\tvalidateFactoryRequest(request);\n\t\tvalidateConfiguration(request.configuration);\n\t\tconst binding = mode === \"resume\" && \"binding\" in request ? request.binding : piBinding(requireUuid(this.#createSessionId(), \"generated Pi session id\"));\n\t\tassertBinding(binding, this.manifest);\n\t\tparsePiBinding(binding);\n\t\ttry {\n\t\t\tawait request.eventSink({\n\t\t\t\ttype: \"binding_changed\",\n\t\t\t\tbinding\n\t\t\t});\n\t\t\treturn new PiAgentRuntime({\n\t\t\t\tbinding,\n\t\t\t\t...this.#mcpAdapterEntry ? { mcpAdapterEntry: this.#mcpAdapterEntry } : {},\n\t\t\t\tconfiguration: request.configuration,\n\t\t\t\tcreateClient: (args, extraEnvironment) => this.#createClient(request.workspace.cwd, args, extraEnvironment ? {\n\t\t\t\t\t...request.workspace.environment,\n\t\t\t\t\t...extraEnvironment\n\t\t\t\t} : request.workspace.environment, request.workspace.pathPrepend),\n\t\t\t\teventSink: request.eventSink,\n\t\t\t\tpolicy: request.policy,\n\t\t\t\tresume: mode === \"resume\",\n\t\t\t\tsessionDirectory: this.#sessionDirectory,\n\t\t\t\tskillPaths: request.skillPaths,\n\t\t\t\tsystemPrompt: request.systemPrompt\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger$5.debug({\n\t\t\t\tcode: \"runtime_create_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Pi runtime creation failed\");\n\t\t\tthrow new AgentRuntimeError(mode === \"create\" ? \"create_failed\" : \"resume_failed\", `Pi ${mode} failed`, { cause: error });\n\t\t}\n\t}\n};\nfunction piAgentRuntimeEnvironment(source = process.env) {\n\tconst exact = /* @__PURE__ */ new Set([\n\t\t\"AI_GATEWAY_API_KEY\",\n\t\t\"ANTHROPIC_API_KEY\",\n\t\t\"ANTHROPIC_AUTH_TOKEN\",\n\t\t\"ANTHROPIC_OAUTH_TOKEN\",\n\t\t\"ANT_LING_API_KEY\",\n\t\t\"APPDATA\",\n\t\t\"AZURE_OPENAI_API_KEY\",\n\t\t\"AZURE_OPENAI_API_VERSION\",\n\t\t\"AZURE_OPENAI_BASE_URL\",\n\t\t\"AZURE_OPENAI_DEPLOYMENT_NAME_MAP\",\n\t\t\"AZURE_OPENAI_RESOURCE_NAME\",\n\t\t\"CEREBRAS_API_KEY\",\n\t\t\"CLOUDFLARE_ACCOUNT_ID\",\n\t\t\"CLOUDFLARE_API_KEY\",\n\t\t\"CLOUDFLARE_GATEWAY_ID\",\n\t\t\"COMSPEC\",\n\t\t\"DEEPSEEK_API_KEY\",\n\t\t\"FIREWORKS_API_KEY\",\n\t\t\"GEMINI_API_KEY\",\n\t\t\"GOOGLE_APPLICATION_CREDENTIALS\",\n\t\t\"GROQ_API_KEY\",\n\t\t\"HOME\",\n\t\t\"HTTPS_PROXY\",\n\t\t\"HTTP_PROXY\",\n\t\t\"KIMI_API_KEY\",\n\t\t\"LANG\",\n\t\t\"LC_ALL\",\n\t\t\"LOCALAPPDATA\",\n\t\t\"LOGNAME\",\n\t\t\"MINIMAX_API_KEY\",\n\t\t\"MISTRAL_API_KEY\",\n\t\t\"MOONSHOT_API_KEY\",\n\t\t\"NODE_EXTRA_CA_CERTS\",\n\t\t\"NVIDIA_API_KEY\",\n\t\t\"OPENCODE_API_KEY\",\n\t\t\"OPENAI_API_KEY\",\n\t\t\"OPENROUTER_API_KEY\",\n\t\t\"OPENTAG_HOME\",\n\t\t\"OPENTAG_PROVIDER_ENV_FILE\",\n\t\t\"OPENTAG_SESSION_PROOF_FILE\",\n\t\t\"PATH\",\n\t\t\"PATHEXT\",\n\t\t\"PI_CODING_AGENT_DIR\",\n\t\t\"PI_CODING_AGENT_SESSION_DIR\",\n\t\t\"PI_OFFLINE\",\n\t\t\"PI_PACKAGE_DIR\",\n\t\t\"PI_SHARE_VIEWER_URL\",\n\t\t\"PI_TELEMETRY\",\n\t\t\"QWEN_TOKEN_PLAN_API_KEY\",\n\t\t\"QWEN_TOKEN_PLAN_CN_API_KEY\",\n\t\t\"SHELL\",\n\t\t\"SSL_CERT_DIR\",\n\t\t\"SSL_CERT_FILE\",\n\t\t\"SystemRoot\",\n\t\t\"TEMP\",\n\t\t\"TMP\",\n\t\t\"TMPDIR\",\n\t\t\"TOGETHER_API_KEY\",\n\t\t\"USER\",\n\t\t\"USERPROFILE\",\n\t\t\"WINDIR\",\n\t\t\"XAI_API_KEY\",\n\t\t\"XIAOMI_API_KEY\",\n\t\t\"XIAOMI_TOKEN_PLAN_AMS_API_KEY\",\n\t\t\"XIAOMI_TOKEN_PLAN_CN_API_KEY\",\n\t\t\"XIAOMI_TOKEN_PLAN_SGP_API_KEY\",\n\t\t\"ZAI_API_KEY\",\n\t\t\"ZAI_CODING_CN_API_KEY\",\n\t\t\"http_proxy\",\n\t\t\"https_proxy\"\n\t]);\n\tconst environment = {};\n\tfor (const [key, value] of Object.entries(source)) if (value !== void 0 && (exact.has(key) || key.startsWith(\"AWS_\"))) environment[key] = value;\n\treturn environment;\n}\nasync function probePi(command, environment, signal, timeoutMs = PI_PROBE_DEFAULT_TIMEOUT_MS) {\n\tconst execution = {\n\t\tencoding: \"utf8\",\n\t\tenv: environment,\n\t\tsignal,\n\t\ttimeout: timeoutMs,\n\t\twindowsHide: true\n\t};\n\tconst version = (await execFileAsync$2(command, [\"--version\"], execution)).stdout.trim();\n\tlet help = \"\";\n\ttry {\n\t\thelp = (await execFileAsync$2(command, [...PI_RESOURCE_DISABLE_ARGUMENTS, \"--help\"], execution)).stdout;\n\t} catch (error) {\n\t\tif (signal?.aborted) throw error;\n\t\tlogger$5.debug({\n\t\t\tcode: \"probe_help_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Pi help probe failed\");\n\t\thelp = \"\";\n\t}\n\tconst requiredOptions = [\n\t\t\"--mode\",\n\t\t\"rpc\",\n\t\t\"--session-id\",\n\t\t\"--session-dir\",\n\t\t...PI_RESOURCE_DISABLE_ARGUMENTS,\n\t\t\"--tools\",\n\t\t\"--model\",\n\t\t\"--thinking\",\n\t\t\"--append-system-prompt\",\n\t\t\"--name\"\n\t];\n\tconst rpc = supportsPiProtocol(version) && requiredOptions.every((token) => help.includes(token));\n\tlet credential = false;\n\ttry {\n\t\tcredential = piListModelsHaveAvailableRows((await execFileAsync$2(command, [...PI_RESOURCE_DISABLE_ARGUMENTS, \"--list-models\"], execution)).stdout);\n\t} catch (error) {\n\t\tif (signal?.aborted) throw error;\n\t\tlogger$5.debug({\n\t\t\tcode: \"probe_models_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Pi model probe failed\");\n\t\tcredential = false;\n\t}\n\treturn {\n\t\tcredential,\n\t\trpc,\n\t\tversion\n\t};\n}\nfunction piListModelsHaveAvailableRows(stdout) {\n\tconst [headerLine, ...rows] = stdout.trim().split(/\\r?\\n/);\n\tif (!headerLine || rows.length === 0) return false;\n\tconst header = piListModelsColumns(headerLine);\n\tif (header.length !== PI_LIST_MODELS_COLUMNS.length || PI_LIST_MODELS_COLUMNS.some((column, index) => header[index] !== column)) return false;\n\treturn rows.every((line) => piListModelsColumns(line).length === PI_LIST_MODELS_COLUMNS.length);\n}\nfunction piListModelsColumns(line) {\n\treturn line.trim().split(/\\s+/).filter((column) => column.length > 0);\n}\nfunction supportsPiProtocol(version) {\n\tconst match = /^(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(version);\n\tif (!match) return false;\n\tconst actual = match.slice(1).map(Number);\n\tif (actual.some((part) => !Number.isSafeInteger(part))) return false;\n\tconst firstDifference = actual.findIndex((part, index) => part !== PI_MINIMUM_VERSION[index]);\n\treturn firstDifference === -1 || actual[firstDifference] > PI_MINIMUM_VERSION[firstDifference];\n}\nfunction validateFactoryRequest(request) {\n\tif (!request || typeof request !== \"object\" || typeof request.eventSink !== \"function\") throw new AgentRuntimeError(\"configuration_invalid\", \"eventSink is required\");\n\tif (!request.workspace || !isAbsolute(request.workspace.cwd)) throw new AgentRuntimeError(\"configuration_invalid\", \"workspace.cwd must be absolute\");\n\tassertSystemPrompt(request.systemPrompt);\n\tfor (const root of request.workspace.writableRoots ?? []) if (!isAbsolute(root)) throw new AgentRuntimeError(\"configuration_invalid\", \"writable roots must be absolute\");\n\tif (request.policy.approvals !== \"never\") throw new AgentRuntimeError(\"configuration_invalid\", \"Pi requires approvals=never because it has no approval gate\");\n\tif (request.policy.fileSystem === \"workspace-write\") throw new AgentRuntimeError(\"configuration_invalid\", \"Pi cannot confine writes to workspace roots without a sandbox\");\n\tif (request.policy.fileSystem === \"read-only\" && (request.workspace.writableRoots?.length ?? 0) > 0) throw new AgentRuntimeError(\"configuration_invalid\", \"read-only policy cannot have writable roots\");\n\tif (request.hostedTools !== void 0) throw new AgentRuntimeError(\"configuration_invalid\", \"Pi RPC does not implement common hosted tools\");\n\tvalidateToolPolicy(request.policy);\n}\nfunction validateToolPolicy(policy) {\n\tif (policy.tools.mode === \"allow-list\") throw new AgentRuntimeError(\"configuration_invalid\", \"Pi RPC does not implement the common hosted-tool allow-list contract\");\n\tif (policy.fileSystem === \"unrestricted\" && policy.network === \"disabled\" && policy.tools.mode === \"provider-default\") throw new AgentRuntimeError(\"configuration_invalid\", \"Pi provider-default tools include unrestricted bash network access\");\n}\nfunction validateConfiguration(configuration) {\n\tif (!configuration) return;\n\tif (configuration.model !== void 0 && configuration.model.trim().length === 0) throw new AgentRuntimeError(\"configuration_invalid\", \"model must be non-empty\");\n\tif (configuration.reasoningEffort && !PI_THINKING_LEVELS.has(configuration.reasoningEffort)) throw new AgentRuntimeError(\"configuration_invalid\", \"Pi thinking level is unsupported\");\n\tparseProviderConfiguration(configuration.provider);\n}\nfunction parseProviderConfiguration(value) {\n\tif (value === void 0) return {};\n\tassertJsonValue(value, \"configuration.provider\");\n\tconst object = record(value);\n\tif (!object) throw new AgentRuntimeError(\"configuration_invalid\", \"Pi provider configuration must be an object\");\n\tconst allowed = /* @__PURE__ */ new Set([\n\t\t\"sessionName\",\n\t\t\"webTools\",\n\t\t\"mcpGateway\"\n\t]);\n\tfor (const key of Object.keys(object)) if (!allowed.has(key)) throw new AgentRuntimeError(\"configuration_invalid\", `unknown Pi configuration field: ${key}`);\n\tconst sessionName = boundedConfigurationString(object.sessionName, \"sessionName\", 4096);\n\treturn {\n\t\t...sessionName ? { sessionName } : {},\n\t\t...object.webTools !== void 0 ? { webTools: parseWebToolsConfiguration(object.webTools) } : {},\n\t\t...object.mcpGateway !== void 0 ? { mcpGateway: parseMcpGatewayConfiguration(object.mcpGateway) } : {}\n\t};\n}\nfunction parseMcpGatewayConfiguration(value) {\n\tassertJsonValue(value, \"configuration.provider.mcpGateway\");\n\tconst object = record(value);\n\tif (!object) throw new AgentRuntimeError(\"configuration_invalid\", \"Pi mcpGateway must be an object\");\n\tfor (const key of Object.keys(object)) if (!(/* @__PURE__ */ new Set([\"url\", \"token\"])).has(key)) throw new AgentRuntimeError(\"configuration_invalid\", `unknown Pi mcpGateway field: ${key}`);\n\tconst url = boundedConfigurationString(object.url, \"mcpGateway.url\", 1024);\n\tconst token = boundedConfigurationString(object.token, \"mcpGateway.token\", 4096);\n\tlet endpoint;\n\ttry {\n\t\tendpoint = new URL(url ?? \"\");\n\t} catch {\n\t\tthrow new AgentRuntimeError(\"configuration_invalid\", \"Pi mcpGateway URL is invalid\");\n\t}\n\tif (![\"http:\", \"https:\"].includes(endpoint.protocol) || endpoint.pathname !== MCP_GATEWAY_PATH || endpoint.username || endpoint.password || endpoint.search || endpoint.hash || !token?.startsWith(\"otmg_\")) throw new AgentRuntimeError(\"configuration_invalid\", \"Pi mcpGateway URL or token is invalid\");\n\treturn {\n\t\turl: endpoint.toString(),\n\t\ttoken\n\t};\n}\n/** Strict trusted launch facts; both are absolute trusted-local paths with hard byte bounds. */\nfunction parseWebToolsConfiguration(value) {\n\tassertJsonValue(value, \"configuration.provider.webTools\");\n\tconst object = record(value);\n\tif (!object) throw new AgentRuntimeError(\"configuration_invalid\", \"Pi webTools must be an object\");\n\tconst allowed = /* @__PURE__ */ new Set([\"extensionPath\", \"socketPath\"]);\n\tfor (const key of Object.keys(object)) if (!allowed.has(key)) throw new AgentRuntimeError(\"configuration_invalid\", `unknown Pi webTools field: ${key}`);\n\tconst extensionPath = boundedConfigurationString(object.extensionPath, \"webTools.extensionPath\", 512);\n\tconst socketPath = boundedConfigurationString(object.socketPath, \"webTools.socketPath\", 200);\n\tif (!extensionPath || !isAbsolute(extensionPath)) throw new AgentRuntimeError(\"configuration_invalid\", \"Pi webTools.extensionPath must be an absolute path\");\n\tif (!socketPath || !isAbsolute(socketPath)) throw new AgentRuntimeError(\"configuration_invalid\", \"Pi webTools.socketPath must be an absolute path\");\n\treturn {\n\t\textensionPath,\n\t\tsocketPath\n\t};\n}\n/** Per-run process environment: the MCP bearer stays out of argv and the persisted Pi binding. */\nfunction piExtensionEnvironment(request, base, mcpAdapterEntry) {\n\tconst provider = parseProviderConfiguration(mergeConfiguration(base, request.configuration)?.provider);\n\tconst environment = {};\n\tif (provider.webTools) environment[PI_WEB_TOOLS_SOCKET_ENV] = provider.webTools.socketPath;\n\tif (provider.mcpGateway) {\n\t\tenvironment.OPENTAG_MCP_GATEWAY_URL = provider.mcpGateway.url;\n\t\tenvironment.OPENTAG_MCP_GATEWAY_TOKEN = provider.mcpGateway.token;\n\t\tenvironment.OPENTAG_PI_MCP_ADAPTER_ENTRY = mcpAdapterEntry ?? fileURLToPath(import.meta.resolve(\"pi-mcp-adapter\"));\n\t}\n\treturn Object.keys(environment).length > 0 ? environment : void 0;\n}\nfunction boundedConfigurationString(value, field, maxBytes = AGENT_RUNTIME_TEXT_MAX_BYTES) {\n\tif (value === void 0) return void 0;\n\tif (typeof value !== \"string\" || value.trim().length === 0 || Buffer.byteLength(value, \"utf8\") > maxBytes) throw new AgentRuntimeError(\"configuration_invalid\", `Pi ${field} must be a non-empty bounded string`);\n\treturn value;\n}\nfunction mergeConfiguration(base, override) {\n\tif (!base) {\n\t\tvalidateConfiguration(override);\n\t\treturn override;\n\t}\n\tif (!override) return base;\n\tconst merged = {\n\t\t...base,\n\t\t...override,\n\t\tprovider: {\n\t\t\t...parseProviderConfiguration(base.provider),\n\t\t\t...parseProviderConfiguration(override.provider)\n\t\t}\n\t};\n\tvalidateConfiguration(merged);\n\treturn merged;\n}\nfunction piPolicyArguments(policy) {\n\tif (policy.fileSystem === \"read-only\") return [\"--tools\", PI_READ_ONLY_TOOLS.join(\",\")];\n\treturn [];\n}\nfunction piInput(request) {\n\treturn piItems(request.input.items);\n}\nfunction piItems(items) {\n\treturn items.map((item) => item.text).join(\"\\n\");\n}\nfunction piBinding(sessionId, sessionFileHash) {\n\treturn {\n\t\tproviderId: PI_PROVIDER_ID,\n\t\tschemaVersion: PI_BINDING_SCHEMA_VERSION,\n\t\tpayload: {\n\t\t\tsessionId,\n\t\t\t...sessionFileHash ? { sessionFileHash } : {}\n\t\t}\n\t};\n}\nfunction parsePiBinding(binding) {\n\tconst payload = record(binding.payload);\n\tif (!payload) throw new AgentRuntimeError(\"binding_incompatible\", \"Pi binding payload is invalid\");\n\tfor (const key of Object.keys(payload)) if (key !== \"sessionId\" && key !== \"sessionFileHash\") throw new AgentRuntimeError(\"binding_incompatible\", `Pi binding field is unsupported: ${key}`);\n\ttry {\n\t\tconst sessionId = requireUuid(payload.sessionId, \"Pi binding sessionId\");\n\t\tconst sessionFileHash = payload.sessionFileHash;\n\t\tif (sessionFileHash !== void 0 && (typeof sessionFileHash !== \"string\" || !/^[0-9a-f]{64}$/.test(sessionFileHash))) throw protocolError(\"Pi binding sessionFileHash is invalid\");\n\t\treturn {\n\t\t\tsessionId,\n\t\t\t...sessionFileHash ? { sessionFileHash } : {}\n\t\t};\n\t} catch (error) {\n\t\tlogger$5.debug({\n\t\t\tcode: \"binding_invalid\",\n\t\t\terror: String(error)\n\t\t}, \"Pi binding was rejected\");\n\t\tthrow new AgentRuntimeError(\"binding_incompatible\", error.message, { cause: error });\n\t}\n}\nfunction parseModel(value) {\n\tif (value === void 0 || value === null) return void 0;\n\tconst model = requireRecord(value, \"Pi get_state model is invalid\");\n\treturn {\n\t\tid: requireString$1(model.id, \"Pi get_state model has no id\"),\n\t\tprovider: requireString$1(model.provider, \"Pi get_state model has no provider\")\n\t};\n}\nfunction parseUsage(value) {\n\tconst usage = record(value);\n\tif (!usage) return void 0;\n\tconst result = {};\n\tconst input = isNonNegativeNumber(usage.input) ? usage.input : void 0;\n\tconst cacheWrite = isNonNegativeNumber(usage.cacheWrite) ? usage.cacheWrite : void 0;\n\tif (input !== void 0 || cacheWrite !== void 0) result.inputTokens = addTokenCounts(input, cacheWrite, \"input\");\n\tif (isNonNegativeNumber(usage.cacheRead)) result.cachedInputTokens = usage.cacheRead;\n\tif (isNonNegativeNumber(usage.output)) result.outputTokens = usage.output;\n\treturn hasUsage(result) ? result : void 0;\n}\nfunction addUsage(left, right) {\n\tconst inputTokens = addTokenCounts(left.inputTokens, right.inputTokens, \"input\");\n\tconst cachedInputTokens = addTokenCounts(left.cachedInputTokens, right.cachedInputTokens, \"cached input\");\n\tconst outputTokens = addTokenCounts(left.outputTokens, right.outputTokens, \"output\");\n\treturn {\n\t\t...inputTokens === void 0 ? {} : { inputTokens },\n\t\t...cachedInputTokens === void 0 ? {} : { cachedInputTokens },\n\t\t...outputTokens === void 0 ? {} : { outputTokens }\n\t};\n}\nfunction addTokenCounts(left, right, field) {\n\tif (left === void 0 && right === void 0) return void 0;\n\tconst total = (left ?? 0) + (right ?? 0);\n\tif (!Number.isSafeInteger(total)) throw protocolError(`Pi ${field} token usage overflowed`);\n\treturn total;\n}\nfunction hasUsage(usage) {\n\treturn usage.inputTokens !== void 0 || usage.cachedInputTokens !== void 0 || usage.outputTokens !== void 0;\n}\nfunction isIrrecoverablePiFailure(error) {\n\treturn error instanceof AgentProviderError || error instanceof PiRpcError && error.code !== \"command\";\n}\nfunction deferred() {\n\tlet resolvePromise;\n\tlet rejectPromise;\n\treturn {\n\t\tpromise: new Promise((resolve, reject) => {\n\t\t\tresolvePromise = resolve;\n\t\t\trejectPromise = reject;\n\t\t}),\n\t\tresolve: resolvePromise,\n\t\treject: rejectPromise\n\t};\n}\nfunction requireIndex(value) {\n\tif (!Number.isSafeInteger(value) || value < 0) throw protocolError(\"Pi content index is invalid\");\n\treturn value;\n}\nfunction requireUuid(value, field) {\n\tconst result = requireString$1(value, `${field} must be a UUID`);\n\tif (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(result)) throw protocolError(`${field} must be a UUID`);\n\treturn result;\n}\nfunction requireString$1(value, message, allowEmpty = false) {\n\tif (typeof value !== \"string\" || !allowEmpty && value.length === 0 || Buffer.byteLength(value, \"utf8\") > PI_RPC_EVENT_STRING_MAX_BYTES) throw protocolError(message);\n\treturn value;\n}\nconst PI_RPC_EVENT_STRING_MAX_BYTES = 8388608;\nfunction requireArray(value, message) {\n\tif (!Array.isArray(value)) throw protocolError(message);\n\treturn value;\n}\nfunction requireRecord(value, message) {\n\tconst result = record(value);\n\tif (!result) throw protocolError(message);\n\treturn result;\n}\nfunction record(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? value : void 0;\n}\nfunction toJsonValue(value) {\n\tassertJsonValue(value, \"Pi event payload\");\n\treturn value;\n}\nfunction protocolError(message) {\n\treturn new AgentProviderError(\"provider_protocol_error\", message);\n}\nfunction piFailedStopMessage(stopReason) {\n\tif (stopReason === \"length\") return \"Pi stopped because the model reached its output limit\";\n\tif (stopReason === \"toolUse\") return \"Pi stopped with unfinished tool use\";\n\treturn \"Pi model request failed\";\n}\n/**\n* The bounded compaction diagnostic text: Pi's own message when present (already sanitized for\n* Cloud executions by the model proxy's fixed error classes), truncated to a small bound so the\n* provider-warning budget can never fail the run, with a fixed fallback otherwise.\n*/\nfunction compactionDiagnostic(message) {\n\tconst raw = message.errorMessage;\n\tif (typeof raw !== \"string\" || raw.trim().length === 0) return message.aborted === true ? \"Pi context compaction was cancelled\" : \"Pi context compaction failed\";\n\tif (Buffer.byteLength(raw, \"utf8\") <= COMPACTION_DIAGNOSTIC_MAX_BYTES) return raw;\n\treturn `${Buffer.from(raw, \"utf8\").subarray(0, COMPACTION_DIAGNOSTIC_MAX_BYTES).toString(\"utf8\")}…`;\n}\nconst COMPACTION_DIAGNOSTIC_MAX_BYTES = 2048;\nfunction isNonNegativeNumber(value) {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\nfunction requireNonNegativeSafeInteger(value, message) {\n\tif (!isNonNegativeNumber(value)) throw protocolError(message);\n\treturn value;\n}\nfunction requireAbsolutePath(value, message) {\n\tconst path = requireString$1(value, message);\n\tif (!isAbsolute(path)) throw protocolError(message);\n\treturn path;\n}\nfunction requireStopReason(value, message) {\n\tconst stopReason = requireString$1(value, message);\n\tif (!PI_STOP_REASONS.has(stopReason)) throw protocolError(message);\n\treturn stopReason;\n}\nfunction fingerprint(value) {\n\treturn createHash(\"sha256\").update(value).digest(\"hex\");\n}\n/** Local event reference only; the original provider ID stays unchanged in Pi's Session and model requests. */\nfunction piToolEventId(id) {\n\treturn Buffer.byteLength(id, \"utf8\") <= 256 ? id : `pi-tool-${fingerprint(id)}`;\n}\n//#endregion\n//#region src/runtime/provider-cli/catalog.ts\nconst MIB = 1048576;\nconst LARK_VERSION = \"1.0.92\";\nconst LARK_RELEASE_BASE = `https://github.com/larksuite/cli/releases/download/v${LARK_VERSION}`;\nconst SLACK_VERSION = \"4.7.0\";\nconst SLACK_RELEASE_BASE = `https://downloads.slack-edge.com/slack-cli`;\nconst PROVIDER_CLI_CATALOG = [{\n\tprovider: \"feishu\",\n\tcommand: \"lark-cli\",\n\tdisplayName: \"Feishu/Lark CLI\",\n\tversion: LARK_VERSION,\n\tcompatibility: \">=1.0.92 <2.0.0\",\n\tprobes: {\n\t\tversionArgs: [\"--version\"],\n\t\tsurfaceArgs: [\"im\", \"--help\"],\n\t\tversionPattern: \"lark-cli version ([0-9]+\\\\.[0-9]+\\\\.[0-9]+(?:-[0-9A-Za-z.-]+)?)\",\n\t\ttimeoutMs: 1e4,\n\t\tmaxOutputBytes: MIB\n\t},\n\tmanagedEnvironment: {\n\t\tLARKSUITE_CLI_NO_UPDATE_NOTIFIER: \"1\",\n\t\tLARKSUITE_CLI_NO_SKILLS_NOTIFIER: \"1\"\n\t},\n\tmanagedArguments: [],\n\tlicense: {\n\t\tname: \"MIT\",\n\t\tcopyright: \"Copyright (c) 2026 Lark Technologies Pte. Ltd.\",\n\t\tnotices: \"lark-cli is published by Lark Technologies under the MIT License.\"\n\t},\n\tartifacts: [\n\t\t{\n\t\t\tplatform: \"darwin\",\n\t\t\tarch: \"arm64\",\n\t\t\tarchiveType: \"tar.gz\",\n\t\t\turl: `${LARK_RELEASE_BASE}/lark-cli-${LARK_VERSION}-darwin-arm64.tar.gz`,\n\t\t\tsha256: \"abb1b96eee5ad32da4e12f434e44d48a9e01ebb0e81772419ac0347f91c34265\",\n\t\t\tarchiveBytes: 13799162,\n\t\t\tmaxExtractedBytes: 50808410,\n\t\t\texecutablePath: \"lark-cli\",\n\t\t\texecutableSha256: \"d98aa671fc74c3c47a6f6b350bb7f1f59d730399df8d86e890e1cbba00c1beec\",\n\t\t\texecutableBytes: 46614106\n\t\t},\n\t\t{\n\t\t\tplatform: \"darwin\",\n\t\t\tarch: \"x64\",\n\t\t\tarchiveType: \"tar.gz\",\n\t\t\turl: `${LARK_RELEASE_BASE}/lark-cli-${LARK_VERSION}-darwin-amd64.tar.gz`,\n\t\t\tsha256: \"421b36f95966028fb047231cb6351c4224a0fdcb076d2bc434d4aed1bb6d1891\",\n\t\t\tarchiveBytes: 14949574,\n\t\t\tmaxExtractedBytes: 53766632,\n\t\t\texecutablePath: \"lark-cli\",\n\t\t\texecutableSha256: \"b7c125bb33e50fe6032adf6852be9a81ecd03d42ee3714a2a8ead964e0e6be2b\",\n\t\t\texecutableBytes: 49572328\n\t\t},\n\t\t{\n\t\t\tplatform: \"linux\",\n\t\t\tarch: \"x64\",\n\t\t\tarchiveType: \"tar.gz\",\n\t\t\turl: `${LARK_RELEASE_BASE}/lark-cli-${LARK_VERSION}-linux-amd64.tar.gz`,\n\t\t\tsha256: \"ef0e19799c1edd94eb52d3bb5d587e00d0a2898e0a4b407a1b8dc66d56181ef1\",\n\t\t\tarchiveBytes: 14185288,\n\t\t\tmaxExtractedBytes: 52060322,\n\t\t\texecutablePath: \"lark-cli\",\n\t\t\texecutableSha256: \"0317b9a76b2d8e27c9e787d89294a922af13ec8caa7eb610531a7f184617bba0\",\n\t\t\texecutableBytes: 47866018\n\t\t},\n\t\t{\n\t\t\tplatform: \"linux\",\n\t\t\tarch: \"arm64\",\n\t\t\tarchiveType: \"tar.gz\",\n\t\t\turl: `${LARK_RELEASE_BASE}/lark-cli-${LARK_VERSION}-linux-arm64.tar.gz`,\n\t\t\tsha256: \"683546b6754c780e0f828e87cb00ccf7c0710798a9f1ddb8c6b956afbfb570ae\",\n\t\t\tarchiveBytes: 13074832,\n\t\t\tmaxExtractedBytes: 48824482,\n\t\t\texecutablePath: \"lark-cli\",\n\t\t\texecutableSha256: \"22fe63fd7057044c80142e11792b3cd7989beaf435cdd4ecbfeacead837349e3\",\n\t\t\texecutableBytes: 44630178\n\t\t}\n\t]\n}, {\n\tprovider: \"slack\",\n\tcommand: \"slack\",\n\tdisplayName: \"Slack CLI\",\n\tversion: SLACK_VERSION,\n\tcompatibility: \">=4.2.0 <5.0.0\",\n\tprobes: {\n\t\tversionArgs: [\"version\"],\n\t\tsurfaceArgs: [\"api\", \"--help\"],\n\t\tversionPattern: \"Using slack v([0-9]+\\\\.[0-9]+\\\\.[0-9]+(?:-[0-9A-Za-z.-]+)?)\",\n\t\ttimeoutMs: 1e4,\n\t\tmaxOutputBytes: MIB\n\t},\n\tmanagedEnvironment: {},\n\tmanagedArguments: [\"--skip-update\"],\n\tlicense: {\n\t\tname: \"Apache-2.0\",\n\t\tcopyright: \"Copyright Slack Technologies, LLC\",\n\t\tnotices: \"Slack CLI is published by Slack Technologies under the Apache License 2.0.\"\n\t},\n\tartifacts: [\n\t\t{\n\t\t\tplatform: \"darwin\",\n\t\t\tarch: \"arm64\",\n\t\t\tarchiveType: \"tar.gz\",\n\t\t\turl: `${SLACK_RELEASE_BASE}/slack_cli_${SLACK_VERSION}_macOS_arm64.tar.gz`,\n\t\t\tsha256: \"ccb6dc5910e06e8b12ff4d9690d015b72f8a81249ea716e8829dddddfd39d404\",\n\t\t\tarchiveBytes: 7414910,\n\t\t\tmaxExtractedBytes: 24376144,\n\t\t\texecutablePath: \"bin/slack\",\n\t\t\texecutableSha256: \"61edbf3b490dc552fb223d623fbc10e01338db07043504f2cd01a6da349840aa\",\n\t\t\texecutableBytes: 20181840\n\t\t},\n\t\t{\n\t\t\tplatform: \"darwin\",\n\t\t\tarch: \"x64\",\n\t\t\tarchiveType: \"tar.gz\",\n\t\t\turl: `${SLACK_RELEASE_BASE}/slack_cli_${SLACK_VERSION}_macOS_amd64.tar.gz`,\n\t\t\tsha256: \"8a66be49be2e23cb19a08dc58fb1d7695eaad9b649556ea9a06a3f7c9b5142dc\",\n\t\t\tarchiveBytes: 8265622,\n\t\t\tmaxExtractedBytes: 26284272,\n\t\t\texecutablePath: \"bin/slack\",\n\t\t\texecutableSha256: \"cdb7ba5142c07192dea457d3f13f6f828e20618713205e4236a636fe0a46281e\",\n\t\t\texecutableBytes: 22089968\n\t\t},\n\t\t{\n\t\t\tplatform: \"linux\",\n\t\t\tarch: \"x64\",\n\t\t\tarchiveType: \"tar.gz\",\n\t\t\turl: `${SLACK_RELEASE_BASE}/slack_cli_${SLACK_VERSION}_linux_amd64.tar.gz`,\n\t\t\tsha256: \"9d06c481bca07c1afffd106462e5ad3a8748334eb3b09aba3911a557673b5429\",\n\t\t\tarchiveBytes: 8060859,\n\t\t\tmaxExtractedBytes: 25596066,\n\t\t\texecutablePath: \"bin/slack\",\n\t\t\texecutableSha256: \"54d9ea4405cea1fd9bb3803b1d243f699236d5ac2ae0fe8e2ac4c8a23cbb670f\",\n\t\t\texecutableBytes: 21401762\n\t\t},\n\t\t{\n\t\t\tplatform: \"linux\",\n\t\t\tarch: \"arm64\",\n\t\t\tarchiveType: \"tar.gz\",\n\t\t\turl: `${SLACK_RELEASE_BASE}/slack_cli_${SLACK_VERSION}_linux_arm64.tar.gz`,\n\t\t\tsha256: \"365834eda454783c6229a4cf5fe392df650d81a0465b8701c57b7c2a544db11a\",\n\t\t\tarchiveBytes: 7281730,\n\t\t\tmaxExtractedBytes: 23789730,\n\t\t\texecutablePath: \"bin/slack\",\n\t\t\texecutableSha256: \"0024b00f1c6cf8a41fffaaf8d5feb7dee58b814dec37bea58242e243c7f3e2fa\",\n\t\t\texecutableBytes: 19595426\n\t\t}\n\t]\n}];\nfunction findProviderCliCatalogEntry(provider, catalog = PROVIDER_CLI_CATALOG) {\n\treturn catalog.find((entry) => entry.provider === provider);\n}\nfunction requireProviderCliCatalogEntry(provider, catalog = PROVIDER_CLI_CATALOG) {\n\tconst entry = findProviderCliCatalogEntry(provider, catalog);\n\tif (!entry) throw new Error(`The reviewed Provider CLI catalog has no entry for ${provider}`);\n\treturn entry;\n}\n/** Find the reviewed artifact for one platform/architecture pair. */\nfunction findCatalogArtifact(entry, platform, arch) {\n\treturn entry.artifacts.find((artifact) => artifact.platform === platform && artifact.arch === arch);\n}\n/** Every reviewed executable digest for a provider; backs `catalog-verified` trust. */\nfunction catalogExecutableDigests(entry) {\n\treturn new Set(entry.artifacts.map((artifact) => artifact.executableSha256));\n}\n//#endregion\n//#region src/runner/catalog.ts\n/** Reviewed first-line banners of the pinned CLIs' surface help commands. */\nconst SURFACE_PATTERNS = {\n\t\"lark-cli\": /^Message and group chat management$/m,\n\tslack: /^Call any Slack API method directly\\.$/m\n};\n/** Linux amd64 artifacts from the reviewed catalog — the only Slack/Lark pin for the Runner image. */\nfunction linuxAmd64ProviderCliPlans(catalog = PROVIDER_CLI_CATALOG) {\n\treturn catalog.map((entry) => {\n\t\tconst artifact = findCatalogArtifact(entry, \"linux\", \"x64\");\n\t\tif (!artifact) throw new Error(`Provider CLI catalog has no linux/x64 artifact for ${entry.provider} ${entry.version}`);\n\t\tconst surfacePattern = SURFACE_PATTERNS[entry.command];\n\t\tif (!surfacePattern) throw new Error(`Provider CLI catalog has no reviewed surface pattern for ${entry.command}`);\n\t\treturn {\n\t\t\tprovider: entry.provider,\n\t\t\tcommand: entry.command,\n\t\t\tdisplayName: entry.displayName,\n\t\t\tversion: entry.version,\n\t\t\tprobes: entry.probes,\n\t\t\tmanagedEnvironment: entry.managedEnvironment,\n\t\t\tmanagedArguments: entry.managedArguments,\n\t\t\tartifact,\n\t\t\tentry,\n\t\t\tsurfacePattern\n\t\t};\n\t});\n}\n//#endregion\n//#region src/runner/probe.ts\nconst execFileAsync$1 = promisify(execFile);\nconst DEFAULT_TOOLS = [\n\t{\n\t\tname: \"node\",\n\t\targs: [\"--version\"]\n\t},\n\t{\n\t\tname: \"git\",\n\t\targs: [\"--version\"]\n\t},\n\t{\n\t\tname: \"gh\",\n\t\targs: [\"--version\"]\n\t},\n\t{\n\t\tname: \"pi\",\n\t\targs: [\"--version\"]\n\t},\n\t{\n\t\tname: \"context-tree\",\n\t\targs: [\"--version\"]\n\t},\n\t{\n\t\tname: \"opentag\",\n\t\targs: [\"--version\"]\n\t}\n];\n/** Anchored output patterns; capture group 1 is the exact version to compare. Never substring. */\nconst TOOL_VERSION_PATTERNS = {\n\tnode: /^(v\\d+\\.\\d+\\.\\d+)$/,\n\tgit: /^git version (\\d+\\.\\d+\\.\\d+)$/,\n\tgh: /^gh version (\\d+\\.\\d+\\.\\d+) \\([0-9-]+\\)$/,\n\tpi: /^(\\d+\\.\\d+\\.\\d+)$/,\n\t\"context-tree\": /^(\\d+\\.\\d+\\.\\d+)$/,\n\topentag: /^(\\d+\\.\\d+\\.\\d+(?:-staging\\.\\d+\\.\\d+)?)$/\n};\n/** The upstream Git version carried inside the Debian epoch pin, e.g. `1:2.39.5-0+deb12u3`. */\nfunction gitUpstreamVersion(identity) {\n\treturn /^\\d+:(\\d+\\.\\d+\\.\\d+)-/.exec(identity.toolLock.git ?? \"\")?.[1];\n}\n/** Exact expected versions derived from the image identity and the reviewed catalog. */\nfunction expectedFromIdentity(identity) {\n\tconst catalogVersions = Object.fromEntries(linuxAmd64ProviderCliPlans().map((plan) => [plan.command, plan.version]));\n\tconst git = gitUpstreamVersion(identity);\n\treturn {\n\t\tnode: identity.nodeVersion.startsWith(\"v\") ? identity.nodeVersion : `v${identity.nodeVersion}`,\n\t\t...git ? { git } : {},\n\t\t...identity.toolLock.gh ? { gh: identity.toolLock.gh } : {},\n\t\tpi: identity.piVersion,\n\t\t\"context-tree\": identity.contextTreeVersion,\n\t\topentag: identity.version,\n\t\t...catalogVersions\n\t};\n}\n/** Catalog patterns are grouped full-line matches (capture group 1 preserved), never substring. */\nfunction catalogLinePattern(catalogPattern) {\n\treturn new RegExp(`^(?:${catalogPattern})$`);\n}\n/**\n* A probe is ok only when the first output line matches the tool's anchored pattern and the\n* captured version equals the expected one exactly (`0.84.20` must never satisfy `0.84.2`).\n*/\nfunction evaluateVersionProbe(name, detail, expected, catalogPattern) {\n\tconst pattern = catalogPattern !== void 0 ? catalogLinePattern(catalogPattern) : TOOL_VERSION_PATTERNS[name];\n\tif (!pattern) return true;\n\tconst match = pattern.exec(detail);\n\tif (!match) return false;\n\tconst want = expected?.[name];\n\tif (want !== void 0 && match[1] !== want) return false;\n\treturn true;\n}\nasync function probeCommand(run, command, label, args, env, timeoutMs, evaluate) {\n\ttry {\n\t\tconst result = await run(command, [...args], {\n\t\t\tencoding: \"utf8\",\n\t\t\tenv,\n\t\t\ttimeout: timeoutMs,\n\t\t\twindowsHide: true\n\t\t});\n\t\tconst firstLine = `${result.stdout}${result.stderr}`.trim().split(/\\r?\\n/)[0] ?? \"\";\n\t\treturn {\n\t\t\tname: label,\n\t\t\tok: evaluate(firstLine),\n\t\t\t...firstLine ? { detail: firstLine.slice(0, 200) } : {}\n\t\t};\n\t} catch (error) {\n\t\tconst detail = probeFailureDetail(error);\n\t\treturn {\n\t\t\tname: label,\n\t\t\tok: false,\n\t\t\t...detail ? { detail } : {}\n\t\t};\n\t}\n}\n/**\n* Best-effort diagnostic text for a failed probe command. execFile rejects with `stdout`/`stderr`\n* as (possibly empty) strings; `??` never falls through an empty string, so an empty capture must\n* explicitly fall back to the failure message or the error itself. Signal/killed/code metadata is\n* preserved when present so a native startup timeout or kill is diagnosable without a re-run.\n*/\nfunction probeFailureDetail(error) {\n\tconst err = error;\n\tconst captured = `${err.stdout ?? \"\"}${err.stderr ?? \"\"}`.trim();\n\tconst fallback = (typeof err.message === \"string\" ? err.message : String(error)).trim();\n\tconst status = [\n\t\terr.code !== void 0 && err.code !== null ? `code=${err.code}` : \"\",\n\t\terr.signal ? `signal=${err.signal}` : \"\",\n\t\terr.killed ? \"killed\" : \"\"\n\t].filter((part) => part.length > 0).join(\" \");\n\treturn `${captured || fallback}${status ? ` (${status})` : \"\"}`.trim().slice(0, 400);\n}\nasync function probeRunnerTools(options = {}) {\n\tconst run = options.execFile ?? execFileAsync$1;\n\tconst timeoutMs = options.timeoutMs ?? 1e4;\n\tconst env = {\n\t\t...options.env ?? process.env,\n\t\tHOME: options.env?.HOME ?? \"/nonexistent-runner-home\"\n\t};\n\tconst results = [];\n\tfor (const tool of DEFAULT_TOOLS) results.push(await probeCommand(run, tool.name, tool.name, tool.args, env, (tool.name === \"pi\" ? options.piTimeoutMs : void 0) ?? timeoutMs, (detail) => evaluateVersionProbe(tool.name, detail, options.expected)));\n\tfor (const plan of linuxAmd64ProviderCliPlans()) {\n\t\tresults.push(await probeCommand(run, plan.command, plan.command, plan.probes.versionArgs, env, timeoutMs, (detail) => evaluateVersionProbe(plan.command, detail, options.expected, plan.probes.versionPattern)));\n\t\tresults.push(await probeCommand(run, plan.command, `${plan.command}:surface`, plan.probes.surfaceArgs, env, timeoutMs, (detail) => plan.surfacePattern.test(detail)));\n\t}\n\treturn results;\n}\nfunction runnerToolsReady(probes) {\n\treturn probes.every((probe) => probe.ok);\n}\n//#endregion\n//#region src/runner/processes.ts\nconst execFileAsync = promisify(execFile);\nasync function readProcChildren(pid) {\n\ttry {\n\t\tconst { stdout } = await execFileAsync(\"ps\", [\n\t\t\t\"ax\",\n\t\t\t\"-o\",\n\t\t\t\"pid=,ppid=\"\n\t\t], {\n\t\t\tencoding: \"utf8\",\n\t\t\ttimeout: 2e3,\n\t\t\twindowsHide: true\n\t\t});\n\t\tconst children = [];\n\t\tfor (const line of stdout.split(\"\\n\")) {\n\t\t\tconst [child, parent] = line.trim().split(/\\s+/).map(Number);\n\t\t\tif (parent === pid && typeof child === \"number\" && Number.isInteger(child) && child > 1) children.push(child);\n\t\t}\n\t\treturn children;\n\t} catch {\n\t\treturn [];\n\t}\n}\nasync function processExists(pid) {\n\ttry {\n\t\tawait access(`/proc/${pid}`);\n\t\treturn true;\n\t} catch {\n\t\ttry {\n\t\t\tprocess.kill(pid, 0);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n}\nasync function collectDescendantPids(pid, listChildren = readProcChildren) {\n\tconst found = /* @__PURE__ */ new Set();\n\tconst queue = [pid];\n\twhile (queue.length > 0) {\n\t\tconst current = queue.shift();\n\t\tif (current === void 0 || found.has(current)) continue;\n\t\tfound.add(current);\n\t\tfor (const child of await listChildren(current)) queue.push(child);\n\t}\n\treturn [...found];\n}\nasync function waitForProcessTreeGone(pids, options = {}) {\n\tconst timeoutMs = options.timeoutMs ?? 1e4;\n\tconst exists = options.exists ?? processExists;\n\tconst deadline = Date.now() + timeoutMs;\n\tfor (;;) {\n\t\tconst live = [];\n\t\tfor (const pid of pids) if (await exists(pid)) live.push(pid);\n\t\tif (live.length === 0) return;\n\t\tif (Date.now() >= deadline) throw new Error(`process tree still alive: ${live.join(\", \")}`);\n\t\tawait new Promise((resolve) => setTimeout(resolve, 50));\n\t}\n}\n//#endregion\n//#region src/runner/redact.ts\nconst JSON_SECRET_FIELD = /(\"[^\"]*(?:api[_-]?key|key|token|secret|password|authorization)[^\"]*\"\\s*:\\s*\")((?:\\\\.|[^\"\\\\])+)(\")/gi;\nconst SECRET_PATTERN = /(api[_-]?key|token|secret|password|authorization|bearer)(=|\\s*[:=]\\s*)((?:bearer\\s+)?[^\\s\"',}]+)/gi;\nconst BEARER_STANDALONE = /\\b(bearer)\\s+([^\\s\"',}]+)/gi;\nconst KEY_LIKE = /\\b(?:sk-|rk-|ghp_|xox[baprs]-)[A-Za-z0-9_-]{8,}\\b/g;\nconst ENV_ASSIGNMENT = /\\b([A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL))\\s*=\\s*([^\\s]+)/g;\nfunction redactText(value) {\n\treturn value.replace(JSON_SECRET_FIELD, \"$1[redacted]$3\").replace(SECRET_PATTERN, \"$1$2[redacted]\").replace(BEARER_STANDALONE, (_match, scheme) => `${scheme} [redacted]`).replace(KEY_LIKE, \"[redacted]\").replace(ENV_ASSIGNMENT, \"$1=[redacted]\");\n}\nfunction redactUnknown(value, depth) {\n\tif (depth > 8) return \"[truncated]\";\n\tif (typeof value === \"string\") return redactText(value);\n\tif (typeof value !== \"object\" || value === null) return value;\n\tif (Array.isArray(value)) return value.map((entry) => redactUnknown(entry, depth + 1));\n\tconst record = {};\n\tfor (const [key, entry] of Object.entries(value)) {\n\t\tconst lower = key.toLowerCase();\n\t\tif (lower.includes(\"key\") || lower.includes(\"token\") || lower.includes(\"secret\") || lower.includes(\"password\") || lower.includes(\"authorization\") || lower.includes(\"credential\")) {\n\t\t\trecord[key] = \"[redacted]\";\n\t\t\tcontinue;\n\t\t}\n\t\trecord[key] = redactUnknown(entry, depth + 1);\n\t}\n\treturn record;\n}\n/** Redact secrets from acceptance events. Failures stay visible; only sensitive content is removed. */\nfunction redactAcceptanceRecord(value) {\n\treturn redactUnknown(value, 0);\n}\n//#endregion\n//#region src/storage/context-tree-home.ts\n/** The OS account home, canonicalized where possible. Shared with the standalone Context Tree CLI. */\nfunction resolveAccountHome(environment = process.env) {\n\tlet home = resolve((process.platform === \"win32\" ? environment.USERPROFILE : environment.HOME) || homedir());\n\ttry {\n\t\thome = realpathSync(home);\n\t} catch {}\n\treturn home;\n}\n/** Account storage shared with the standalone Context Tree CLI, independent of OPENTAG_HOME. */\nfunction resolveContextTreeHome(environment = process.env) {\n\treturn { directory: join(resolveAccountHome(environment), \".context-tree\") };\n}\nasync function prepareContextTreeHome(environment = process.env) {\n\tconst { directory } = resolveContextTreeHome(environment);\n\ttry {\n\t\tawait ensureOneDirectory(directory);\n\t} catch (error) {\n\t\tif (error instanceof RuntimeStorageError) throw new RuntimeStorageError(\"unsafe\", `Context Tree managed directory must be a real directory: ${directory}`);\n\t\tthrow error;\n\t}\n\treturn directory;\n}\n//#endregion\n//#region src/runtime/context-tree-connections.ts\nconst PathSchema = z.string().min(1).refine((path) => isAbsolute(path) && !/[\\r\\n\\0]/u.test(path));\nconst TreeSchema = z.discriminatedUnion(\"kind\", [z.object({\n\tkind: z.literal(\"github\"),\n\tpath: PathSchema,\n\trepository: ContextTreeRepositorySchema\n}).strict(), z.object({\n\tkind: z.literal(\"local\"),\n\tpath: PathSchema\n}).strict()]);\nconst StoredConnectionsSchema = z.object({\n\tschemaVersion: z.literal(2),\n\tconnections: z.array(z.object({\n\t\talias: ContextTreeAliasSchema,\n\t\tprojectPath: PathSchema,\n\t\ttree: TreeSchema\n\t}).strict())\n}).strict();\nconst DiscoverySchema = z.object({\n\tschemaVersion: z.literal(2),\n\tconnections: z.array(z.object({\n\t\talias: ContextTreeAliasSchema,\n\t\ttree: TreeSchema,\n\t\tok: z.boolean(),\n\t\terror: z.object({ code: z.string() }).optional(),\n\t\tbranch: z.string().optional(),\n\t\tsha: z.string().optional()\n\t}))\n});\nconst ConnectedSchema = z.object({\n\tschemaVersion: z.literal(2),\n\talias: ContextTreeAliasSchema,\n\ttree: TreeSchema\n});\nfunction connectedTree(payload, connection) {\n\tconst parsed = ConnectedSchema.safeParse(payload);\n\tif (!parsed.success || parsed.data.alias !== connection.alias || parsed.data.tree.kind !== \"github\" || parsed.data.tree.repository.toLowerCase() !== connection.repository.toLowerCase()) return void 0;\n\treturn parsed.data.tree;\n}\nfunction syncedTree(payload, connection) {\n\tconst parsed = DiscoverySchema.safeParse(payload);\n\treturn parsed.success ? parsed.data.connections.find((entry) => entry.alias === connection.alias && entry.tree.kind === \"github\" && entry.tree.repository.toLowerCase() === connection.repository.toLowerCase()) : void 0;\n}\n/** Remove linkage through the CLI only. Checkouts and unpublished work are never deleted. */\nasync function reconcileContextTreeConnections(run, workspace, wanted) {\n\tconst attachedAliases = /* @__PURE__ */ new Set();\n\tconst discovered = await run([\n\t\t\"resolve\",\n\t\t\"--project-path\",\n\t\tworkspace,\n\t\t\"--json\"\n\t], false);\n\tif (discovered.failureCode === \"NO_CONNECTION\") return { attachedAliases };\n\tconst parsed = DiscoverySchema.safeParse(discovered.payload);\n\tif (!parsed.success) return {\n\t\tfailureCode: discovered.failureCode ?? \"UNSUPPORTED_CONNECTIONS\",\n\t\tattachedAliases\n\t};\n\tfor (const entry of parsed.data.connections) {\n\t\tif (wanted.some((connection) => connection.alias === entry.alias && entry.tree.kind === \"github\" && connection.repository.toLowerCase() === entry.tree.repository.toLowerCase())) {\n\t\t\tif (entry.ok) attachedAliases.add(entry.alias);\n\t\t\tcontinue;\n\t\t}\n\t\tconst removed = await run([\n\t\t\t\"disconnect\",\n\t\t\t\"--tree\",\n\t\t\tentry.alias,\n\t\t\t\"--project-path\",\n\t\t\tworkspace,\n\t\t\t\"--json\"\n\t\t], false);\n\t\tif (removed.failureCode) return {\n\t\t\tfailureCode: removed.failureCode,\n\t\t\tattachedAliases\n\t\t};\n\t}\n\treturn { attachedAliases };\n}\n//#endregion\n//#region src/runtime/context-tree.ts\n/** Context Tree commands are local and bounded; a hung CLI must not stall Session start. */\nconst CLI_TIMEOUT_MS = 2e4;\n/** A GitHub target clones on first use, so its first connect is allowed to take longer. */\nconst CLI_NETWORK_TIMEOUT_MS = 12e4;\n/** SIGTERM grace before SIGKILL; the owned tree is awaited either way. */\nconst CLI_KILL_GRACE_MS = 2e3;\nconst CLI_MAX_BUFFER = 1048576;\nconst SESSION_START_BUDGET_MS = 5e3;\nconst FAILURE_COOLDOWN_MS = 6e4;\nfunction cliProcessError(message, fields) {\n\treturn Object.assign(new Error(message), fields);\n}\nfunction cliAbortError(message) {\n\treturn cliProcessError(message, {\n\t\tkilled: true,\n\t\tsignal: \"SIGTERM\",\n\t\tstdout: \"\"\n\t});\n}\nfunction cliExitError(terminating, bufferExceeded, code, signal, stdout) {\n\tif (!terminating && !bufferExceeded && code === 0) return void 0;\n\treturn cliProcessError(`Context Tree CLI exited with ${code ?? signal ?? \"unknown\"}`, {\n\t\tkilled: terminating,\n\t\tstdout,\n\t\t...terminating ? { signal: \"SIGTERM\" } : signal ? { signal } : {}\n\t});\n}\nfunction signalOwned(pid, signal, detached) {\n\ttry {\n\t\tif (detached) process.kill(-pid, signal);\n\t\telse process.kill(pid, signal);\n\t} catch {\n\t\ttry {\n\t\t\tprocess.kill(pid, signal);\n\t\t} catch {}\n\t}\n}\n/**\n* Stop the CLI and every descendant it owns. `git` children are detached into their own process\n* groups, so the CLI group alone is not the whole tree: enumerate descendants before signalling,\n* stop each group, escalate after a grace period, and resolve only once none remain.\n*/\nfunction createOwnedTreeStopper(child, detached) {\n\tlet stopped;\n\treturn () => {\n\t\tstopped ??= (async () => {\n\t\t\tconst descendants = child.pid === void 0 ? [] : await collectDescendantPids(child.pid);\n\t\t\tconst pids = [child.pid, ...descendants].filter((pid) => typeof pid === \"number\");\n\t\t\tfor (const pid of pids) signalOwned(pid, \"SIGTERM\", detached);\n\t\t\ttry {\n\t\t\t\tawait waitForProcessTreeGone(pids, { timeoutMs: CLI_KILL_GRACE_MS });\n\t\t\t\treturn;\n\t\t\t} catch {}\n\t\t\tfor (const pid of pids) signalOwned(pid, \"SIGKILL\", detached);\n\t\t\tawait waitForProcessTreeGone(pids, { timeoutMs: CLI_KILL_GRACE_MS }).catch(() => void 0);\n\t\t})();\n\t\treturn stopped;\n\t};\n}\n/**\n* Production exec: one CLI child in its own process group. `execFile` signals only the direct\n* child, so a nested `git` would keep mutating the workspace after the caller stopped waiting.\n* A timeout or abort therefore stops the whole owned tree and the returned promise settles only\n* after those processes are gone.\n*/\nconst defaultExecFile = (file, args, options) => new Promise((resolveRun, rejectRun) => {\n\tif (options.signal?.aborted) {\n\t\trejectRun(cliAbortError(\"Context Tree CLI was aborted before it started\"));\n\t\treturn;\n\t}\n\tconst detached = process.platform !== \"win32\";\n\tconst child = spawn(file, [...args], {\n\t\tcwd: options.cwd,\n\t\tdetached,\n\t\tenv: options.env,\n\t\tstdio: [\n\t\t\t\"ignore\",\n\t\t\t\"pipe\",\n\t\t\t\"pipe\"\n\t\t],\n\t\twindowsHide: options.windowsHide\n\t});\n\tlet stdout = \"\";\n\tlet bufferExceeded = false;\n\tlet settled = false;\n\tlet terminating = false;\n\tlet cleanup;\n\tconst stopOwnedTree = createOwnedTreeStopper(child, detached);\n\tconst terminate = () => {\n\t\tif (terminating) return;\n\t\tterminating = true;\n\t\tcleanup = stopOwnedTree();\n\t};\n\tconst timer = setTimeout(terminate, options.timeout);\n\ttimer.unref?.();\n\toptions.signal?.addEventListener(\"abort\", terminate, { once: true });\n\tconst finish = (error) => {\n\t\tif (settled) return;\n\t\tsettled = true;\n\t\tclearTimeout(timer);\n\t\toptions.signal?.removeEventListener(\"abort\", terminate);\n\t\tif (error) rejectRun(error);\n\t\telse resolveRun({ stdout });\n\t};\n\tchild.stdout?.on(\"data\", (chunk) => {\n\t\tstdout += chunk.toString(\"utf8\");\n\t\tif (!bufferExceeded && stdout.length > options.maxBuffer) {\n\t\t\tbufferExceeded = true;\n\t\t\tterminate();\n\t\t}\n\t});\n\tchild.stderr?.resume();\n\tchild.once(\"error\", (error) => {\n\t\tfinish(cliProcessError(error.message, {\n\t\t\tkilled: terminating,\n\t\t\tstdout,\n\t\t\t...terminating ? { signal: \"SIGTERM\" } : {}\n\t\t}));\n\t});\n\tchild.once(\"close\", (code, signal) => {\n\t\tconst error = cliExitError(terminating, bufferExceeded, code, signal, stdout);\n\t\tconst complete = () => finish(error);\n\t\tif (cleanup) cleanup.then(complete, complete);\n\t\telse complete();\n\t});\n});\nfunction resolveContextTreePackage(from = import.meta.url) {\n\ttry {\n\t\tconst root = dirname(createRequire(from).resolve(\"@first-tree-ai/context-tree/package.json\"));\n\t\treturn {\n\t\t\troot,\n\t\t\tcliPath: join(root, \"dist\", \"cli\", \"index.mjs\"),\n\t\t\tskillsPath: join(root, \"skills\")\n\t\t};\n\t} catch {\n\t\treturn;\n\t}\n}\nvar ContextTreeCliFailure = class extends Error {\n\treason;\n\tconstructor(reason) {\n\t\tsuper(reason);\n\t\tthis.reason = reason;\n\t\tthis.name = \"ContextTreeCliFailure\";\n\t}\n};\n/**\n* The failure code in one CLI payload, or undefined when it reports success.\n*\n* Most commands use an `error.code` envelope, but `verify` reports an unusable tree as\n* `ok: false` with findings instead, so the flag has to be honoured on its own.\n*/\nfunction contextTreeFailureCode(payload) {\n\tif (typeof payload !== \"object\" || payload === null) return \"CLI_FAILED\";\n\tconst record = payload;\n\tif (typeof record.error?.code === \"string\") return record.error.code;\n\tif (record.ok !== false) return void 0;\n\tconst finding = record.findings?.find((entry) => typeof entry.code === \"string\")?.code;\n\treturn typeof finding === \"string\" ? finding : \"INVALID_TREE\";\n}\n/**\n* Why the Codex host install did not install, or undefined when it did.\n*\n* The CLI reports a missing host as a `skipped` entry with an explanatory reason rather than as a\n* failure, so the payload itself has to be inspected: claiming `ready` while the Agent has no\n* skills is the worst available outcome.\n*/\nfunction codexInstallSkipReason(payload) {\n\tif (typeof payload !== \"object\" || payload === null) return \"CODEX_INSTALL_FAILED\";\n\tconst record = payload;\n\tif ((record.installed ?? []).some((entry) => entry.host === \"codex\")) return void 0;\n\tconst reason = (record.skipped ?? []).find((entry) => entry.host === \"codex\")?.reason;\n\treturn typeof reason === \"string\" && reason.length > 0 ? reason : \"CODEX_NOT_INSTALLED\";\n}\n/**\n* Run one Context Tree command and return its single JSON line.\n*\n* The CLI reports operational failures as JSON on stdout with exit code 1, and sometimes with\n* exit code 0, so the payload is authoritative and the exit code is not.\n*/\nasync function runContextTreeCli(contextTreePackage, args, options = {}) {\n\tconst run = options.execFile ?? defaultExecFile;\n\tlet stdout;\n\ttry {\n\t\t({stdout} = await run(options.nodePath ?? process.execPath, [contextTreePackage.cliPath, ...args], {\n\t\t\tcwd: options.cwd ?? process.cwd(),\n\t\t\tmaxBuffer: CLI_MAX_BUFFER,\n\t\t\ttimeout: options.network === true ? CLI_NETWORK_TIMEOUT_MS : CLI_TIMEOUT_MS,\n\t\t\twindowsHide: true,\n\t\t\t...options.signal ? { signal: options.signal } : {},\n\t\t\t...options.env ? { env: options.env } : {}\n\t\t}));\n\t} catch (error) {\n\t\tconst failure = error;\n\t\tif (failure.killed === true || failure.signal === \"SIGTERM\") return {\n\t\t\tpayload: void 0,\n\t\t\tfailureCode: \"TIMEOUT\"\n\t\t};\n\t\tstdout = typeof failure.stdout === \"string\" ? failure.stdout : \"\";\n\t}\n\tlet payload;\n\ttry {\n\t\tpayload = JSON.parse(stdout.trim());\n\t} catch {\n\t\treturn {\n\t\t\tpayload: void 0,\n\t\t\tfailureCode: \"CLI_FAILED\"\n\t\t};\n\t}\n\tconst failureCode = contextTreeFailureCode(payload);\n\treturn failureCode === void 0 ? { payload } : {\n\t\tpayload,\n\t\tfailureCode\n\t};\n}\n/**\n* Owns each Agent's optional Context Tree wiring for Sessions.\n*\n* The repository comes from the Agent runtime snapshot; local legacy configuration is ignored.\n*\n* Every operation here is optional memory, never a Session availability dependency: each failure\n* is reported through the managed prompt, and nothing in this class throws into Session start.\n*/\nvar ContextTreeManager = class {\n\t#home;\n\t#environment;\n\t#logger;\n\t#managedCredentials;\n\t#package;\n\t#execFile;\n\t#platform;\n\t#nodePath;\n\t#codexHome;\n\t#sessionStartBudgetMs;\n\t#failureCooldownMs;\n\t#cache = /* @__PURE__ */ new Map();\n\t#inFlight = /* @__PURE__ */ new Map();\n\t#observedTarget = /* @__PURE__ */ new Map();\n\t#skillsInstalled = /* @__PURE__ */ new Set();\n\t#shimPreparation;\n\t#shimRetryAt = 0;\n\t#pending = Promise.resolve();\n\tconstructor(options) {\n\t\tthis.#home = resolve(options.home);\n\t\tthis.#environment = { ...options.environment ?? process.env };\n\t\tthis.#logger = options.logger ?? createLogger(\"context-tree\");\n\t\tthis.#managedCredentials = options.managedCredentials === true;\n\t\tthis.#package = options.contextTreePackage === void 0 ? resolveContextTreePackage() : options.contextTreePackage ?? void 0;\n\t\tthis.#execFile = options.execFile;\n\t\tthis.#platform = options.platform ?? process.platform;\n\t\tthis.#nodePath = options.nodePath ?? process.execPath;\n\t\tthis.#codexHome = resolve(options.codexHome ?? join(resolveAccountHome(this.#environment), \".codex\"));\n\t\tthis.#sessionStartBudgetMs = options.sessionStartBudgetMs ?? SESSION_START_BUDGET_MS;\n\t\tthis.#failureCooldownMs = options.failureCooldownMs ?? FAILURE_COOLDOWN_MS;\n\t}\n\t/** Directory to prepend to a Session PATH so the packaged skills can invoke `context-tree`. */\n\tbinDirectory() {\n\t\treturn resolveOpenTagHomeLayout(this.#home).contextTreeBin;\n\t}\n\t/**\n\t* Resolve Context Tree for one Agent workspace, connecting it on first use.\n\t*\n\t* `cwd` must come from `AgentWorkspaceManager.cwd(agentId)`, which refuses to return a path\n\t* until the workspace layout state is schema-v3 `complete`. That ordering is what keeps the\n\t* connection from writing into a workspace still mid-migration.\n\t*/\n\tasync ensureAgent(cwd, provider, connections = [], environment) {\n\t\tconst ordered = normalizeContextTrees(connections);\n\t\tconst target = JSON.stringify([provider ?? \"codex\", ordered]);\n\t\tif (this.#observedTarget.get(cwd) !== target) {\n\t\t\tthis.#observedTarget.set(cwd, target);\n\t\t\tthis.#cache.delete(cwd);\n\t\t}\n\t\tconst identity = JSON.stringify([target, this.#managedCredentials ? environment?.OPENTAG_GITHUB_REPOSITORIES ?? null : null]);\n\t\tlet active = this.#inFlight.get(cwd);\n\t\tif (active?.target !== identity) {\n\t\t\tconst results = this.#initialResults(cwd, connections, environment);\n\t\t\tconst promise = this.#serialize(() => this.#prepareSafely(cwd, provider, connections, target, results, environment));\n\t\t\tactive = {\n\t\t\t\ttarget: identity,\n\t\t\t\tresults,\n\t\t\t\tpromise\n\t\t\t};\n\t\t\tthis.#inFlight.set(cwd, active);\n\t\t\tpromise.finally(() => {\n\t\t\t\tif (this.#inFlight.get(cwd)?.promise === promise) this.#inFlight.delete(cwd);\n\t\t\t});\n\t\t}\n\t\tlet timer;\n\t\tconst pending = active;\n\t\tconst budget = new Promise((resolveBudget) => {\n\t\t\ttimer = setTimeout(() => resolveBudget(connections.length ? {\n\t\t\t\tstatus: \"configured\",\n\t\t\t\tconnections: [...pending.results]\n\t\t\t} : {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\treason: \"PREPARING\"\n\t\t\t}), this.#sessionStartBudgetMs);\n\t\t\ttimer.unref();\n\t\t});\n\t\ttry {\n\t\t\treturn await Promise.race([active.promise, budget]);\n\t\t} finally {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t}\n\t}\n\t#initialResults(cwd, connections, environment) {\n\t\tconst cache = this.#cache.get(cwd);\n\t\treturn connections.map((connection) => {\n\t\t\tconst denied = this.#managedFailure(connection.repository, environment);\n\t\t\tif (denied) return {\n\t\t\t\t...connection,\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\treason: denied\n\t\t\t};\n\t\t\tconst cached = cache?.results.get(connection.alias);\n\t\t\tif (cached?.result.status === \"ready\") return cached.result;\n\t\t\tif (cached && cached.retryAt > Date.now()) return cached.result;\n\t\t\treturn {\n\t\t\t\t...connection,\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\treason: \"PREPARING\"\n\t\t\t};\n\t\t});\n\t}\n\tasync #prepareSafely(cwd, provider, connections, target, results, environment) {\n\t\tif (this.#managedCredentials && !environment) return connections.length ? {\n\t\t\tstatus: \"configured\",\n\t\t\tconnections: [...results]\n\t\t} : { status: \"unconfigured\" };\n\t\ttry {\n\t\t\treturn await this.#prepareConnections(cwd, provider, connections, target, results, environment);\n\t\t} catch (error) {\n\t\t\tconst reason = error instanceof ContextTreeCliFailure ? error.reason : \"CLI_FAILED\";\n\t\t\tconnections.forEach((connection, index) => {\n\t\t\t\tif (results[index]?.status !== \"ready\") results[index] = {\n\t\t\t\t\t...connection,\n\t\t\t\t\tstatus: \"unavailable\",\n\t\t\t\t\treason\n\t\t\t\t};\n\t\t\t});\n\t\t\treturn connections.length ? {\n\t\t\t\tstatus: \"configured\",\n\t\t\t\tconnections: [...results]\n\t\t\t} : {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\treason\n\t\t\t};\n\t\t}\n\t}\n\tasync #prepareConnections(cwd, provider, connections, target, results, environment) {\n\t\tconst failAll = (reason) => {\n\t\t\tconnections.forEach((entry, index) => {\n\t\t\t\tresults[index] = {\n\t\t\t\t\t...entry,\n\t\t\t\t\tstatus: \"unavailable\",\n\t\t\t\t\treason\n\t\t\t\t};\n\t\t\t});\n\t\t\treturn connections.length ? {\n\t\t\t\tstatus: \"configured\",\n\t\t\t\tconnections: [...results]\n\t\t\t} : {\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\treason\n\t\t\t};\n\t\t};\n\t\tconst pack = this.#package;\n\t\tif (!pack) return connections.length ? failAll(\"PACKAGE_MISSING\") : { status: \"unconfigured\" };\n\t\tconst permitted = connections.filter((entry) => !this.#managedFailure(entry.repository, environment));\n\t\tconst run = (args, network) => runContextTreeCli(pack, args, {\n\t\t\tcwd,\n\t\t\tnetwork,\n\t\t\tnodePath: this.#nodePath,\n\t\t\tenv: mergeContextTreeEnvironment(this.#environment, environment),\n\t\t\t...this.#execFile ? { execFile: this.#execFile } : {}\n\t\t});\n\t\tconst reconciliation = await reconcileContextTreeConnections(run, cwd, permitted);\n\t\tif (reconciliation.failureCode) return failAll(reconciliation.failureCode);\n\t\tconst previousCache = this.#cache.get(cwd);\n\t\tfor (const [alias, cached] of previousCache?.results ?? []) if (cached.result.status === \"ready\" && !reconciliation.attachedAliases.has(alias)) previousCache?.results.delete(alias);\n\t\tconst shimReady = await this.#prepareShim();\n\t\tif (!connections.length) return { status: \"unconfigured\" };\n\t\tif (!shimReady) return failAll(\"SHIM_UNAVAILABLE\");\n\t\tconst installFailure = await this.#installSkills(cwd, provider, environment);\n\t\tif (installFailure) return failAll(installFailure);\n\t\treturn this.#connectAll(cwd, connections, target, results, environment);\n\t}\n\tasync #installSkills(cwd, provider, environment) {\n\t\tif (provider === \"pi\" || this.#skillsInstalled.has(cwd)) return void 0;\n\t\tawait this.#run([\n\t\t\t\"install\",\n\t\t\t\"--host\",\n\t\t\t\"claude\",\n\t\t\t\"--project\",\n\t\t\tcwd\n\t\t], cwd, false, environment);\n\t\tconst failure = codexInstallSkipReason(await this.#run([\n\t\t\t\"install\",\n\t\t\t\"--host\",\n\t\t\t\"codex\"\n\t\t], cwd, false, {\n\t\t\t...this.#environment,\n\t\t\tHOME: resolveAccountHome(this.#environment),\n\t\t\tCODEX_HOME: this.#codexHome\n\t\t}));\n\t\tif (!failure) this.#skillsInstalled.add(cwd);\n\t\treturn failure;\n\t}\n\tasync #connectAll(cwd, connections, target, results, environment) {\n\t\tlet cache = this.#cache.get(cwd);\n\t\tif (cache?.target !== target) {\n\t\t\tcache = {\n\t\t\t\ttarget,\n\t\t\t\tresults: /* @__PURE__ */ new Map()\n\t\t\t};\n\t\t\tif (this.#observedTarget.get(cwd) === target) this.#cache.set(cwd, cache);\n\t\t}\n\t\tfor (const [index, connection] of connections.entries()) {\n\t\t\tconst denied = this.#managedFailure(connection.repository, environment);\n\t\t\tif (denied) {\n\t\t\t\tresults[index] = {\n\t\t\t\t\t...connection,\n\t\t\t\t\tstatus: \"unavailable\",\n\t\t\t\t\treason: denied\n\t\t\t\t};\n\t\t\t\tcache.results.delete(connection.alias);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst cached = cache.results.get(connection.alias);\n\t\t\tif (cached && (cached.result.status === \"ready\" || cached.retryAt > Date.now())) {\n\t\t\t\tresults[index] = cached.result;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst result = await this.#connect(cwd, connection, environment);\n\t\t\tresults[index] = result;\n\t\t\tcache.results.set(connection.alias, {\n\t\t\t\tresult,\n\t\t\t\tretryAt: Date.now() + this.#failureCooldownMs\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tstatus: \"configured\",\n\t\t\tconnections: [...results]\n\t\t};\n\t}\n\t#managedFailure(repository, environment) {\n\t\tif (!this.#managedCredentials) return void 0;\n\t\tif (!environment) return \"AUTHENTICATION_REQUIRED\";\n\t\treturn managedRepositoryAllowed(environment, repository) ? void 0 : \"GITHUB_PERMISSION\";\n\t}\n\tasync #connect(cwd, connection, environment) {\n\t\ttry {\n\t\t\tconst tree = connectedTree(await this.#run([\n\t\t\t\t\"connect\",\n\t\t\t\tconnection.repository,\n\t\t\t\t\"--as\",\n\t\t\t\tconnection.alias,\n\t\t\t\t\"--project-path\",\n\t\t\t\tcwd,\n\t\t\t\t\"--json\"\n\t\t\t], cwd, true, environment), connection);\n\t\t\treturn tree ? {\n\t\t\t\t...connection,\n\t\t\t\tstatus: \"ready\",\n\t\t\t\ttreePath: tree.path\n\t\t\t} : {\n\t\t\t\t...connection,\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\treason: \"CONNECT_FAILED\"\n\t\t\t};\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\t...connection,\n\t\t\t\tstatus: \"unavailable\",\n\t\t\t\treason: error instanceof ContextTreeCliFailure ? error.reason : \"CLI_FAILED\"\n\t\t\t};\n\t\t}\n\t}\n\t/** OpenTag always invokes the packaged CLI directly, so a broken shim cannot redirect it. */\n\tasync #run(args, cwd, network, environment) {\n\t\tif (!this.#package) throw new ContextTreeCliFailure(\"PACKAGE_MISSING\");\n\t\tif (this.#managedCredentials && network && !environment) throw new ContextTreeCliFailure(\"AUTHENTICATION_REQUIRED\");\n\t\tconst { payload, failureCode } = await runContextTreeCli(this.#package, args, {\n\t\t\tcwd,\n\t\t\tnetwork,\n\t\t\tnodePath: this.#nodePath,\n\t\t\tenv: mergeContextTreeEnvironment(this.#environment, environment),\n\t\t\t...this.#execFile ? { execFile: this.#execFile } : {}\n\t\t});\n\t\tif (failureCode !== void 0) throw new ContextTreeCliFailure(failureCode);\n\t\treturn payload;\n\t}\n\t/**\n\t* Write the `context-tree` shim the packaged skills invoke by name.\n\t*\n\t* The shim pins the same Node.js runtime OpenTag uses, so a Session cannot resolve a different\n\t* one from the user's shell configuration.\n\t*/\n\t#prepareShim() {\n\t\tif (this.#shimPreparation && Date.now() < this.#shimRetryAt) return this.#shimPreparation;\n\t\tif (this.#shimPreparation && this.#shimRetryAt === 0) return this.#shimPreparation;\n\t\tthis.#shimRetryAt = 0;\n\t\tthis.#shimPreparation = this.#writeShim().catch((error) => {\n\t\t\tthis.#logger.warn({ err: describe(error) }, \"Context Tree shim could not be created\");\n\t\t\treturn false;\n\t\t}).then((success) => {\n\t\t\tif (!success) this.#shimRetryAt = Date.now() + this.#failureCooldownMs;\n\t\t\treturn success;\n\t\t});\n\t\treturn this.#shimPreparation;\n\t}\n\tasync #writeShim() {\n\t\tif (!this.#package) return false;\n\t\tif (this.#platform === \"win32\") {\n\t\t\tthis.#logger.warn({ platform: this.#platform }, \"Context Tree shim is not supported on this platform\");\n\t\t\treturn false;\n\t\t}\n\t\tconst bin = resolveOpenTagHomeLayout(this.#home).contextTreeBin;\n\t\tawait ensurePrivateDirectory(this.#home, bin);\n\t\tconst quote = (value) => `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n\t\tawait writeDurableFile(join(bin, \"context-tree\"), `#!/bin/sh\\n# Generated by OpenTag; edits are overwritten.\\nexec ${quote(this.#nodePath)} ${quote(this.#package.cliPath)} \"$@\"\\n`, 448);\n\t\treturn true;\n\t}\n\trunExclusive(operation) {\n\t\treturn this.#serialize(operation);\n\t}\n\t#serialize(operation) {\n\t\tconst next = this.#pending.then(operation, operation);\n\t\tthis.#pending = next.then(() => void 0, () => void 0);\n\t\treturn next;\n\t}\n};\n/** Never log tree contents, credentials, or full command output. */\nfunction describe(error) {\n\treturn error instanceof Error ? error.name : \"unknown\";\n}\n/**\n* Merge an execution-local environment over the base environment. `undefined` override entries\n* unset the inherited variable, so a managed CLI child never inherits ambient credentials.\n*/\nfunction mergeContextTreeEnvironment(base, overrides) {\n\tconst merged = { ...base };\n\tif (!overrides) return merged;\n\tfor (const [key, value] of Object.entries(overrides)) if (value === void 0) delete merged[key];\n\telse merged[key] = value;\n\treturn merged;\n}\n/**\n* True when the execution-local GitHub metadata grants this repository. Managed Context Tree\n* preparation must never reach a repository outside the current execution's granted set; this is\n* a consistency pre-check only, and the GitHub proxy still revalidates the exact target on every\n* request.\n*/\nfunction managedRepositoryAllowed(environment, repository) {\n\tconst raw = environment.OPENTAG_GITHUB_REPOSITORIES;\n\tif (typeof raw !== \"string\" || raw.length === 0) return false;\n\tlet entries;\n\ttry {\n\t\tentries = JSON.parse(raw);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (!Array.isArray(entries)) return false;\n\tconst wanted = repository.toLowerCase();\n\treturn entries.some((entry) => {\n\t\tif (!entry || typeof entry !== \"object\") return false;\n\t\tconst { fullName, role } = entry;\n\t\treturn role === \"context_tree\" && typeof fullName === \"string\" && fullName.toLowerCase() === wanted;\n\t});\n}\n//#endregion\n//#region src/runner/skills.ts\n/** Packaged Context Tree skills OpenTag ships to Pi. Matches scripts/portable/runtime-dependencies.mjs. */\nconst CONTEXT_TREE_PACKAGED_SKILL_DIRECTORIES = Object.freeze([\n\t\"context-tree-connect\",\n\t\"context-tree-create\",\n\t\"context-tree-publish\",\n\t\"context-tree-read\",\n\t\"context-tree-setup\",\n\t\"context-tree-write\"\n]);\n/**\n* Source-owned Git/gh/Slack/Lark skill guidance assembled into the image at /opt/opentag/skills.\n* Host checkouts do not ship them; override with OPENTAG_RUNNER_SKILLS_DIR for relocated runs.\n*/\nconst RUNNER_TOOL_SKILL_DIRECTORIES = Object.freeze([\n\t\"git\",\n\t\"gh\",\n\t\"lark-cli\",\n\t\"slack\"\n]);\nconst DEFAULT_RUNNER_SKILLS_DIR = \"/opt/opentag/skills\";\n/** Image-assembled tool skills; empty when the runner skills directory is absent (host dev). */\nasync function assembleRunnerToolSkills(from) {\n\tconst skillsPath = from ?? process.env.OPENTAG_RUNNER_SKILLS_DIR ?? DEFAULT_RUNNER_SKILLS_DIR;\n\tconst skills = [];\n\tlet present = false;\n\ttry {\n\t\tpresent = (await stat(skillsPath)).isDirectory();\n\t} catch {\n\t\tpresent = false;\n\t}\n\tif (present) for (const name of RUNNER_TOOL_SKILL_DIRECTORIES) {\n\t\tconst directory = join(skillsPath, name);\n\t\tconst skillFile = join(directory, \"SKILL.md\");\n\t\tconst [dirStats, fileStats] = await Promise.all([stat(directory), stat(skillFile)]);\n\t\tif (!dirStats.isDirectory() || !fileStats.isFile()) throw new Error(`Runner tool skill ${name} is incomplete under ${skillsPath}`);\n\t\tskills.push({\n\t\t\tdirectory,\n\t\t\tname,\n\t\t\tskillFile\n\t\t});\n\t}\n\treturn {\n\t\tskills,\n\t\tskillsPath\n\t};\n}\nasync function requireSkillDirectory(skillsPath, name) {\n\tconst directory = join(skillsPath, name);\n\tconst skillFile = join(directory, \"SKILL.md\");\n\tconst [dirStats, fileStats] = await Promise.all([stat(directory), stat(skillFile)]);\n\tif (!dirStats.isDirectory()) throw new Error(`Context Tree skill ${name} is not a directory`);\n\tif (!fileStats.isFile()) throw new Error(`Context Tree skill ${name} is missing SKILL.md`);\n\treturn {\n\t\tdirectory,\n\t\tname,\n\t\tskillFile\n\t};\n}\n/**\n* Assemble the six packaged Context Tree skills using the real Client package resolver.\n* Extra directories that may exist in the npm package are ignored on purpose.\n*/\nasync function assembleContextTreeSkills(from) {\n\tconst contextTreePackage = resolveContextTreePackage(from);\n\tif (!contextTreePackage) throw new Error(\"Context Tree package is not resolvable\");\n\tconst entries = await readdir(contextTreePackage.skillsPath);\n\tconst present = new Set(entries);\n\tconst missing = CONTEXT_TREE_PACKAGED_SKILL_DIRECTORIES.filter((name) => !present.has(name));\n\tif (missing.length > 0) throw new Error(`Context Tree packaged skills missing: ${missing.join(\", \")}`);\n\tconst skills = await Promise.all(CONTEXT_TREE_PACKAGED_SKILL_DIRECTORIES.map((name) => requireSkillDirectory(contextTreePackage.skillsPath, name)));\n\treturn {\n\t\tpackage: contextTreePackage,\n\t\tskillsPath: contextTreePackage.skillsPath,\n\t\tskillPaths: skills.map((skill) => skill.directory),\n\t\tskills\n\t};\n}\n//#endregion\n//#region src/runner/tree.ts\nasync function prepareDisposableContextTree(options) {\n\tconst assembled = await assembleContextTreeSkills();\n\tconst accountHome = await mkdtemp(join(tmpdir(), \"opentag-runner-ct-\"));\n\tlet seed;\n\tconst cleanup = async () => {\n\t\tawait Promise.all([rm(accountHome, {\n\t\t\tforce: true,\n\t\t\trecursive: true\n\t\t}), ...seed ? [rm(seed, {\n\t\t\tforce: true,\n\t\t\trecursive: true\n\t\t})] : []]);\n\t};\n\ttry {\n\t\tawait writeFile(join(accountHome, \".gitconfig\"), \"[user]\\n\tname = OpenTag Runner\\n\temail = opentag-runner@localhost\\n[init]\\n\tdefaultBranch = master\\n\", \"utf8\");\n\t\tconst environment = {\n\t\t\tHOME: accountHome,\n\t\t\tPATH: process.env.PATH ?? \"/usr/bin:/bin\"\n\t\t};\n\t\tseed = await mkdtemp(join(tmpdir(), \"opentag-runner-ct-seed-\"));\n\t\tconst created = await runContextTreeCli(assembled.package, [\n\t\t\t\"create\",\n\t\t\t\"--project-path\",\n\t\t\tseed,\n\t\t\t\"--json\"\n\t\t], { env: environment });\n\t\tif (created.failureCode) throw new Error(`context-tree create failed: ${created.failureCode}`);\n\t\tconst treePath = created.payload?.treePath;\n\t\tif (!treePath) throw new Error(\"context-tree create did not return a tree path\");\n\t\tconst connected = await runContextTreeCli(assembled.package, [\n\t\t\t\"connect\",\n\t\t\tbasename(treePath),\n\t\t\t\"--as\",\n\t\t\t\"diagnostic\",\n\t\t\t\"--project-path\",\n\t\t\toptions.workspace,\n\t\t\t\"--json\"\n\t\t], { env: environment });\n\t\tif (connected.failureCode) throw new Error(`Context Tree connect failed: ${connected.failureCode}`);\n\t\tconst verified = await runContextTreeCli(assembled.package, [\n\t\t\t\"verify\",\n\t\t\t\"--tree-path\",\n\t\t\ttreePath,\n\t\t\t\"--json\"\n\t\t], { env: environment });\n\t\tif (verified.failureCode) throw new Error(`context-tree verify failed: ${verified.failureCode}`);\n\t\treturn {\n\t\t\taccountHome,\n\t\t\tassembled,\n\t\t\tcleanup,\n\t\t\tskillArguments: assembled.skillPaths.flatMap((path) => [\"--skill\", path]),\n\t\t\ttreePath,\n\t\t\tverified: verified.payload\n\t\t};\n\t} catch (error) {\n\t\tawait cleanup();\n\t\tthrow error;\n\t}\n}\n//#endregion\n//#region src/runner/acceptance.ts\nconst POLICY = {\n\tapprovals: \"never\",\n\tfileSystem: \"unrestricted\",\n\tnetwork: \"enabled\",\n\ttools: { mode: \"provider-default\" }\n};\nconst RUNNER_DEEPSEEK_MODEL = \"deepseek-v4.1-flash-expires-on-0910\";\nconst RUNNER_DEEPSEEK_PROVIDER = \"deepseek\";\nconst RUNNER_MODEL_ID = `${RUNNER_DEEPSEEK_PROVIDER}/${RUNNER_DEEPSEEK_MODEL}`;\n/** Native Pi `--version` startup measured ~6s on Cloud Run; the provider's 5s local default is too tight. */\nconst RUNNER_PI_PROBE_TIMEOUT_MS = 3e4;\nfunction event(name, status, detail) {\n\treturn {\n\t\tname,\n\t\tstatus,\n\t\t...detail ? { detail } : {}\n\t};\n}\nfunction textOf(result) {\n\treturn result.output.filter((item) => item.type === \"text\").map((item) => item.text?.trim() ?? \"\").join(\"\\n\");\n}\nasync function waitForPath(path, timeoutMs) {\n\tconst deadline = Date.now() + timeoutMs;\n\tfor (;;) try {\n\t\tawait access(path);\n\t\treturn;\n\t} catch {\n\t\tif (Date.now() >= deadline) throw new Error(`timed out waiting for ${path}`);\n\t\tawait new Promise((resolve) => setTimeout(resolve, 50));\n\t}\n}\nasync function waitForCondition(check, description, timeoutMs) {\n\tconst deadline = Date.now() + timeoutMs;\n\tfor (;;) {\n\t\tif (check()) return;\n\t\tif (Date.now() >= deadline) throw new Error(`timed out waiting for ${description}`);\n\t\tawait new Promise((resolve) => setTimeout(resolve, 50));\n\t}\n}\nfunction delay(ms) {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\nfunction toolEvents(events, runId) {\n\tconst started = events.filter((item) => item.type === \"tool_started\" && item.runId === runId);\n\tconst completed = events.filter((item) => item.type === \"tool_completed\" && item.runId === runId);\n\treturn {\n\t\tstarted,\n\t\tsuccessful: completed.filter((item) => item.type === \"tool_completed\" && item.status === \"completed\"),\n\t\tfailed: completed.filter((item) => item.type === \"tool_completed\" && item.status !== \"completed\")\n\t};\n}\n/** Exact Pi arguments for an explicit managed skill set (never the ambient Local set). */\nfunction skillArgsOf(skillPaths) {\n\treturn [\"--no-skills\", ...skillPaths.flatMap((path) => [\"--skill\", path])];\n}\nfunction trackedSpawn$1(pids) {\n\treturn (command, args, spawnOptions) => {\n\t\tconst child = spawn(command, [...args], {\n\t\t\t...spawnOptions,\n\t\t\tstdio: \"pipe\"\n\t\t});\n\t\tif (typeof child.pid === \"number\") pids.add(child.pid);\n\t\treturn child;\n\t};\n}\nfunction runtimeEnvironment(options) {\n\treturn {\n\t\tHOME: options.runtimeHome,\n\t\tPATH: options.path ?? process.env.PATH,\n\t\tPI_CODING_AGENT_DIR: options.piHome,\n\t\tPI_CODING_AGENT_SESSION_DIR: options.sessionDirectory\n\t};\n}\nfunction createTrackedFactory(options, skillPaths, pids) {\n\treturn new PiAgentRuntimeFactory({ process: {\n\t\targs: skillArgsOf(skillPaths),\n\t\tcommand: \"pi\",\n\t\tenv: runtimeEnvironment(options),\n\t\tprobeTimeoutMs: RUNNER_PI_PROBE_TIMEOUT_MS,\n\t\tsessionDirectory: options.sessionDirectory,\n\t\tspawnProcess: trackedSpawn$1(pids)\n\t} });\n}\n/**\n* Ask a short-lived, dedicated Pi RPC process which skills it actually loaded with the exact\n* Runner skill arguments. The process and its request id never touch the acceptance runtime;\n* only command names are read, never resource contents.\n*/\nasync function loadPiSkillNames(options, skillPaths, pids) {\n\tconst rpc = new PiRpcProcess({\n\t\tcommand: \"pi\",\n\t\targs: [\n\t\t\t...skillArgsOf(skillPaths),\n\t\t\t\"--mode\",\n\t\t\t\"rpc\"\n\t\t],\n\t\tcwd: options.workspace,\n\t\tenv: runtimeEnvironment(options),\n\t\trequestTimeoutMs: 3e4,\n\t\tspawnProcess: trackedSpawn$1(pids)\n\t});\n\ttry {\n\t\tconst commands = (await rpc.request({ type: \"get_commands\" }, AbortSignal.timeout(3e4)))?.commands;\n\t\tif (!Array.isArray(commands)) throw new Error(\"Pi get_commands returned no command list\");\n\t\tconst skills = commands.filter((command) => command.source === \"skill\" && typeof command.name === \"string\").map((command) => command.name);\n\t\treturn [...new Set(skills)].sort();\n\t} finally {\n\t\tawait rpc.close(1e3);\n\t}\n}\nasync function runFixtureTurn(runtime, workspace, events) {\n\tconst left = randomInt(10, 99);\n\tconst right = randomInt(10, 99);\n\tconst sum = String(left + right);\n\tconst fixture = join(workspace, \"fixture.txt\");\n\tconst sumFile = join(workspace, \"sum.txt\");\n\tawait writeFile(fixture, `${left} ${right}\\n`, \"utf8\");\n\tconst started = Date.now();\n\tconst result = await runtime.prompt({\n\t\trunId: \"runner-fixture\",\n\t\tconfiguration: {\n\t\t\tmodel: RUNNER_MODEL_ID,\n\t\t\treasoningEffort: \"max\"\n\t\t},\n\t\tinput: { items: [{\n\t\t\ttype: \"text\",\n\t\t\ttext: `Read ${fixture} with file tools. Sum the two integers. Write the sum to ${sumFile} using file tools. Reply with only the integer sum.`\n\t\t}] },\n\t\tsignal: AbortSignal.timeout(18e4)\n\t});\n\tconst firstTaskMs = Date.now() - started;\n\tif (result.status !== \"completed\") throw new Error(`fixture run failed: ${JSON.stringify(redactAcceptanceRecord(result.error))}`);\n\tif (textOf(result) !== sum) throw new Error(`expected ${sum}, got ${JSON.stringify(textOf(result))}`);\n\tif ((await readFile(sumFile, \"utf8\")).trim() !== sum) throw new Error(\"sum.txt mismatch\");\n\tconst tools = toolEvents(events, \"runner-fixture\");\n\tif (tools.started.length === 0 || tools.successful.length === 0) throw new Error(`fixture run did not emit successful tool events (started=${tools.started.length}, successful=${tools.successful.length}, failed=${JSON.stringify(redactAcceptanceRecord(tools.failed))})`);\n\tif (tools.failed.length > 0) throw new Error(`fixture run had failed tool events: ${JSON.stringify(redactAcceptanceRecord(tools.failed))}`);\n\tif (!runtime.binding) throw new Error(\"Pi create did not produce a binding\");\n\treturn {\n\t\tbinding: runtime.binding,\n\t\tfirstTaskMs,\n\t\tsum\n\t};\n}\nconst CANCELLATION_CAUSES = /* @__PURE__ */ new Map([[\"aborted\", \"run_aborted\"], [\"cancelled\", \"run_cancelled\"]]);\nfunction assertCancelledOutcome(outcome) {\n\tif (outcome.settled === \"error\") throw new Error(`cancelled run rejected instead of reporting a cancellation status: ${JSON.stringify(redactAcceptanceRecord(outcome.error instanceof Error ? outcome.error.message : outcome.error))}`);\n\tconst { result } = outcome;\n\tconst expectedCause = CANCELLATION_CAUSES.get(result.status);\n\tif (!expectedCause || result.error?.code !== expectedCause) throw new Error(`expected a confirmed cancellation status/cause, got status=${result.status} code=${result.error?.code ?? \"none\"}`);\n}\nasync function readFixturePid(path) {\n\tconst raw = (await readFile(path, \"utf8\")).trim();\n\tconst pid = Number(raw);\n\tif (!Number.isInteger(pid) || pid <= 1) throw new Error(`fixture child wrote an invalid PID: ${JSON.stringify(raw)}`);\n\treturn pid;\n}\n/** Wait for the synchronous Bash fixture to be live: marker, PID file, tool event, live child. */\nasync function waitForLiveFixture(workspace, events) {\n\tawait waitForPath(join(workspace, \"child-ready.txt\"), 9e4);\n\tconst pidFile = join(workspace, \"child.pid\");\n\tawait waitForPath(pidFile, 5e3);\n\tawait waitForCondition(() => events.some((item) => item.type === \"tool_started\" && item.runId === \"runner-child\" && /bash/i.test(item.name)), \"Bash tool_started event for the fixture\", 5e3);\n\tconst childPid = await readFixturePid(pidFile);\n\tif (!await processExists(childPid)) throw new Error(`fixture child ${childPid} is not alive before cancel`);\n\treturn childPid;\n}\n/**\n* The shared tracked set covers probe/create/resume; PIDs of runtimes we already closed ourselves\n* are pruned, then every process serving the active run must be verifiably live.\n*/\nasync function collectLivePids(childPid, pids, requireTrackedPi) {\n\tconst live = /* @__PURE__ */ new Set([childPid, ...await collectDescendantPids(childPid)]);\n\tfor (const pid of [...pids]) if (!await processExists(pid)) pids.delete(pid);\n\tif (requireTrackedPi && pids.size === 0) throw new Error(\"no tracked live Pi process before cancel\");\n\tfor (const pid of pids) for (const descendant of await collectDescendantPids(pid)) live.add(descendant);\n\tif (live.size < 2) throw new Error(\"expected live Pi/watchdog/fixture PIDs before cancel\");\n\tfor (const pid of live) if (!await processExists(pid)) throw new Error(`expected live PID ${pid} before cancel`);\n\treturn live;\n}\n/** Grace window after the tree is gone: a delayed write from an orphan must never appear. */\nasync function assertNoDelayedWrite(marker) {\n\tawait delay(2e3);\n\ttry {\n\t\tawait readFile(marker, \"utf8\");\n\t\tthrow new Error(\"delayed child write was observed after cancel/close\");\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t}\n}\n/**\n* Cancel an actively running Bash fixture through the real Pi adapter.\n*\n* The fixture command runs synchronously inside the Bash tool: it writes a ready\n* marker and its own PID, then sleeps, so the run stays active until we abort.\n* Cancellation only counts when the run settles with a confirmed cancellation\n* status/cause; every observed Pi/watchdog/fixture PID must be gone afterwards\n* and the delayed write must never land.\n*/\nasync function cancelLongLivedChild(runtime, workspace, pids, events, requireTrackedPi) {\n\tconst ready = join(workspace, \"child-ready.txt\");\n\tconst pidFile = join(workspace, \"child.pid\");\n\tconst marker = join(workspace, \"delayed.txt\");\n\tconst abort = new AbortController();\n\tconst quote = (path) => `'${path.replaceAll(\"'\", \"'\\\"'\\\"'\")}'`;\n\tconst fixtureCommand = `printf READY > ${quote(ready)}; echo $$ > ${quote(pidFile)}; sleep 300; echo leaked > ${quote(marker)}`;\n\tconst pending = runtime.prompt({\n\t\trunId: \"runner-child\",\n\t\tconfiguration: {\n\t\t\tmodel: RUNNER_MODEL_ID,\n\t\t\treasoningEffort: \"max\"\n\t\t},\n\t\tinput: { items: [{\n\t\t\ttype: \"text\",\n\t\t\ttext: `Run this exact command with the Bash tool, synchronously in the foreground; do not background it and do not return before it exits:\\n${fixtureCommand}\\nAfter it exits, reply DONE.`\n\t\t}] },\n\t\tsignal: abort.signal\n\t}).then((result) => ({\n\t\tsettled: \"result\",\n\t\tresult\n\t}), (error) => ({\n\t\tsettled: \"error\",\n\t\terror\n\t}));\n\ttry {\n\t\tconst live = await collectLivePids(await waitForLiveFixture(workspace, events), pids, requireTrackedPi);\n\t\tconst evidence = {\n\t\t\tlivePidsBeforeCancel: live.size,\n\t\t\ttrackedPiPids: pids.size\n\t\t};\n\t\tabort.abort();\n\t\tawait runtime.close();\n\t\tassertCancelledOutcome(await pending);\n\t\tawait waitForProcessTreeGone([...live], { timeoutMs: 15e3 });\n\t\tawait assertNoDelayedWrite(marker);\n\t\treturn evidence;\n\t} finally {\n\t\tif (!abort.signal.aborted) abort.abort();\n\t\tawait pending.catch(() => void 0);\n\t}\n}\nasync function runResumeTurn(factory, request, first) {\n\tconst runtime = await factory.resume({\n\t\t...request,\n\t\tbinding: first.binding\n\t});\n\ttry {\n\t\tif (JSON.stringify(runtime.binding) !== JSON.stringify(first.binding)) throw new Error(\"Pi resume changed the binding\");\n\t\tconst second = await runtime.prompt({\n\t\t\trunId: \"runner-resume\",\n\t\t\tconfiguration: request.configuration,\n\t\t\tinput: { items: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: \"What sum did you compute from the fixture file? Reply with only that integer.\"\n\t\t\t}] },\n\t\t\tsignal: AbortSignal.timeout(18e4)\n\t\t});\n\t\tif (second.status !== \"completed\" || textOf(second) !== first.sum) throw new Error(`resume expected ${first.sum}, got ${JSON.stringify(textOf(second))}`);\n\t\treturn runtime;\n\t} catch (error) {\n\t\treturn await closeAfterFailure(runtime, error);\n\t}\n}\n/** Close after a failure without ever swallowing either the primary or the cleanup error. */\nasync function closeAfterFailure(runtime, error) {\n\tconst primary = error instanceof Error ? error.message : String(error);\n\ttry {\n\t\tawait runtime.close();\n\t} catch (closeError) {\n\t\tthrow new Error(`${primary}; runtime cleanup close also failed: ${closeError instanceof Error ? closeError.message : String(closeError)}`);\n\t}\n\tthrow error;\n}\nasync function runModelAcceptance(options, factory, skillPaths, pids, expectedSkills, events) {\n\tconst sink = [];\n\tconst request = {\n\t\teventSink: (item) => {\n\t\t\tsink.push(item);\n\t\t},\n\t\tpolicy: POLICY,\n\t\tsystemPrompt: \"Follow the user's exact response-format request. Do not mention secrets.\",\n\t\tworkspace: {\n\t\t\tcwd: options.workspace,\n\t\t\tenvironment: {\n\t\t\t\tPATH: options.path ?? process.env.PATH ?? \"/usr/bin:/bin\",\n\t\t\t\tHOME: options.runtimeHome\n\t\t\t}\n\t\t},\n\t\tconfiguration: {\n\t\t\tmodel: RUNNER_MODEL_ID,\n\t\t\treasoningEffort: \"max\"\n\t\t}\n\t};\n\tlet skillsLoaded;\n\tif (!options.factory) {\n\t\tconst loaded = await loadPiSkillNames(options, skillPaths, pids);\n\t\tconst actual = loaded.map((name) => name.replace(/^skill:/, \"\")).sort();\n\t\tif (JSON.stringify(actual) !== JSON.stringify([...expectedSkills].sort())) throw new Error(`Pi skill list mismatch; expected: ${expectedSkills.join(\", \")}; loaded: ${loaded.join(\", \")}`);\n\t\tskillsLoaded = loaded;\n\t\tevents.push(event(\"model-skills\", \"passed\", loaded.join(\",\")));\n\t}\n\tlet runtime = await factory.create(request);\n\ttry {\n\t\tconst first = await runFixtureTurn(runtime, options.workspace, sink);\n\t\tawait runtime.close();\n\t\truntime = await runResumeTurn(factory, request, first);\n\t\tconst cancel = await cancelLongLivedChild(runtime, options.workspace, pids, sink, !options.factory);\n\t\truntime = void 0;\n\t\tconst tools = [...toolEvents(sink, \"runner-fixture\").successful, ...toolEvents(sink, \"runner-child\").successful];\n\t\tconst toolNames = [...new Set(tools.map((item) => item.type === \"tool_completed\" ? item.name : \"\"))].filter((name) => name.length > 0);\n\t\tevents.push(event(\"model-fixture\", \"passed\", first.sum), event(\"model-resume\", \"passed\"));\n\t\tevents.push(event(\"model-cancel\", \"passed\", `livePids=${cancel.livePidsBeforeCancel} trackedPi=${cancel.trackedPiPids}`));\n\t\treturn {\n\t\t\tfirstTaskMs: first.firstTaskMs,\n\t\t\tevidence: {\n\t\t\t\tcancel,\n\t\t\t\ttools: {\n\t\t\t\t\tnames: toolNames.sort(),\n\t\t\t\t\tsuccessfulCount: tools.length\n\t\t\t\t},\n\t\t\t\t...skillsLoaded ? { skillsLoaded } : {}\n\t\t\t}\n\t\t};\n\t} catch (error) {\n\t\tif (runtime !== void 0) {\n\t\t\tconst closing = runtime;\n\t\t\truntime = void 0;\n\t\t\tawait closeAfterFailure(closing, error);\n\t\t}\n\t\tthrow error;\n\t}\n}\nasync function collectOfflineEvents(options) {\n\tconst defaultProbeTools = () => probeRunnerTools({\n\t\tenv: {\n\t\t\tPATH: options.path ?? process.env.PATH ?? \"/usr/bin:/bin\",\n\t\t\tHOME: options.runtimeHome\n\t\t},\n\t\t...options.identity ? { expected: expectedFromIdentity(options.identity) } : {},\n\t\tpiTimeoutMs: RUNNER_PI_PROBE_TIMEOUT_MS\n\t});\n\tconst probes = await (options.probeTools ?? defaultProbeTools)();\n\tconst events = probes.map((probe) => event(`probe:${probe.name}`, probe.ok ? \"passed\" : \"failed\", probe.detail));\n\ttry {\n\t\tconst toolSkills = await assembleRunnerToolSkills();\n\t\tconst toolSkillPaths = toolSkills.skills.map((skill) => skill.directory);\n\t\tevents.push(event(\"tool-skills\", toolSkills.skills.length > 0 ? \"passed\" : \"skipped\", toolSkills.skills.length > 0 ? toolSkills.skills.map((skill) => skill.name).join(\",\") : \"no runner tool skills directory (host development)\"));\n\t\tif (options.assembleSkills) {\n\t\t\tconst assembled = await options.assembleSkills();\n\t\t\tevents.push(event(\"skills\", \"passed\", assembled.skills.map((skill) => skill.name).join(\",\")));\n\t\t\treturn {\n\t\t\t\tevents,\n\t\t\t\tprobesOk: runnerToolsReady(probes),\n\t\t\t\tskillArguments: skillArgsOf([...assembled.skillPaths, ...toolSkillPaths])\n\t\t\t};\n\t\t}\n\t\tconst prepared = await prepareDisposableContextTree({\n\t\t\thome: options.runtimeHome,\n\t\t\tworkspace: options.workspace\n\t\t});\n\t\ttry {\n\t\t\tconst allSkillArguments = skillArgsOf([...prepared.assembled.skillPaths, ...toolSkillPaths]);\n\t\t\tevents.push(event(\"skills\", \"passed\", prepared.assembled.skills.map((skill) => skill.name).join(\",\")));\n\t\t\tevents.push(event(\"skills-args\", \"passed\", allSkillArguments.join(\" \")));\n\t\t\tevents.push(event(\"context-tree\", \"passed\", prepared.treePath));\n\t\t\treturn {\n\t\t\t\tevents,\n\t\t\t\tprobesOk: runnerToolsReady(probes),\n\t\t\t\tskillArguments: allSkillArguments\n\t\t\t};\n\t\t} finally {\n\t\t\tawait prepared.cleanup();\n\t\t}\n\t} catch (error) {\n\t\tevents.push(event(\"skills\", \"failed\", error instanceof Error ? error.message : String(error)));\n\t\treturn {\n\t\t\tevents,\n\t\t\tprobesOk: runnerToolsReady(probes)\n\t\t};\n\t}\n}\n/** The assembled skill paths (Context Tree + Runner tool skills) Pi receives through --skill. */\nasync function assembledSkillPaths(options) {\n\tconst assembled = await (options.assembleSkills ?? assembleContextTreeSkills)();\n\tconst toolSkills = await assembleRunnerToolSkills();\n\tconst skillPaths = [...assembled.skillPaths, ...toolSkills.skills.map((skill) => skill.directory)];\n\treturn {\n\t\tskillPaths,\n\t\tskillArguments: skillArgsOf(skillPaths),\n\t\texpectedSkills: [...assembled.skills.map((skill) => skill.name), ...toolSkills.skills.map((skill) => skill.name)]\n\t};\n}\nasync function runRunnerAcceptance(options) {\n\tawait mkdir(options.workspace, { recursive: true });\n\tconst offline = await collectOfflineEvents(options);\n\tconst events = offline.events;\n\tconst offlineFailed = events.some((item) => item.status === \"failed\") || !offline.probesOk;\n\tconst report = (model, failed, extra = {}) => redactAcceptanceRecord({\n\t\tevents,\n\t\tfailed,\n\t\toffline: offlineFailed ? \"failed\" : \"passed\",\n\t\tmodel,\n\t\t...options.identity ? { identity: options.identity } : {},\n\t\t...offline.skillArguments ? { skillArguments: offline.skillArguments } : {},\n\t\t...extra\n\t});\n\tif (options.mode !== \"real\") return report(\"skipped\", offlineFailed);\n\tif (offlineFailed) {\n\t\tevents.push(event(\"model\", \"failed\", \"offline checks must pass before real mode\"));\n\t\treturn report(\"failed\", true);\n\t}\n\ttry {\n\t\tconst pids = /* @__PURE__ */ new Set();\n\t\tconst skills = await assembledSkillPaths(options);\n\t\tconst factory = options.factory ?? createTrackedFactory(options, skills.skillPaths, pids);\n\t\tconst probe = await factory.probe({});\n\t\tif (probe.issues.some((issue) => issue.code === \"credential_missing\")) throw new Error(\"Pi has no configured model credential\");\n\t\tif (!probe.ready) throw new Error(`Pi probe failed: ${JSON.stringify(redactAcceptanceRecord(probe.issues))}`);\n\t\tconst model = await runModelAcceptance(options, factory, skills.skillPaths, pids, skills.expectedSkills, events);\n\t\tconst failed = events.some((item) => item.status === \"failed\");\n\t\treturn report(failed ? \"failed\" : \"passed\", failed, {\n\t\t\tfirstTaskMs: model.firstTaskMs,\n\t\t\tevidence: model.evidence\n\t\t});\n\t} catch (error) {\n\t\tevents.push(event(\"model\", \"failed\", error instanceof Error ? error.message : String(error)));\n\t\treturn report(\"failed\", true);\n\t}\n}\n//#endregion\n//#region src/runner/types.ts\nconst RUNNER_IDENTITY_SCHEMA_VERSION = 1;\nconst RUNNER_CLI_NAME = \"opentag-runner\";\n//#endregion\n//#region src/runner/args.ts\nconst COMMANDS$1 = /* @__PURE__ */ new Set([\n\t\"probe\",\n\t\"accept\",\n\t\"identity\",\n\t\"skills\",\n\t\"serve\",\n\t\"worker\"\n]);\nconst USAGE = `Usage: ${RUNNER_CLI_NAME} <probe|accept|identity|skills|serve|worker> [options]\n\nOptions:\n  --mode <offline|real>     Acceptance mode (default: offline)\n  --pi-config-dir <path>    Isolated Pi config directory to copy (whitelist only)\n  --provider <name>         Provider key whitelist when copying Pi config\n  --workspace <path>        Workspace directory\n  --json                    Machine-readable output\n\nserve runs the long-lived Cloud Runner: outbound WSS control channel plus native sandbox.\nserve configuration arrives through the environment (never argv):\n  OPENTAG_RUNNER_BACKEND_URL      wss:// control channel URL (required)\n  OPENTAG_RUNNER_BOOTSTRAP_TOKEN  Server-minted bootstrap token (required, env only)\n  OPENTAG_RUNNER_SANDBOX_NAME     Native sandbox name\n  OPENTAG_RUNNER_WORKSPACE        Per-sandbox workspace host path\n\nworker runs INSIDE the native sandbox and reads exactly one bounded JSON request from stdin.\n`;\nfunction invalid(error, exitCode = 2) {\n\treturn {\n\t\tok: false,\n\t\terror: `${error}\\n${USAGE}`,\n\t\texitCode\n\t};\n}\nfunction takeValue(argv, index, token) {\n\tconst value = argv[index + 1];\n\tif (value === void 0 || value.startsWith(\"--\")) return `${token} requires a value`;\n\treturn {\n\t\tvalue,\n\t\tnext: index + 1\n\t};\n}\nfunction applyOption(token, value, current) {\n\tif (token === \"--mode\") {\n\t\tif (value !== \"offline\" && value !== \"real\") return `--mode must be offline or real, got ${value}`;\n\t\treturn {\n\t\t\t...current,\n\t\t\tmode: value\n\t\t};\n\t}\n\tif (token === \"--pi-config-dir\") return {\n\t\t...current,\n\t\tpiConfigDir: value\n\t};\n\tif (token === \"--provider\") return {\n\t\t...current,\n\t\tprovider: value\n\t};\n\tif (token === \"--workspace\") return {\n\t\t...current,\n\t\tworkspace: value\n\t};\n\treturn `unknown option: ${token}`;\n}\nfunction parseToken(argv, index, current) {\n\tconst token = argv[index];\n\tif (token === \"--json\") return {\n\t\tjson: true,\n\t\tcurrent,\n\t\tnext: index\n\t};\n\tif (token === \"--help\" || token === \"-h\") return invalid(\"unexpected help flag after command\");\n\tif (!token?.startsWith(\"--\")) return invalid(`unexpected argument: ${token ?? \"\"}`);\n\tconst taken = takeValue(argv, index, token);\n\tif (typeof taken === \"string\") return invalid(taken);\n\tconst applied = applyOption(token, taken.value, current);\n\tif (typeof applied === \"string\") return invalid(applied);\n\treturn {\n\t\tcurrent: applied,\n\t\tnext: taken.next\n\t};\n}\nfunction parseOptions(argv) {\n\tlet json = false;\n\tlet current = { mode: \"offline\" };\n\tfor (let index = 0; index < argv.length; index += 1) {\n\t\tconst parsed = parseToken(argv, index, current);\n\t\tif (\"ok\" in parsed) return parsed;\n\t\tif (parsed.json) json = true;\n\t\tcurrent = parsed.current;\n\t\tindex = parsed.next;\n\t}\n\treturn {\n\t\tjson,\n\t\tcurrent\n\t};\n}\nfunction validateInvocation(command, current) {\n\tif ((command === \"serve\" || command === \"worker\") && (current.piConfigDir || current.provider)) return `${command} takes no Pi config options; real-mode credentials arrive via stdin inside the sandbox`;\n\tif (current.mode === \"real\" && command === \"accept\" && !current.piConfigDir) return \"real mode requires --pi-config-dir\";\n\tif ((current.mode === \"real\" || current.piConfigDir) && !current.provider) return \"copying Pi config requires --provider\";\n\tif (current.provider && current.provider !== \"deepseek\") return `unsupported provider for real acceptance: ${current.provider} (only ${RUNNER_DEEPSEEK_PROVIDER} is currently supported)`;\n}\nfunction parseRunnerCliArgv(argv) {\n\tif (argv.length === 0) return invalid(\"missing command\");\n\tconst command = argv[0];\n\tif (command === \"--help\" || command === \"-h\") return invalid(\"missing command\");\n\tif (!command || !COMMANDS$1.has(command)) return invalid(`unknown command: ${command ?? \"\"}`);\n\tconst parsed = parseOptions(argv.slice(1));\n\tif (\"ok\" in parsed) return parsed;\n\tconst { json, current } = parsed;\n\tconst violation = validateInvocation(command, current);\n\tif (violation) return invalid(violation);\n\treturn {\n\t\tok: true,\n\t\tinvocation: {\n\t\t\tcommand,\n\t\t\tjson,\n\t\t\tmode: current.mode,\n\t\t\t...current.piConfigDir ? { piConfigDir: current.piConfigDir } : {},\n\t\t\t...current.provider ? { provider: current.provider } : {},\n\t\t\t...current.workspace ? { workspace: current.workspace } : {}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/runner/config.ts\nconst PI_CONFIG_WHITELIST = Object.freeze([\n\t\"auth.json\",\n\t\"models.json\",\n\t\"settings.json\"\n]);\nconst PI_SAFE_SETTINGS_KEYS = Object.freeze([\n\t\"defaultProvider\",\n\t\"defaultModel\",\n\t\"defaultThinkingLevel\"\n]);\nfunction fail$2(message) {\n\tthrow new Error(message);\n}\nfunction isInside(root, candidate) {\n\tconst suffix = relative(root, candidate);\n\treturn suffix !== \"\" && !isAbsolute(suffix) && !suffix.startsWith(\"..\");\n}\n/** Reject any symlink directory between the canonical root and the path. */\nasync function assertNoSymlinkAncestors(root, filePath) {\n\tlet current = dirname(filePath);\n\tfor (;;) {\n\t\tconst suffix = relative(root, current);\n\t\tif (suffix === \"\") return;\n\t\tif (isAbsolute(suffix) || suffix.startsWith(\"..\")) fail$2(`path is not inside the selected directory: ${filePath}`);\n\t\tif ((await lstat(current)).isSymbolicLink()) fail$2(`refusing symlink ancestor directory: ${current}`);\n\t\tcurrent = dirname(current);\n\t}\n}\nasync function assertSafeFile(root, filePath) {\n\tconst stats = await lstat(filePath);\n\tif (stats.isSymbolicLink()) fail$2(`refusing to copy symlink Pi config: ${filePath}`);\n\tif (!stats.isFile()) fail$2(`Pi config path is not a file: ${filePath}`);\n\tawait assertNoSymlinkAncestors(root, filePath);\n\tconst canonical = await realpath(filePath);\n\tif (!isInside(root, canonical) && canonical !== root) fail$2(`Pi config escapes the selected directory: ${filePath}`);\n}\nfunction filterProviderObject(value, providers) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return value;\n\tconst filtered = {};\n\tfor (const [key, entry] of Object.entries(value)) if (providers.has(key)) filtered[key] = entry;\n\treturn filtered;\n}\nfunction filterModelsDocument(value, providers) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) fail$2(\"models.json must be a JSON object\");\n\tconst record = value;\n\tconst filtered = {};\n\tif (record.models !== void 0) {\n\t\tif (!Array.isArray(record.models)) fail$2(\"models.json has a malformed models field\");\n\t\tfiltered.models = record.models.filter((entry) => typeof entry === \"object\" && entry !== null && providers.has(String(entry.provider ?? \"\")));\n\t}\n\tif (record.providers !== void 0) {\n\t\tif (typeof record.providers !== \"object\" || record.providers === null || Array.isArray(record.providers)) fail$2(\"models.json has a malformed providers field\");\n\t\tfiltered.providers = filterProviderObject(record.providers, providers);\n\t}\n\treturn filtered;\n}\nfunction filterSettingsDocument(value, providers) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) return {};\n\tconst record = value;\n\tconst filtered = {};\n\tfor (const key of PI_SAFE_SETTINGS_KEYS) if (record[key] !== void 0) filtered[key] = record[key];\n\tif (typeof filtered.defaultProvider === \"string\" && !providers.has(filtered.defaultProvider)) fail$2(`settings defaultProvider ${filtered.defaultProvider} is outside the provider filter`);\n\treturn filtered;\n}\nfunction filterDocument(name, raw, providers) {\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\tfail$2(`${name} is not valid JSON`);\n\t}\n\tconst next = name === \"auth.json\" ? filterProviderObject(parsed, providers) : name === \"settings.json\" ? filterSettingsDocument(parsed, providers) : filterModelsDocument(parsed, providers);\n\tassertNoShellCommandIndirection(name, next);\n\treturn `${JSON.stringify(next, null, 2)}\\n`;\n}\n/** Pi supports `\"!command\"` credential indirection; the Runner never executes host shell commands. */\nfunction assertNoShellCommandIndirection(name, value) {\n\tif (typeof value === \"string\") {\n\t\tif (value.startsWith(\"!\")) fail$2(`${name} uses a shell-command credential indirection (!); refusing to copy`);\n\t\treturn;\n\t}\n\tif (Array.isArray(value)) {\n\t\tfor (const entry of value) assertNoShellCommandIndirection(name, entry);\n\t\treturn;\n\t}\n\tif (typeof value === \"object\" && value !== null) for (const entry of Object.values(value)) assertNoShellCommandIndirection(name, entry);\n}\nasync function copyWhitelistFile(sourceCanonical, destination, name, providers) {\n\tconst from = join(sourceCanonical, name);\n\tlet stats;\n\ttry {\n\t\tstats = await lstat(from);\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return;\n\t\tthrow error;\n\t}\n\tif (stats.isSymbolicLink()) fail$2(`refusing to copy symlink Pi config: ${from}`);\n\tif (!stats.isFile()) fail$2(`Pi config path is not a file: ${from}`);\n\tawait assertSafeFile(sourceCanonical, from);\n\tconst text = filterDocument(name, await readFile(from, \"utf8\"), providers);\n\tconst to = join(destination, name);\n\tawait writeFile(to, text, {\n\t\tencoding: \"utf8\",\n\t\tmode: 384\n\t});\n\tawait chmod(to, 384);\n}\n/**\n* Copies the whitelisted Pi config documents into a FRESH destination the Runner owns. The\n* destination must not exist yet (a preexisting directory, file, or symlink — including a\n* symlinked ancestor — is rejected, so a planted `auth.json` link can never redirect writes),\n* must not physically overlap the source, and partial copies are removed on any error.\n*/\nasync function copyIsolatedPiConfig(options) {\n\tif (!isAbsolute(options.source) || !isAbsolute(options.destination)) fail$2(\"Pi config source and destination must be absolute\");\n\tif (!options.providers?.length) fail$2(\"Pi config copy requires an explicit provider filter\");\n\tconst sourceRoot = resolve(options.source);\n\tconst destination = resolve(options.destination);\n\tconst sourceStats = await lstat(sourceRoot);\n\tif (sourceStats.isSymbolicLink() || !sourceStats.isDirectory()) fail$2(\"Pi config source must be a real directory\");\n\tconst sourceCanonical = await realpath(sourceRoot);\n\tconst parent = dirname(destination);\n\tlet parentStats;\n\ttry {\n\t\tparentStats = await lstat(parent);\n\t} catch {\n\t\tfail$2(\"Pi config destination parent must be an existing real directory\");\n\t}\n\tif (parentStats.isSymbolicLink() || !parentStats.isDirectory()) fail$2(\"Pi config destination parent must be an existing real directory\");\n\ttry {\n\t\tawait lstat(destination);\n\t\tfail$2(\"Pi config destination must be fresh; refusing to reuse an existing path\");\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t}\n\tconst canonicalParent = await realpath(parent);\n\tconst canonicalDestination = join(canonicalParent, destination.slice(parent.length + 1));\n\tif (canonicalDestination === sourceCanonical || isInside(sourceCanonical, canonicalDestination) || isInside(canonicalDestination, sourceCanonical)) fail$2(\"Pi config destination physically overlaps the source directory\");\n\tawait mkdir(destination, { mode: 448 });\n\tawait chmod(destination, 448);\n\tconst providers = new Set(options.providers);\n\ttry {\n\t\tfor (const name of PI_CONFIG_WHITELIST) await copyWhitelistFile(sourceCanonical, destination, name, providers);\n\t} catch (error) {\n\t\tawait rm(destination, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t\tthrow error;\n\t}\n\treturn destination;\n}\n//#endregion\n//#region src/runner/identity.ts\nconst SHA = /^[0-9a-f]{40}$/i;\nfunction fail$1(message) {\n\tthrow new Error(message);\n}\nfunction requireString(value, label) {\n\tif (typeof value !== \"string\" || value.trim() === \"\") fail$1(`${label} is required`);\n\treturn value;\n}\nfunction isRecord$4(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction parseChannel(value) {\n\tif (value === \"dev\" || value === \"staging\" || value === \"prod\") return value;\n\tfail$1(`channel must be dev, staging, or prod, got ${JSON.stringify(value)}`);\n}\nfunction parseToolLock(value) {\n\tif (!isRecord$4(value)) fail$1(\"toolLock must be an object\");\n\tconst git = value.git === void 0 ? void 0 : requireString(value.git, \"toolLock.git\");\n\tconst gh = value.gh === void 0 ? void 0 : requireString(value.gh, \"toolLock.gh\");\n\treturn {\n\t\tnode: requireString(value.node, \"toolLock.node\"),\n\t\tpiPackage: requireString(value.piPackage, \"toolLock.piPackage\"),\n\t\tpiVersion: requireString(value.piVersion, \"toolLock.piVersion\"),\n\t\tpnpm: requireString(value.pnpm, \"toolLock.pnpm\"),\n\t\t...git ? { git } : {},\n\t\t...gh ? { gh } : {}\n\t};\n}\n/** Client 0.0.0 is a private workspace coordinate and is never the Runner version. */\nfunction assertRunnerVersionIsNotClientPlaceholder(version) {\n\tif (version === \"0.0.0\") fail$1(\"Runner version must share the CLI release coordinate, not private Client 0.0.0\");\n}\nfunction parseRunnerIdentity(value) {\n\tif (!isRecord$4(value)) fail$1(\"runner identity must be an object\");\n\tif (value.schemaVersion !== 1) fail$1(`runner identity schemaVersion must be 1`);\n\tconst channel = parseChannel(value.channel);\n\tconst version = requireString(value.version, \"version\");\n\tassertRunnerVersionIsNotClientPlaceholder(version);\n\tconst sourceSha = requireString(value.sourceSha, \"sourceSha\");\n\tif (!SHA.test(sourceSha)) fail$1(`sourceSha must be a 40-character git SHA, got \"${sourceSha}\"`);\n\tif (typeof value.sourceDirty !== \"boolean\") fail$1(\"sourceDirty must be a boolean\");\n\tconst identity = {\n\t\tschemaVersion: 1,\n\t\tchannel,\n\t\tversion,\n\t\tsourceSha: sourceSha.toLowerCase(),\n\t\tsourceDirty: value.sourceDirty,\n\t\tcliPackageName: requireString(value.cliPackageName, \"cliPackageName\"),\n\t\tnodeVersion: requireString(value.nodeVersion, \"nodeVersion\"),\n\t\tpnpmVersion: requireString(value.pnpmVersion, \"pnpmVersion\"),\n\t\tpiPackage: requireString(value.piPackage, \"piPackage\"),\n\t\tpiVersion: requireString(value.piVersion, \"piVersion\"),\n\t\tcontextTreeVersion: requireString(value.contextTreeVersion, \"contextTreeVersion\"),\n\t\ttoolLock: parseToolLock(value.toolLock),\n\t\t...typeof value.imageId === \"string\" && value.imageId.length > 0 ? { imageId: value.imageId } : {}\n\t};\n\tif (identity.toolLock.piPackage !== identity.piPackage || identity.toolLock.piVersion !== identity.piVersion) fail$1(\"toolLock Pi coordinates must match identity Pi coordinates\");\n\treturn identity;\n}\nfunction createRunnerIdentity(input) {\n\treturn parseRunnerIdentity(input);\n}\n//#endregion\n//#region src/runtime/web-tools-artifact.ts\n/**\n* Resolve the fixed trusted Pi web-tools extension artifact shipped inside the Client package.\n* The artifact is built into `dist/pi-extensions/web-tools.mjs`; resolution never follows\n* environment variables, workspaces, or cwd, so an Agent can never substitute its own extension.\n* An explicit path exists only as a composition/test seam. Failure returns undefined (web tools\n* stay off), never a guessed path.\n*/\nasync function resolveWebToolsExtensionPath(options = {}) {\n\tif (options.explicitPath !== void 0) return verifyExtensionFile(options.explicitPath);\n\tconst candidates = [\n\t\tnew URL(\"./pi-extensions/web-tools.mjs\", import.meta.url),\n\t\tnew URL(\"../pi-extensions/web-tools.mjs\", import.meta.url),\n\t\tnew URL(\"../pi-extensions/web-tools.ts\", import.meta.url)\n\t];\n\tfor (const candidate of candidates) {\n\t\tconst verified = await verifyExtensionFile(fileURLToPath(candidate));\n\t\tif (verified) return verified;\n\t}\n}\nasync function verifyExtensionFile(path) {\n\ttry {\n\t\tconst resolved = await realpath(path);\n\t\tif (!(await lstat(resolved)).isFile()) return void 0;\n\t\treturn resolved;\n\t} catch {\n\t\treturn;\n\t}\n}\n//#endregion\n//#region src/runner/assignment-state.ts\n/**\n* Trusted-parent assignment marker for one physical Runner Instance. Cloud Run container config is\n* immutable, so after an ownership transfer the SAME process is asked to serve a different\n* Session. The marker records which assignment currently owns the local workspace/journal and\n* whether its workspace was successfully sealed.\n*\n* Rebind discipline:\n* - a marker that matches the welcomed assignment keeps all local unsaved bytes;\n* - a marker for another assignment may be discarded ONLY when it is sealed, because a sealed\n*   assignment has no unsettled durable work;\n* - an unsealed (or unreadable) marker fails closed: the Runner never restores another Session's\n*   archive over state that might still hold unsaved work.\n*/\nconst ASSIGNMENT_FILE = \"assignment.json\";\nfunction parseAssignment(raw) {\n\tlet value;\n\ttry {\n\t\tvalue = JSON.parse(raw);\n\t} catch {\n\t\tthrow new Error(\"The Runner assignment marker is not valid JSON\");\n\t}\n\tif (typeof value !== \"object\" || value === null) throw new Error(\"The Runner assignment marker is not an object\");\n\tconst record = value;\n\tif (typeof record.sandboxId !== \"string\" || typeof record.sessionId !== \"string\" || typeof record.environmentGeneration !== \"number\" || !Number.isSafeInteger(record.environmentGeneration) || record.environmentGeneration < 0 || typeof record.resourceName !== \"string\" || typeof record.resourceUid !== \"string\" || typeof record.sealed !== \"boolean\") throw new Error(\"The Runner assignment marker has an unsupported shape\");\n\treturn {\n\t\tsandboxId: record.sandboxId,\n\t\tsessionId: record.sessionId,\n\t\tenvironmentGeneration: record.environmentGeneration,\n\t\tresourceName: record.resourceName,\n\t\tresourceUid: record.resourceUid,\n\t\tsealed: record.sealed\n\t};\n}\nfunction assignmentsMatch(assignment, scope) {\n\treturn assignment.sandboxId === scope.sandboxId && assignment.environmentGeneration === scope.environmentGeneration && assignment.resourceName === scope.resourceName;\n}\n/** Read the marker; `undefined` means no prior assignment on this trusted state root. */\nasync function readRunnerAssignment(stateDir) {\n\tlet raw;\n\ttry {\n\t\traw = await readFile(join(stateDir, ASSIGNMENT_FILE), \"utf8\");\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return void 0;\n\t\tthrow new Error(\"The Runner assignment marker could not be read\");\n\t}\n\treturn parseAssignment(raw);\n}\n/** Atomic marker write (temp + rename) so a crash never leaves a half-written assignment. */\nasync function writeRunnerAssignment(stateDir, assignment) {\n\tawait mkdir(stateDir, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tconst target = join(stateDir, ASSIGNMENT_FILE);\n\tconst temporary = `${target}.${process.pid}.tmp`;\n\tconst file = await open(temporary, \"w\", 384);\n\ttry {\n\t\tawait file.writeFile(`${JSON.stringify(assignment)}\\n`, \"utf8\");\n\t\tawait file.sync();\n\t} finally {\n\t\tawait file.close();\n\t}\n\ttry {\n\t\tawait rename(temporary, target);\n\t} catch {\n\t\tawait rm(temporary, { force: true }).catch(() => void 0);\n\t\tthrow new Error(\"The Runner assignment marker was not durable\");\n\t}\n}\n/**\n* True when local state exists without a usable assignment marker: the Runner cannot prove the\n* old workspace was sealed, so the new assignment must fail closed rather than execute over it.\n*/\nasync function hasUnmarkedAssignmentState(paths) {\n\treturn await directoryHasEntries(paths.workspace) || await directoryHasEntries(paths.journalDir) || await directoryHasEntries(paths.privateTurnRoot) || await directoryHasEntries(paths.publicRoot);\n}\nasync function directoryHasEntries(directory) {\n\ttry {\n\t\treturn (await readdir(directory)).length > 0;\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return false;\n\t\tthrow new Error(\"The Runner local assignment state could not be inspected\");\n\t}\n}\nconst CLOUD_JOURNAL_PHASES = [\n\t\"received\",\n\t\"started\",\n\t\"reported\"\n];\n/** Hard cap per entry: the dispatch/session frame budget plus scope/hash overhead. Oversize fails loudly. */\nconst CLOUD_JOURNAL_ENTRY_MAX_BYTES = 327680;\n/** Hard cap on entries scanned per operation; bounds reconnect reconciliation work. */\nconst CLOUD_JOURNAL_MAX_ENTRIES = 1024;\n/** Exact allocation identity that owns a journaled entry. */\nconst CloudJournalScopeSchema = z.object({\n\tsandboxId: z.string().min(1).max(256),\n\tsessionId: z.string().min(1).max(256),\n\tenvironmentGeneration: z.number().int().nonnegative(),\n\tresourceName: z.string().min(1).max(1024),\n\tresourceUid: z.string().min(1).max(128)\n}).strict();\nconst CloudJournalSettlementOutcomeSchema = z.enum([\n\t\"completed\",\n\t\"failed\",\n\t\"cancelled\",\n\t\"unknown\"\n]);\n/** Terminal Session settlement; immutable once journaled and replayed until the Server acks it. */\nconst CloudJournalSettlementSchema = z.object({ outcome: CloudJournalSettlementOutcomeSchema }).strict();\nconst CloudJournalDeliveryEntrySchema = z.object({\n\tversion: z.literal(2),\n\t/** Missing on E7 v2 files, which predate Session entries. */\n\tkind: z.literal(\"delivery\").default(\"delivery\"),\n\tdelivery: DirectImMessageDeliveryRequestSchema,\n\tinputHash: z.string().regex(/^[a-f0-9]{64}$/),\n\tscope: CloudJournalScopeSchema,\n\tdeliveryId: z.string().min(1).max(256),\n\trequestId: z.string().min(1).max(256),\n\tturnId: z.string().min(1).max(256),\n\tphase: z.enum(CLOUD_JOURNAL_PHASES),\n\treport: TurnReportRequestSchema.optional()\n}).strict();\nconst CloudJournalSessionEntrySchema = z.object({\n\tversion: z.literal(2),\n\tkind: z.literal(\"session-message\"),\n\tmessage: SessionMessageDeliveryRequestSchema,\n\tsessionKind: z.enum([\"internal\", \"visible\"]),\n\toutboxContext: RuntimeImOutboxContextSchema.optional(),\n\tinputHash: z.string().regex(/^[a-f0-9]{64}$/),\n\tscope: CloudJournalScopeSchema,\n\tmessageId: z.string().uuid(),\n\trequestId: z.string().min(1).max(256),\n\tturnId: z.string().min(1).max(256),\n\tphase: z.enum(CLOUD_JOURNAL_PHASES),\n\tsettlement: CloudJournalSettlementSchema.optional()\n}).strict().superRefine((value, context) => {\n\tif (value.sessionKind === \"visible\" && value.outboxContext === void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"outboxContext\"],\n\t\tmessage: \"A visible Session entry requires its outbox context\"\n\t});\n\tif (value.sessionKind === \"internal\" && value.outboxContext !== void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"outboxContext\"],\n\t\tmessage: \"An internal Session entry forbids IM outbox context\"\n\t});\n\tif (value.phase === \"reported\" && value.settlement === void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"settlement\"],\n\t\tmessage: \"A reported Session entry requires a settlement\"\n\t});\n\tif (value.phase !== \"reported\" && value.settlement !== void 0) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"settlement\"],\n\t\tmessage: \"Only a reported Session entry may carry a settlement\"\n\t});\n});\nconst ENTRY_NAME = /^[a-zA-Z0-9-]{1,256}\\.json$/;\nvar CloudJournalError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = \"CloudJournalError\";\n\t}\n};\n/** Canonical (key-sorted) JSON so the same logical payload always hashes identically. */\nfunction canonicalJson(value) {\n\tif (value === null || typeof value !== \"object\") return JSON.stringify(value) ?? \"null\";\n\tif (Array.isArray(value)) return `[${value.map(canonicalJson).join(\",\")}]`;\n\treturn `{${Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(\",\")}}`;\n}\n/** Stable identity of one IM dispatch payload. */\nfunction computeCloudDeliveryInputHash(delivery) {\n\treturn createHash(\"sha256\").update(canonicalJson(delivery)).digest(\"hex\");\n}\n/** Stable identity of one Session run-frame payload (message plus its target envelope). */\nfunction computeCloudSessionInputHash(input) {\n\tconst { requestId: _requestId, ...message } = input.message;\n\treturn createHash(\"sha256\").update(canonicalJson({\n\t\tmessage,\n\t\tsessionKind: input.sessionKind,\n\t\toutboxContext: input.outboxContext ?? null\n\t})).digest(\"hex\");\n}\n/** The durable file key of one entry: the delivery id or the Session message id. */\nfunction cloudJournalEntryKey(entry) {\n\treturn entry.kind === \"delivery\" ? entry.deliveryId : entry.messageId;\n}\n/** Fail visibly when a durable entry belongs to another allocation. */\nfunction assertCloudJournalScope(entry, scope) {\n\tif (!CloudJournalScopeSchema.safeParse(entry.scope).success) throw new CloudJournalError(\"store_failed\", `Journal entry ${cloudJournalEntryKey(entry)} has an unreadable allocation scope`);\n\tfor (const field of [\n\t\t\"sandboxId\",\n\t\t\"sessionId\",\n\t\t\"environmentGeneration\",\n\t\t\"resourceName\",\n\t\t\"resourceUid\"\n\t]) if (entry.scope[field] !== scope[field]) throw new CloudJournalError(\"scope_mismatch\", `Journal entry ${cloudJournalEntryKey(entry)} belongs to allocation ${entry.scope.sandboxId}/${entry.scope.environmentGeneration} (${entry.scope.resourceUid}), not the current one`);\n}\n/** The internal/visible outbox contract is enforced before anything is written. */\nfunction assertSessionEnvelope(sessionKind, outboxContext) {\n\tif (sessionKind === \"visible\" && outboxContext === void 0) throw new CloudJournalError(\"conflict\", \"A visible Session message requires its outbox context\");\n\tif (sessionKind === \"internal\" && outboxContext !== void 0) throw new CloudJournalError(\"conflict\", \"An internal Session message forbids IM outbox context\");\n}\nvar CloudJournal = class CloudJournal {\n\t#directory;\n\t/** Serializes every mutation so concurrent frames cannot interleave read-modify-write. */\n\t#mutations = Promise.resolve();\n\tconstructor(directory) {\n\t\tthis.#directory = directory;\n\t}\n\tget directory() {\n\t\treturn this.#directory;\n\t}\n\t/** Open (and create) the journal directory with owner-only permissions. */\n\tstatic async open(directory) {\n\t\tawait mkdir(directory, {\n\t\t\trecursive: true,\n\t\t\tmode: 448\n\t\t});\n\t\treturn new CloudJournal(directory);\n\t}\n\t/** Every entry, for reconnect reconciliation. Corrupt files fail loudly, never silently skipped. */\n\tasync list() {\n\t\tconst entryNames = await this.#entryNames();\n\t\tif (entryNames.length > 1024) throw new CloudJournalError(\"store_failed\", `The Cloud delivery journal holds more than ${CLOUD_JOURNAL_MAX_ENTRIES} entries`);\n\t\tconst entries = [];\n\t\tfor (const name of entryNames) entries.push(await this.#readFile(name));\n\t\treturn entries;\n\t}\n\t/**\n\t* E7 rebind cleanup: remove every entry that belongs to exactly the seal-complete assignment.\n\t* Any entry from another allocation fails closed instead of being silently discarded, so a\n\t* broken rebind can never erase durable work that was not proven settled.\n\t*/\n\tasync resetScope(scope) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst entries = await this.list();\n\t\t\tfor (const entry of entries) try {\n\t\t\t\tassertCloudJournalScope(entry, scope);\n\t\t\t} catch {\n\t\t\t\tthrow new CloudJournalError(\"scope_mismatch\", `The Cloud delivery journal holds ${cloudJournalEntryKey(entry)} outside the sealed assignment; refusing to discard`);\n\t\t\t}\n\t\t\tfor (const entry of entries) await this.#remove(cloudJournalEntryKey(entry));\n\t\t});\n\t}\n\t/**\n\t* Durable receipt: fsync BEFORE the receipt frame is sent. Recording the same dispatch twice\n\t* (idempotent retransmission) keeps the original turn id; a different request id, a different\n\t* input payload, or a different allocation for the same delivery is a visible conflict and must\n\t* never be silently merged or re-run.\n\t*/\n\tasync recordReceived(input) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst scope = CloudJournalScopeSchema.parse(input.scope);\n\t\t\tconst inputHash = computeCloudDeliveryInputHash(input.delivery);\n\t\t\tconst existing = await this.#readEntry(input.deliveryId);\n\t\t\tif (existing) {\n\t\t\t\tif (existing.kind !== \"delivery\") throw new CloudJournalError(\"conflict\", `Journal entry ${input.deliveryId} is not an IM delivery`);\n\t\t\t\tassertCloudJournalScope(existing, scope);\n\t\t\t\tif (existing.requestId !== input.requestId) throw new CloudJournalError(\"conflict\", `Journal entry for delivery ${input.deliveryId} belongs to a different dispatch`);\n\t\t\t\tif (existing.inputHash !== inputHash) throw new CloudJournalError(\"conflict\", `Journal entry for delivery ${input.deliveryId} was already received with different input`);\n\t\t\t\treturn existing;\n\t\t\t}\n\t\t\tawait this.#assertCapacity();\n\t\t\tconst entry = {\n\t\t\t\tkind: \"delivery\",\n\t\t\t\tdelivery: input.delivery,\n\t\t\t\tinputHash,\n\t\t\t\tscope,\n\t\t\t\tdeliveryId: input.deliveryId,\n\t\t\t\trequestId: input.requestId,\n\t\t\t\tturnId: input.turnId,\n\t\t\t\tphase: \"received\"\n\t\t\t};\n\t\t\tawait this.#write(input.deliveryId, entry);\n\t\t\treturn entry;\n\t\t});\n\t}\n\t/** received -> started, fsynced BEFORE the native worker launches. */\n\tasync markStarted(deliveryId, scope) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst entry = await this.#requireScopedDeliveryEntry(deliveryId, scope);\n\t\t\tif (entry.phase === \"received\") return this.#transitionDelivery(entry, \"started\");\n\t\t\tif (entry.phase === \"started\") return entry;\n\t\t\tthrow new CloudJournalError(\"invalid_transition\", `Delivery ${deliveryId} cannot start from phase ${entry.phase}`);\n\t\t});\n\t}\n\t/**\n\t* started -> reported with the exact Turn Report, fsynced BEFORE the report frame is sent.\n\t* received -> reported is admitted ONLY for a terminal `not_started` failure that proves no\n\t* native/Pi/tool work happened (missing/expired model grant, expired deadline, cancel).\n\t*/\n\tasync recordReport(deliveryId, scope, report) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst entry = await this.#requireScopedDeliveryEntry(deliveryId, scope);\n\t\t\tif (entry.phase === \"reported\") {\n\t\t\t\tif (entry.report?.resultHash !== report.resultHash) throw new CloudJournalError(\"conflict\", `Delivery ${deliveryId} already has a different journaled report`);\n\t\t\t\treturn entry;\n\t\t\t}\n\t\t\tif (entry.phase === \"received\" && report.executionEffects !== \"not_started\") throw new CloudJournalError(\"invalid_transition\", `Delivery ${deliveryId} cannot report effects \"${report.executionEffects}\" from phase received`);\n\t\t\treturn this.#transitionDelivery(entry, \"reported\", report);\n\t\t});\n\t}\n\t/**\n\t* The Server explicitly refused custody before any start (stale scope/generation). Only a\n\t* `received` entry may retire this way; a started/reported entry represents real durable state.\n\t*/\n\tasync clearRejected(deliveryId, scope) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst entry = await this.#requireScopedDeliveryEntry(deliveryId, scope);\n\t\t\tif (entry.phase !== \"received\") throw new CloudJournalError(\"invalid_transition\", `Delivery ${deliveryId} cannot be retired as rejected from phase ${entry.phase}`);\n\t\t\tawait this.#remove(deliveryId);\n\t\t});\n\t}\n\t/**\n\t* The Server durably acknowledged THIS exact report: only a matching turn id, result hash, and\n\t* recorded/already_recorded status retires the entry. Conflicts and stale-generation acks leave\n\t* the durable report in place for reconciliation.\n\t*/\n\tasync clearAcknowledged(deliveryId, scope, ack) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst entry = await this.#requireScopedDeliveryEntry(deliveryId, scope);\n\t\t\tif (entry.phase !== \"reported\" || !entry.report) throw new CloudJournalError(\"invalid_transition\", `Delivery ${deliveryId} has no durable report to acknowledge (phase ${entry.phase})`);\n\t\t\tif (entry.turnId !== ack.turnId || entry.report.resultHash !== ack.resultHash || ack.status !== \"recorded\" && ack.status !== \"already_recorded\") throw new CloudJournalError(\"ack_mismatch\", `The acknowledgement does not match the journaled report`);\n\t\t\tawait this.#remove(deliveryId);\n\t\t});\n\t}\n\t/** Journal one authorized Session message (fsync) BEFORE its receipt frame. */\n\tasync recordSessionReceived(input) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst scope = CloudJournalScopeSchema.parse(input.scope);\n\t\t\tassertSessionEnvelope(input.sessionKind, input.outboxContext);\n\t\t\tconst messageId = input.message.messageId;\n\t\t\tconst inputHash = computeCloudSessionInputHash({\n\t\t\t\tmessage: input.message,\n\t\t\t\tsessionKind: input.sessionKind,\n\t\t\t\t...input.outboxContext ? { outboxContext: input.outboxContext } : {}\n\t\t\t});\n\t\t\tconst existing = await this.#readEntry(messageId);\n\t\t\tif (existing) return this.#reuseSessionEntry(existing, input, inputHash, scope);\n\t\t\tawait this.#assertCapacity();\n\t\t\tconst entry = {\n\t\t\t\tkind: \"session-message\",\n\t\t\t\tmessage: input.message,\n\t\t\t\tinputHash,\n\t\t\t\tscope,\n\t\t\t\tmessageId,\n\t\t\t\trequestId: input.requestId,\n\t\t\t\tturnId: input.turnId,\n\t\t\t\tphase: \"received\",\n\t\t\t\tsessionKind: input.sessionKind,\n\t\t\t\t...input.outboxContext ? { outboxContext: input.outboxContext } : {}\n\t\t\t};\n\t\t\tawait this.#write(messageId, entry);\n\t\t\treturn entry;\n\t\t});\n\t}\n\t/**\n\t* Reuse one already-journaled Session dispatch: same request identity and input under the same\n\t* allocation. Any difference is a visible conflict, never a second execution.\n\t*/\n\t#reuseSessionEntry(existing, input, inputHash, scope) {\n\t\tconst messageId = input.message.messageId;\n\t\tif (existing.kind !== \"session-message\") throw new CloudJournalError(\"conflict\", `Journal entry ${messageId} is not a Session message`);\n\t\tassertCloudJournalScope(existing, scope);\n\t\tif (existing.requestId !== input.requestId) throw new CloudJournalError(\"conflict\", `Journal entry for Session message ${messageId} belongs to a different dispatch`);\n\t\tif (existing.inputHash !== inputHash) throw new CloudJournalError(\"conflict\", `Journal entry for Session message ${messageId} was already received with different input`);\n\t\treturn existing;\n\t}\n\t/** received -> started, fsynced BEFORE the native worker launches. */\n\tasync markSessionStarted(messageId, scope) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst entry = await this.#requireScopedSessionEntry(messageId, scope);\n\t\t\tif (entry.phase === \"received\") return this.#transitionSession(entry, \"started\");\n\t\t\tif (entry.phase === \"started\") return entry;\n\t\t\tthrow new CloudJournalError(\"invalid_transition\", `Session message ${messageId} cannot start from phase ${entry.phase}`);\n\t\t});\n\t}\n\t/**\n\t* Terminal Session settlement, fsynced BEFORE the settled frame. Immutable once written: a\n\t* replay with the same outcome returns the recorded entry and a different one is a conflict.\n\t* `received -> reported` is admitted only for a non-completed outcome (cancel/failure before any\n\t* effect), never for `completed`.\n\t*/\n\tasync recordSessionSettled(messageId, scope, outcome) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst entry = await this.#requireScopedSessionEntry(messageId, scope);\n\t\t\tif (entry.phase === \"reported\") {\n\t\t\t\tif (entry.settlement?.outcome !== outcome) throw new CloudJournalError(\"conflict\", `Session message ${messageId} already has a different journaled settlement`);\n\t\t\t\treturn entry;\n\t\t\t}\n\t\t\tif (entry.phase === \"received\" && outcome === \"completed\") throw new CloudJournalError(\"invalid_transition\", `Session message ${messageId} cannot report completion from phase received`);\n\t\t\treturn this.#transitionSession(entry, \"reported\", outcome);\n\t\t});\n\t}\n\t/** The Server refused custody before any start; only a `received` Session entry may retire. */\n\tasync clearSessionRejected(messageId, scope) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst entry = await this.#requireScopedSessionEntry(messageId, scope);\n\t\t\tif (entry.phase !== \"received\") throw new CloudJournalError(\"invalid_transition\", `Session message ${messageId} cannot be retired as rejected from phase ${entry.phase}`);\n\t\t\tawait this.#remove(messageId);\n\t\t});\n\t}\n\t/**\n\t* Retire a `received` Session entry whose journaled input was superseded by a new dispatch\n\t* attempt and journal the new attempt instead. The old entry never started — a verified that\n\t* arrives later misses its retired request id — so no execution evidence is erased; the Server\n\t* replaces its never-executed custody record with the new attempt. The new entry REPLACES the\n\t* entry file through the existing atomic temp-write + rename (`#write`), so a crash or IO\n\t* failure leaves either the old entry or the new entry fully intact — never a torn file — and\n\t* the failed call surfaces instead of silently erasing custody.\n\t*/\n\tasync replaceSessionReceived(input) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst scope = CloudJournalScopeSchema.parse(input.scope);\n\t\t\tassertSessionEnvelope(input.sessionKind, input.outboxContext);\n\t\t\tconst messageId = input.message.messageId;\n\t\t\tconst existing = await this.#requireScopedSessionEntry(messageId, scope);\n\t\t\tif (existing.phase !== \"received\") throw new CloudJournalError(\"invalid_transition\", `Session message ${messageId} cannot be superseded from phase ${existing.phase}`);\n\t\t\tconst entry = {\n\t\t\t\tkind: \"session-message\",\n\t\t\t\tmessage: input.message,\n\t\t\t\tinputHash: computeCloudSessionInputHash({\n\t\t\t\t\tmessage: input.message,\n\t\t\t\t\tsessionKind: input.sessionKind,\n\t\t\t\t\t...input.outboxContext ? { outboxContext: input.outboxContext } : {}\n\t\t\t\t}),\n\t\t\t\tscope,\n\t\t\t\tmessageId,\n\t\t\t\trequestId: input.requestId,\n\t\t\t\tturnId: input.turnId,\n\t\t\t\tphase: \"received\",\n\t\t\t\tsessionKind: input.sessionKind,\n\t\t\t\t...input.outboxContext ? { outboxContext: input.outboxContext } : {}\n\t\t\t};\n\t\t\tawait this.#write(messageId, entry);\n\t\t\treturn entry;\n\t\t});\n\t}\n\t/**\n\t* Correlate a `received` Session entry with a new dispatch attempt of identical input. The Turn\n\t* identity and phase are untouched — only the receipt correlation id moves, fsynced before the\n\t* new attempt's receipt is sent. A started/reported entry keeps its established identity: its\n\t* settlement is already correlated with the Server's custody record.\n\t*/\n\tasync updateSessionRequestId(messageId, scope, requestId) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst entry = await this.#requireScopedSessionEntry(messageId, scope);\n\t\t\tif (entry.requestId === requestId) return entry;\n\t\t\tif (entry.phase !== \"received\") throw new CloudJournalError(\"invalid_transition\", `Session message ${messageId} cannot be re-correlated from phase ${entry.phase}`);\n\t\t\tconst next = {\n\t\t\t\t...entry,\n\t\t\t\trequestId\n\t\t\t};\n\t\t\tawait this.#write(messageId, next);\n\t\t\treturn next;\n\t\t});\n\t}\n\t/**\n\t* Exact settlement ack: only a matching turn id and recorded/already_recorded status retire the\n\t* immutable terminal entry. Unknown or mismatched acks leave it durable for replay.\n\t*/\n\tasync clearSessionAcknowledged(messageId, scope, ack) {\n\t\treturn this.#mutate(async () => {\n\t\t\tconst entry = await this.#requireScopedSessionEntry(messageId, scope);\n\t\t\tif (entry.phase !== \"reported\" || !entry.settlement) throw new CloudJournalError(\"invalid_transition\", `Session message ${messageId} has no durable settlement to acknowledge (phase ${entry.phase})`);\n\t\t\tif (entry.turnId !== ack.turnId || ack.status !== \"recorded\" && ack.status !== \"already_recorded\") throw new CloudJournalError(\"ack_mismatch\", \"The acknowledgement does not match the journaled settlement\");\n\t\t\tawait this.#remove(messageId);\n\t\t});\n\t}\n\t/** Read one entry without scope assumptions; callers assert scope before acting on it. */\n\tasync read(entryKey) {\n\t\treturn this.#readEntry(entryKey);\n\t}\n\tasync #requireScopedDeliveryEntry(deliveryId, scope) {\n\t\tconst entry = await this.#readEntry(deliveryId);\n\t\tif (!entry) throw new CloudJournalError(\"unknown_entry\", `No journaled delivery ${deliveryId}`);\n\t\tif (entry.kind !== \"delivery\") throw new CloudJournalError(\"unknown_entry\", `No journaled delivery ${deliveryId}`);\n\t\tassertCloudJournalScope(entry, scope);\n\t\treturn entry;\n\t}\n\tasync #requireScopedSessionEntry(messageId, scope) {\n\t\tconst entry = await this.#readEntry(messageId);\n\t\tif (entry?.kind !== \"session-message\") throw new CloudJournalError(\"unknown_entry\", `No journaled Session message ${messageId}`);\n\t\tassertCloudJournalScope(entry, scope);\n\t\treturn entry;\n\t}\n\tasync #assertCapacity() {\n\t\tif ((await this.#entryNames()).length >= 1024) throw new CloudJournalError(\"store_failed\", `The Cloud delivery journal is at its ${CLOUD_JOURNAL_MAX_ENTRIES}-entry capacity`);\n\t}\n\tasync #mutate(operation) {\n\t\tconst run = this.#mutations.then(operation, operation);\n\t\tthis.#mutations = run.then(() => void 0, () => void 0);\n\t\treturn run;\n\t}\n\t/** Durable entry file names, sorted; used for the capacity check and full reads. */\n\tasync #entryNames() {\n\t\tlet names;\n\t\ttry {\n\t\t\tnames = await readdir(this.#directory);\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return [];\n\t\t\tthrow error;\n\t\t}\n\t\treturn names.filter((name) => ENTRY_NAME.test(name)).sort();\n\t}\n\tasync #readEntry(entryKey) {\n\t\ttry {\n\t\t\treturn await this.#readFile(`${entryKey}.json`);\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return void 0;\n\t\t\tthrow error;\n\t\t}\n\t}\n\tasync #readFile(name) {\n\t\tif (!ENTRY_NAME.test(name)) throw new CloudJournalError(\"store_failed\", `Unsafe Cloud delivery journal entry name ${name}`);\n\t\tlet raw;\n\t\ttry {\n\t\t\traw = await readFile(join(this.#directory, name), \"utf8\");\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") throw error;\n\t\t\tthrow new CloudJournalError(\"store_failed\", `The Cloud delivery journal entry ${name} could not be read`);\n\t\t}\n\t\tlet parsedJson;\n\t\ttry {\n\t\t\tparsedJson = JSON.parse(raw);\n\t\t} catch {\n\t\t\tthrow new CloudJournalError(\"store_failed\", `The Cloud delivery journal entry ${name} is not valid JSON`);\n\t\t}\n\t\tconst session = CloudJournalSessionEntrySchema.safeParse(parsedJson);\n\t\tif (session.success) return {\n\t\t\tkind: \"session-message\",\n\t\t\tmessage: session.data.message,\n\t\t\tinputHash: session.data.inputHash,\n\t\t\tscope: session.data.scope,\n\t\t\tmessageId: session.data.messageId,\n\t\t\trequestId: session.data.requestId,\n\t\t\tturnId: session.data.turnId,\n\t\t\tphase: session.data.phase,\n\t\t\tsessionKind: session.data.sessionKind,\n\t\t\t...session.data.outboxContext ? { outboxContext: session.data.outboxContext } : {},\n\t\t\t...session.data.settlement ? { settlement: session.data.settlement } : {}\n\t\t};\n\t\tconst delivery = CloudJournalDeliveryEntrySchema.safeParse(parsedJson);\n\t\tif (delivery.success) return {\n\t\t\tkind: \"delivery\",\n\t\t\tdelivery: delivery.data.delivery,\n\t\t\tinputHash: delivery.data.inputHash,\n\t\t\tscope: delivery.data.scope,\n\t\t\tdeliveryId: delivery.data.deliveryId,\n\t\t\trequestId: delivery.data.requestId,\n\t\t\tturnId: delivery.data.turnId,\n\t\t\tphase: delivery.data.phase,\n\t\t\t...delivery.data.report ? { report: delivery.data.report } : {}\n\t\t};\n\t\tthrow new CloudJournalError(\"store_failed\", `The Cloud delivery journal entry ${name} is unreadable`);\n\t}\n\tasync #transitionDelivery(entry, phase, report) {\n\t\tconst next = {\n\t\t\t...entry,\n\t\t\tphase,\n\t\t\t...report ? { report } : {}\n\t\t};\n\t\tawait this.#write(entry.deliveryId, next);\n\t\treturn next;\n\t}\n\tasync #transitionSession(entry, phase, settlement) {\n\t\tconst next = {\n\t\t\t...entry,\n\t\t\tphase,\n\t\t\t...settlement ? { settlement: { outcome: settlement } } : {}\n\t\t};\n\t\tawait this.#write(entry.messageId, next);\n\t\treturn next;\n\t}\n\t/** Atomic write: temp file, fsync, rename, directory fsync. Serialized by the caller. */\n\tasync #write(entryKey, entry) {\n\t\tconst target = this.#path(entryKey);\n\t\tconst serialized = `${JSON.stringify({\n\t\t\tversion: 2,\n\t\t\t...entry\n\t\t})}\\n`;\n\t\tif (Buffer.byteLength(serialized, \"utf8\") > 327680) throw new CloudJournalError(\"store_failed\", `The Cloud delivery journal entry for ${entryKey} exceeds ${CLOUD_JOURNAL_ENTRY_MAX_BYTES} bytes`);\n\t\tconst temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;\n\t\tlet file;\n\t\ttry {\n\t\t\tfile = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 384);\n\t\t} catch {\n\t\t\tthrow new CloudJournalError(\"store_failed\", `The Cloud delivery journal entry for ${entryKey} could not be written`);\n\t\t}\n\t\ttry {\n\t\t\tawait file.writeFile(serialized, \"utf8\");\n\t\t\tawait file.sync();\n\t\t} catch {\n\t\t\tthrow new CloudJournalError(\"store_failed\", `The Cloud delivery journal entry for ${entryKey} could not be synced`);\n\t\t} finally {\n\t\t\tawait file.close();\n\t\t}\n\t\ttry {\n\t\t\tawait rename(temporary, target);\n\t\t\tawait this.#syncDirectory();\n\t\t} catch {\n\t\t\tawait rm(temporary, { force: true }).catch(() => void 0);\n\t\t\tthrow new CloudJournalError(\"store_failed\", `The Cloud delivery journal entry for ${entryKey} was not durable`);\n\t\t}\n\t}\n\tasync #remove(entryKey) {\n\t\tawait rm(this.#path(entryKey), { force: true });\n\t\tawait this.#syncDirectory();\n\t}\n\tasync #syncDirectory() {\n\t\tconst directory = await open(this.#directory, constants.O_RDONLY);\n\t\ttry {\n\t\t\tawait directory.sync();\n\t\t} finally {\n\t\t\tawait directory.close();\n\t\t}\n\t}\n\t#path(entryKey) {\n\t\tif (!/^[a-zA-Z0-9-]{1,256}$/.test(entryKey)) throw new CloudJournalError(\"store_failed\", \"Unsafe delivery id for the journal path\");\n\t\treturn join(this.#directory, `${entryKey}.json`);\n\t}\n};\n//#endregion\n//#region src/agent-runtime/provider-id.ts\nconst AGENT_RUNTIME_PROVIDER_ID_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;\nfunction isAgentRuntimeProviderId(value) {\n\treturn typeof value === \"string\" && AGENT_RUNTIME_PROVIDER_ID_PATTERN.test(value);\n}\n//#endregion\n//#region src/runtime/agent-runtime-provider-registry.ts\nconst logger$4 = createLogger(\"runtime-provider-registry\");\nvar AgentRuntimeProviderUnavailableError = class extends Error {\n\tproviderId;\n\tresult;\n\tconstructor(providerId, result, options) {\n\t\tconst detail = result.issues.map((issue) => `${issue.code}: ${issue.message}`).join(\"; \") || \"not ready\";\n\t\tsuper(`Agent Runtime provider is unavailable (${providerId}): ${detail}`, options);\n\t\tthis.providerId = providerId;\n\t\tthis.result = result;\n\t\tthis.name = \"AgentRuntimeProviderUnavailableError\";\n\t}\n};\nvar AgentRuntimeProviderRegistry = class {\n\t#providers = /* @__PURE__ */ new Map();\n\t#ready = /* @__PURE__ */ new Set();\n\t#probeResults = /* @__PURE__ */ new Map();\n\t#probes = /* @__PURE__ */ new Map();\n\tconstructor(registrations = []) {\n\t\tfor (const registration of registrations) {\n\t\t\tconst providerId = registration.factory.manifest.providerId;\n\t\t\tif (!isAgentRuntimeProviderId(providerId) || this.#providers.has(providerId)) throw new Error(`Agent Runtime provider registration is invalid or duplicated: ${providerId}`);\n\t\t\tif (registration.factory.manifest.contractVersion !== 2) throw new Error(`Agent Runtime provider contract version is incompatible: ${providerId} requires 2`);\n\t\t\tif (!/^[0-9a-f]{64}$/.test(registration.artifactIdentity)) throw new Error(`Agent Runtime provider artifact identity is invalid: ${providerId}`);\n\t\t\tthis.#providers.set(providerId, Object.freeze({ ...registration }));\n\t\t}\n\t}\n\tregistration(providerId) {\n\t\treturn this.#providers.get(providerId);\n\t}\n\tproviderIds() {\n\t\treturn [...this.#providers.keys()];\n\t}\n\tartifactIdentity(providerId) {\n\t\treturn this.#providers.get(providerId)?.artifactIdentity;\n\t}\n\tisReady(providerId) {\n\t\treturn this.#ready.has(providerId);\n\t}\n\tinvalidate(providerId, result) {\n\t\tthis.#ready.delete(providerId);\n\t\tif (result) this.#probeResults.set(providerId, result);\n\t}\n\tprobeResult(providerId) {\n\t\treturn this.#probeResults.get(providerId);\n\t}\n\tvalidate(snapshot) {\n\t\tconst configured = this.validateConfiguration(snapshot);\n\t\tif (configured) return configured;\n\t\tif (!this.#ready.has(snapshot.provider)) return \"provider_unavailable\";\n\t}\n\tvalidateConfiguration(snapshot) {\n\t\tconst provider = this.#providers.get(snapshot.provider);\n\t\tif (!provider) return \"configuration_unsupported\";\n\t\treturn provider.validate(snapshot);\n\t}\n\tasync ensureReady(providerId, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (this.#ready.has(providerId)) return;\n\t\tawait this.#probe(providerId, signal);\n\t}\n\tasync refresh(providerId, signal) {\n\t\tsignal?.throwIfAborted();\n\t\ttry {\n\t\t\tawait this.#probe(providerId, signal);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (signal?.aborted) throw error;\n\t\t\tlogger$4.debug({\n\t\t\t\tcode: \"provider_refresh_failed\",\n\t\t\t\tproviderId,\n\t\t\t\terror: String(error)\n\t\t\t}, \"Agent Runtime provider refresh failed\");\n\t\t\tthis.#ready.delete(providerId);\n\t\t\treturn false;\n\t\t}\n\t}\n\tasync #probe(providerId, signal) {\n\t\tlet probe = this.#probes.get(providerId);\n\t\tif (!probe) {\n\t\t\tconst provider = this.#providers.get(providerId);\n\t\t\tif (!provider) throw new Error(`Agent Runtime provider is not registered: ${providerId}`);\n\t\t\tthis.#probeResults.delete(providerId);\n\t\t\tconst controller = new AbortController();\n\t\t\tlet record;\n\t\t\tconst promise = (async () => {\n\t\t\t\tconst result = await provider.factory.probe({ signal: controller.signal });\n\t\t\t\tif (this.#probes.get(providerId) === record) this.#probeResults.set(providerId, result);\n\t\t\t\tif (!result.ready) throw new AgentRuntimeProviderUnavailableError(providerId, result);\n\t\t\t\ttry {\n\t\t\t\t\tawait provider.verifyArtifact?.(controller.signal);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger$4.debug({\n\t\t\t\t\t\tcode: \"provider_artifact_verification_failed\",\n\t\t\t\t\t\tproviderId,\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Agent Runtime provider artifact verification failed\");\n\t\t\t\t\tif (this.#probes.get(providerId) === record) this.#probeResults.set(providerId, {\n\t\t\t\t\t\tready: false,\n\t\t\t\t\t\tissues: [{\n\t\t\t\t\t\t\tcode: \"temporarily_unavailable\",\n\t\t\t\t\t\t\tmessage: \"Provider artifact verification failed\"\n\t\t\t\t\t\t}]\n\t\t\t\t\t});\n\t\t\t\t\tthrow new AgentRuntimeProviderUnavailableError(providerId, {\n\t\t\t\t\t\tready: false,\n\t\t\t\t\t\tissues: [{\n\t\t\t\t\t\t\tcode: \"temporarily_unavailable\",\n\t\t\t\t\t\t\tmessage: \"Provider artifact verification failed\"\n\t\t\t\t\t\t}]\n\t\t\t\t\t}, { cause: error });\n\t\t\t\t}\n\t\t\t\tcontroller.signal.throwIfAborted();\n\t\t\t\tif (this.#probes.get(providerId) === record) this.#ready.add(providerId);\n\t\t\t})().finally(() => {\n\t\t\t\trecord.settled = true;\n\t\t\t\tif (this.#probes.get(providerId) === record) this.#probes.delete(providerId);\n\t\t\t});\n\t\t\tpromise.catch((error) => {\n\t\t\t\tlogger$4.debug({\n\t\t\t\t\tcode: \"provider_probe_failed\",\n\t\t\t\t\tproviderId,\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Agent Runtime provider probe failed\");\n\t\t\t});\n\t\t\trecord = {\n\t\t\t\tcontroller,\n\t\t\t\tpromise,\n\t\t\t\tsettled: false,\n\t\t\t\twaiters: 0\n\t\t\t};\n\t\t\tprobe = record;\n\t\t\tthis.#probes.set(providerId, probe);\n\t\t}\n\t\tprobe.waiters += 1;\n\t\ttry {\n\t\t\tawait waitForProbe(probe.promise, signal);\n\t\t} finally {\n\t\t\tprobe.waiters -= 1;\n\t\t\tif (probe.waiters === 0 && !probe.settled) {\n\t\t\t\tprobe.controller.abort(/* @__PURE__ */ new Error(`Agent Runtime provider probe has no waiters: ${providerId}`));\n\t\t\t\t/* v8 ignore else -- the registry still maps this probe while its last waiter unwinds. */\n\t\t\t\tif (this.#probes.get(providerId) === probe) this.#probes.delete(providerId);\n\t\t\t}\n\t\t}\n\t}\n};\nasync function waitForProbe(probe, signal) {\n\tif (!signal) return probe;\n\tsignal.throwIfAborted();\n\tlet rejectAborted;\n\tconst aborted = new Promise((_resolve, reject) => {\n\t\trejectAborted = reject;\n\t});\n\tconst onAbort = () => rejectAborted(signal.reason);\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\ttry {\n\t\tawait Promise.race([probe, aborted]);\n\t\tsignal.throwIfAborted();\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\n//#endregion\n//#region src/runtime/provider-cli/outgoing-reply-post.ts\nfunction isRecord$3(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction postToPlainText(post) {\n\tif (!isRecord$3(post)) return \"\";\n\tconst body = unwrapPostLocale(post);\n\tconst parts = [];\n\tif (body) {\n\t\tif (typeof body.title === \"string\" && body.title !== \"\") parts.push(body.title);\n\t\tfor (const paragraph of selectContentBlocks(body)) parts.push(Array.isArray(paragraph) ? paragraph.map(renderPostElem).join(\"\") : \"\");\n\t}\n\tconst attachments = renderPostAttachments(post);\n\tif (attachments.length === 0) return parts.join(\"\\n\");\n\tif (parts.length === 0) return attachments;\n\treturn `${parts.join(\"\\n\")}\\n${attachments}`;\n}\nfunction unwrapPostLocale(parsed) {\n\tif (\"content\" in parsed || \"content_v2\" in parsed || \"title\" in parsed) return parsed;\n\tfor (const locale of [\n\t\t\"zh_cn\",\n\t\t\"en_us\",\n\t\t\"ja_jp\"\n\t]) {\n\t\tconst value = parsed[locale];\n\t\tif (isRecord$3(value)) return value;\n\t}\n\tfor (const value of Object.values(parsed)) if (isRecord$3(value) && (Array.isArray(value.content) || Array.isArray(value.content_v2))) return value;\n}\nfunction selectContentBlocks(body) {\n\tif (Array.isArray(body.content_v2) && body.content_v2.length > 0) return body.content_v2;\n\treturn Array.isArray(body.content) ? body.content : [];\n}\nfunction renderPostElem(element) {\n\tif (!isRecord$3(element)) return \"\";\n\tconst tag = typeof element.tag === \"string\" ? element.tag : \"\";\n\tconst text = typeof element.text === \"string\" ? element.text : \"\";\n\tif (tag === \"text\" || tag === \"md\") return text;\n\tif (tag === \"a\") return renderPostLink(text, typeof element.href === \"string\" ? element.href : \"\");\n\tif (tag === \"at\") return renderPostMention(element);\n\treturn renderPostMediaElem(tag, element, text);\n}\nfunction renderPostMediaElem(tag, element, text) {\n\tif (tag === \"emotion\" || tag === \"img\" || tag === \"media\") return renderPostEmbed(tag, element);\n\tif (tag === \"code_block\") return renderPostCode(text, typeof element.language === \"string\" ? element.language : \"\");\n\tif (tag === \"hr\") return \"\\n---\\n\";\n\treturn text;\n}\nfunction renderPostEmbed(tag, element) {\n\tif (tag === \"emotion\") return typeof element.emoji_type === \"string\" && element.emoji_type ? `:${element.emoji_type}:` : \"\";\n\tif (tag === \"img\") return typeof element.image_key === \"string\" && element.image_key ? `![Image](${element.image_key})` : \"[Image]\";\n\treturn typeof element.file_key === \"string\" && element.file_key ? `[Media: ${element.file_key}]` : \"[Media]\";\n}\nfunction renderPostLink(text, href) {\n\tif (href && text) return `[${text}](${href})`;\n\treturn href || text;\n}\nfunction renderPostMention(element) {\n\tconst userId = typeof element.user_id === \"string\" ? element.user_id : \"\";\n\tconst name = typeof element.user_name === \"string\" ? element.user_name : \"\";\n\tif (userId === \"@_all\" || userId === \"all\") return \"<at user_id=\\\"all\\\"></at>\";\n\tif (name) return userId.startsWith(\"ou\") ? `<at user_id=\"${userId}\">${name}</at>` : `@${name}`;\n\treturn userId ? `@${userId}` : \"@mention\";\n}\nfunction renderPostCode(code, language) {\n\treturn language ? `\\n\\`\\`\\`${language}\\n${code}\\n\\`\\`\\`\\n` : `\\n\\`\\`\\`\\n${code}\\n\\`\\`\\`\\n`;\n}\nfunction renderPostAttachments(parsed) {\n\tif (!Array.isArray(parsed.files) || parsed.files.length === 0) return \"\";\n\tconst lines = [];\n\tfor (const raw of parsed.files) {\n\t\tif (!isRecord$3(raw)) continue;\n\t\tconst key = typeof raw.file_key === \"string\" ? raw.file_key : \"\";\n\t\tif (!key) continue;\n\t\tconst tag = raw.is_folder === true ? \"folder\" : \"file\";\n\t\tconst name = typeof raw.file_name === \"string\" ? raw.file_name : \"\";\n\t\tlines.push(name ? `<${tag} key=\"${key}\" name=\"${name}\"/>` : `<${tag} key=\"${key}\"/>`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n//#endregion\n//#region src/runtime/provider-cli/outgoing-reply-process.ts\nasync function spawnInheritedProcess(options) {\n\treturn new Promise((resolveExit, reject) => {\n\t\tconst child = spawn(options.file, [...options.args], {\n\t\t\tenv: options.env,\n\t\t\tshell: false,\n\t\t\tstdio: \"inherit\",\n\t\t\twindowsHide: true\n\t\t});\n\t\tconst forward = (signal) => {\n\t\t\tif (child.killed || child.exitCode !== null) return;\n\t\t\tchild.kill(signal);\n\t\t};\n\t\tconst onSigterm = () => forward(\"SIGTERM\");\n\t\tconst onSigint = () => forward(\"SIGINT\");\n\t\tprocess.on(\"SIGTERM\", onSigterm);\n\t\tprocess.on(\"SIGINT\", onSigint);\n\t\tconst stopListening = () => {\n\t\t\tprocess.off(\"SIGTERM\", onSigterm);\n\t\t\tprocess.off(\"SIGINT\", onSigint);\n\t\t};\n\t\tchild.once(\"error\", (error) => {\n\t\t\tstopListening();\n\t\t\treject(error);\n\t\t});\n\t\tchild.once(\"exit\", (code, signal) => {\n\t\t\tstopListening();\n\t\t\tif (code !== null) {\n\t\t\t\tresolveExit(code);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (signal === \"SIGTERM\") {\n\t\t\t\tresolveExit(143);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (signal === \"SIGINT\") {\n\t\t\t\tresolveExit(130);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolveExit(1);\n\t\t});\n\t});\n}\nasync function flushStdout() {\n\tconst stdout = process.stdout;\n\tif (!stdout.writable || stdout.destroyed) return;\n\tif (typeof stdout.writableLength === \"number\" && stdout.writableLength === 0 && !stdout.writableNeedDrain) return;\n\tawait new Promise((resolve) => {\n\t\tconst finish = () => resolve();\n\t\tstdout.once(\"drain\", finish);\n\t\tif (stdout.write(Buffer.alloc(0))) {\n\t\t\tstdout.off(\"drain\", finish);\n\t\t\tresolve();\n\t\t}\n\t});\n}\nasync function spawnCapturedProcess(options) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst child = spawn(options.file, [...options.args], {\n\t\t\tenv: options.env,\n\t\t\tshell: false,\n\t\t\tstdio: options.forward ? [\n\t\t\t\t\"inherit\",\n\t\t\t\t\"pipe\",\n\t\t\t\t\"inherit\"\n\t\t\t] : [\n\t\t\t\t\"ignore\",\n\t\t\t\t\"pipe\",\n\t\t\t\t\"pipe\"\n\t\t\t],\n\t\t\twindowsHide: true\n\t\t});\n\t\tconst capture = createStdoutCapture(options.maxBytes, options.forward, {\n\t\t\tpause: () => child.stdout?.pause(),\n\t\t\tresume: () => child.stdout?.resume()\n\t\t});\n\t\tlet exitCode = 1;\n\t\tlet timedOut = false;\n\t\tlet settled = false;\n\t\tconst settle = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tstopListening();\n\t\t\tresolve({\n\t\t\t\tcode: exitCode,\n\t\t\t\tstdout: Buffer.concat(capture.chunks),\n\t\t\t\ttruncated: capture.truncated,\n\t\t\t\ttimedOut\n\t\t\t});\n\t\t};\n\t\tconst stopListening = () => {\n\t\t\tif (options.forward) {\n\t\t\t\tprocess.off(\"SIGTERM\", onSigterm);\n\t\t\t\tprocess.off(\"SIGINT\", onSigint);\n\t\t\t}\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tif (forceTimer) clearTimeout(forceTimer);\n\t\t};\n\t\tconst forwardSignal = (signal) => {\n\t\t\tif (child.killed || child.exitCode !== null) return;\n\t\t\tchild.kill(signal);\n\t\t};\n\t\tconst onSigterm = () => forwardSignal(\"SIGTERM\");\n\t\tconst onSigint = () => forwardSignal(\"SIGINT\");\n\t\tif (options.forward) {\n\t\t\tprocess.on(\"SIGTERM\", onSigterm);\n\t\t\tprocess.on(\"SIGINT\", onSigint);\n\t\t}\n\t\tchild.stdout?.on(\"data\", capture.onChunk);\n\t\tchild.stdout?.on(\"error\", () => void 0);\n\t\tif (!options.forward) child.stderr?.resume();\n\t\tchild.once(\"error\", (error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tstopListening();\n\t\t\treject(error);\n\t\t});\n\t\tchild.once(\"exit\", (code, signal) => {\n\t\t\tif (code !== null) exitCode = code;\n\t\t\telse if (signal === \"SIGTERM\") exitCode = 143;\n\t\t\telse if (signal === \"SIGINT\") exitCode = 130;\n\t\t\telse exitCode = 1;\n\t\t});\n\t\tchild.once(\"close\", () => settle());\n\t\tlet forceTimer;\n\t\tconst timer = options.timeoutMs === void 0 ? void 0 : setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tchild.stdout?.destroy();\n\t\t\tchild.stderr?.destroy();\n\t\t\tif (child.exitCode === null && !child.killed) child.kill(\"SIGKILL\");\n\t\t\tforceTimer = setTimeout(settle, 50);\n\t\t\tforceTimer.unref();\n\t\t}, options.timeoutMs);\n\t\ttimer?.unref();\n\t});\n}\nfunction createStdoutCapture(maxBytes, forward, flow) {\n\tconst chunks = [];\n\tlet captured = 0;\n\tlet truncated = false;\n\tlet waitingForDrain = false;\n\treturn {\n\t\tchunks,\n\t\tget truncated() {\n\t\t\treturn truncated;\n\t\t},\n\t\tonChunk(chunk) {\n\t\t\tconst buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n\t\t\tif (forward) {\n\t\t\t\tif (!process.stdout.write(buf) && !waitingForDrain) {\n\t\t\t\t\twaitingForDrain = true;\n\t\t\t\t\tflow.pause();\n\t\t\t\t\tprocess.stdout.once(\"drain\", () => {\n\t\t\t\t\t\twaitingForDrain = false;\n\t\t\t\t\t\tflow.resume();\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (truncated) return;\n\t\t\tconst next = appendCapturedChunk(chunks, captured, buf, maxBytes);\n\t\t\tcaptured = next.captured;\n\t\t\ttruncated = next.truncated;\n\t\t}\n\t};\n}\nfunction truncateUtf8(value, maxBytes) {\n\tconst encoded = Buffer.from(value, \"utf8\");\n\tif (encoded.byteLength <= maxBytes) return {\n\t\ttext: value,\n\t\ttruncated: false\n\t};\n\tlet end = maxBytes;\n\twhile (end > 0 && ((encoded[end] ?? 0) & 192) === 128) end -= 1;\n\treturn {\n\t\ttext: encoded.subarray(0, end).toString(\"utf8\"),\n\t\ttruncated: true\n\t};\n}\nfunction appendCapturedChunk(chunks, captured, buf, maxBytes) {\n\tif (captured + buf.length <= maxBytes) {\n\t\tchunks.push(buf);\n\t\treturn {\n\t\t\tcaptured: captured + buf.length,\n\t\t\ttruncated: false\n\t\t};\n\t}\n\tconst take = maxBytes - captured;\n\tif (take > 0) chunks.push(buf.subarray(0, take));\n\treturn {\n\t\tcaptured: maxBytes,\n\t\ttruncated: true\n\t};\n}\n//#endregion\n//#region src/runtime/provider-cli/outgoing-reply-content.ts\nfunction contentFromBody(msgType, body) {\n\tconst payload = parseBodyPayload(body.content);\n\tif (payload.parseFailed) return {\n\t\tcontent: {\n\t\t\tmsgType,\n\t\t\traw: truncateUtf8(String(body.content), RUNTIME_OUTGOING_REPLY_RAW_MAX_BYTES).text,\n\t\t\tunavailable: \"content_read_failed\"\n\t\t},\n\t\ttruncated: false\n\t};\n\tif (msgType === \"text\") return contentFromText(payload.value);\n\tif (msgType === \"post\") return contentFromPost(payload.value);\n\tif (msgType === \"image\" || msgType === \"sticker\") return contentFromImage(msgType, payload.value);\n\tif (msgType === \"file\" || msgType === \"audio\" || msgType === \"video\" || msgType === \"media\") return contentFromFile(msgType, payload.value);\n\treturn contentFromRaw(msgType, payload.value ?? body);\n}\nfunction parseBodyPayload(content) {\n\tif (typeof content !== \"string\") return {\n\t\tvalue: content,\n\t\tparseFailed: false\n\t};\n\ttry {\n\t\treturn {\n\t\t\tvalue: JSON.parse(content),\n\t\t\tparseFailed: false\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tvalue: content,\n\t\t\tparseFailed: true\n\t\t};\n\t}\n}\nfunction contentFromText(payload) {\n\tconst text = isRecord$2(payload) && typeof payload.text === \"string\" ? payload.text : void 0;\n\tif (text === void 0) return {\n\t\tcontent: {\n\t\t\tmsgType: \"text\",\n\t\t\tunavailable: \"content_read_failed\"\n\t\t},\n\t\ttruncated: false\n\t};\n\tconst truncated = truncateUtf8(text, RUNTIME_OUTGOING_REPLY_TEXT_MAX_BYTES);\n\treturn {\n\t\tcontent: {\n\t\t\tmsgType: \"text\",\n\t\t\ttext: truncated.text,\n\t\t\t...truncated.truncated ? { unavailable: \"content_truncated\" } : {}\n\t\t},\n\t\ttruncated: truncated.truncated\n\t};\n}\nfunction contentFromPost(payload) {\n\tconst truncatedText = truncateUtf8(postToPlainText(payload), RUNTIME_OUTGOING_REPLY_TEXT_MAX_BYTES);\n\tconst raw = truncateUtf8(JSON.stringify(payload), RUNTIME_OUTGOING_REPLY_RAW_MAX_BYTES);\n\treturn {\n\t\tcontent: {\n\t\t\tmsgType: \"post\",\n\t\t\t...truncatedText.text ? { text: truncatedText.text } : {},\n\t\t\tpost: raw.truncated ? void 0 : payload,\n\t\t\t...raw.truncated ? { raw: raw.text } : {},\n\t\t\t...truncatedText.truncated || raw.truncated ? { unavailable: \"content_truncated\" } : {}\n\t\t},\n\t\ttruncated: truncatedText.truncated || raw.truncated\n\t};\n}\nfunction contentFromImage(msgType, payload) {\n\tconst imageKey = isRecord$2(payload) ? asNonEmptyString$1(payload.image_key) ?? asNonEmptyString$1(payload.file_key) : void 0;\n\treturn {\n\t\tcontent: {\n\t\t\tmsgType,\n\t\t\t...imageKey ? { imageKey } : { unavailable: \"content_read_failed\" }\n\t\t},\n\t\ttruncated: false\n\t};\n}\nfunction contentFromFile(msgType, payload) {\n\tconst record = isRecord$2(payload) ? payload : void 0;\n\tconst fileKey = record ? asNonEmptyString$1(record.file_key) : void 0;\n\tconst filename = record ? asNonEmptyString$1(record.file_name) : void 0;\n\tconst imageKey = record ? asNonEmptyString$1(record.image_key) : void 0;\n\treturn {\n\t\tcontent: {\n\t\t\tmsgType,\n\t\t\t...fileKey ? { fileKey } : {},\n\t\t\t...filename ? { filename } : {},\n\t\t\t...imageKey ? { imageKey } : {},\n\t\t\t...fileKey || imageKey ? {} : { unavailable: \"content_read_failed\" }\n\t\t},\n\t\ttruncated: false\n\t};\n}\nfunction contentFromRaw(msgType, payload) {\n\tconst raw = truncateUtf8(JSON.stringify(payload), RUNTIME_OUTGOING_REPLY_RAW_MAX_BYTES);\n\treturn {\n\t\tcontent: {\n\t\t\tmsgType,\n\t\t\traw: raw.text,\n\t\t\t...raw.truncated ? { unavailable: \"content_truncated\" } : {}\n\t\t},\n\t\ttruncated: raw.truncated\n\t};\n}\nfunction isRecord$2(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction asNonEmptyString$1(value) {\n\treturn typeof value === \"string\" && value.length > 0 ? value : void 0;\n}\n//#endregion\n//#region src/runtime/provider-cli/turn-plan.ts\nconst PROVIDER_CLI_TURN_PLAN_SCHEMA_VERSION = 1;\nconst MAX_PROVIDER_CLI_TURN_PLAN_BYTES = 16384;\nconst MAX_PROVIDER_CLI_TURN_IDENTITY_BYTES = 4096;\nconst HOME_NAMESPACE_PATTERN = /^h-[0-9a-f]{40}$/;\nconst SESSION_KEY_PATTERN = /^s-[0-9a-f]{40}$/;\nconst RUN_KEY_PATTERN = /^r-[0-9a-f]{40}$/;\nconst FINGERPRINT_PATTERN = /^v1:[0-9a-f]{64}$/;\nconst logger$3 = createLogger(\"runtime-provider-cli-turn-plan\");\nconst SHARED_PLAN_KEYS = [\n\t\"schemaVersion\",\n\t\"provider\",\n\t\"command\",\n\t\"selectionKind\",\n\t\"selectionVersion\",\n\t\"selectionGeneration\",\n\t\"targetPath\",\n\t\"fingerprint\",\n\t\"homeNamespace\",\n\t\"sessionId\",\n\t\"runId\"\n];\n/** Optional plan keys every selection kind may carry. */\nconst OPTIONAL_SHARED_PLAN_KEYS = [\"captureOutgoingReplies\", \"environmentManifest\"];\nconst OPTIONAL_SLACK_PLAN_KEYS = [...OPTIONAL_SHARED_PLAN_KEYS, \"slackApiHost\"];\nconst MANAGED_PLAN_KEYS = [...SHARED_PLAN_KEYS, \"artifactId\"];\nconst EXTERNAL_PLAN_KEYS = SHARED_PLAN_KEYS;\nconst MANAGED_SLACK_PLAN_KEYS = [...MANAGED_PLAN_KEYS, \"configDir\"];\nconst EXTERNAL_SLACK_PLAN_KEYS = [...EXTERNAL_PLAN_KEYS, \"configDir\"];\nvar ProviderCliTurnPlanError = class extends Error {\n\tcode;\n\tname = \"ProviderCliTurnPlanError\";\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t}\n};\nfunction providerCliCommandForProvider(provider) {\n\treturn provider === \"feishu\" ? \"lark-cli\" : \"slack\";\n}\n/** Irreversible namespace for one canonical OpenTag Home under the account-global plans root. */\nfunction deriveProviderCliHomeNamespace(home) {\n\tif (!isAbsolute(home)) throw new ProviderCliTurnPlanError(\"invalid_identity\", \"The OpenTag Home must be an absolute path\");\n\tlet canonical;\n\ttry {\n\t\tcanonical = realpathSync(resolve(home));\n\t} catch (error) {\n\t\tlogger$3.debug({\n\t\t\tcode: \"home_canonicalization_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI Turn Home canonicalization failed\");\n\t\tthrow new ProviderCliTurnPlanError(\"invalid_identity\", \"The OpenTag Home cannot be canonicalized\");\n\t}\n\treturn irreversibleKey(\"home\", canonical);\n}\n/** Irreversible Session directory key; caller-supplied IDs never become path segments. */\nfunction deriveProviderCliSessionKey(sessionId) {\n\tassertIdentity(\"sessionId\", sessionId);\n\treturn irreversibleKey(\"session\", sessionId);\n}\nfunction isProviderCliHomeNamespace(value) {\n\treturn HOME_NAMESPACE_PATTERN.test(value);\n}\nfunction isProviderCliSessionKey(value) {\n\treturn SESSION_KEY_PATTERN.test(value);\n}\n/** Irreversible Run directory key; caller-supplied IDs never become path segments. */\nfunction deriveProviderCliRunKey(runId) {\n\tassertIdentity(\"runId\", runId);\n\treturn irreversibleKey(\"run\", runId);\n}\nfunction isProviderCliRunKey(value) {\n\treturn RUN_KEY_PATTERN.test(value);\n}\nfunction providerCliPlanHomeDir(layout, homeNamespace) {\n\tassertSafeKey(homeNamespace, HOME_NAMESPACE_PATTERN, \"home namespace\");\n\treturn join(layout.plans, homeNamespace);\n}\nfunction providerCliPlanSessionDir(layout, homeNamespace, sessionKey) {\n\tassertSafeKey(sessionKey, SESSION_KEY_PATTERN, \"session key\");\n\treturn join(providerCliPlanHomeDir(layout, homeNamespace), sessionKey);\n}\nfunction providerCliTurnPlanPath(sessionDir) {\n\treturn join(sessionDir, \"plan.json\");\n}\nfunction providerCliOutgoingReplyRunDir(sessionDir, runId) {\n\treturn join(sessionDir, \"runs\", deriveProviderCliRunKey(runId));\n}\nfunction providerCliOutgoingReplyReceiptsDir(sessionDir, runId) {\n\treturn join(providerCliOutgoingReplyRunDir(sessionDir, runId), \"outgoing-replies\");\n}\nfunction providerCliOutgoingReplyInflightDir(sessionDir, runId) {\n\treturn join(providerCliOutgoingReplyRunDir(sessionDir, runId), \"inflight\");\n}\nfunction providerCliTurnLauncherPath(sessionDir, command) {\n\treturn join(sessionDir, command);\n}\nfunction assertIdentity(name, value) {\n\tif (typeof value !== \"string\" || value.length === 0) throw new ProviderCliTurnPlanError(\"invalid_identity\", `Provider CLI Turn ${name} is missing`);\n\tif (Buffer.byteLength(value, \"utf8\") > 4096) throw new ProviderCliTurnPlanError(\"invalid_identity\", `Provider CLI Turn ${name} exceeds the identity bound`);\n\tif (/[\\0\\n\\r]/.test(value)) throw new ProviderCliTurnPlanError(\"invalid_identity\", `Provider CLI Turn ${name} contains control characters`);\n\treturn value;\n}\n/** Absolute canonical Slack config leaf frozen into a Turn plan. Feishu callers must not supply one. */\nfunction assertProviderCliSlackConfigDir(value) {\n\tif (typeof value !== \"string\" || value.length === 0) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Slack Provider CLI Turn plans require an absolute config directory\");\n\tconst configDir = assertIdentity(\"configDir\", value);\n\tif (!isAbsolute(configDir) || resolve(configDir) !== configDir) throw new ProviderCliTurnPlanError(\"unsafe\", \"Slack config directory must be an absolute canonical path\");\n\treturn configDir;\n}\nfunction assertProviderCliTurnPlanConfigDir(provider, configDir) {\n\tif (provider === \"feishu\") {\n\t\tif (configDir !== void 0) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Feishu Provider CLI Turn plans do not accept a config directory\");\n\t\treturn;\n\t}\n\treturn assertProviderCliSlackConfigDir(configDir);\n}\nfunction parseProviderCliTurnPlan(value) {\n\tconst record = requirePlanRecord(value);\n\tconst shared = parsePlanSharedIdentity(record);\n\treturn shared.provider === \"slack\" ? parseSlackTurnPlan(record, shared) : parseFeishuTurnPlan(record, shared);\n}\nfunction requirePlanRecord(value) {\n\tif (!isRecord$1(value) || value.schemaVersion !== 1) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn plan schema is unsupported\");\n\treturn value;\n}\nfunction parseSlackTurnPlan(record, shared) {\n\tconst configDir = assertProviderCliSlackConfigDir(record.configDir);\n\tassertSlackCaptureOutgoingReplies(record);\n\tconst environmentManifest = parseEnvironmentManifest(record);\n\tconst slackApiHost = parseSlackApiHost(record);\n\tif (record.selectionKind === \"managed\") {\n\t\tif (!hasPlanKeys(record, MANAGED_SLACK_PLAN_KEYS, OPTIONAL_SLACK_PLAN_KEYS) || !isNonEmptyString(record.artifactId)) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn managed plan is malformed\");\n\t\treturn {\n\t\t\t...shared,\n\t\t\tprovider: \"slack\",\n\t\t\tcommand: \"slack\",\n\t\t\tselectionKind: \"managed\",\n\t\t\tartifactId: record.artifactId,\n\t\t\tconfigDir,\n\t\t\t...environmentManifest ? { environmentManifest } : {},\n\t\t\t...slackApiHost ? { slackApiHost } : {}\n\t\t};\n\t}\n\tif (record.selectionKind === \"external\") {\n\t\tif (!hasPlanKeys(record, EXTERNAL_SLACK_PLAN_KEYS, OPTIONAL_SLACK_PLAN_KEYS)) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn external plan is malformed\");\n\t\treturn {\n\t\t\t...shared,\n\t\t\tprovider: \"slack\",\n\t\t\tcommand: \"slack\",\n\t\t\tselectionKind: \"external\",\n\t\t\tconfigDir,\n\t\t\t...environmentManifest ? { environmentManifest } : {},\n\t\t\t...slackApiHost ? { slackApiHost } : {}\n\t\t};\n\t}\n\tthrow new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn plan selection kind is unknown\");\n}\nfunction parseFeishuTurnPlan(record, shared) {\n\tconst captureOutgoingReplies = parseCaptureOutgoingReplies(record);\n\tconst environmentManifest = parseEnvironmentManifest(record);\n\tif (record.selectionKind === \"managed\") {\n\t\tif (!hasPlanKeys(record, MANAGED_PLAN_KEYS) || !isNonEmptyString(record.artifactId)) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn managed plan is malformed\");\n\t\treturn {\n\t\t\t...shared,\n\t\t\tprovider: \"feishu\",\n\t\t\tcommand: \"lark-cli\",\n\t\t\tselectionKind: \"managed\",\n\t\t\tartifactId: record.artifactId,\n\t\t\t...captureOutgoingReplies ? { captureOutgoingReplies: true } : {},\n\t\t\t...environmentManifest ? { environmentManifest } : {}\n\t\t};\n\t}\n\tif (record.selectionKind === \"external\") {\n\t\tif (!hasPlanKeys(record, EXTERNAL_PLAN_KEYS)) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn external plan is malformed\");\n\t\treturn {\n\t\t\t...shared,\n\t\t\tprovider: \"feishu\",\n\t\t\tcommand: \"lark-cli\",\n\t\t\tselectionKind: \"external\",\n\t\t\t...captureOutgoingReplies ? { captureOutgoingReplies: true } : {},\n\t\t\t...environmentManifest ? { environmentManifest } : {}\n\t\t};\n\t}\n\tthrow new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn plan selection kind is unknown\");\n}\nfunction parseEnvironmentManifest(record) {\n\tif (!Object.hasOwn(record, \"environmentManifest\")) return void 0;\n\tconst value = record.environmentManifest;\n\tif (typeof value !== \"string\" || !isAbsolute(value) || resolve(value) !== value) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn environment manifest must be an absolute canonical path\");\n\treturn assertIdentity(\"environmentManifest\", value);\n}\nfunction parseSlackApiHost(record) {\n\tif (!Object.hasOwn(record, \"slackApiHost\")) return void 0;\n\tconst value = record.slackApiHost;\n\tif (typeof value !== \"string\" || !/^https:\\/\\/127\\.0\\.0\\.1:\\d{1,5}$/.test(value)) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn Slack API host must be a loopback HTTPS endpoint\");\n\treturn value;\n}\nfunction parsePlanSharedIdentity(value) {\n\tif (value.provider !== \"feishu\" && value.provider !== \"slack\") throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn plan provider is unknown\");\n\tconst command = providerCliCommandForProvider(value.provider);\n\tif (value.command !== command) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn plan command does not match provider\");\n\tconst generation = parsePlanGeneration(value.selectionGeneration);\n\tconst identity = parsePlanStringIdentity(value);\n\treturn {\n\t\tschemaVersion: 1,\n\t\tprovider: value.provider,\n\t\tcommand,\n\t\tselectionVersion: identity.selectionVersion,\n\t\tselectionGeneration: generation,\n\t\ttargetPath: identity.targetPath,\n\t\tfingerprint: identity.fingerprint,\n\t\thomeNamespace: identity.homeNamespace,\n\t\tsessionId: identity.sessionId,\n\t\trunId: identity.runId\n\t};\n}\nfunction parsePlanGeneration(value) {\n\tif (typeof value !== \"number\" || !Number.isInteger(value) || value < 1) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn plan generation is malformed\");\n\treturn value;\n}\nfunction parsePlanStringIdentity(value) {\n\tconst { selectionVersion, targetPath, fingerprint, homeNamespace, sessionId, runId } = value;\n\tif (!isNonEmptyString(selectionVersion) || !semver.valid(selectionVersion) || !isNonEmptyString(targetPath) || !isAbsolute(targetPath) || !isFingerprint(fingerprint) || typeof homeNamespace !== \"string\" || !isProviderCliHomeNamespace(homeNamespace) || !isNonEmptyString(sessionId) || !isNonEmptyString(runId)) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn plan identity is malformed\");\n\treturn {\n\t\tselectionVersion,\n\t\ttargetPath,\n\t\tfingerprint,\n\t\thomeNamespace,\n\t\tsessionId: assertIdentity(\"sessionId\", sessionId),\n\t\trunId: assertIdentity(\"runId\", runId)\n\t};\n}\n/** Bounded secure read of an immutable Turn plan. Missing files are `undefined`. */\nasync function readProviderCliTurnPlan(path) {\n\tconst content = await readBoundedPrivatePlanFile(path);\n\tif (content === void 0) return void 0;\n\ttry {\n\t\treturn parseProviderCliTurnPlan(JSON.parse(content));\n\t} catch (error) {\n\t\tif (error instanceof ProviderCliTurnPlanError) throw error;\n\t\tlogger$3.debug({\n\t\t\tcode: \"plan_json_parse_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI Turn plan JSON parsing failed\");\n\t\tthrow new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn plan contains invalid JSON\");\n\t}\n}\nasync function readBoundedPrivatePlanFile(path) {\n\tconst pathStatus = await lstatPlanFile(path);\n\tif (pathStatus === void 0) return void 0;\n\tassertPlanFileShapeAndSize(pathStatus);\n\tlet handle;\n\ttry {\n\t\thandle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n\t\tconst opened = await handle.stat();\n\t\tassertSamePlanFile(pathStatus, opened);\n\t\tassertPrivatePlanFile(opened);\n\t\tassertPlanFileSize(opened.size);\n\t\treturn await readStablePlanContent(handle, opened);\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return void 0;\n\t\tif (error.code === \"ELOOP\") throw new ProviderCliTurnPlanError(\"unsafe\", \"Provider CLI Turn plan must not be a symlink\");\n\t\tlogger$3.debug({\n\t\t\tcode: \"plan_read_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI Turn plan read failed\");\n\t\tthrow error;\n\t} finally {\n\t\tawait handle?.close();\n\t}\n}\nasync function lstatPlanFile(path) {\n\tlet pathStatus;\n\ttry {\n\t\tpathStatus = await lstat(path);\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return void 0;\n\t\tlogger$3.debug({\n\t\t\tcode: \"plan_lstat_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI Turn plan stat failed\");\n\t\tthrow error;\n\t}\n\treturn pathStatus;\n}\nfunction assertPlanFileShapeAndSize(status) {\n\tif (status.isSymbolicLink() || !status.isFile()) throw new ProviderCliTurnPlanError(\"unsafe\", \"Provider CLI Turn plan must be a regular file\");\n\tassertPlanFileSize(status.size);\n}\nfunction assertSamePlanFile(pathStatus, opened) {\n\tif (!opened.isFile() || opened.dev !== pathStatus.dev || opened.ino !== pathStatus.ino) throw new ProviderCliTurnPlanError(\"unsafe\", \"Provider CLI Turn plan changed during open\");\n}\nfunction assertPlanFileSize(size) {\n\tif (size > 16384) throw new ProviderCliTurnPlanError(\"too_large\", \"Provider CLI Turn plan exceeds the read bound\");\n}\nasync function readStablePlanContent(handle, opened) {\n\tconst buffer = Buffer.allocUnsafe(16385);\n\tlet bytesRead = 0;\n\twhile (bytesRead < buffer.byteLength) {\n\t\tconst read = await handle.read(buffer, bytesRead, buffer.byteLength - bytesRead, null);\n\t\tif (read.bytesRead === 0) break;\n\t\tbytesRead += read.bytesRead;\n\t}\n\tassertPlanFileSize(bytesRead);\n\tconst final = await handle.stat();\n\tif (final.dev !== opened.dev || final.ino !== opened.ino || final.size !== opened.size || bytesRead !== opened.size) throw new ProviderCliTurnPlanError(\"unsafe\", \"Provider CLI Turn plan changed during read\");\n\treturn buffer.subarray(0, bytesRead).toString(\"utf8\");\n}\nfunction assertPrivatePlanFile(status) {\n\tconst currentUid = typeof process.getuid === \"function\" ? process.getuid() : void 0;\n\tif (currentUid !== void 0 && status.uid !== currentUid) throw new ProviderCliTurnPlanError(\"unsafe\", \"Provider CLI Turn plan owner does not match the daemon account\");\n\tif ((status.mode & 63) !== 0) throw new ProviderCliTurnPlanError(\"unsafe\", \"Provider CLI Turn plan permissions must be private\");\n}\n/**\n* Atomically publish a new plan. Returns `created` when this caller won the exclusive\n* create, or `exists` when another plan is already at the destination.\n*/\nasync function publishProviderCliTurnPlanExclusive(path, plan) {\n\tconst parent = dirname(path);\n\tconst temporary = resolve(parent, `.${randomUUID()}.tmp`);\n\tconst content = `${JSON.stringify(plan, void 0, 2)}\\n`;\n\tif (Buffer.byteLength(content, \"utf8\") > 16384) throw new ProviderCliTurnPlanError(\"too_large\", \"Provider CLI Turn plan exceeds the write bound\");\n\tawait writeDurableFile(temporary, content, 384);\n\ttry {\n\t\tawait link(temporary, path);\n\t\tawait chmod(path, 384);\n\t\tawait syncDurableDirectory(parent);\n\t\treturn \"created\";\n\t} catch (error) {\n\t\tif (error.code !== \"EEXIST\") throw error;\n\t\treturn \"exists\";\n\t} finally {\n\t\tawait rm(temporary, { force: true });\n\t}\n}\nfunction assertPlanWithinRoot(root, target) {\n\ttry {\n\t\tassertWithin(root, target);\n\t} catch (error) {\n\t\tif (error instanceof RuntimeStorageError) throw new ProviderCliTurnPlanError(\"unsafe\", error.message);\n\t\tthrow error;\n\t}\n}\nfunction managedArtifactDigest(artifactId) {\n\tconst digest = artifactId.split(\"/\").at(-1);\n\treturn digest && digest.length > 0 ? digest : void 0;\n}\nfunction irreversibleKey(kind, value) {\n\tconst digest = createHash(\"sha256\").update(`${kind}\\0${value}`, \"utf8\").digest(\"hex\");\n\treturn `${kind[0]}-${digest.slice(0, 40)}`;\n}\nfunction assertSafeKey(value, pattern, label) {\n\tif (!pattern.test(value)) throw new ProviderCliTurnPlanError(\"unsafe\", `Provider CLI Turn ${label} is not a derived key`);\n}\nfunction isRecord$1(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction isNonEmptyString(value) {\n\treturn typeof value === \"string\" && value.length > 0;\n}\nfunction isFingerprint(value) {\n\treturn typeof value === \"string\" && FINGERPRINT_PATTERN.test(value);\n}\nfunction hasPlanKeys(value, requiredKeys, optionalKeys = OPTIONAL_SHARED_PLAN_KEYS) {\n\tconst allowed = /* @__PURE__ */ new Set([...requiredKeys, ...optionalKeys]);\n\treturn Object.keys(value).every((key) => allowed.has(key)) && requiredKeys.every((key) => Object.hasOwn(value, key));\n}\nfunction parseCaptureOutgoingReplies(record) {\n\tif (!Object.hasOwn(record, \"captureOutgoingReplies\")) return false;\n\tif (typeof record.captureOutgoingReplies !== \"boolean\") throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn captureOutgoingReplies must be a boolean\");\n\treturn record.captureOutgoingReplies;\n}\nfunction assertSlackCaptureOutgoingReplies(record) {\n\tif (!Object.hasOwn(record, \"captureOutgoingReplies\")) return;\n\tif (record.captureOutgoingReplies !== false) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Slack Provider CLI Turn plans do not capture outgoing replies\");\n}\nfunction planCapturesOutgoingReplies(plan) {\n\treturn plan.provider === \"feishu\" && plan.captureOutgoingReplies === true;\n}\n//#endregion\n//#region src/runtime/provider-cli/outgoing-reply-store.ts\nconst logger$2 = createLogger(\"runtime-provider-cli-outgoing-reply\");\nconst PROVIDER_CLI_OUTGOING_REPLY_FILE_MAX_BYTES = 262144;\nconst PROVIDER_CLI_OUTGOING_REPLY_COLLECT_MAX_BYTES = 524288;\nconst CaptureStatusSchema = z.object({\n\tschemaVersion: z.literal(1),\n\tstatus: z.enum([\n\t\t\"complete\",\n\t\t\"incomplete\",\n\t\t\"unavailable\"\n\t])\n}).strict();\nconst OutgoingReplyReceiptSchema = z.object({\n\tschemaVersion: z.literal(1),\n\trecordedAt: z.string().datetime(),\n\tsequenceHint: z.number().int().safe().nonnegative(),\n\tkind: z.enum([\"send\", \"reply\"]),\n\tmessageId: z.string().min(1).max(512),\n\tchatId: z.string().min(1).max(512),\n\tthreadId: z.string().min(1).max(512).optional(),\n\trootId: z.string().min(1).max(512).optional(),\n\tparentId: z.string().min(1).max(512).optional(),\n\tcreateTime: z.string().min(1).max(64).optional(),\n\tsenderType: z.string().min(1).max(64).optional(),\n\tsenderId: z.string().min(1).max(512).optional(),\n\tmsgType: TurnOutgoingReplyMsgTypeSchema.optional(),\n\tcontentStatus: z.enum([\n\t\t\"available\",\n\t\t\"unavailable\",\n\t\t\"truncated\"\n\t]),\n\tcontent: TurnOutgoingReplyContentSchema.optional()\n}).strict();\nasync function beginOutgoingReplyInflight(options) {\n\tconst inflightDir = providerCliOutgoingReplyInflightDir(options.sessionDir, options.runId);\n\tawait ensureOutgoingReplyDirectory(options, inflightDir);\n\tconst path = join(inflightDir, `${process.pid}-${randomUUID()}`);\n\tawait writeDurableJson(path, { pid: process.pid });\n\treturn { async release() {\n\t\tawait rm(path, { force: true }).catch(() => void 0);\n\t} };\n}\nasync function markOutgoingReplyCaptureStatus(options) {\n\tconst runDir = providerCliOutgoingReplyRunDir(options.sessionDir, options.runId);\n\ttry {\n\t\tawait ensureOutgoingReplyDirectory(options, runDir);\n\t\tconst path = captureStatusPath(options.sessionDir, options.runId);\n\t\tconst next = worseCaptureStatus(await readCaptureStatusFile(path), options.status);\n\t\tawait writeDurableFile(path, `${JSON.stringify({\n\t\t\tschemaVersion: 1,\n\t\t\tstatus: next\n\t\t})}\\n`);\n\t} catch {\n\t\tlogger$2.debug({ code: \"outgoing_reply_status_write_failed\" }, \"Outgoing reply capture status write failed\");\n\t}\n}\nasync function writeOutgoingReplyReceipt(options) {\n\tconst receiptsDir = providerCliOutgoingReplyReceiptsDir(options.sessionDir, options.runId);\n\tawait ensureOutgoingReplyDirectory(options, receiptsDir);\n\tconst receipt = OutgoingReplyReceiptSchema.parse({\n\t\tschemaVersion: 1,\n\t\t...options.receipt\n\t});\n\tconst path = join(receiptsDir, receiptFileName(receipt.sequenceHint, receipt.messageId));\n\tconst serialized = `${JSON.stringify(receipt)}\\n`;\n\tif (Buffer.byteLength(serialized, \"utf8\") <= 262144) {\n\t\tawait writeDurableFile(path, serialized);\n\t\treturn;\n\t}\n\tconst reduced = OutgoingReplyReceiptSchema.parse({\n\t\t...receipt,\n\t\tcontentStatus: \"truncated\",\n\t\tcontent: boundReceiptContent(receipt.content, true)\n\t});\n\tawait writeDurableFile(path, `${JSON.stringify(reduced)}\\n`);\n}\nasync function ensureOutgoingReplyDirectory(options, target) {\n\tif (!await validatePrivateDirectory(options.plansRoot, options.sessionDir)) await ensurePrivateDirectory(options.plansRoot, options.sessionDir);\n\tawait assertPrivateAncestry(options.plansRoot, options.sessionDir);\n\tawait ensurePrivateDirectory(join(options.sessionDir, \"runs\"), target);\n\tawait assertPrivateAncestry(options.plansRoot, target);\n}\nasync function collectOutgoingReplyReceipts(options) {\n\tconst sessionStatus = await outgoingReplySessionStatus(options.plansRoot, options.sessionDir, options.runId);\n\tif (sessionStatus !== \"ready\") return {\n\t\tstatus: sessionStatus,\n\t\treceipts: []\n\t};\n\tconst inflight = await waitForOutgoingReplyInflight(options);\n\tconst marked = await readCaptureStatusFile(captureStatusPath(options.sessionDir, options.runId));\n\tconst collected = await readOutgoingReplyReceipts(options.plansRoot, providerCliOutgoingReplyReceiptsDir(options.sessionDir, options.runId));\n\tconst unavailable = marked === \"unavailable\" || inflight === \"unavailable\" || collected.status === \"unavailable\";\n\tconst incomplete = inflight === \"timeout\" || marked === \"incomplete\" || collected.incomplete;\n\tif (unavailable && collected.receipts.length === 0) return {\n\t\tstatus: \"unavailable\",\n\t\treceipts: []\n\t};\n\treturn {\n\t\tstatus: unavailable || incomplete ? \"incomplete\" : \"complete\",\n\t\treceipts: collected.receipts\n\t};\n}\nasync function cleanupOutgoingReplyRun(options) {\n\tconst runDir = providerCliOutgoingReplyRunDir(options.sessionDir, options.runId);\n\ttry {\n\t\tawait assertPrivateAncestry(options.plansRoot, runDir);\n\t\tif (!await validatePrivateDirectory(options.plansRoot, runDir)) return;\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return;\n\t\tif (error instanceof ProviderCliTurnPlanError || error instanceof RuntimeStorageError) return;\n\t\tlogger$2.debug({ code: \"outgoing_reply_cleanup_validation_failed\" }, \"Outgoing reply cleanup validation failed\");\n\t\tthrow error;\n\t}\n\tawait rm(runDir, {\n\t\trecursive: true,\n\t\tforce: true\n\t});\n}\nasync function recoverSessionOutgoingReplyEvidence(options) {\n\ttry {\n\t\tawait assertPrivateAncestry(options.plansRoot, options.sessionDir);\n\t\tif (!await validatePrivateDirectory(options.plansRoot, options.sessionDir)) return false;\n\t\tif (!await sessionHasOutgoingReplyEvidence(options.plansRoot, options.sessionDir)) return false;\n\t\tawait rm(providerCliTurnPlanPath(options.sessionDir), { force: true });\n\t\treturn true;\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return false;\n\t\tthrow new ProviderCliTurnPlanError(\"unsafe\", \"Outgoing reply evidence could not be safely recovered\");\n\t}\n}\nasync function sessionHasOutgoingReplyEvidence(plansRoot, sessionDir) {\n\tconst runsDir = join(sessionDir, \"runs\");\n\tconst listed = await listPrivateFiles(plansRoot, runsDir, 128);\n\tif (listed === \"missing\") return false;\n\tif (listed === \"unavailable\" || listed.length >= 128) return true;\n\tfor (const name of listed) {\n\t\tif (!isProviderCliRunKey(name)) continue;\n\t\tif (await runHasOutgoingReplyEvidence(plansRoot, join(runsDir, name))) return true;\n\t}\n\treturn false;\n}\nasync function runHasOutgoingReplyEvidence(plansRoot, runDir) {\n\tconst runFiles = await listPrivateFiles(plansRoot, runDir, 128);\n\tif (runFiles === \"missing\") return false;\n\tif (runFiles === \"unavailable\") return true;\n\tif (await readCaptureStatusFile(join(runDir, \"capture-status.json\"))) return true;\n\tconst listed = await listPrivateFiles(plansRoot, join(runDir, \"outgoing-replies\"), 128);\n\tif (listed === \"missing\") return false;\n\tif (listed === \"unavailable\") return true;\n\treturn listed.some((name) => name.endsWith(\".json\"));\n}\nasync function outgoingReplySessionStatus(plansRoot, sessionDir, _runId) {\n\ttry {\n\t\tawait assertPrivateAncestry(plansRoot, sessionDir);\n\t\tif (!await validatePrivateDirectory(plansRoot, sessionDir)) return \"complete\";\n\t\treturn \"ready\";\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return \"complete\";\n\t\tlogger$2.debug({ code: \"outgoing_reply_session_dir_invalid\" }, \"Outgoing reply session directory validation failed\");\n\t\treturn \"unavailable\";\n\t}\n}\nasync function waitForOutgoingReplyInflight(options) {\n\tconst inflightDir = providerCliOutgoingReplyInflightDir(options.sessionDir, options.runId);\n\tconst waitMs = options.waitMs ?? 2e3;\n\tconst now = options.now ?? Date.now;\n\tconst sleep = options.sleep ?? defaultSleep;\n\tconst deadline = now() + Math.max(0, waitMs);\n\twhile (true) {\n\t\tconst inflight = await listPrivateFiles(options.plansRoot, inflightDir, 128);\n\t\tif (inflight === \"unavailable\") return \"unavailable\";\n\t\tif (inflight === \"missing\" || inflight.length === 0) return \"clear\";\n\t\tif (now() >= deadline) return \"timeout\";\n\t\tawait sleep(20);\n\t}\n}\nasync function readOutgoingReplyReceipts(plansRoot, receiptsDir) {\n\tconst files = await listPrivateFiles(plansRoot, receiptsDir, 128);\n\tif (files === \"missing\") return {\n\t\tstatus: \"ok\",\n\t\tincomplete: false,\n\t\treceipts: []\n\t};\n\tif (files === \"unavailable\") return {\n\t\tstatus: \"unavailable\",\n\t\tincomplete: true,\n\t\treceipts: []\n\t};\n\tconst receipts = [];\n\tlet incomplete = files.length >= 128;\n\tlet totalBytes = 0;\n\tfor (const name of files) {\n\t\tif (!name.endsWith(\".json\")) continue;\n\t\tif (totalBytes >= 524288) {\n\t\t\tincomplete = true;\n\t\t\tbreak;\n\t\t}\n\t\tconst limit = Math.min(PROVIDER_CLI_OUTGOING_REPLY_FILE_MAX_BYTES, PROVIDER_CLI_OUTGOING_REPLY_COLLECT_MAX_BYTES - totalBytes);\n\t\tconst bounded = await readBoundedJsonFile(join(receiptsDir, name), limit, (value) => OutgoingReplyReceiptSchema.parse(value));\n\t\tif (bounded === \"missing\") continue;\n\t\tif (bounded === \"too-large\" || bounded === \"invalid\") {\n\t\t\ttotalBytes += limit;\n\t\t\tincomplete = true;\n\t\t\tcontinue;\n\t\t}\n\t\ttotalBytes += bounded.bytes;\n\t\tif (totalBytes > 524288) {\n\t\t\tincomplete = true;\n\t\t\tbreak;\n\t\t}\n\t\treceipts.push(bounded.value);\n\t}\n\treceipts.sort(compareOutgoingReplyReceipts);\n\treturn {\n\t\tstatus: \"ok\",\n\t\tincomplete,\n\t\treceipts\n\t};\n}\nfunction compareOutgoingReplyReceipts(left, right) {\n\tconst leftKey = receiptOrderKey(left);\n\tconst rightKey = receiptOrderKey(right);\n\tif (leftKey !== rightKey) return leftKey - rightKey;\n\tif (left.sequenceHint !== right.sequenceHint) return left.sequenceHint - right.sequenceHint;\n\treturn left.messageId.localeCompare(right.messageId);\n}\nfunction receiptOrderKey(receipt) {\n\tconst created = parseProviderCreateTime(receipt.createTime);\n\tif (created !== void 0) return created;\n\treturn receipt.sequenceHint;\n}\nfunction parseProviderCreateTime(value) {\n\tif (!value) return void 0;\n\tif (/^\\d+$/.test(value)) {\n\t\tconst numeric = Number(value);\n\t\treturn Number.isFinite(numeric) ? numeric : void 0;\n\t}\n\tconst parsed = Date.parse(value.includes(\"T\") ? value : value.replace(\" \", \"T\"));\n\treturn Number.isNaN(parsed) ? void 0 : parsed;\n}\nasync function listPrivateFiles(plansRoot, directory, maxEntries) {\n\ttry {\n\t\tawait assertPrivateAncestry(plansRoot, directory);\n\t\tif (!await validatePrivateDirectory(plansRoot, directory)) return \"missing\";\n\t\tconst entries = [];\n\t\tconst handle = await opendir(directory, { bufferSize: Math.min(32, maxEntries) });\n\t\tfor await (const entry of handle) {\n\t\t\tentries.push(entry.name);\n\t\t\tif (entries.length >= maxEntries) break;\n\t\t}\n\t\treturn entries.sort();\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return \"missing\";\n\t\tlogger$2.debug({ code: \"outgoing_reply_dir_list_failed\" }, \"Outgoing reply directory listing failed\");\n\t\treturn \"unavailable\";\n\t}\n}\nasync function readBoundedJsonFile(path, maxBytes, validate) {\n\tlet handle;\n\ttry {\n\t\tconst status = await lstat(path);\n\t\tif (status.isSymbolicLink() || !status.isFile()) return \"invalid\";\n\t\tif (status.size > maxBytes) return \"too-large\";\n\t\thandle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n\t\tconst opened = await handle.stat();\n\t\tif (!opened.isFile() || opened.size > maxBytes) return \"too-large\";\n\t\tif ((opened.mode & 63) !== 0 || typeof process.getuid === \"function\" && opened.uid !== process.getuid()) return \"invalid\";\n\t\tconst buffer = await readCappedBuffer(handle, maxBytes);\n\t\tif (buffer.length > maxBytes) return \"too-large\";\n\t\treturn {\n\t\t\tvalue: validate(JSON.parse(buffer.toString(\"utf8\"))),\n\t\t\tbytes: buffer.length\n\t\t};\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return \"missing\";\n\t\treturn \"invalid\";\n\t} finally {\n\t\tawait handle?.close();\n\t}\n}\nasync function readCappedBuffer(handle, maxBytes) {\n\tconst buffer = Buffer.alloc(maxBytes + 1);\n\tlet bytes = 0;\n\twhile (bytes <= maxBytes) {\n\t\tconst read = await handle.read(buffer, bytes, buffer.length - bytes, bytes);\n\t\tif (read.bytesRead === 0) break;\n\t\tbytes += read.bytesRead;\n\t}\n\treturn buffer.subarray(0, bytes);\n}\nasync function readCaptureStatusFile(path) {\n\tconst parsed = await readBoundedJsonFile(path, 1024, (value) => CaptureStatusSchema.parse(value));\n\tif (parsed === \"missing\") return void 0;\n\tif (parsed === \"too-large\" || parsed === \"invalid\") return \"unavailable\";\n\treturn parsed.value.status;\n}\nfunction captureStatusPath(sessionDir, runId) {\n\treturn join(providerCliOutgoingReplyRunDir(sessionDir, runId), \"capture-status.json\");\n}\nfunction worseCaptureStatus(existing, next) {\n\tconst rank = {\n\t\tcomplete: 0,\n\t\tincomplete: 1,\n\t\tunavailable: 2\n\t};\n\tif (!existing) return next;\n\treturn rank[next] >= rank[existing] ? next : existing;\n}\nasync function assertPrivateAncestry(root, target) {\n\tconst rootPath = resolve(root);\n\tconst targetPath = resolve(target);\n\tassertPlanWithinRoot(rootPath, targetPath);\n\tassertWithin(rootPath, targetPath);\n\tconst suffix = relative(rootPath, targetPath);\n\tlet current = rootPath;\n\tconst uid = typeof process.getuid === \"function\" ? process.getuid() : void 0;\n\tfor (const segment of suffix ? [\"\", ...suffix.split(sep)] : [\"\"]) {\n\t\tif (segment) current = resolve(current, segment);\n\t\tconst status = await lstat(current);\n\t\tif (status.isSymbolicLink()) throw new ProviderCliTurnPlanError(\"unsafe\", \"Outgoing reply path must not traverse a symlink\");\n\t\tif (uid !== void 0 && status.uid !== uid) throw new ProviderCliTurnPlanError(\"unsafe\", \"Outgoing reply path must be owned by the daemon account\");\n\t\tif (status.isDirectory() && (status.mode & 63) !== 0) throw new ProviderCliTurnPlanError(\"unsafe\", \"Outgoing reply directories must be private\");\n\t}\n}\nfunction receiptFileName(sequenceHint, messageId) {\n\tconst safeId = createHash(\"sha256\").update(messageId).digest(\"hex\");\n\treturn `${String(sequenceHint).padStart(16, \"0\")}-${safeId}.json`;\n}\nfunction boundReceiptContent(content, truncated) {\n\treturn {\n\t\tmsgType: content?.msgType ?? \"unknown\",\n\t\t...content?.filename ? { filename: content.filename } : {},\n\t\t...content?.fileKey ? { fileKey: content.fileKey } : {},\n\t\t...content?.imageKey ? { imageKey: content.imageKey } : {},\n\t\tunavailable: truncated ? \"content_truncated\" : content?.unavailable ?? \"content_read_failed\"\n\t};\n}\nconst defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n//#endregion\n//#region src/runtime/provider-cli/outgoing-reply-capture.ts\nconst logger$1 = createLogger(\"runtime-provider-cli-outgoing-reply\");\nconst PROVIDER_CLI_OUTGOING_REPLY_STDOUT_CAPTURE_MAX_BYTES = 262144;\nconst PROVIDER_CLI_OUTGOING_REPLY_QUERY_MAX_BYTES = 65536;\nconst PROVIDER_CLI_OUTGOING_REPLY_QUERY_TIMEOUT_MS = 5e3;\nconst SEND_PATH = /^\\/open-apis\\/im\\/v1\\/messages$/;\nconst REPLY_PATH = /^\\/open-apis\\/im\\/v1\\/messages\\/[^/]+\\/reply$/;\nconst BOOLEAN_FLAGS = /* @__PURE__ */ new Set([\n\t\"--dry-run\",\n\t\"--json\",\n\t\"--yes\",\n\t\"--reply-in-thread\",\n\t\"--page-all\",\n\t\"--help\",\n\t\"--version\",\n\t\"-h\"\n]);\nfunction classifyLarkOutgoingMutation(argv) {\n\tconst { positional, dryRun } = positionalArgv(argv);\n\tif (dryRun) return void 0;\n\tif (positional[0] === \"api\") return classifyRawApiMutation(positional);\n\treturn classifyImCommandMutation(positional[0] === \"im\" ? positional.slice(1) : positional);\n}\nfunction classifyRawApiMutation(positional) {\n\tconst method = positional[1]?.toUpperCase();\n\tconst path = positional[2] ? normalizeApiPath(positional[2]) : \"\";\n\tif (method !== \"POST\") return void 0;\n\tif (SEND_PATH.test(path)) return \"send\";\n\tif (REPLY_PATH.test(path)) return \"reply\";\n}\nfunction classifyImCommandMutation(tokens) {\n\tif (tokens[0] === \"+messages-send\") return \"send\";\n\tif (tokens[0] === \"+messages-reply\") return \"reply\";\n\tif (tokens[0] === \"messages\" && tokens[1] === \"create\") return \"send\";\n\tif (tokens[0] === \"messages\" && tokens[1] === \"reply\") return \"reply\";\n}\nasync function captureFeishuOutgoingReply(options) {\n\tif (options.plan.provider !== \"feishu\") return \"ignored\";\n\tconst kind = classifyLarkOutgoingMutation(options.userArgv);\n\tif (!kind || options.code !== 0) return \"ignored\";\n\tif (options.stdoutTruncated) await markIncomplete(options);\n\tconst parsed = inspectLarkCliEnvelope(options.stdout);\n\tif (parsed.kind === \"rejected\") return \"ignored\";\n\tif (parsed.kind === \"malformed\") {\n\t\tawait markIncomplete(options);\n\t\treturn \"incomplete\";\n\t}\n\tconst receipt = extractSendReceipt(parsed.data);\n\tif (!receipt) {\n\t\tawait markIncomplete(options);\n\t\treturn \"incomplete\";\n\t}\n\tconst acceptedAt = /* @__PURE__ */ new Date();\n\tconst base = {\n\t\t...receipt,\n\t\tsequenceHint: acceptedAt.getTime(),\n\t\trecordedAt: acceptedAt.toISOString(),\n\t\tcontentStatus: receipt.content ? receipt.contentStatus : \"unavailable\"\n\t};\n\ttry {\n\t\tawait persistOutgoingReplyReceipt(kind, applySenderPolicy(base), options);\n\t} catch {\n\t\tlogger$1.debug({ code: \"outgoing_reply_receipt_write_failed\" }, \"Outgoing reply receipt write failed\");\n\t\tawait markIncomplete(options);\n\t\treturn \"incomplete\";\n\t}\n\tif (receipt.content) return \"recorded\";\n\tconst enriched = await enrichReceiptFromQuery(base, options);\n\ttry {\n\t\tawait persistOutgoingReplyReceipt(kind, applySenderPolicy(enriched), options);\n\t} catch {\n\t\tlogger$1.debug({ code: \"outgoing_reply_receipt_enrich_failed\" }, \"Outgoing reply receipt enrich failed\");\n\t\tawait markIncomplete(options);\n\t}\n\treturn \"recorded\";\n}\nasync function enrichReceiptFromQuery(receipt, options) {\n\tconst queried = await queryLarkMessageById({\n\t\tfile: options.plan.targetPath,\n\t\targsPrefix: managedArgPrefix(options.spawnArgs, options.userArgv),\n\t\tenv: options.env,\n\t\tmessageId: receipt.messageId\n\t});\n\tif (queried.status !== \"available\" || !queried.item) return {\n\t\t...receipt,\n\t\tcontentStatus: queried.status === \"truncated\" ? \"truncated\" : \"unavailable\"\n\t};\n\tconst extracted = extractMessageItem(queried.item);\n\tif (!extracted || extracted.messageId !== receipt.messageId || extracted.chatId !== receipt.chatId) return {\n\t\t...receipt,\n\t\tcontentStatus: \"unavailable\"\n\t};\n\treturn {\n\t\t...receipt,\n\t\tthreadId: extracted.threadId ?? receipt.threadId,\n\t\trootId: extracted.rootId ?? receipt.rootId,\n\t\tparentId: extracted.parentId ?? receipt.parentId,\n\t\tcreateTime: extracted.createTime ?? receipt.createTime,\n\t\tsenderType: extracted.senderType ?? receipt.senderType,\n\t\tsenderId: extracted.senderId ?? receipt.senderId,\n\t\tmsgType: extracted.msgType ?? receipt.msgType,\n\t\tcontent: extracted.content,\n\t\tcontentStatus: extracted.contentStatus\n\t};\n}\nfunction applySenderPolicy(receipt) {\n\tif (receipt.senderType && receipt.senderType !== \"app\") return {\n\t\t...receipt,\n\t\tcontent: void 0,\n\t\tcontentStatus: \"unavailable\"\n\t};\n\treturn receipt;\n}\nasync function persistOutgoingReplyReceipt(kind, receipt, options) {\n\tawait writeOutgoingReplyReceipt({\n\t\tplansRoot: options.plansRoot,\n\t\tsessionDir: dirname(options.planPath),\n\t\trunId: options.plan.runId,\n\t\treceipt: {\n\t\t\tkind,\n\t\t\trecordedAt: receipt.recordedAt,\n\t\t\tsequenceHint: receipt.sequenceHint,\n\t\t\tmessageId: receipt.messageId,\n\t\t\tchatId: receipt.chatId,\n\t\t\t...receipt.threadId ? { threadId: receipt.threadId } : {},\n\t\t\t...receipt.rootId ? { rootId: receipt.rootId } : {},\n\t\t\t...receipt.parentId ? { parentId: receipt.parentId } : {},\n\t\t\t...receipt.createTime ? { createTime: receipt.createTime } : {},\n\t\t\t...receipt.senderType ? { senderType: receipt.senderType } : {},\n\t\t\t...receipt.senderId ? { senderId: receipt.senderId } : {},\n\t\t\t...receipt.msgType ? { msgType: receipt.msgType } : {},\n\t\t\tcontentStatus: receipt.contentStatus,\n\t\t\tcontent: receipt.content ?? {\n\t\t\t\tmsgType: receipt.msgType ?? \"unknown\",\n\t\t\t\tunavailable: \"content_read_failed\"\n\t\t\t}\n\t\t}\n\t});\n}\nasync function withOutgoingReplyInflight(options) {\n\tif (!options.enabled) return options.run();\n\tlet inflight;\n\ttry {\n\t\tinflight = await beginOutgoingReplyInflight({\n\t\t\tplansRoot: options.plansRoot,\n\t\t\tsessionDir: dirname(options.planPath),\n\t\t\trunId: options.runId\n\t\t});\n\t} catch {\n\t\tlogger$1.debug({ code: \"outgoing_reply_inflight_begin_failed\" }, \"Outgoing reply inflight begin failed\");\n\t\tawait markOutgoingReplyCaptureStatus({\n\t\t\tplansRoot: options.plansRoot,\n\t\t\tsessionDir: dirname(options.planPath),\n\t\t\trunId: options.runId,\n\t\t\tstatus: \"unavailable\"\n\t\t});\n\t}\n\ttry {\n\t\treturn await options.run();\n\t} finally {\n\t\tawait inflight?.release();\n\t}\n}\nfunction inspectLarkCliEnvelope(stdout) {\n\tconst parsed = parseJsonValue(typeof stdout === \"string\" ? stdout : stdout.toString(\"utf8\"));\n\tif (!isRecord(parsed)) return { kind: \"malformed\" };\n\tif (parsed.dry_run === true) return { kind: \"rejected\" };\n\tif (typeof parsed.identity === \"string\" && parsed.identity !== \"bot\") return { kind: \"rejected\" };\n\tif (parsed.ok === false) return { kind: \"rejected\" };\n\tif (parsed.ok === true && parsed.identity === \"bot\") return {\n\t\tkind: \"success\",\n\t\tdata: parsed.data\n\t};\n\treturn { kind: \"malformed\" };\n}\nfunction parseLarkCliSuccessEnvelope(stdout) {\n\tconst parsed = inspectLarkCliEnvelope(stdout);\n\tif (parsed.kind !== \"success\") return void 0;\n\treturn {\n\t\tok: true,\n\t\tidentity: \"bot\",\n\t\tdata: parsed.data\n\t};\n}\nfunction extractSendReceipt(data) {\n\treturn extractMessageItem(unwrapMessageItem(data));\n}\nfunction unwrapMessageItem(data) {\n\tif (!isRecord(data)) return void 0;\n\tif (Array.isArray(data.items) && isRecord(data.items[0])) return data.items[0];\n\treturn data;\n}\nfunction extractMessageItem(item) {\n\tif (!item) return void 0;\n\tconst messageId = asNonEmptyString(item.message_id);\n\tconst chatId = asNonEmptyString(item.chat_id);\n\tif (!messageId || !chatId) return void 0;\n\tconst bodyContent = messageBodyContent(item);\n\treturn {\n\t\tmessageId,\n\t\tchatId,\n\t\t...optionalMessageIds(item),\n\t\t...optionalSender(item),\n\t\tcontentStatus: bodyContent.contentStatus,\n\t\t...bodyContent.msgType ? { msgType: bodyContent.msgType } : {},\n\t\t...bodyContent.content ? { content: bodyContent.content } : {}\n\t};\n}\nfunction optionalMessageIds(item) {\n\treturn {\n\t\t...asNonEmptyString(item.thread_id) ? { threadId: asNonEmptyString(item.thread_id) } : {},\n\t\t...asNonEmptyString(item.root_id) ? { rootId: asNonEmptyString(item.root_id) } : {},\n\t\t...asNonEmptyString(item.parent_id) ? { parentId: asNonEmptyString(item.parent_id) } : {},\n\t\t...asNonEmptyString(item.create_time) ? { createTime: asNonEmptyString(item.create_time) } : {}\n\t};\n}\nfunction optionalSender(item) {\n\tconst sender = isRecord(item.sender) ? item.sender : void 0;\n\treturn {\n\t\t...asNonEmptyString(sender?.sender_type) ? { senderType: asNonEmptyString(sender?.sender_type) } : {},\n\t\t...asNonEmptyString(sender?.id) ? { senderId: asNonEmptyString(sender?.id) } : {}\n\t};\n}\nfunction messageBodyContent(item) {\n\tconst msgType = normalizeMsgType(item.msg_type);\n\tconst body = isRecord(item.body) ? item.body : void 0;\n\tif (!(typeof body?.content === \"string\" || isRecord(body?.content)) || !body) return {\n\t\t...msgType ? { msgType } : {},\n\t\tcontentStatus: \"unavailable\"\n\t};\n\tconst extracted = contentFromBody(msgType ?? \"unknown\", body);\n\treturn {\n\t\t...msgType ? { msgType } : {},\n\t\tcontent: extracted.content,\n\t\tcontentStatus: extracted.truncated ? \"truncated\" : \"available\"\n\t};\n}\nasync function queryLarkMessageById(options) {\n\tconst args = [\n\t\t...options.argsPrefix,\n\t\t\"api\",\n\t\t\"GET\",\n\t\t`/open-apis/im/v1/messages/${encodeURIComponent(options.messageId)}`,\n\t\t\"--as\",\n\t\t\"bot\",\n\t\t\"--json\"\n\t];\n\ttry {\n\t\tconst result = await spawnCapturedProcess({\n\t\t\tfile: options.file,\n\t\t\targs,\n\t\t\tenv: options.env,\n\t\t\ttimeoutMs: PROVIDER_CLI_OUTGOING_REPLY_QUERY_TIMEOUT_MS,\n\t\t\tmaxBytes: PROVIDER_CLI_OUTGOING_REPLY_QUERY_MAX_BYTES,\n\t\t\tforward: false\n\t\t});\n\t\tif (result.timedOut) return { status: \"timeout\" };\n\t\tif (result.code !== 0) return { status: \"failed\" };\n\t\tconst envelope = parseLarkCliSuccessEnvelope(result.stdout);\n\t\tif (!envelope) return { status: result.truncated ? \"truncated\" : \"failed\" };\n\t\tconst item = unwrapMessageItem(envelope.data);\n\t\tif (!item) return { status: \"failed\" };\n\t\treturn {\n\t\t\tstatus: \"available\",\n\t\t\titem\n\t\t};\n\t} catch {\n\t\tlogger$1.debug({ code: \"outgoing_reply_query_failed\" }, \"Outgoing reply content query failed\");\n\t\treturn { status: \"failed\" };\n\t}\n}\nasync function markIncomplete(options) {\n\tawait markOutgoingReplyCaptureStatus({\n\t\tplansRoot: options.plansRoot,\n\t\tsessionDir: dirname(options.planPath),\n\t\trunId: options.plan.runId,\n\t\tstatus: \"incomplete\"\n\t});\n}\nfunction managedArgPrefix(spawnArgs, userArgv) {\n\tif (userArgv.length === 0) return spawnArgs;\n\tif (spawnArgs.length >= userArgv.length) {\n\t\tconst suffix = spawnArgs.slice(spawnArgs.length - userArgv.length);\n\t\tif (suffix.length === userArgv.length && suffix.every((value, index) => value === userArgv[index])) return spawnArgs.slice(0, spawnArgs.length - userArgv.length);\n\t}\n\treturn [];\n}\nfunction positionalArgv(argv) {\n\tconst positional = [];\n\tlet dryRun = false;\n\tfor (let index = 0; index < argv.length; index += 1) {\n\t\tconst argument = argv[index];\n\t\tif (argument === void 0) continue;\n\t\tif (argument === \"--dry-run\") dryRun = true;\n\t\tif (argument.startsWith(\"--dry-run=\")) dryRun = ![\n\t\t\t\"false\",\n\t\t\t\"0\",\n\t\t\t\"f\"\n\t\t].includes(argument.slice(10).toLowerCase());\n\t\tconst skipped = skipArgvFlag(argument, index);\n\t\tif (skipped === \"stop\") {\n\t\t\tpositional.push(...argv.slice(index + 1));\n\t\t\tbreak;\n\t\t}\n\t\tif (skipped !== void 0) {\n\t\t\tindex = skipped;\n\t\t\tcontinue;\n\t\t}\n\t\tpositional.push(argument);\n\t}\n\treturn {\n\t\tpositional,\n\t\tdryRun\n\t};\n}\nfunction skipArgvFlag(argument, index) {\n\tif (argument === \"--\") return \"stop\";\n\tif (argument.startsWith(\"--\")) {\n\t\tif (argument.includes(\"=\") || BOOLEAN_FLAGS.has(argument)) return index;\n\t\treturn index + 1;\n\t}\n\tif (argument.startsWith(\"-\") && argument !== \"-\") return argument === \"-q\" || argument === \"-o\" ? index + 1 : index;\n}\nfunction normalizeApiPath(path) {\n\tlet value = path.trim();\n\tconst matched = /^https?:\\/\\/[^/]+(\\/open-apis\\/.+)$/.exec(value);\n\tif (matched?.[1]) value = matched[1];\n\tif (!value.startsWith(\"/open-apis/\")) value = `/open-apis/${value.replace(/^\\/+/, \"\")}`;\n\tif (value.length > 1 && value.endsWith(\"/\")) value = value.slice(0, -1);\n\treturn value;\n}\nfunction normalizeMsgType(value) {\n\tif (typeof value !== \"string\") return void 0;\n\treturn [\n\t\t\"text\",\n\t\t\"post\",\n\t\t\"image\",\n\t\t\"file\",\n\t\t\"audio\",\n\t\t\"video\",\n\t\t\"media\",\n\t\t\"interactive\",\n\t\t\"sticker\",\n\t\t\"share_chat\",\n\t\t\"share_user\",\n\t\t\"unknown\"\n\t].includes(value) ? value : \"unknown\";\n}\nfunction parseJsonValue(text) {\n\tconst trimmed = text.trim();\n\tif (!trimmed) return void 0;\n\ttry {\n\t\treturn JSON.parse(trimmed);\n\t} catch {\n\t\tconst lines = trimmed.split(/\\r?\\n/).map((line) => line.trim()).filter((line) => line.startsWith(\"{\"));\n\t\tfor (let index = lines.length - 1; index >= 0; index -= 1) {\n\t\t\tconst line = lines[index];\n\t\t\tif (line === void 0) continue;\n\t\t\ttry {\n\t\t\t\treturn JSON.parse(line);\n\t\t\t} catch {}\n\t\t}\n\t\treturn;\n\t}\n}\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction asNonEmptyString(value) {\n\treturn typeof value === \"string\" && value.length > 0 ? value : void 0;\n}\n//#endregion\n//#region src/runtime/provider-cli/outgoing-reply-report.ts\nfunction feishuOutgoingReplyScope(providerRef) {\n\tif (providerRef.provider !== \"feishu\") return void 0;\n\treturn {\n\t\tappId: providerRef.appId,\n\t\tbotOpenId: providerRef.botOpenId,\n\t\tchatId: providerRef.chatId,\n\t\tmessageId: providerRef.messageId,\n\t\t...providerRef.threadId ? { threadId: providerRef.threadId } : {},\n\t\t...providerRef.rootId ? { rootId: providerRef.rootId } : {},\n\t\t...providerRef.parentId ? { parentId: providerRef.parentId } : {},\n\t\t...providerRef.chatType ? { chatType: providerRef.chatType } : {},\n\t\tteamBrand: providerRef.teamBrand\n\t};\n}\nfunction isOutgoingReplyInScope(scope, receipt) {\n\tif (receipt.chatId !== scope.chatId) return false;\n\tif (receipt.senderType && receipt.senderType !== \"app\") return false;\n\tif (receipt.senderId && scope.appId && scope.botOpenId && receipt.senderId !== scope.appId && receipt.senderId !== scope.botOpenId) return false;\n\tif (scope.chatType === \"p2p\") return true;\n\tif (scope.threadId && receipt.threadId) return receipt.threadId === scope.threadId;\n\tconst rootId = scope.rootId ?? scope.messageId;\n\tif (receipt.rootId && receipt.rootId !== rootId) return false;\n\tif (receipt.rootId === rootId || receipt.parentId === scope.messageId) return true;\n\treturn !scope.chatType && !scope.threadId && !scope.rootId;\n}\nfunction snapshotOutgoingReplies(collected, scope) {\n\tif (collected.status === \"unavailable\" && collected.receipts.length === 0) return TurnOutgoingReplySnapshotSchema.parse({\n\t\tstatus: \"unavailable\",\n\t\treplies: []\n\t});\n\tconst replies = [];\n\tlet omittedCount = 0;\n\tlet incomplete = collected.status !== \"complete\";\n\tfor (const receipt of uniqueReceipts(collected.receipts)) {\n\t\tif (!isOutgoingReplyInScope(scope, receipt)) {\n\t\t\tomittedCount += 1;\n\t\t\tincomplete = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (replies.length >= RUNTIME_OUTGOING_REPLY_MAX_COUNT) {\n\t\t\tomittedCount += 1;\n\t\t\tincomplete = true;\n\t\t\tcontinue;\n\t\t}\n\t\tconst parsed = TurnOutgoingReplySchema.safeParse(toOutgoingReply(receipt, scope.teamBrand));\n\t\tif (!parsed.success) {\n\t\t\tomittedCount += 1;\n\t\t\tincomplete = true;\n\t\t\tcontinue;\n\t\t}\n\t\treplies.push(parsed.data);\n\t\tif (parsed.data.content.unavailable) incomplete = true;\n\t}\n\treturn fitSnapshot({\n\t\tstatus: incomplete ? \"incomplete\" : \"complete\",\n\t\treplies,\n\t\t...omittedCount > 0 ? { omittedCount } : {}\n\t});\n}\nfunction uniqueReceipts(receipts) {\n\tconst unique = /* @__PURE__ */ new Map();\n\tfor (const receipt of receipts) {\n\t\tconst previous = unique.get(receipt.messageId);\n\t\tif (!previous || previous.contentStatus !== \"available\" && receipt.contentStatus === \"available\") unique.set(receipt.messageId, receipt);\n\t}\n\treturn [...unique.values()];\n}\nfunction budgetTurnReportHashInput(input) {\n\tconst initial = input.outgoingReplies;\n\tif (initial === void 0) return input;\n\tlet snapshot = fitSnapshot(initial);\n\tlet current = {\n\t\t...input,\n\t\toutgoingReplies: snapshot\n\t};\n\tif (frameBytes(current) <= RUNTIME_MAX_FRAME_BYTES && snapshotBytes(snapshot) <= RUNTIME_OUTGOING_REPLY_SNAPSHOT_MAX_BYTES) return current;\n\tif (current.finalText) {\n\t\tcurrent = truncateFinalTextToFit(current);\n\t\tsnapshot = current.outgoingReplies ?? snapshot;\n\t}\n\tif (frameBytes(current) <= RUNTIME_MAX_FRAME_BYTES && snapshotBytes(snapshot) <= RUNTIME_OUTGOING_REPLY_SNAPSHOT_MAX_BYTES) return current;\n\tsnapshot = fitSnapshot(stripReplyBodies(snapshot, snapshot.omittedCount ?? 0));\n\tcurrent = {\n\t\t...current,\n\t\toutgoingReplies: snapshot\n\t};\n\tif (frameBytes(current) <= RUNTIME_MAX_FRAME_BYTES) return current;\n\tlet replies = [...snapshot.replies];\n\tlet omittedCount = snapshot.omittedCount ?? 0;\n\twhile (replies.length > 0 && frameBytes(withReplies(current, replies, omittedCount)) > RUNTIME_MAX_FRAME_BYTES) {\n\t\treplies = replies.slice(0, -1);\n\t\tomittedCount += 1;\n\t}\n\treturn withReplies(current, replies, omittedCount);\n}\nfunction toOutgoingReply(receipt, teamBrand) {\n\treturn {\n\t\tprovider: \"feishu\",\n\t\tteamBrand,\n\t\tmessageId: receipt.messageId,\n\t\tchatId: receipt.chatId,\n\t\t...optionalReplyIds(receipt),\n\t\tcontent: outgoingReplyContent(receipt)\n\t};\n}\nfunction optionalReplyIds(receipt) {\n\treturn {\n\t\t...receipt.threadId ? { threadId: receipt.threadId } : {},\n\t\t...receipt.rootId ? { rootId: receipt.rootId } : {},\n\t\t...receipt.parentId ? { parentId: receipt.parentId } : {},\n\t\t...receipt.createTime ? { createTime: receipt.createTime } : {}\n\t};\n}\nfunction outgoingReplyContent(receipt) {\n\tconst unavailable = receipt.contentStatus === \"available\" ? receipt.content?.unavailable : receipt.content?.unavailable ?? (receipt.contentStatus === \"truncated\" ? \"content_truncated\" : \"content_read_failed\");\n\treturn {\n\t\tmsgType: receipt.content?.msgType ?? receipt.msgType ?? \"unknown\",\n\t\t...receipt.content?.text !== void 0 ? { text: receipt.content.text } : {},\n\t\t...receipt.content?.post !== void 0 ? { post: receipt.content.post } : {},\n\t\t...receipt.content?.filename ? { filename: receipt.content.filename } : {},\n\t\t...receipt.content?.fileKey ? { fileKey: receipt.content.fileKey } : {},\n\t\t...receipt.content?.imageKey ? { imageKey: receipt.content.imageKey } : {},\n\t\t...receipt.content?.raw ? { raw: receipt.content.raw } : {},\n\t\t...unavailable ? { unavailable } : {}\n\t};\n}\nfunction truncateFinalTextToFit(input) {\n\tconst current = input.outgoingReplies;\n\tif (!current) return input;\n\tconst snapshot = {\n\t\t...current,\n\t\truntimeSummaryTruncated: true\n\t};\n\tif (!input.finalText) return {\n\t\t...input,\n\t\toutgoingReplies: snapshot\n\t};\n\tlet high = Buffer.byteLength(input.finalText, \"utf8\");\n\tlet low = 0;\n\tlet best = \"\";\n\twhile (low <= high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tconst text = truncateUtf8(input.finalText, mid).text;\n\t\tif (frameBytes({\n\t\t\t...omitFinalText(input),\n\t\t\t...text ? { finalText: text } : {},\n\t\t\toutgoingReplies: snapshot\n\t\t}) <= RUNTIME_MAX_FRAME_BYTES) {\n\t\t\tbest = text;\n\t\t\tlow = mid + 1;\n\t\t} else high = mid - 1;\n\t}\n\tif (!best) {\n\t\tconst { finalText: _removed, ...rest } = input;\n\t\treturn {\n\t\t\t...rest,\n\t\t\toutgoingReplies: snapshot\n\t\t};\n\t}\n\treturn {\n\t\t...input,\n\t\tfinalText: best,\n\t\toutgoingReplies: snapshot\n\t};\n}\nfunction omitFinalText(input) {\n\tconst { finalText: _finalText, ...rest } = input;\n\treturn rest;\n}\nfunction stripReplyBodies(snapshot, omittedCount) {\n\treturn {\n\t\tstatus: snapshot.status === \"complete\" ? \"incomplete\" : snapshot.status,\n\t\treplies: snapshot.replies.map((reply) => ({\n\t\t\t...reply,\n\t\t\tcontent: {\n\t\t\t\tmsgType: reply.content.msgType,\n\t\t\t\t...reply.content.filename ? { filename: reply.content.filename } : {},\n\t\t\t\t...reply.content.fileKey ? { fileKey: reply.content.fileKey } : {},\n\t\t\t\t...reply.content.imageKey ? { imageKey: reply.content.imageKey } : {},\n\t\t\t\tunavailable: \"content_truncated\"\n\t\t\t}\n\t\t})),\n\t\tomittedCount,\n\t\t...snapshot.runtimeSummaryTruncated ? { runtimeSummaryTruncated: true } : {}\n\t};\n}\nfunction withReplies(input, replies, omittedCount) {\n\tconst snapshot = fitSnapshot({\n\t\tstatus: omittedCount > 0 || input.outgoingReplies?.status !== \"complete\" ? \"incomplete\" : \"complete\",\n\t\treplies: [...replies],\n\t\t...omittedCount > 0 ? { omittedCount } : {},\n\t\t...input.outgoingReplies?.runtimeSummaryTruncated ? { runtimeSummaryTruncated: true } : {}\n\t});\n\treturn {\n\t\t...input,\n\t\toutgoingReplies: snapshot\n\t};\n}\nfunction fitSnapshot(snapshot) {\n\tconst parsed = TurnOutgoingReplySnapshotSchema.safeParse(snapshot);\n\tif (parsed.success) return parsed.data;\n\tconst replies = [...snapshot.replies];\n\tlet omittedCount = snapshot.omittedCount ?? 0;\n\tfor (let index = replies.length - 1; index >= 0; index -= 1) {\n\t\tconst reply = replies[index];\n\t\tif (!reply) continue;\n\t\treplies[index] = stripReplyBodies({\n\t\t\tstatus: \"incomplete\",\n\t\t\treplies: [reply]\n\t\t}, 0).replies[0] ?? reply;\n\t\tconst candidate = {\n\t\t\t...snapshot,\n\t\t\tstatus: \"incomplete\",\n\t\t\treplies\n\t\t};\n\t\tconst next = TurnOutgoingReplySnapshotSchema.safeParse(candidate);\n\t\tif (next.success) return next.data;\n\t}\n\twhile (replies.length > 0) {\n\t\treplies.pop();\n\t\tomittedCount += 1;\n\t\tconst candidate = {\n\t\t\tstatus: \"incomplete\",\n\t\t\treplies,\n\t\t\tomittedCount,\n\t\t\t...snapshot.runtimeSummaryTruncated ? { runtimeSummaryTruncated: true } : {}\n\t\t};\n\t\tconst next = TurnOutgoingReplySnapshotSchema.safeParse(candidate);\n\t\tif (next.success) return next.data;\n\t}\n\treturn TurnOutgoingReplySnapshotSchema.parse({\n\t\tstatus: \"incomplete\",\n\t\treplies: [],\n\t\tomittedCount: Math.max(omittedCount, 1),\n\t\t...snapshot.runtimeSummaryTruncated ? { runtimeSummaryTruncated: true } : {}\n\t});\n}\nfunction frameBytes(input) {\n\tconst report = {\n\t\ttype: \"turn:report\",\n\t\trequestId: \"00000000-0000-4000-8000-000000000000\",\n\t\tconnectionId: \"00000000-0000-4000-8000-000000000000\",\n\t\t...input,\n\t\tresultHash: computeTurnResultHash(input)\n\t};\n\treturn runtimeFrameByteLength(JSON.stringify(report));\n}\nfunction snapshotBytes(snapshot) {\n\treturn runtimeFrameByteLength(JSON.stringify(snapshot));\n}\nfunction emptyCompleteOutgoingReplies() {\n\treturn TurnOutgoingReplySnapshotSchema.parse({\n\t\tstatus: \"complete\",\n\t\treplies: []\n\t});\n}\nfunction unavailableOutgoingReplies() {\n\treturn TurnOutgoingReplySnapshotSchema.parse({\n\t\tstatus: \"unavailable\",\n\t\treplies: []\n\t});\n}\n//#endregion\n//#region src/runtime/provider-outbox-instructions.ts\nfunction buildProviderOutboxInstructions(options) {\n\tconst providerCommand = options.provider === \"feishu\" ? \"lark-cli\" : \"slack api\";\n\treturn [\n\t\t\"Who reads your output: inside OpenTag, the \\\"user\\\" your underlying agent addresses — the reader of everything you produce apart from running a provider CLI command, including the text that closes this Turn — is the OpenTag runtime. This is your runtime console; ordinary output is not delivered to the IM participant.\",\n\t\t`The IM participant is a separate audience. The official ${providerCommand} CLI is your outbox and the only path from this Turn to that audience.`,\n\t\t\"The console addresses OpenTag; running the provider CLI performs the provider action. Describing a reply, reaction, or proactive message in your output only records it in OpenTag; it does not deliver it.\",\n\t\toptions.actionInstruction,\n\t\t`To write to this ${options.provider} conversation, load the credentials from $OPENTAG_PROVIDER_ENV_FILE in your shell, then use the official ${providerCommand} CLI directly.`,\n\t\t...providerBodyInstructions(options.provider),\n\t\t\"OpenTag has no message send, reply, or reaction interface, and you do not report provider send results to OpenTag.\",\n\t\t\"Use the provider-native identifiers below. Do not substitute an OpenTag Session or message ID.\",\n\t\t\"If a provider result is unknown, query the provider before deciding whether to retry.\",\n\t\t`${options.targetLabel}: ${JSON.stringify(options.target)}`,\n\t\t`For version-specific commands and native formats, run ${options.provider === \"feishu\" ? \"lark-cli im --help\" : \"slack api --help\"}.`\n\t];\n}\nconst SLACK_NATIVE_CLI_GUIDANCE = [\n\t\"Use the native CLI as `slack api chat.postMessage --json '<json>'`. Other methods use the same form: `slack api <method> --json '<json>'`. Pass exactly one JSON object; never key=value pairs, which form-encode the token into the request body.\",\n\t\"Do not pass --token, --app, --team, -w, --workspace, --config-dir, --skip-update, or other token, app, team, workspace, config, or update override flags. The launcher and environment already bind this Turn.\",\n\t\"Set channel to the supplied channelId. Thread placement is a Session policy decision: when the current context includes threadTs, that value is this Session's Slack thread_ts; otherwise messageTs identifies the source message you may thread from.\",\n\t\"You may discover, read, or write another public channel, private channel, DM, or existing MPIM with its provider-native ID when that conversation is relevant to the current task, even if the user did not name it. Otherwise stay in this Session's conversation. Do not roam through, bulk-join, or inspect task-unrelated conversations.\",\n\t\"Discover the Team, users, channels, DMs, and existing MPIMs with team.info, users.info, users.list, conversations.info, and conversations.list. Paginate list methods with limit and response_metadata.next_cursor; stop when the cursor is empty.\",\n\t\"Read a targeted channel with conversations.history and a thread with conversations.replies (channel plus ts). conversations.history and similar reads are rate-limited; query sparingly and do not poll in a tight loop. On HTTP 429, wait Retry-After seconds or a short backoff once before retrying.\",\n\t\"Post with chat.postMessage, edit with chat.update, delete with chat.delete, and schedule with chat.scheduleMessage. Cancel a scheduled message immediately by its scheduled_message_id with chat.deleteScheduledMessage, leave enough lead time, and verify it is absent with chat.scheduledMessages.list. Put the body in `text` (at most 4,000 characters) or `markdown_text` (at most 12,000 characters). Split longer content across multiple chat.postMessage calls rather than truncating silently. Post at most 1 message per second per channel. Mention users as `<@U...>` with provider-native user IDs.\",\n\t\"Open or resume a 1:1 DM with conversations.open `{users}` containing exactly one user ID. Do not use it to create an MPIM; read or write an existing MPIM only when the bot already has access.\",\n\t\"For not_in_channel, first confirm with conversations.info or conversations.list that the target is a public channel and relevant to the current task. Then call conversations.join `{channel}` once and retry the original action once. Joining enrolls future messages in normal OpenTag ingress: they are persisted, then mention_only or all_message controls delivery. Do not join merely to explore. For private channels, MPIMs, channel_not_found, or an unknown type, ask the user to invite the bot; do not guess or retry.\",\n\t\"Add, read, or remove emoji with reactions.add, reactions.get, and reactions.remove using channel, timestamp, and name.\",\n\t\"Upload files with Slack's current external flow only: files.getUploadURLExternal `{filename,length}` → HTTP POST the raw bytes to upload_url (not via slack api) → files.completeUploadExternal `{files:[{id,title}],channel_id,thread_ts?}`. Do not call the deprecated files.upload method. Load $OPENTAG_PROVIDER_ENV_FILE in the same shell before any raw upload_url, url_private, or url_private_download request: only the provider proxy scope in that file can route and trust those URLs.\",\n\t\"Never print credentials, tokens, or the environment file. CLI argv and command output are visible on the OpenTag runtime console.\"\n];\nfunction providerBodyInstructions(provider) {\n\tif (provider === \"slack\") return SLACK_NATIVE_CLI_GUIDANCE;\n\treturn [\n\t\t\"For lark-cli text and Markdown bodies, intended line breaks must reach the CLI as real newline characters; never write literal `\\\\n` sequences for layout.\",\n\t\t\"Before sending, inspect the body: if it has no real newline and contains two or more literal `\\\\n` sequences, treat it as malformed and rebuild it instead of sending. Do not blindly replace `\\\\n`, because code or prose may intentionally discuss that token.\",\n\t\t\"Keep rich or multiline bodies out of ordinary inline shell quoting. Populate a task-specific variable with shell-native, non-interpolating multiline syntax, then pass the variable as one quoted `--text` or `--markdown` argument.\",\n\t\t\"POSIX shell pattern:\",\n\t\t\"```bash\",\n\t\t\"IFS= read -r -d '' OPENTAG_LARK_BODY <<'EOF' || true\",\n\t\t\"first line\",\n\t\t\"\",\n\t\t\"second line with `code`, $variables, \\\"quotes\\\", and apostrophes\",\n\t\t\"EOF\",\n\t\t\"lark-cli ... --markdown \\\"$OPENTAG_LARK_BODY\\\"\",\n\t\t\"```\",\n\t\t\"PowerShell pattern:\",\n\t\t\"```powershell\",\n\t\t\"$OpenTagLarkBody = @'\",\n\t\t\"first line\",\n\t\t\"\",\n\t\t\"second line with `code`, $variables, \\\"quotes\\\", and apostrophes\",\n\t\t\"'@\",\n\t\t\"lark-cli ... --markdown $OpenTagLarkBody\",\n\t\t\"```\",\n\t\t\"Replace `...` with the version-specific lark-cli subcommand and provider-native target options before running it.\"\n\t];\n}\n/** Non-secret execution metadata is discovered without changing native CLI authentication. */\nconst GITHUB_NATIVE_CLI_INSTRUCTIONS = \"GitHub integration, when enabled, preconfigures native git and gh. Read OPENTAG_GITHUB_REPOSITORIES for granted repositories, role, branch, publish mode and workBranchPrefix. Create task branches under the supplied workBranchPrefix; Context Tree direct mode targets its configured branch. Authentication and renewal are automatic; do not run interactive login or replace managed credentials.\";\n//#endregion\n//#region src/runtime/managed-instructions.ts\n/**\n* The Agent is told plainly when durable memory is absent, so it cannot mistake a failed\n* connection for an empty tree and start re-deriving decisions. Its own slug is not repeated\n* here — the trusted Platform section above already states it.\n*/\nfunction renderContextTree(status) {\n\tif (status.status === \"configured\") return [\n\t\t\"Context Trees (no precedence is implied by their order):\",\n\t\t...status.connections.flatMap((entry) => [`Alias ${entry.alias} — ${entry.repository}:`, ...renderContextTreeFacts(entry)]),\n\t\t...new Set(status.connections.flatMap(renderContextTreeGuidance)),\n\t\t\"Use the upstream Context Tree skills to select relevant trees, attribute disagreements to their aliases, and choose an explicit alias for every write.\"\n\t];\n\treturn [...renderContextTreeFacts(status), ...renderContextTreeGuidance(status)];\n}\nfunction renderContextTreeFacts(status) {\n\tif (status.status === \"ready\") return [`Context Tree: ${status.treePath}`];\n\tif (status.status === \"unconfigured\") return [\"Context Tree: disabled for this Agent. Connect one on the Agent's Context Tree page.\"];\n\treturn [status.reason === \"PREPARING\" ? \"Context Tree preparation is continuing in the background.\" : `Context Tree unavailable (${status.reason}).`];\n}\nfunction renderContextTreeGuidance(status) {\n\tif (status.status === \"ready\") return [\n\t\t\"Ready Context Trees are connected on this Agent's Context Tree page. Other Agents share this memory only when they select the same repository. Read the decisions that bear on a task before planning or changing code, and record durable decisions there.\",\n\t\t\"Use the context-tree-read and context-tree-write skills rather than editing the tree by hand.\",\n\t\t\"`members/<your Agent slug>/` is your own private working memory; the Agent slug is stated in the Platform section above. Do not write to another Agent's member directory.\",\n\t\t\"\"\n\t];\n\tif (status.status === \"unconfigured\") return [\"Durable memory is not active. Do not assume earlier decisions were recorded, and do not attempt to create a tree yourself.\", \"\"];\n\treturn [\n\t\t\"Unavailable trees are not active for this Session. Other ready trees remain usable.\",\n\t\tstatus.reason === \"PREPARING\" ? \"Trees still preparing may become usable in a later Session.\" : \"Do not assume earlier decisions were recorded in unavailable trees, and do not attempt to repair the tree yourself.\",\n\t\t\"\"\n\t];\n}\nfunction renderAgentHome(agentHome) {\n\treturn [\n\t\t\"## Agent Home\",\n\t\t\"\",\n\t\tagentHome ? `Your Agent Home is ${agentHome}. One persistent Home is shared across this Agent's Sessions on this Computer.` : \"One persistent Home is shared across this Agent's Sessions on this Computer.\",\n\t\t\"Files survive tasks. Use absolute paths; resolve the directories below from Agent Home, not the task cwd.\",\n\t\t\"\",\n\t\t\"These directories are prompt conventions, not platform-managed resources or automatic cleanup policies. Create them only as needed:\",\n\t\t\"- `source-repos/<unique-repo-key>/` — agent-managed bare source clones. Repository identity comes from the user or task, not from platform bindings. Before reusing an existing clone, verify it belongs to the intended repository. Preserve existing files. Do not clone into the Home root.\",\n\t\t\"- `worktrees/<unique-task-key>/` — agent-managed checkouts for source access and code work. Concurrent code tasks each use a distinct worktree (and a distinct branch when editing). Keep later operations for the same task in its own worktree. No two code tasks edit one checkout.\",\n\t\t\"- `files/<unique-task-key>/` — non-repository task artifacts, created only when needed.\",\n\t\t\"\",\n\t\t\"OpenTag provides the bundled `context-tree` command. If it cannot run, report a runtime setup problem; do not install it globally.\",\n\t\t\"Context Tree stays the separately configured shared tree managed by its matching CLI and skills. When running Context Tree project commands from a task subdirectory, pass `--project-path \\\"<Agent Home>\\\"` to use the connected Home; do not create or reconnect a tree just because the task cwd changed. Follow the matching skill write protocol. Do not invent an independent Git policy for Tree writes.\",\n\t\t\"\"\n\t];\n}\n/**\n* Reusable know-how an Agent discovers can be saved to its own platform account and restored on\n* every Computer it runs on, so a good routine is not trapped in one workspace.\n*/\nfunction renderSkills(cliCommand) {\n\treturn [\n\t\t\"## Skills\",\n\t\t\"\",\n\t\t`Reusable routines can be captured as a skill: a directory with a \\`SKILL.md\\` whose frontmatter has \\`name\\` and \\`description\\`. Save one to the platform with \\`${cliCommand} skill push <dir>\\`. Saved skills are restored on every Computer this Agent runs on.`,\n\t\t\"\"\n\t];\n}\n/**\n* The Agent may tune its own configuration through the Session proof. Instructions, model, and\n* reasoning effort feed the effective snapshot hash, so a change applies from the next Turn and that\n* Turn starts a new provider conversation instead of resuming the old one. The Agent is told so it\n* does not change them casually mid-task.\n*/\nfunction renderSelfConfiguration(cliCommand) {\n\treturn [\n\t\t\"## Self-configuration\",\n\t\t\"\",\n\t\t`Inspect your own configuration with \\`${cliCommand} agent self show\\`. When a user asks you to change how you work, you may update your own instructions, model, or reasoning effort with \\`${cliCommand} agent self update\\`, and mount or enable Account MCP Servers with \\`${cliCommand} agent self mcp\\`. Instruction, model, and reasoning-effort changes apply from your next Turn and start a new provider conversation in every existing Session, so earlier conversation context is not carried over; change them only when asked, not mid-task. MCP mount changes apply to your next MCP request. Replacing instructions overwrites them entirely, so read the current value first and keep what still applies.`,\n\t\t\"\"\n\t];\n}\nfunction renderManagedSystemPrompt(snapshot, context) {\n\tconst session = context ? [\n\t\t...renderAgentHome(context.agentHome),\n\t\t...renderSkills(context.cliCommand),\n\t\t...context.sessionCliAvailable ? renderSelfConfiguration(context.cliCommand) : [],\n\t\t\"## Session\",\n\t\t\"\",\n\t\t`Current Session: ${context.sessionId}`,\n\t\t`Session kind: ${context.sessionKind}`,\n\t\t...context.creatorSessionId ? [`Creator Session: ${context.creatorSessionId}`] : [],\n\t\t\"\",\n\t\t...context.sessionKind === \"internal\" ? [\"You are an internal Session. Focus on the delegated task, report progress, questions, and the final result to the creating or coordinating Session, and do not publish directly to IM.\", \"You may create further internal Sessions when platform-level Session collaboration is useful.\"] : [\n\t\t\t\"You are a visible Session. You may handle work directly, use Provider-native subagents when available, or create OpenTag internal Sessions when platform-level Session collaboration is useful.\",\n\t\t\t\"Lean toward a lively, friendly tone, adapting naturally to the user and the situation.\",\n\t\t\t\"For a lengthy user task, optionally add one emoji reaction via the provider CLI before starting work. Skip unnecessary or duplicate acknowledgments and observer deliveries.\"\n\t\t],\n\t\t\"OpenTag internal Sessions and Provider-native subagents are separate mechanisms and are not interchangeable.\",\n\t\t`When a user explicitly requests an OpenTag internal Session and Session collaboration is available, use ${context.cliCommand} session create; do not substitute a Provider-native subagent.`,\n\t\t\"\",\n\t\t...context.sessionCliAvailable ? [\n\t\t\t\"Session collaboration is available through these commands:\",\n\t\t\t`- ${context.cliCommand} session create --message <task>`,\n\t\t\t`- ${context.cliCommand} session send <target-session-id> --message <text>`,\n\t\t\t`- ${context.cliCommand} session list`,\n\t\t\t\"The current Session identity is supplied by runtime-managed CLI context. Do not pass or look for agentId or sourceSessionId arguments.\",\n\t\t\t\"An accepted result means the target accepted the message for processing; it does not mean the delegated task is complete.\",\n\t\t\t\"If a command result is uncertain, retry with the same messageId and exactly the same semantic input.\"\n\t\t] : [\"Session collaboration commands are unavailable because managed Session context is missing.\"],\n\t\t\"\",\n\t\t...context.contextTree ? renderContextTree(context.contextTree) : []\n\t] : [];\n\treturn [\n\t\t\"# OpenTag managed instructions\",\n\t\t\"\",\n\t\t\"These trusted instructions are injected through the Agent Runtime Provider's native system prompt.\",\n\t\t\"Session-specific instructions and message context are injected for each Turn.\",\n\t\t\"\",\n\t\t\"## Platform\",\n\t\t\"\",\n\t\tsnapshot.instructions.platform,\n\t\t\"\",\n\t\t\"## Agent\",\n\t\t\"\",\n\t\tsnapshot.instructions.agent,\n\t\t\"\",\n\t\t...session\n\t].join(\"\\n\");\n}\n//#endregion\n//#region src/runtime/session-runtime-manager.ts\nconst logger = createLogger(\"runtime-session-manager\");\nvar ClientRuntimeProviderStartError = class extends Error {\n\tproviderId;\n\tconstructor(providerId, options) {\n\t\tconst detail = options?.cause instanceof Error ? `: ${options.cause.message}` : \"\";\n\t\tsuper(`Agent Runtime provider failed to start (${providerId})${detail}`, options);\n\t\tthis.providerId = providerId;\n\t\tthis.name = \"ClientRuntimeProviderStartError\";\n\t}\n};\n/**\n* The manager has no prepared runtime entry for a Session. The fixed code identifies this\n* local readiness failure in logs without including paths, credentials, or cause content.\n*/\nvar SessionRuntimeNotPreparedError = class extends Error {\n\tcode = \"session_runtime_not_prepared\";\n\tconstructor() {\n\t\tsuper(\"The Session Agent Runtime has not been prepared\");\n\t\tthis.name = \"SessionRuntimeNotPreparedError\";\n\t}\n};\nvar SessionRuntimeManager = class {\n\t#bindingStore;\n\t#cliCommand;\n\t#cleanupProviderEnvironment;\n\t#contextTree;\n\t#skills;\n\t#ensureProviderReady;\n\t#providers;\n\t#environment;\n\t#home;\n\t#providerEnvironmentPath;\n\t#providerEnvironment;\n\t#contextTreeEnvironment;\n\t#proofManager;\n\t#slackConfigWritableRoot;\n\t#providerCliLaunchPath;\n\t#providerCliReplyWritableRoot;\n\t#workspace;\n\t#sessions = /* @__PURE__ */ new Map();\n\t#prepares = /* @__PURE__ */ new Set();\n\t#starts = /* @__PURE__ */ new Set();\n\t#closeFailures = [];\n\t#closing = false;\n\t#closePromise;\n\tconstructor(options) {\n\t\tthis.#bindingStore = options.bindingStore;\n\t\tthis.#cliCommand = options.cliCommand ?? \"opentag\";\n\t\tthis.#cleanupProviderEnvironment = options.cleanupProviderEnvironment;\n\t\tthis.#environment = { ...options.environment ?? process.env };\n\t\tif (options.contextTree) this.#contextTree = options.contextTree;\n\t\tif (options.skills) this.#skills = options.skills;\n\t\tthis.#ensureProviderReady = options.ensureProviderReady;\n\t\tthis.#providers = options.providers;\n\t\tthis.#home = options.home;\n\t\tthis.#providerEnvironmentPath = options.providerEnvironmentPath;\n\t\tthis.#providerEnvironment = options.providerEnvironment;\n\t\tthis.#contextTreeEnvironment = options.contextTreeEnvironment;\n\t\tthis.#slackConfigWritableRoot = options.slackConfigWritableRoot;\n\t\tthis.#providerCliLaunchPath = options.providerCliLaunchPath;\n\t\tthis.#providerCliReplyWritableRoot = options.providerCliReplyWritableRoot;\n\t\tthis.#proofManager = options.proofManager ?? {\n\t\t\tcleanup: async () => void 0,\n\t\t\tmaterialize: async () => {\n\t\t\t\tthrow new Error(\"Session CLI proof manager is unavailable\");\n\t\t\t}\n\t\t};\n\t\tthis.#workspace = options.workspace;\n\t}\n\tvalidate(snapshot) {\n\t\treturn this.#providers.validateConfiguration(snapshot);\n\t}\n\tvalidateDelivery(snapshot) {\n\t\treturn this.#providers.validateConfiguration(snapshot);\n\t}\n\tprepareAgent(snapshot, hashes) {\n\t\treturn this.#workspace.prepareAgent(snapshot, hashes);\n\t}\n\tverifyAgent(snapshot, hashes) {\n\t\treturn this.#workspace.verifyAgent(snapshot, hashes);\n\t}\n\trequiresSessionPreparation(request) {\n\t\tconst current = this.#sessions.get(request.sessionId);\n\t\tif (!current) return true;\n\t\treturn current.proofId !== request.sessionCliProof?.proofId;\n\t}\n\tprepareSession(request, hashes) {\n\t\tthis.#assertOpen();\n\t\tconst operation = this.#prepareSession(request, hashes);\n\t\tthis.#prepares.add(operation);\n\t\toperation.finally(() => this.#prepares.delete(operation)).catch((error) => {\n\t\t\tlogger.debug({\n\t\t\t\tcode: \"session_prepare_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Session preparation failed\");\n\t\t});\n\t\treturn operation;\n\t}\n\tasync #prepareSession(request, hashes) {\n\t\tconst prepared = await this.#workspace.prepareSession(request, hashes);\n\t\tthis.#assertOpen();\n\t\tif (prepared.unresolvedTurn) return prepared;\n\t\tconst snapshot = request.runtime;\n\t\tif (!snapshot) throw new Error(\"A ready Session requires a runtime snapshot\");\n\t\tif (!this.#providers.registration(snapshot.provider)) throw new Error(`Agent Runtime provider is not registered: ${snapshot.provider}`);\n\t\tconst proofPath = request.sessionCliProof ? await this.#proofManager.materialize(request.sessionId, request.sessionCliProof) : void 0;\n\t\tconst current = this.#sessions.get(request.sessionId);\n\t\tif (current && current.effectiveSnapshotHash === hashes.effectiveSnapshotHash && current.providerId === snapshot.provider && current.placementGeneration === request.placementGeneration && current.sessionKind === (request.sessionKind ?? \"visible\")) {\n\t\t\tcurrent.binding = prepared.binding;\n\t\t\tcurrent.proofId = request.sessionCliProof?.proofId;\n\t\t\tcurrent.proofPath = proofPath;\n\t\t\tif (current.runtime?.state.phase === \"closed\") current.runtime = void 0;\n\t\t\treturn prepared;\n\t\t}\n\t\tif (current) {\n\t\t\tthis.#sessions.delete(request.sessionId);\n\t\t\ttry {\n\t\t\t\tawait this.#closeManaged(current);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.debug({\n\t\t\t\t\tcode: \"managed_runtime_close_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Managed Session Runtime close failed\");\n\t\t\t\t/* v8 ignore else -- close failures outside shutdown propagate without being collected. */\n\t\t\t\tif (this.#closing) this.#closeFailures.push(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tthis.#assertOpen();\n\t\t}\n\t\tconst cwd = await this.#workspace.cwd(request.agentId);\n\t\tthis.#assertOpen();\n\t\tthis.#sessions.set(request.sessionId, {\n\t\t\tagentId: request.agentId,\n\t\t\tbinding: prepared.binding,\n\t\t\tcwd,\n\t\t\teffectiveSnapshotHash: hashes.effectiveSnapshotHash,\n\t\t\t...request.creatorSessionId ? { creatorSessionId: request.creatorSessionId } : {},\n\t\t\t...request.sessionCliProof ? { proofId: request.sessionCliProof.proofId } : {},\n\t\t\t...proofPath ? { proofPath } : {},\n\t\t\tproviderId: snapshot.provider,\n\t\t\tsessionKind: request.sessionKind ?? \"visible\",\n\t\t\tplacementGeneration: request.placementGeneration,\n\t\t\tsnapshot\n\t\t});\n\t\treturn prepared;\n\t}\n\tasync ensureRuntime(sessionId, signal) {\n\t\tthis.#assertOpen();\n\t\tconst managed = this.#sessions.get(sessionId);\n\t\tif (!managed) throw new SessionRuntimeNotPreparedError();\n\t\tawait this.#ensureProviderReady(managed.providerId, signal);\n\t\tthis.#assertOpen();\n\t\tif (managed.runtime && managed.runtime.state.phase !== \"closed\") return managed.runtime;\n\t\tif (managed.start) return waitForStart(managed.start, signal);\n\t\tconst start = this.#startRuntime(managed).finally(() => {\n\t\t\t/* v8 ignore else -- only the owning start clears its own slot. */\n\t\t\tif (managed.start === start) managed.start = void 0;\n\t\t\tthis.#starts.delete(start);\n\t\t});\n\t\tmanaged.start = start;\n\t\tthis.#starts.add(start);\n\t\tstart.catch((error) => {\n\t\t\tlogger.debug({\n\t\t\t\tcode: \"runtime_start_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Session Runtime start failed\");\n\t\t});\n\t\treturn waitForStart(start, signal);\n\t}\n\tsessionKind(sessionId) {\n\t\tconst managed = this.#sessions.get(sessionId);\n\t\tif (!managed) throw new SessionRuntimeNotPreparedError();\n\t\treturn managed.sessionKind;\n\t}\n\t/** The prepared Session's Agent Runtime provider id; undefined when not prepared. */\n\tproviderId(sessionId) {\n\t\treturn this.#sessions.get(sessionId)?.providerId;\n\t}\n\tasync #startRuntime(managed) {\n\t\tconst provider = this.#providers.registration(managed.providerId);\n\t\t/* v8 ignore next -- registrations are immutable for the lifetime of a managed Session. */\n\t\tif (!provider) throw new Error(`Agent Runtime provider is not registered: ${managed.providerId}`);\n\t\tlet bindingPersisted = false;\n\t\tconst eventSink = async (event) => {\n\t\t\tif (event.type === \"binding_changed\") {\n\t\t\t\tthis.#assertOpen();\n\t\t\t\tconst binding = await this.#bindingStore.saveRuntimeBinding(managed.agentId, managed.binding.sessionId, managed.effectiveSnapshotHash, event.binding);\n\t\t\t\tif (!binding) throw new Error(\"The durable Session binding disappeared\");\n\t\t\t\tmanaged.binding = binding;\n\t\t\t\tbindingPersisted = true;\n\t\t\t\tthis.#assertOpen();\n\t\t\t}\n\t\t\tawait managed.eventSink?.(event);\n\t\t};\n\t\tconst contextTreeEnvironment = this.#contextTreeEnvironment?.(managed.binding.sessionId);\n\t\tconst contextTree = await prepareContextTree(this.#contextTree, managed.cwd, managed.snapshot.provider, managed.snapshot.contextTrees, contextTreeEnvironment);\n\t\tconst configurationRoots = await prepareConfigurationRoots(this.#environment);\n\t\tconst skills = await prepareAgentSkills(this.#skills, {\n\t\t\tagentId: managed.agentId,\n\t\t\tcwd: managed.cwd,\n\t\t\tprovider: managed.snapshot.provider\n\t\t});\n\t\tconst replyRoots = await visibleReplyWritableRoots(managed, this.#providerCliReplyWritableRoot);\n\t\tconst common = {\n\t\t\teventSink,\n\t\t\tsystemPrompt: renderManagedSystemPrompt(managed.snapshot, {\n\t\t\t\tsessionId: managed.binding.sessionId,\n\t\t\t\tsessionKind: managed.sessionKind,\n\t\t\t\t...managed.creatorSessionId ? { creatorSessionId: managed.creatorSessionId } : {},\n\t\t\t\tcliCommand: this.#cliCommand,\n\t\t\t\tsessionCliAvailable: Boolean(managed.proofPath),\n\t\t\t\tagentHome: managed.cwd,\n\t\t\t\t...contextTree.promptContext\n\t\t\t}),\n\t\t\tworkspace: {\n\t\t\t\tcwd: managed.cwd,\n\t\t\t\t...visibleProviderCliPath(managed, this.#providerCliLaunchPath),\n\t\t\t\tenvironment: {\n\t\t\t\t\t...this.#home ? { OPENTAG_HOME: this.#home } : {},\n\t\t\t\t\t...managed.proofPath ? { OPENTAG_SESSION_PROOF_FILE: managed.proofPath } : {},\n\t\t\t\t\t...managed.sessionKind === \"visible\" ? {\n\t\t\t\t\t\tOPENTAG_PROVIDER_ENV_FILE: this.#providerEnvironmentPath(managed.binding.sessionId),\n\t\t\t\t\t\t...this.#providerEnvironment?.(managed.binding.sessionId)\n\t\t\t\t\t} : {}\n\t\t\t\t},\n\t\t\t\twritableRoots: [\n\t\t\t\t\t...replyRoots,\n\t\t\t\t\t...visibleSlackWritableRoots(managed.sessionKind, managed.cwd, managed.binding.sessionId, this.#slackConfigWritableRoot),\n\t\t\t\t\t...configurationRoots,\n\t\t\t\t\t...dropCoveredRoots(contextTree.writableRoots, configurationRoots)\n\t\t\t\t]\n\t\t\t},\n\t\t\tpolicy: provider.policy(managed.snapshot),\n\t\t\tconfiguration: {\n\t\t\t\t...managed.snapshot.model ? { model: managed.snapshot.model } : {},\n\t\t\t\t...managed.snapshot.reasoningEffort ? { reasoningEffort: managed.snapshot.reasoningEffort } : {}\n\t\t\t},\n\t\t\t...skills\n\t\t};\n\t\tlet runtime;\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tconst runtimeBinding = managed.binding.runtimeBinding;\n\t\t\t\tconst replaceBinding = runtimeBinding && provider.requiresBindingReplacement?.(runtimeBinding, void 0) === true;\n\t\t\t\truntime = runtimeBinding && !replaceBinding ? await provider.factory.resume({\n\t\t\t\t\t...common,\n\t\t\t\t\tbinding: runtimeBinding\n\t\t\t\t}) : await provider.factory.create(common);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.debug({\n\t\t\t\t\tcode: \"provider_start_failed\",\n\t\t\t\t\tproviderId: managed.providerId,\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Session provider Runtime start failed\");\n\t\t\t\tthrow new ClientRuntimeProviderStartError(managed.providerId, { cause: error });\n\t\t\t}\n\t\t\tthis.#assertOpen();\n\t\t\tif (!runtime.binding) throw new ClientRuntimeProviderStartError(managed.providerId, { cause: /* @__PURE__ */ new Error(\"Agent Runtime did not produce a durable binding\") });\n\t\t\tif (!bindingPersisted) {\n\t\t\t\tconst binding = await this.#bindingStore.saveRuntimeBinding(managed.agentId, managed.binding.sessionId, managed.effectiveSnapshotHash, runtime.binding);\n\t\t\t\tif (!binding) throw new Error(\"The durable Session binding disappeared\");\n\t\t\t\tmanaged.binding = binding;\n\t\t\t}\n\t\t\tthis.#assertOpen();\n\t\t\tmanaged.runtime = runtime;\n\t\t\treturn runtime;\n\t\t} catch (error) {\n\t\t\tif (runtime) try {\n\t\t\t\tawait runtime.close();\n\t\t\t} catch (closeError) {\n\t\t\t\tlogger.debug({\n\t\t\t\t\tcode: \"runtime_cleanup_failed\",\n\t\t\t\t\terror: String(closeError)\n\t\t\t\t}, \"Session Runtime cleanup after start failure failed\");\n\t\t\t\tif (this.#closing) this.#closeFailures.push(closeError);\n\t\t\t\telse throw new AggregateError([error, closeError], \"Agent Runtime creation and cleanup both failed\");\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\thasAgentSessions(agentId) {\n\t\treturn [...this.#sessions.values()].some((session) => session.agentId === agentId);\n\t}\n\tasync stopSession(sessionId, placementGeneration) {\n\t\tconst sessionKind = this.#sessions.get(sessionId)?.sessionKind;\n\t\ttry {\n\t\t\tconst current = this.#sessions.get(sessionId);\n\t\t\tif (current) {\n\t\t\t\tawait this.#closeManaged(current);\n\t\t\t\tthis.#sessions.delete(sessionId);\n\t\t\t}\n\t\t\tawait this.#workspace.stopSession(sessionId, placementGeneration);\n\t\t} finally {\n\t\t\tawait this.#proofManager.cleanup(sessionId);\n\t\t\t/* v8 ignore else -- internal sessions have no provider environment to clean up. */\n\t\t\tif (sessionKind !== \"internal\") await this.#cleanupProviderEnvironment?.(sessionId);\n\t\t}\n\t}\n\truntime(sessionId) {\n\t\tthis.#assertOpen();\n\t\tconst managed = this.#sessions.get(sessionId);\n\t\tif (!managed?.runtime || managed.runtime.state.phase === \"closed\") throw new Error(\"The Session Agent Runtime is not ready\");\n\t\treturn managed.runtime;\n\t}\n\tcwd(sessionId) {\n\t\tthis.#assertOpen();\n\t\tconst managed = this.#sessions.get(sessionId);\n\t\tif (!managed) throw new SessionRuntimeNotPreparedError();\n\t\treturn managed.cwd;\n\t}\n\tobserve(sessionId, sink) {\n\t\tthis.#assertOpen();\n\t\tconst managed = this.#sessions.get(sessionId);\n\t\tif (!managed?.runtime || managed.runtime.state.phase === \"closed\") throw new Error(\"The Session Agent Runtime is not ready\");\n\t\tif (managed.eventSink) throw new Error(\"The Session Agent Runtime already has an active observer\");\n\t\tmanaged.eventSink = sink;\n\t\treturn () => {\n\t\t\tif (managed.eventSink === sink) managed.eventSink = void 0;\n\t\t};\n\t}\n\tclose() {\n\t\tif (this.#closePromise) return this.#closePromise;\n\t\tthis.#closing = true;\n\t\tthis.#closePromise = (async () => {\n\t\t\tawait Promise.allSettled([...this.#prepares, ...this.#starts]);\n\t\t\tconst sessions = [...this.#sessions.values()];\n\t\t\tthis.#sessions.clear();\n\t\t\tconst results = await Promise.allSettled(sessions.map(async (session) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait this.#closeManaged(session);\n\t\t\t\t} finally {\n\t\t\t\t\tawait this.#proofManager.cleanup(session.binding.sessionId);\n\t\t\t\t}\n\t\t\t}));\n\t\t\tfor (const result of results) if (result.status === \"rejected\") this.#closeFailures.push(result.reason);\n\t\t\tif (this.#closeFailures.length > 0) throw new AggregateError(this.#closeFailures, \"One or more Agent Runtimes failed to close\");\n\t\t})();\n\t\treturn this.#closePromise;\n\t}\n\tasync #closeManaged(managed) {\n\t\tconst start = managed.start;\n\t\tif (start) await start.catch((error) => {\n\t\t\tlogger.debug({\n\t\t\t\tcode: \"pending_runtime_start_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Pending Session Runtime start failed\");\n\t\t});\n\t\tif (!managed.runtime || managed.runtime.state.phase === \"closed\") return;\n\t\tawait managed.runtime.close();\n\t\tmanaged.runtime = void 0;\n\t}\n\t#assertOpen() {\n\t\tif (this.#closing) throw new Error(\"The Session Runtime manager is closing\");\n\t}\n};\n/**\n* Resolve Context Tree for one Agent Workspace into the two things a Provider Runtime needs.\n*\n* The shared tree lives outside the Workspace, so a workspace-write Provider such as Codex cannot\n* write to it unless it is named as a writable root. Optional memory: an absent or unavailable\n* tree yields no roots and only changes what the prompt reports.\n*/\nasync function prepareContextTree(manager, cwd, provider, connections, environment) {\n\tconst status = environment ? await manager?.ensureAgent(cwd, provider, connections, environment) : await manager?.ensureAgent(cwd, provider, connections);\n\tif (!status) return {\n\t\tpromptContext: {},\n\t\twritableRoots: []\n\t};\n\treturn {\n\t\tpromptContext: { contextTree: status },\n\t\twritableRoots: status.status === \"configured\" ? status.connections.flatMap((entry) => entry.status === \"ready\" ? [entry.treePath] : []) : status.status === \"ready\" ? [status.treePath] : []\n\t};\n}\n/**\n* Resolve the Agent's synced Skill directories for the provider start request.\n*\n* `SkillSyncManager` already swallows its own failures, but this guard is the hard boundary that\n* keeps a rejecting or stalled sync from ever failing runtime start: the worst case is no paths.\n*/\nasync function prepareAgentSkills(manager, input) {\n\tif (!manager) return {};\n\ttry {\n\t\tconst result = await manager.ensureAgent(input);\n\t\treturn result.skillPaths.length > 0 ? { skillPaths: result.skillPaths } : {};\n\t} catch (error) {\n\t\tlogger.warn({\n\t\t\tcode: \"skill_sync_failed\",\n\t\t\treason: String(error)\n\t\t}, \"Agent Skill sync failed; continuing without synced Skills\");\n\t\treturn {};\n\t}\n}\n/**\n* Drop a Context Tree root already covered by the shared account directory grant. A managed\n* checkout lives under `~/.context-tree`, so re-listing it would grant the same subtree twice.\n*/\nfunction dropCoveredRoots(roots, parents) {\n\treturn roots.filter((root) => !parents.some((parent) => resolve(root).startsWith(`${resolve(parent)}${sep}`)));\n}\nfunction visibleSlackWritableRoots(sessionKind, cwd, sessionId, resolveSlackConfig) {\n\tif (sessionKind !== \"visible\" || !resolveSlackConfig) return [cwd];\n\tconst configDir = resolveSlackConfig(sessionId);\n\tif (!configDir) return [cwd];\n\treturn [cwd, configDir];\n}\nasync function waitForStart(start, signal) {\n\tif (!signal) return start;\n\tsignal.throwIfAborted();\n\tlet rejectAborted;\n\tconst aborted = new Promise((_resolve, reject) => {\n\t\trejectAborted = reject;\n\t});\n\tconst onAbort = () => rejectAborted(signal.reason);\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\ttry {\n\t\tconst runtime = await Promise.race([start, aborted]);\n\t\tsignal.throwIfAborted();\n\t\treturn runtime;\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\nfunction visibleProviderCliPath(managed, resolveLaunchPath) {\n\treturn managed.sessionKind === \"visible\" ? { pathPrepend: resolveLaunchPath?.(managed.binding.sessionId) } : {};\n}\nasync function visibleReplyWritableRoots(managed, prepareRoot) {\n\tif (managed.sessionKind !== \"visible\" || !prepareRoot) return [];\n\treturn [await prepareRoot(managed.binding.sessionId)];\n}\nasync function prepareConfigurationRoots(environment) {\n\ttry {\n\t\treturn [await prepareContextTreeHome(environment)];\n\t} catch (error) {\n\t\tlogger.warn({ code: error.code }, \"Context Tree configuration directory could not be created\");\n\t\treturn [];\n\t}\n}\n//#endregion\n//#region src/runtime/trace-buffer.ts\nconst TURN_TRACE_MAX_BUFFER_BYTES = 262144;\nconst TURN_TRACE_MAX_BUFFER_EVENTS = 256;\nconst TURN_TRACE_SEND_DEADLINE_MS = 500;\nconst TURN_TRACE_BATCH_SOFT_LIMIT_BYTES = 61440;\nvar TurnTraceBuffer = class {\n\t#id;\n\t#maxBufferBytes;\n\t#maxBufferEvents;\n\t#now;\n\t#placementGeneration;\n\t#sender;\n\t#sessionId;\n\t#turnId;\n\t#events = [];\n\t#bufferBytes = 0;\n\t#droppedEvents = 0;\n\t#finishing = false;\n\t#frozen = false;\n\t#inFlight = 0;\n\t#lastSequence = 0;\n\t#flushPromise;\n\t#flushRequested = false;\n\t#turnCompleted = false;\n\t#turnStarted = false;\n\tconstructor(options) {\n\t\tthis.#id = options.id ?? randomUUID;\n\t\tthis.#maxBufferBytes = options.maxBufferBytes ?? 262144;\n\t\tthis.#maxBufferEvents = options.maxBufferEvents ?? 256;\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#placementGeneration = options.placementGeneration;\n\t\tthis.#sender = options.sender;\n\t\tthis.#sessionId = options.sessionId;\n\t\tthis.#turnId = options.turnId;\n\t\tif (!Number.isSafeInteger(this.#maxBufferBytes) || this.#maxBufferBytes < 1024) throw new Error(\"Trace byte limit must be a safe integer of at least 1024\");\n\t\tif (!Number.isSafeInteger(this.#maxBufferEvents) || this.#maxBufferEvents < 1) throw new Error(\"Trace event limit must be a positive safe integer\");\n\t}\n\tturnStarted() {\n\t\tif (this.#turnStarted) return;\n\t\tthis.#turnStarted = true;\n\t\tthis.#append({ kind: \"turn_started\" });\n\t}\n\titemCompleted(itemType, status) {\n\t\tthis.#append({\n\t\t\tkind: \"item_completed\",\n\t\t\titemType,\n\t\t\tstatus\n\t\t});\n\t}\n\tusageUpdated(usage) {\n\t\tthis.#append({\n\t\t\tkind: \"usage_updated\",\n\t\t\tusage\n\t\t});\n\t}\n\twarning(code, _message) {\n\t\tthis.#append({\n\t\t\tkind: \"warning\",\n\t\t\tcode: /^[A-Za-z0-9:_-]{1,128}$/.test(code) ? code : \"provider_warning\",\n\t\t\tmessage: \"Provider reported a runtime warning\"\n\t\t});\n\t}\n\tturnCompleted(outcome) {\n\t\tif (this.#turnCompleted) return;\n\t\tthis.#turnCompleted = true;\n\t\tthis.#append({\n\t\t\tkind: \"turn_completed\",\n\t\t\toutcome\n\t\t});\n\t}\n\trecord(event) {\n\t\tif (event.type === \"run_started\") {\n\t\t\tthis.turnStarted();\n\t\t\treturn;\n\t\t}\n\t\tif (event.type === \"message_completed\") {\n\t\t\tthis.itemCompleted(\"agent_message\", \"completed\");\n\t\t\treturn;\n\t\t}\n\t\tif (event.type === \"tool_completed\") {\n\t\t\tthis.itemCompleted(\"tool\", event.status === \"completed\" ? \"completed\" : \"failed\");\n\t\t\treturn;\n\t\t}\n\t\tif (event.type === \"usage_updated\") {\n\t\t\tthis.usageUpdated(event.usage);\n\t\t\treturn;\n\t\t}\n\t\tif (event.type === \"provider_warning\") {\n\t\t\tthis.warning(event.code, event.message);\n\t\t\treturn;\n\t\t}\n\t\tif (event.type === \"run_completed\") this.turnCompleted(\"completed\");\n\t\telse if (event.type === \"run_aborted\" || event.type === \"run_cancelled\") this.turnCompleted(\"cancelled\");\n\t\telse if (event.type === \"run_failed\") this.turnCompleted(\"failed\");\n\t}\n\tsummary() {\n\t\treturn {\n\t\t\tlastSequence: this.#lastSequence,\n\t\t\tdroppedEvents: this.#droppedEvents\n\t\t};\n\t}\n\tasync finish() {\n\t\tif (this.#frozen) return this.summary();\n\t\tthis.#finishing = true;\n\t\tconst active = this.#flushPromise;\n\t\tif (active) await active;\n\t\tif (this.#events.length > 0) await this.#flush();\n\t\tthis.#frozen = true;\n\t\tthis.#droppedEvents += this.#events.length;\n\t\tthis.#events.length = 0;\n\t\tthis.#bufferBytes = 0;\n\t\treturn this.summary();\n\t}\n\t#append(input) {\n\t\tif (this.#frozen) return;\n\t\tthis.#lastSequence += 1;\n\t\tconst event = AgentTraceEventSchema.parse({\n\t\t\t...input,\n\t\t\tsequence: this.#lastSequence,\n\t\t\tat: new Date(this.#now()).toISOString()\n\t\t});\n\t\tconst bytes = Buffer.byteLength(JSON.stringify(event), \"utf8\");\n\t\tif (this.#events.length >= this.#maxBufferEvents || this.#bufferBytes + bytes > this.#maxBufferBytes) {\n\t\t\tif (event.kind !== \"warning\" && event.kind !== \"turn_completed\") {\n\t\t\t\tthis.#droppedEvents += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst expendableOffset = this.#events.slice(this.#inFlight).findIndex((candidate) => candidate.kind !== \"warning\" && candidate.kind !== \"turn_completed\");\n\t\t\tconst expendable = expendableOffset < 0 ? -1 : this.#inFlight + expendableOffset;\n\t\t\tif (expendable < 0) {\n\t\t\t\tthis.#droppedEvents += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#dropBuffered(expendable);\n\t\t\tif (this.#bufferBytes + bytes > this.#maxBufferBytes) {\n\t\t\t\tthis.#droppedEvents += 1;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthis.#events.push(event);\n\t\tthis.#bufferBytes += bytes;\n\t\tthis.#scheduleFlush();\n\t}\n\t#scheduleFlush() {\n\t\tif (this.#frozen || this.#finishing) return;\n\t\tif (this.#flushPromise) {\n\t\t\tthis.#flushRequested = true;\n\t\t\treturn;\n\t\t}\n\t\tconst active = this.#flush();\n\t\tthis.#flushPromise = active;\n\t\tconst settled = () => {\n\t\t\tif (this.#flushPromise !== active) return;\n\t\t\tthis.#flushPromise = void 0;\n\t\t\tif (!this.#flushRequested || this.#finishing || this.#frozen) return;\n\t\t\tthis.#flushRequested = false;\n\t\t\tthis.#scheduleFlush();\n\t\t};\n\t\tactive.then(settled, settled);\n\t}\n\tasync #flush() {\n\t\twhile (!this.#frozen && this.#events.length > 0) {\n\t\t\tconst events = this.#events.slice(0, RUNTIME_TRACE_BATCH_MAX_EVENTS);\n\t\t\twhile (events.length > 1 && batchBytes(events) > 61440) events.pop();\n\t\t\tthis.#inFlight = events.length;\n\t\t\tconst batch = {\n\t\t\t\ttype: \"agent:trace\",\n\t\t\t\tbatchId: this.#id(),\n\t\t\t\tsessionId: this.#sessionId,\n\t\t\t\tturnId: this.#turnId,\n\t\t\t\tplacementGeneration: this.#placementGeneration,\n\t\t\t\tevents\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tawait this.#sender.send(batch, {\n\t\t\t\t\tpriority: \"trace\",\n\t\t\t\t\tdeadline: this.#now() + 500\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\tthis.#inFlight = 0;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#events.splice(0, events.length);\n\t\t\tthis.#bufferBytes -= events.reduce((total, event) => total + eventBytes(event), 0);\n\t\t\tthis.#inFlight = 0;\n\t\t}\n\t}\n\t#dropBuffered(index) {\n\t\tconst [removed] = this.#events.splice(index, 1);\n\t\tif (!removed) return;\n\t\tthis.#bufferBytes -= eventBytes(removed);\n\t\tthis.#droppedEvents += 1;\n\t}\n};\nfunction eventBytes(event) {\n\treturn Buffer.byteLength(JSON.stringify(event), \"utf8\");\n}\nfunction batchBytes(events) {\n\treturn events.reduce((total, event) => total + eventBytes(event), 1024);\n}\n//#endregion\n//#region src/runtime/agent-turn-runner.ts\nvar AgentTurnRunner = class {\n\t#bindingStore;\n\t#connection;\n\t#custody;\n\t#logger;\n\t#now;\n\t#onRuntimeEvent;\n\t#reportOwner;\n\t#resourceFetcher;\n\t#runtimeManager;\n\t#credentialEnvironment;\n\t#turnPlan;\n\t#outgoingReplies;\n\t#agentErrorReporter;\n\t#turns = /* @__PURE__ */ new Map();\n\t#stopped = false;\n\tconstructor(options) {\n\t\tthis.#bindingStore = options.bindingStore;\n\t\tthis.#connection = options.connection;\n\t\tthis.#custody = options.custody;\n\t\tthis.#logger = options.logger ?? createLogger(\"turn\");\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#onRuntimeEvent = options.onRuntimeEvent;\n\t\tthis.#reportOwner = options.reportOwner;\n\t\tthis.#resourceFetcher = options.resourceFetcher;\n\t\tthis.#runtimeManager = options.runtimeManager;\n\t\tthis.#credentialEnvironment = options.credentialEnvironment;\n\t\tthis.#turnPlan = options.turnPlan;\n\t\tthis.#outgoingReplies = options.outgoingReplies;\n\t\tthis.#agentErrorReporter = options.agentErrorReporter ?? (() => void 0);\n\t}\n\tget activeCount() {\n\t\treturn this.#turns.size;\n\t}\n\tstart(owner) {\n\t\tif (this.#stopped || this.#turns.has(owner.turnId)) return;\n\t\tconst abort = new AbortController();\n\t\tconst turn = {\n\t\t\tabort,\n\t\t\towner,\n\t\t\tcaptureInReport: this.#connection.capabilityVersion?.(RUNTIME_CAPABILITY.turnReport) === 2,\n\t\t\tphase: \"starting\",\n\t\t\tpromise: Promise.resolve()\n\t\t};\n\t\tturn.promise = this.#run(turn, abort.signal).catch(\n\t\t\t/* v8 ignore next -- turn failures are reported through completion events, not this promise. */\n\t\t\t() => void 0\n\t\t).finally(() => this.#turns.delete(owner.turnId));\n\t\tthis.#turns.set(owner.turnId, turn);\n\t}\n\tasync steer(request) {\n\t\tconst semanticHash = computeRuntimeImMessageSemanticHash(request);\n\t\ttry {\n\t\t\tif (await this.#bindingStore.getSteerReceipt(request, semanticHash)) return steerResult(request, \"steered\");\n\t\t} catch {\n\t\t\treturn steerResult(request, \"rejected\", \"input_conflict\");\n\t\t}\n\t\tconst turn = this.#turns.get(request.expectedTurnId);\n\t\tif (!turn) return steerResult(request, \"deferred\", \"turn_not_running\");\n\t\tconst owner = turn.owner;\n\t\tif (owner.request.deliveryId !== request.rootDeliveryId || owner.request.sessionId !== request.sessionId || owner.request.agentId !== request.agentId || owner.request.placementGeneration !== request.placementGeneration) return steerResult(request, \"rejected\", \"target_mismatch\");\n\t\tif (turn.phase === \"starting\") return steerResult(request, \"retry\", \"turn_starting\");\n\t\tconst runtime = turn.runtime;\n\t\tif (turn.phase !== \"running\" || !runtime) return steerResult(request, \"deferred\", \"turn_not_running\");\n\t\tif (runtime.capabilities.steer !== \"supported\") return steerResult(request, \"deferred\", \"steer_unsupported\");\n\t\tif (runtime.state.phase !== \"running\" || runtime.state.activeRunId !== request.expectedTurnId) return steerResult(request, \"deferred\", \"turn_not_running\");\n\t\ttry {\n\t\t\tconst cwd = this.#runtimeManager.cwd(request.sessionId);\n\t\t\tconst supplementalContext = await this.#resourceFetcher?.fetchForTurn(request, cwd);\n\t\t\tif (turn.phase !== \"running\" || runtime.state.phase !== \"running\" || runtime.state.activeRunId !== request.expectedTurnId) return steerResult(request, \"deferred\", \"turn_not_running\");\n\t\t\tawait runtime.steer({\n\t\t\t\texpectedRunId: request.expectedTurnId,\n\t\t\t\tinput: buildAgentInput(request, supplementalContext, owner.request.runtime)\n\t\t\t});\n\t\t} catch {\n\t\t\treturn steerResult(request, \"deferred\", \"steer_state_unknown\");\n\t\t}\n\t\ttry {\n\t\t\tawait this.#bindingStore.recordSteer(request, semanticHash);\n\t\t} catch {\n\t\t\treturn steerResult(request, \"deferred\", \"steer_state_unknown\");\n\t\t}\n\t\treturn steerResult(request, \"steered\");\n\t}\n\tstop() {\n\t\tif (this.#stopped) return;\n\t\tthis.#stopped = true;\n\t\tfor (const turn of this.#turns.values()) turn.abort.abort(\"client_shutdown\");\n\t}\n\tasync settled() {\n\t\tawait Promise.all([...this.#turns.values()].map((turn) => turn.promise));\n\t}\n\tasync #run(turn, shutdownSignal) {\n\t\tconst owner = turn.owner;\n\t\tconst startedAt = this.#now();\n\t\tconst fields = {\n\t\t\tagentId: owner.request.agentId,\n\t\t\tdeliveryId: owner.request.deliveryId,\n\t\t\tsessionId: owner.request.sessionId,\n\t\t\tturnId: owner.turnId\n\t\t};\n\t\tthis.#logger.info(fields, \"Turn started\");\n\t\tconst timeout = new AbortController();\n\t\t/* v8 ignore next -- the turn-timeout callback only fires for wall-clock overruns tests cannot wait out. */\n\t\tconst timer = setTimeout(() => timeout.abort(\"turn_timeout\"), turnTimeoutMs(owner.request, this.#now()));\n\t\ttimer.unref();\n\t\tconst signal = AbortSignal.any([shutdownSignal, timeout.signal]);\n\t\tconst trace = new TurnTraceBuffer({\n\t\t\tsender: this.#connection,\n\t\t\tsessionId: owner.request.sessionId,\n\t\t\tturnId: owner.turnId,\n\t\t\tplacementGeneration: owner.request.placementGeneration,\n\t\t\tnow: this.#now\n\t\t});\n\t\tlet completion;\n\t\tlet terminalObserved = false;\n\t\tlet releaseObserver = () => void 0;\n\t\tlet turnPlanInput;\n\t\tlet preparedExecutionId;\n\t\ttry {\n\t\t\tconst started = await this.#startTurn(owner, turn, signal);\n\t\t\tpreparedExecutionId = started.preparedExecutionId;\n\t\t\tturnPlanInput = started.turnPlanInput;\n\t\t\tconst runSignal = started.runSignal;\n\t\t\trunSignal.throwIfAborted();\n\t\t\tconst runtime = await this.#runtimeManager.ensureRuntime(owner.request.sessionId, runSignal);\n\t\t\tturn.runtime = runtime;\n\t\t\tconst cwd = this.#runtimeManager.cwd(owner.request.sessionId);\n\t\t\tconst supplementalContext = await this.#resourceFetcher?.fetchForTurn(owner.request, cwd);\n\t\t\treleaseObserver = this.#runtimeManager.observe(owner.request.sessionId, async (event) => {\n\t\t\t\ttrace.record(event);\n\t\t\t\tif (event.type === \"run_started\" && event.runId === owner.turnId) {\n\t\t\t\t\tawait this.#bindingStore.updateUnresolved(owner.request.agentId, owner.request.sessionId, owner.turnId, \"running\");\n\t\t\t\t\tturn.phase = \"running\";\n\t\t\t\t}\n\t\t\t\tif (event.type === \"run_completed\" || event.type === \"run_failed\" || event.type === \"run_aborted\" || event.type === \"run_cancelled\") terminalObserved = true;\n\t\t\t\tawait this.#onRuntimeEvent?.(event);\n\t\t\t});\n\t\t\tconst result = await runtime.prompt({\n\t\t\t\trunId: owner.turnId,\n\t\t\t\tinput: buildAgentInput(owner.request, supplementalContext),\n\t\t\t\tsignal: runSignal,\n\t\t\t\t...started.webTools || started.mcpGateway ? this.#providerLaunchConfiguration(started, owner) : {}\n\t\t\t});\n\t\t\tturn.phase = \"reporting\";\n\t\t\tcompletion = completionForResult(result, signal.reason);\n\t\t\tif (completion.outcome !== \"completed\") this.#reportFailure(owner, completion, returnedFailure(result, completion));\n\t\t} catch (error) {\n\t\t\tturn.phase = \"reporting\";\n\t\t\tcompletion = completionForError(error, signal.reason);\n\t\t\tthis.#logger.warn({\n\t\t\t\t...fields,\n\t\t\t\tdurationMs: Math.max(0, this.#now() - startedAt),\n\t\t\t\terrorReason: completion.errorReason,\n\t\t\t\t...errorFieldsForLog(error),\n\t\t\t\toutcome: completion.outcome\n\t\t\t}, \"Turn failed\");\n\t\t\tthis.#reportFailure(owner, completion, error);\n\t\t\t/* v8 ignore else -- a terminal event observed before the failure already recorded the outcome. */\n\t\t\tif (!terminalObserved) trace.turnCompleted(completion.outcome);\n\t\t} finally {\n\t\t\treleaseObserver();\n\t\t\tif (turnPlanInput)\n /* v8 ignore next -- turn-plan teardown is best-effort. */\n\t\t\tawait this.#turnPlan?.cleanup(turnPlanInput).catch(() => void 0);\n\t\t\t/* v8 ignore next -- credential teardown is best-effort. */\n\t\t\tawait this.#credentialEnvironment.cleanup(owner.request.sessionId, preparedExecutionId).catch(() => void 0);\n\t\t\tclearTimeout(timer);\n\t\t}\n\t\tconst traceSummary = await trace.finish();\n\t\tif (completion.outcome === \"completed\") this.#logger.info({\n\t\t\t...fields,\n\t\t\tdurationMs: Math.max(0, this.#now() - startedAt),\n\t\t\toutcome: completion.outcome\n\t\t}, \"Turn completed\");\n\t\tconst outgoingReplies = await this.#collectOutgoingReplies(turnPlanInput, owner, turn.captureInReport);\n\t\tconst reportInput = budgetTurnReportHashInput({\n\t\t\tdeliveryId: owner.request.deliveryId,\n\t\t\tturnId: owner.turnId,\n\t\t\tsessionId: owner.request.sessionId,\n\t\t\tagentId: owner.request.agentId,\n\t\t\tplacementGeneration: owner.request.placementGeneration,\n\t\t\toutcome: completion.outcome,\n\t\t\texecutionEffects: completion.executionEffects,\n\t\t\t...completion.finalText ? { finalText: completion.finalText } : {},\n\t\t\t...completion.errorReason ? { errorReason: completion.errorReason } : {},\n\t\t\t...completion.usage ? { usage: completion.usage } : {},\n\t\t\ttraceSummary,\n\t\t\t...outgoingReplies ? { outgoingReplies } : {}\n\t\t});\n\t\tlet report;\n\t\ttry {\n\t\t\treport = this.#reportOwner.create(reportInput);\n\t\t\tawait this.#custody.markReporting(owner.turnId, report);\n\t\t} catch {\n\t\t\tthis.#logger.warn(fields, \"Turn could not enter the reporting phase\");\n\t\t\treturn;\n\t\t}\n\t\tawait this.#cleanupOutgoingReplies(turnPlanInput, owner.turnId);\n\t\tthis.#reportOwner.submit(report, () => this.#custody.recordResult(owner.turnId, report.resultHash)).catch((error) => {\n\t\t\tthis.#logger.warn({\n\t\t\t\t...fields,\n\t\t\t\treason: redactForLog(error instanceof Error ? error.message : \"Unknown Turn Report submission failure\")\n\t\t\t}, \"Turn Report submission failed\");\n\t\t});\n\t}\n\t/**\n\t* Hand a turn that did not complete to the reporter, whichever way it failed: a value the\n\t* provider threw, or a result it returned. Every failure goes; which of them is a defect is the\n\t* reporter's judgement, so the invariant the docs state holds literally.\n\t*/\n\t#reportFailure(owner, completion, error) {\n\t\tthis.#agentErrorReporter({\n\t\t\terror,\n\t\t\tagentId: owner.request.agentId,\n\t\t\tsessionId: owner.request.sessionId,\n\t\t\tturnId: owner.turnId,\n\t\t\terrorReason: completion.errorReason,\n\t\t\toutcome: completion.outcome\n\t\t});\n\t}\n\t#providerLaunchConfiguration(launch, owner) {\n\t\tconst providerId = this.#runtimeManager.providerId(owner.request.sessionId);\n\t\tconst fields = {\n\t\t\tagentId: owner.request.agentId,\n\t\t\tsessionId: owner.request.sessionId,\n\t\t\tturnId: owner.turnId\n\t\t};\n\t\tif (launch.mcpGateway) {\n\t\t\tif (providerSupportsMcpGateway(providerId)) this.#logger.info({\n\t\t\t\t...fields,\n\t\t\t\tproviderId\n\t\t\t}, \"MCP gateway delivered to the provider\");\n\t\t\telse this.#logger.warn({\n\t\t\t\t...fields,\n\t\t\t\tproviderId,\n\t\t\t\tcode: \"mcp_gateway_unsupported_provider\"\n\t\t\t}, \"MCP gateway was granted but the provider cannot mount it; MCP tools are unavailable this turn\");\n\t\t}\n\t\treturn providerLaunchConfiguration(launch, providerId);\n\t}\n\t/**\n\t* Marks the Turn as starting, prepares the trusted execution, and links revocation /\n\t* control-owner replacement into the Run abort signal. The provider prompt only starts\n\t* after this returns (or after an accepted delivery the Server already holds).\n\t*/\n\tasync #startTurn(owner, turn, signal) {\n\t\tawait this.#bindingStore.updateUnresolved(owner.request.agentId, owner.request.sessionId, owner.turnId, \"starting\");\n\t\tconst credentials = await this.#credentialEnvironment.prepare({\n\t\t\tagentId: owner.request.agentId,\n\t\t\tplacementGeneration: owner.request.placementGeneration,\n\t\t\tsessionId: owner.request.sessionId,\n\t\t\trun: {\n\t\t\t\trunId: owner.turnId,\n\t\t\t\tsource: {\n\t\t\t\t\tkind: \"delivery\",\n\t\t\t\t\tdeliveryId: owner.request.deliveryId,\n\t\t\t\t\tturnId: owner.turnId\n\t\t\t\t}\n\t\t\t}\n\t\t}, signal);\n\t\tconst runSignal = credentials.signal ? AbortSignal.any([signal, credentials.signal]) : signal;\n\t\tconst turnPlanInput = await this.#prepareTurnPlanForRun(owner, turn, credentials, signal);\n\t\treturn {\n\t\t\t...credentials.executionId ? { preparedExecutionId: credentials.executionId } : {},\n\t\t\trunSignal,\n\t\t\t...turnPlanInput ? { turnPlanInput } : {},\n\t\t\t...credentials.web ? { webTools: credentials.web } : {},\n\t\t\t...credentials.mcp ? { mcpGateway: credentials.mcp } : {}\n\t\t};\n\t}\n\tasync #prepareTurnPlanForRun(owner, turn, credentials, signal) {\n\t\tif (!this.#turnPlan || this.#runtimeManager.sessionKind(owner.request.sessionId) !== \"visible\") return void 0;\n\t\tif (!credentials.provider) throw new ImCredentialEnvironmentError(\"credential_provider_missing\");\n\t\tconst turnPlanInput = {\n\t\t\tprovider: credentials.provider,\n\t\t\tsessionId: owner.request.sessionId,\n\t\t\trunId: owner.turnId,\n\t\t\t...outgoingReplyCapturePlan(credentials.provider, turn.captureInReport),\n\t\t\t...credentials.slackConfigDir ? { configDir: credentials.slackConfigDir } : {},\n\t\t\t...credentials.environmentManifest ? { environmentManifest: credentials.environmentManifest } : {},\n\t\t\t...credentials.slackApiHost ? { slackApiHost: credentials.slackApiHost } : {}\n\t\t};\n\t\tawait this.#turnPlan.prepare(turnPlanInput, signal);\n\t\treturn turnPlanInput;\n\t}\n\tasync #collectOutgoingReplies(turnPlanInput, owner, includeInReport) {\n\t\tif (turnPlanInput?.provider !== \"feishu\" || !this.#outgoingReplies) return void 0;\n\t\tlet collected;\n\t\ttry {\n\t\t\tcollected = await this.#outgoingReplies.collect({\n\t\t\t\tsessionId: turnPlanInput.sessionId,\n\t\t\t\trunId: owner.turnId\n\t\t\t});\n\t\t} catch {\n\t\t\tthis.#logger.debug({ code: \"outgoing_reply_collect_failed\" }, \"Outgoing reply collection failed\");\n\t\t\treturn includeInReport ? unavailableOutgoingReplies() : void 0;\n\t\t}\n\t\tif (!includeInReport) return void 0;\n\t\tconst scope = feishuOutgoingReplyScope(owner.request.content.providerRef);\n\t\tif (!scope) return emptyCompleteOutgoingReplies();\n\t\ttry {\n\t\t\treturn snapshotOutgoingReplies(collected, scope);\n\t\t} catch {\n\t\t\treturn unavailableOutgoingReplies();\n\t\t}\n\t}\n\tasync #cleanupOutgoingReplies(turnPlanInput, runId) {\n\t\tif (turnPlanInput?.provider !== \"feishu\" || !this.#outgoingReplies) return;\n\t\tawait this.#outgoingReplies.cleanup({\n\t\t\tsessionId: turnPlanInput.sessionId,\n\t\t\trunId\n\t\t}).catch(() => void 0);\n\t}\n};\nfunction outgoingReplyCapturePlan(provider, includeInReport) {\n\treturn provider === \"feishu\" && includeInReport ? { captureOutgoingReplies: true } : {};\n}\n/**\n* Per-Turn provider launch facts, assembled from the freshly prepared execution.\n*\n* Every fact here is trusted and execution-scoped: it comes from what this Client just prepared,\n* never from Server content, and it is re-derived each Turn so a descriptor can never outlive the\n* execution that owns it. Each provider sees only what it can act on — Pi's extension socket never\n* reaches Claude Code, and the MCP gateway never reaches a provider with no MCP configuration.\n*/\nfunction providerLaunchConfiguration(launch, providerId) {\n\tconst provider = {};\n\tif (launch.webTools && providerId === \"pi\") provider.webTools = {\n\t\textensionPath: launch.webTools.extensionPath,\n\t\tsocketPath: launch.webTools.socketPath\n\t};\n\tif (launch.mcpGateway && providerSupportsMcpGateway(providerId)) provider.mcpGateway = {\n\t\turl: launch.mcpGateway.url,\n\t\ttoken: launch.mcpGateway.token\n\t};\n\tif (Object.keys(provider).length === 0) return {};\n\treturn { configuration: { provider } };\n}\nfunction providerSupportsMcpGateway(providerId) {\n\treturn providerId === \"claude-code\" || providerId === \"codex\" || providerId === \"pi\";\n}\nfunction buildAgentInput(request, supplementalContext, rootRuntime) {\n\tconst runtime = request.type === \"im:deliver\" ? request.runtime : rootRuntime;\n\tif (!runtime) throw new Error(\"A steer input requires the root runtime snapshot\");\n\tconst sessionInstructions = runtime.instructions.session?.trim() || \"No additional Session instructions.\";\n\tconst provider = request.content.providerRef.provider;\n\tconst attentionMeaning = request.attention === \"direct\" ? \"A human explicitly addressed this Agent/Session. Handle the message normally, then choose whether to reply, react, send proactively, or take no provider action.\" : \"This Agent overheard the message. Use the conversation context to choose whether to reply, react, send proactively, or take no action; by default avoid meaningless, duplicate, intrusive, or attention-seeking intervention.\";\n\tconst observer = request.replyRole === \"observer\";\n\tconst replyRoleMeaning = observer ? \"A Thread Session owns the provider reply for this same message. Use this Channel delivery only for ambient channel context; do not reply, react, or perform any other provider mutation for this message.\" : \"This Session is the reply owner for this message. It may reply, react, send another provider message, or take no provider action.\";\n\treturn { items: [\n\t\t{\n\t\t\ttype: \"text\",\n\t\t\ttext: [\n\t\t\t\t\"<opentag-im-context source=\\\"managed\\\">\",\n\t\t\t\t\"OpenTag managed runtime context (not user-authored).\",\n\t\t\t\tGITHUB_NATIVE_CLI_INSTRUCTIONS,\n\t\t\t\t`Agent: ${request.agentId}`,\n\t\t\t\t`Session: ${request.sessionId}`,\n\t\t\t\t`Agent revision: ${runtime.revision.agent.sequence}/${runtime.revision.agent.id}`,\n\t\t\t\t`Session revision: ${runtime.revision.session.sequence}/${runtime.revision.session.id}`,\n\t\t\t\t...buildProviderOutboxInstructions({\n\t\t\t\t\tactionInstruction: observer ? \"Do not run a provider CLI mutation for this observer copy. The CLI and credentials remain available because they are Session capabilities, not reply-role authorization.\" : \"If you choose to reply, react, or send proactively, run the provider CLI command before ending this Turn. Choosing to take no provider action remains valid.\",\n\t\t\t\t\tprovider,\n\t\t\t\t\ttarget: request.content.providerRef,\n\t\t\t\t\ttargetLabel: \"Current provider reference\"\n\t\t\t\t}),\n\t\t\t\t`Attention: ${request.attention}`,\n\t\t\t\t`Attention meaning: ${attentionMeaning}`,\n\t\t\t\t\"Attention does not change provider CLI or credential availability for this Turn.\",\n\t\t\t\t`Reply role: ${observer ? \"observer\" : \"owner\"}`,\n\t\t\t\t`Reply role meaning: ${replyRoleMeaning}`,\n\t\t\t\t\"Reply role constrains provider actions for this delivery; it does not change this Session's authority or credential availability.\",\n\t\t\t\t\"Session instructions:\",\n\t\t\t\tsessionInstructions,\n\t\t\t\t\"</opentag-im-context>\"\n\t\t\t].join(\"\\n\")\n\t\t},\n\t\t{\n\t\t\ttype: \"text\",\n\t\t\ttext: request.content.text\n\t\t},\n\t\t...request.content.history?.length ? [{\n\t\t\ttype: \"text\",\n\t\t\ttext: `Bounded prior IM history${request.content.historyTruncated ? \" (truncated)\" : \"\"}:\\n${request.content.history.map((item) => `[${item.occurredAt}] ${JSON.stringify(item.providerRef)}: ${item.text}`).join(\"\\n\")}`\n\t\t}] : [],\n\t\t...supplementalContext ? [{\n\t\t\ttype: \"text\",\n\t\t\ttext: supplementalContext\n\t\t}] : []\n\t] };\n}\nfunction turnTimeoutMs(request, now) {\n\tconst limits = [];\n\tif (request.runtime.budget?.maxDurationMs) limits.push(request.runtime.budget.maxDurationMs);\n\tif (request.deadlineAt) limits.push(Math.max(1, Date.parse(request.deadlineAt) - now));\n\treturn Math.max(1, Math.min(...limits.length > 0 ? limits : [RUNTIME_DEFAULT_MAX_DURATION_MS]));\n}\nfunction completionForResult(result, abortReason) {\n\tif (abortReason === \"client_shutdown\") return {\n\t\toutcome: \"cancelled\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\terrorReason: \"client_shutdown\"\n\t};\n\tif (abortReason === \"turn_timeout\") return {\n\t\toutcome: \"failed\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\terrorReason: \"turn_timeout\"\n\t};\n\tif (result.status === \"completed\") {\n\t\tconst finalText = result.output.filter((item) => item.type === \"text\").at(-1)?.text;\n\t\tif (finalText && Buffer.byteLength(finalText, \"utf8\") > RUNTIME_FINAL_TEXT_MAX_BYTES) return {\n\t\t\toutcome: \"failed\",\n\t\t\texecutionEffects: \"completed\",\n\t\t\terrorReason: \"output_too_large\"\n\t\t};\n\t\treturn {\n\t\t\toutcome: \"completed\",\n\t\t\texecutionEffects: \"completed\",\n\t\t\t...finalText ? { finalText } : {},\n\t\t\t...result.usage ? { usage: result.usage } : {}\n\t\t};\n\t}\n\tif (result.status === \"aborted\" || result.status === \"cancelled\") return {\n\t\toutcome: \"cancelled\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\terrorReason: \"provider_failed\",\n\t\t...result.usage ? { usage: result.usage } : {}\n\t};\n\tif (result.error?.code === \"provider_start_failed\") return {\n\t\toutcome: \"failed\",\n\t\texecutionEffects: \"not_started\",\n\t\terrorReason: \"provider_start_failed\"\n\t};\n\treturn {\n\t\toutcome: result.error?.code === \"provider_protocol_error\" ? \"unknown\" : \"failed\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\terrorReason: result.error?.code === \"provider_protocol_error\" ? \"provider_protocol_error\" : \"provider_failed\",\n\t\t...result.usage ? { usage: result.usage } : {}\n\t};\n}\n/**\n* The failure a returned result carries, as the thing the reporter is given. A provider that\n* returned a failed result threw nothing, so the reported value is built from the result's own\n* error; a result the runner itself refused — an oversized final text, a run cut short by the\n* signal — carries none, and is described by the reason the runner classified it under.\n*/\nfunction returnedFailure(result, completion) {\n\tif (result.error) {\n\t\tconst error = new Error(result.error.message);\n\t\terror.name = `AgentRunError:${result.error.code}`;\n\t\treturn error;\n\t}\n\treturn /* @__PURE__ */ new Error(`Agent run ${result.status} was classified as ${completion.errorReason}`);\n}\n/** The specific pre-execution rejection code behind a typed Turn failure, for the Computer's log only. */\nfunction errorFieldsForLog(error) {\n\tif (error instanceof ImCredentialEnvironmentError || error instanceof ProviderCliTurnPlanError) return { errorCode: error.code };\n\tif (error instanceof SessionRuntimeNotPreparedError) return { errorCode: error.code };\n\treturn {};\n}\nfunction completionForError(error, abortReason) {\n\tif (abortReason === \"client_shutdown\") return {\n\t\toutcome: \"cancelled\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\terrorReason: \"client_shutdown\"\n\t};\n\tif (abortReason === \"turn_timeout\") return {\n\t\toutcome: \"failed\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\terrorReason: \"turn_timeout\"\n\t};\n\tif (error instanceof ImCredentialEnvironmentError || error instanceof ProviderCliTurnPlanError) return {\n\t\toutcome: \"failed\",\n\t\texecutionEffects: \"not_started\",\n\t\terrorReason: \"credential_unavailable\"\n\t};\n\tif (error instanceof AgentRuntimeProviderUnavailableError) return {\n\t\toutcome: \"failed\",\n\t\texecutionEffects: \"not_started\",\n\t\terrorReason: error.result.issues.some((issue) => issue.code === \"credential_missing\") ? \"credential_unavailable\" : \"provider_start_failed\"\n\t};\n\tif (error instanceof ClientRuntimeProviderStartError) return {\n\t\toutcome: \"failed\",\n\t\texecutionEffects: \"not_started\",\n\t\terrorReason: \"provider_start_failed\"\n\t};\n\tif (error instanceof SessionRuntimeNotPreparedError) return {\n\t\toutcome: \"failed\",\n\t\texecutionEffects: \"not_started\",\n\t\terrorReason: \"provider_start_failed\"\n\t};\n\tif (error instanceof AgentProviderError) return completionForProviderError(error);\n\treturn {\n\t\toutcome: \"unknown\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\terrorReason: \"turn_state_unknown\"\n\t};\n}\n/**\n* A thrown provider error keeps the code it was thrown with, the same way a returned one does.\n*\n* Both shipped providers throw `provider_protocol_error` rather than returning it, so without this\n* branch a real protocol failure reached the reporter as the catch-all `turn_state_unknown` and the\n* taxonomy's own name for it was never filed. `provider_error` is a run the provider refused or\n* lost, which the reporter declines like any other `provider_failed`.\n*/\nfunction completionForProviderError(error) {\n\tif (error.code === \"provider_start_failed\") return {\n\t\toutcome: \"failed\",\n\t\texecutionEffects: \"not_started\",\n\t\terrorReason: \"provider_start_failed\"\n\t};\n\tif (error.code === \"provider_protocol_error\") return {\n\t\toutcome: \"unknown\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\terrorReason: \"provider_protocol_error\"\n\t};\n\treturn {\n\t\toutcome: \"failed\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\terrorReason: \"provider_failed\"\n\t};\n}\nfunction steerResult(request, status, reason) {\n\tconst base = {\n\t\ttype: \"im:steer:result\",\n\t\trequestId: request.requestId,\n\t\tdeliveryId: request.deliveryId,\n\t\tsessionId: request.sessionId,\n\t\tplacementGeneration: request.placementGeneration,\n\t\trootDeliveryId: request.rootDeliveryId,\n\t\texpectedTurnId: request.expectedTurnId\n\t};\n\tif (status === \"steered\") return {\n\t\t...base,\n\t\tstatus\n\t};\n\treturn {\n\t\t...base,\n\t\tstatus,\n\t\treason\n\t};\n}\n//#endregion\n//#region src/runtime/web-tools-gateway.ts\n/** Controlled gateway dispatch failure; `code` maps deterministically to an HTTP status. */\nvar WebGatewayDispatchError = class extends Error {\n\tcode;\n\tretryable;\n\tconstructor(code, message, options) {\n\t\tsuper(message);\n\t\tthis.name = \"WebGatewayDispatchError\";\n\t\tthis.code = code;\n\t\tif (options?.retryable !== void 0) this.retryable = options.retryable;\n\t}\n};\n/**\n* Deterministic status per bounded error code, including the agreed Router lifecycle/credit\n* codes; unknown codes fall back to 500 and never pass through raw.\n*/\nconst ERROR_STATUS = {\n\tinvalid_request: 400,\n\tunauthenticated: 401,\n\tinsufficient_credit: 402,\n\tweb_disabled: 403,\n\tcredential_scope_denied: 403,\n\texecution_unknown: 404,\n\texecution_closed: 409,\n\tidempotency_conflict: 409,\n\trequest_in_progress: 409,\n\trequest_uncertain: 409,\n\trate_limited: 429,\n\ttimeout: 504,\n\taborted: 499,\n\tupstream_unavailable: 503,\n\tupstream_error: 502,\n\tprovider_protocol_error: 502,\n\tresponse_too_large: 502,\n\tresult_unavailable: 410,\n\tunknown: 500\n};\n/** Unix socket paths are kernel-bounded (≈104 bytes on common platforms); fail before bind. */\nconst SOCKET_PATH_MAX_BYTES = 100;\n/**\n* Allocate a fresh, short, private per-execution gateway endpoint. `mkdtemp` under the OS temp\n* root keeps the path independent of long Session storage layouts, and a brand-new directory per\n* call is the ownership proof: a stale descriptor from an earlier execution can never be\n* rebound and a late close can never unlink a successor's socket.\n*/\nasync function allocateWebGatewaySocket() {\n\tconst directory = await mkdtemp(join(tmpdir(), \"opentag-web-\"));\n\treturn {\n\t\tdirectory,\n\t\tsocketPath: join(directory, \"web.sock\")\n\t};\n}\n/** Hop header carrying the remaining end-to-end budget (metadata only, never in the digest). */\nconst WEB_GATEWAY_REMAINING_HEADER = \"x-web-remaining-ms\";\n/**\n* Effective per-operation budget for an already-parsed numeric remaining value. When no value\n* was supplied the operation cap applies; an explicit invalid/expired value yields 0 so the\n* caller fails before dispatch instead of restarting the full budget.\n*/\nfunction effectiveWebBudgetMs(operation, remainingMs) {\n\tconst cap = operation === \"search\" ? WEB_SEARCH_TIMEOUT_CAP_MS : WEB_FETCH_TIMEOUT_CAP_MS;\n\tif (remainingMs === void 0) return cap;\n\tif (!Number.isSafeInteger(remainingMs) || remainingMs < 1) return 0;\n\treturn Math.min(remainingMs, cap);\n}\n/**\n* Raw hop-header budget: at most 7 ASCII digits and positive. An absent header returns the\n* operation cap; a present but malformed header is invalid (undefined) and must be rejected.\n*/\nfunction resolveWebBudgetHeader(operation, raw) {\n\tif (raw === void 0) return effectiveWebBudgetMs(operation);\n\tif (!/^[0-9]{1,7}$/.test(raw)) return void 0;\n\tconst value = Number(raw);\n\tif (!Number.isSafeInteger(value) || value < 1) return void 0;\n\treturn Math.min(value, operation === \"search\" ? WEB_SEARCH_TIMEOUT_CAP_MS : WEB_FETCH_TIMEOUT_CAP_MS);\n}\nasync function executeGatewayCall(input) {\n\tconst ingressAtMs = input.ingressAtMs ?? input.now();\n\tconst budgetMs = resolveWebBudgetHeader(input.operation, input.remainingHeader);\n\tif (budgetMs === void 0) return errorOutcome(400, \"invalid_request\", \"The remaining-budget header is invalid\");\n\tif (input.rawBody.byteLength > WEB_REQUEST_MAX_BYTES) return errorOutcome(413, \"invalid_request\", \"The web gateway request exceeds the bound\");\n\tconst remainingMs = budgetMs - (input.now() - ingressAtMs);\n\tif (remainingMs <= 0) return errorOutcome(504, \"timeout\", \"The web request budget was exhausted\", true);\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(input.rawBody.toString(\"utf8\"));\n\t} catch {\n\t\treturn errorOutcome(400, \"invalid_request\", \"The web gateway request is not valid JSON\");\n\t}\n\tif (input.operation === \"search\") {\n\t\tconst body = WebGatewaySearchRequestSchema.safeParse(parsed);\n\t\tif (!body.success) return errorOutcome(400, \"invalid_request\", \"The web gateway request failed validation\");\n\t\treturn dispatchGatewayCall(input, body.data, remainingMs);\n\t}\n\tconst body = WebGatewayFetchRequestSchema.safeParse(parsed);\n\tif (!body.success) return errorOutcome(400, \"invalid_request\", \"The web gateway request failed validation\");\n\treturn dispatchGatewayCall(input, body.data, remainingMs);\n}\nasync function dispatchGatewayCall(input, body, remainingMs) {\n\tconst deadline = new AbortController();\n\tconst onCallerAbort = () => deadline.abort(/* @__PURE__ */ new Error(\"gateway call aborted\"));\n\tinput.signal.addEventListener(\"abort\", onCallerAbort, { once: true });\n\tconst timer = setTimeout(() => deadline.abort(/* @__PURE__ */ new Error(\"gateway call deadline exceeded\")), remainingMs);\n\ttimer.unref?.();\n\ttry {\n\t\tif (input.signal.aborted) return abortedOutcome();\n\t\tconst outcome = await settleDispatch(input.dispatch(buildDispatchInput(input.operation, body, remainingMs), deadline.signal), deadline.signal);\n\t\tif (outcome.kind === \"aborted\") return abortOrTimeoutOutcome(input.signal);\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\tbody: JSON.stringify(outcome.value)\n\t\t};\n\t} catch (error) {\n\t\treturn mapDispatchError(error, input, deadline.signal);\n\t} finally {\n\t\tclearTimeout(timer);\n\t\tinput.signal.removeEventListener(\"abort\", onCallerAbort);\n\t}\n}\nfunction buildDispatchInput(operation, body, remainingMs) {\n\tif (operation === \"search\") return {\n\t\toperation: \"search\",\n\t\ttoolCallId: body.toolCallId,\n\t\tremainingMs,\n\t\tparams: searchParams(body)\n\t};\n\treturn {\n\t\toperation: \"fetch\",\n\t\ttoolCallId: body.toolCallId,\n\t\tremainingMs,\n\t\tparams: fetchParams(body)\n\t};\n}\nfunction abortedOutcome() {\n\treturn errorOutcome(499, \"aborted\", \"The web gateway request was aborted\");\n}\nfunction abortOrTimeoutOutcome(callerSignal) {\n\treturn callerSignal.aborted ? abortedOutcome() : errorOutcome(504, \"timeout\", \"The web request budget was exhausted\", true);\n}\nfunction mapDispatchError(error, input, deadlineSignal) {\n\tif (error instanceof WebGatewayDispatchError) return errorOutcome(ERROR_STATUS[error.code] ?? 500, error.code, error.message, error.retryable);\n\tif (deadlineSignal.aborted) return abortOrTimeoutOutcome(input.signal);\n\ttry {\n\t\tinput.logger?.warn({\n\t\t\tcode: \"web_gateway_dispatch_failed\",\n\t\t\terror: errorName(error)\n\t\t}, \"Web gateway dispatch failed\");\n\t} catch {}\n\treturn errorOutcome(500, \"unknown\", \"The web gateway request failed\");\n}\n/** Race one dispatch promise against the shared deadline without leaking listeners. */\nfunction settleDispatch(promise, signal) {\n\treturn new Promise((resolve, reject) => {\n\t\tlet done = false;\n\t\tconst onAbort = () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve({ kind: \"aborted\" });\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tif (signal.aborted) {\n\t\t\tonAbort();\n\t\t\treturn;\n\t\t}\n\t\tpromise.then((value) => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve({\n\t\t\t\tkind: \"value\",\n\t\t\t\tvalue\n\t\t\t});\n\t\t}, (error) => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\treject(error);\n\t\t});\n\t});\n}\nfunction searchParams(body) {\n\tconst { protocolVersion: _protocol, toolCallId: _call, ...params } = body;\n\treturn params;\n}\nfunction fetchParams(body) {\n\tconst { protocolVersion: _protocol, toolCallId: _call, ...params } = body;\n\treturn params;\n}\n/**\n* The per-execution trusted web gateway: an HTTP/1.1 server on a fresh, owned Unix socket\n* offering exactly `/web/search` and `/web/fetch`. Local (trusted Client) it lives on a short\n* private per-execution path; native it lives inside the Sandbox namespace and its traffic rides\n* the dedicated exec pipe — no network listener anywhere. Bodies are bounded and read under the\n* same decreasing deadline as the dispatch itself.\n*/\nvar WebToolsGatewayServer = class WebToolsGatewayServer {\n\t#server;\n\t#socketPath;\n\t#sockets = /* @__PURE__ */ new Set();\n\t#ownedIdentity;\n\t#closed = false;\n\tconstructor(server, socketPath) {\n\t\tthis.#server = server;\n\t\tthis.#socketPath = socketPath;\n\t}\n\tget socketPath() {\n\t\treturn this.#socketPath;\n\t}\n\tstatic async start(options) {\n\t\tif (Buffer.byteLength(options.socketPath) > SOCKET_PATH_MAX_BYTES) throw new Error(\"The web gateway socket path exceeds the platform bound\");\n\t\tawait mkdir(dirname(options.socketPath), {\n\t\t\trecursive: true,\n\t\t\tmode: 448\n\t\t});\n\t\tawait chmod(dirname(options.socketPath), 448);\n\t\tif (await lstat(options.socketPath).catch((error) => {\n\t\t\tif (error.code === \"ENOENT\") return void 0;\n\t\t\tthrow error;\n\t\t})) throw new Error(\"The web gateway socket path is occupied\");\n\t\tconst logger = options.logger ?? createLogger(\"web-tools-gateway\");\n\t\tconst now = options.now ?? Date.now;\n\t\tconst server = http.createServer((request, response) => {\n\t\t\thandleGatewayRequest(request, response, options.dispatch, logger, now).catch((error) => {\n\t\t\t\ttry {\n\t\t\t\t\tlogger.debug({\n\t\t\t\t\t\tcode: \"web_gateway_request_failed\",\n\t\t\t\t\t\terror: errorName(error)\n\t\t\t\t\t}, \"Web gateway request failed\");\n\t\t\t\t} catch {}\n\t\t\t\tif (!response.headersSent && !response.destroyed) {\n\t\t\t\t\tresponse.writeHead(500, { \"content-type\": \"application/json\" });\n\t\t\t\t\tresponse.end(JSON.stringify({ error: {\n\t\t\t\t\t\tcode: \"unknown\",\n\t\t\t\t\t\tmessage: \"The web gateway request failed\"\n\t\t\t\t\t} }));\n\t\t\t\t} else response.end();\n\t\t\t});\n\t\t});\n\t\tconst gateway = new WebToolsGatewayServer(server, options.socketPath);\n\t\tserver.on(\"connection\", (socket) => {\n\t\t\tif (gateway.#closed) {\n\t\t\t\tsocket.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tgateway.#sockets.add(socket);\n\t\t\tsocket.on(\"close\", () => gateway.#sockets.delete(socket));\n\t\t});\n\t\ttry {\n\t\t\tawait new Promise((resolve, reject) => {\n\t\t\t\tconst onError = (error) => reject(error);\n\t\t\t\tserver.once(\"error\", onError);\n\t\t\t\tserver.listen(options.socketPath, () => {\n\t\t\t\t\tserver.removeListener(\"error\", onError);\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t\tawait chmod(options.socketPath, 384);\n\t\t\tconst owned = await lstat(options.socketPath);\n\t\t\tif (!owned.isSocket()) throw new Error(\"The web gateway socket path is not a socket after bind\");\n\t\t\tgateway.#ownedIdentity = {\n\t\t\t\tdev: owned.dev,\n\t\t\t\tino: owned.ino\n\t\t\t};\n\t\t\treturn gateway;\n\t\t} catch (error) {\n\t\t\tgateway.#closed = true;\n\t\t\tawait new Promise((resolve) => server.close(() => resolve())).catch(() => void 0);\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/** Stop listening, destroy in-flight connections, and remove only the socket we created. */\n\tasync close() {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tfor (const socket of [...this.#sockets]) socket.destroy();\n\t\tthis.#sockets.clear();\n\t\tawait new Promise((resolve) => this.#server.close(() => resolve()));\n\t\tconst ownedIdentity = this.#ownedIdentity;\n\t\tthis.#ownedIdentity = void 0;\n\t\tif (!ownedIdentity) return;\n\t\tconst current = await lstat(this.#socketPath).catch(() => void 0);\n\t\tif (current?.isSocket() && current.dev === ownedIdentity.dev && current.ino === ownedIdentity.ino) await rm(this.#socketPath, { force: true }).catch(() => void 0);\n\t}\n};\nasync function handleGatewayRequest(request, response, dispatch, logger, now) {\n\tconst ingressAtMs = now();\n\tconst abort = new AbortController();\n\tconst onRequestAbort = () => abort.abort(/* @__PURE__ */ new Error(\"request aborted\"));\n\tconst onResponseClose = () => {\n\t\tif (!response.writableFinished) abort.abort(/* @__PURE__ */ new Error(\"response closed\"));\n\t};\n\tconst swallowTransportError = () => void 0;\n\trequest.on(\"aborted\", onRequestAbort);\n\trequest.on(\"error\", swallowTransportError);\n\tresponse.on(\"close\", onResponseClose);\n\ttry {\n\t\tconst operation = request.method === \"POST\" && request.url === WEB_GATEWAY_SEARCH_PATH ? \"search\" : request.method === \"POST\" && request.url === WEB_GATEWAY_FETCH_PATH ? \"fetch\" : void 0;\n\t\tif (!operation) {\n\t\t\tsendGatewayError(response, 404, \"invalid_request\", \"Unknown web gateway operation\");\n\t\t\treturn;\n\t\t}\n\t\tconst rawRemaining = headerValue(request.headers[WEB_GATEWAY_REMAINING_HEADER]);\n\t\tconst budgetMs = resolveWebBudgetHeader(operation, rawRemaining);\n\t\tif (budgetMs === void 0) {\n\t\t\tsendGatewayError(response, 400, \"invalid_request\", \"The remaining-budget header is invalid\");\n\t\t\treturn;\n\t\t}\n\t\tconst deadlineAtMs = ingressAtMs + budgetMs;\n\t\tif (deadlineAtMs - now() <= 0) {\n\t\t\tsendGatewayError(response, 504, \"timeout\", \"The web request budget was exhausted\", true);\n\t\t\treturn;\n\t\t}\n\t\tlet raw;\n\t\ttry {\n\t\t\traw = await readBoundedRequest(request, WEB_REQUEST_MAX_BYTES, abort.signal, deadlineAtMs, now);\n\t\t} catch (error) {\n\t\t\tif (abort.signal.aborted) sendGatewayError(response, 499, \"aborted\", \"The web gateway request was aborted\");\n\t\t\telse if (error instanceof GatewayBodyTimeoutError) sendGatewayError(response, 504, \"timeout\", \"The web gateway request body stalled\", true);\n\t\t\telse sendGatewayError(response, 413, \"invalid_request\", \"The web gateway request exceeds the bound\");\n\t\t\treturn;\n\t\t}\n\t\tsendGatewayOutcome(response, await executeGatewayCall({\n\t\t\toperation,\n\t\t\trawBody: raw,\n\t\t\tremainingHeader: rawRemaining,\n\t\t\tdispatch,\n\t\t\tsignal: abort.signal,\n\t\t\tnow,\n\t\t\tingressAtMs,\n\t\t\tlogger\n\t\t}));\n\t} finally {\n\t\trequest.off(\"aborted\", onRequestAbort);\n\t\tresponse.off(\"close\", onResponseClose);\n\t}\n}\nfunction sendGatewayOutcome(response, outcome) {\n\tif (response.headersSent) {\n\t\tresponse.end();\n\t\treturn;\n\t}\n\tif (response.destroyed) return;\n\tresponse.writeHead(outcome.status, {\n\t\t\"content-type\": \"application/json\",\n\t\t\"cache-control\": \"no-store\"\n\t});\n\tresponse.end(outcome.body);\n}\nfunction errorOutcome(status, code, message, retryable) {\n\treturn {\n\t\tstatus,\n\t\tbody: JSON.stringify({ error: {\n\t\t\tcode,\n\t\t\tmessage: message.slice(0, 256),\n\t\t\t...retryable !== void 0 ? { retryable } : {}\n\t\t} })\n\t};\n}\nfunction headerValue(value) {\n\tif (Array.isArray(value)) return value[0];\n\treturn value;\n}\nvar GatewayBodyTimeoutError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"The web gateway request body stalled\");\n\t\tthis.name = \"GatewayBodyTimeoutError\";\n\t}\n};\n/**\n* Bounded body read under the request's absolute deadline. Every wait attaches and removes its\n* own listeners and timer, so an aborted client or a stalled body settles deterministically\n* instead of leaving a hung async iterator or a leaked timer.\n*/\nasync function readBoundedRequest(request, maxBytes, signal, deadlineAtMs, now) {\n\tconst chunks = [];\n\tlet total = 0;\n\tfor (;;) {\n\t\tif (signal.aborted) throw new Error(\"aborted\");\n\t\tconst remaining = deadlineAtMs - now();\n\t\tif (remaining <= 0) throw new GatewayBodyTimeoutError();\n\t\tconst outcome = await readOneChunk(request, remaining, signal);\n\t\tif (outcome.kind === \"end\") break;\n\t\tif (outcome.kind === \"timeout\") throw new GatewayBodyTimeoutError();\n\t\tif (outcome.kind === \"aborted\") throw new Error(\"aborted\");\n\t\ttotal += outcome.chunk.byteLength;\n\t\tif (total > maxBytes) {\n\t\t\trequest.pause();\n\t\t\tthrow new Error(\"The web gateway request exceeds the bound\");\n\t\t}\n\t\tchunks.push(outcome.chunk);\n\t}\n\treturn Buffer.concat(chunks);\n}\nfunction readOneChunk(request, waitMs, signal) {\n\treturn new Promise((resolve) => {\n\t\tlet settled = false;\n\t\tlet ended = false;\n\t\tconst cleanup = () => {\n\t\t\tclearTimeout(timer);\n\t\t\trequest.off(\"data\", onData);\n\t\t\trequest.off(\"end\", onEnd);\n\t\t\trequest.off(\"close\", onClose);\n\t\t\trequest.off(\"aborted\", onAborted);\n\t\t\tsignal.removeEventListener(\"abort\", onSignalAbort);\n\t\t\tif (!ended) request.pause();\n\t\t};\n\t\tconst settle = (outcome) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tresolve(outcome);\n\t\t};\n\t\tconst onData = (chunk) => settle({\n\t\t\tkind: \"chunk\",\n\t\t\tchunk\n\t\t});\n\t\tconst onEnd = () => {\n\t\t\tended = true;\n\t\t\tsettle({ kind: \"end\" });\n\t\t};\n\t\tconst onClose = () => settle({ kind: \"aborted\" });\n\t\tconst onAborted = () => settle({ kind: \"aborted\" });\n\t\tconst onSignalAbort = () => {\n\t\t\trequest.destroy();\n\t\t\tsettle({ kind: \"aborted\" });\n\t\t};\n\t\tconst timer = setTimeout(() => settle({ kind: \"timeout\" }), Math.max(1, waitMs));\n\t\ttimer.unref?.();\n\t\trequest.on(\"data\", onData);\n\t\trequest.resume();\n\t\trequest.once(\"end\", onEnd);\n\t\trequest.once(\"close\", onClose);\n\t\trequest.once(\"aborted\", onAborted);\n\t\tsignal.addEventListener(\"abort\", onSignalAbort, { once: true });\n\t\tif (signal.aborted) onSignalAbort();\n\t});\n}\nfunction sendGatewayError(response, status, code, message, retryable) {\n\tsendGatewayOutcome(response, errorOutcome(status, code, message, retryable));\n}\nfunction errorName(error) {\n\treturn error instanceof Error ? error.name : \"Error\";\n}\n//#endregion\n//#region src/runtime/web-tools-client.ts\nconst LIFECYCLE_ERROR_CODES = [\n\t\"request_in_progress\",\n\t\"request_uncertain\",\n\t\"insufficient_credit\"\n];\nconst KNOWN_ERROR_CODES = /* @__PURE__ */ new Set([...WEB_TOOL_ERROR_CODES, ...LIFECYCLE_ERROR_CODES]);\n/** Controlled trusted-client web failure. `code` is the only detail shared with the Sandbox. */\nvar WebToolsClientError = class extends Error {\n\tcode;\n\tretryable;\n\tconstructor(code, message, options) {\n\t\tsuper(message);\n\t\tthis.name = \"WebToolsClientError\";\n\t\tthis.code = code;\n\t\tif (options?.retryable !== void 0) this.retryable = options.retryable;\n\t}\n};\n/**\n* Trusted runner → Server web client. The path set is fixed, the bearer is the only credential, the\n* body is the strict execution request, and the response is byte-bounded and schema-validated before\n* anything returns to the Sandbox-facing gateway. One combined deadline spans request headers AND\n* the full response body.\n*/\nvar WebToolsServerClient = class {\n\t#baseUrl;\n\t#bearerToken;\n\t#fetch;\n\t#logger;\n\tconstructor(options) {\n\t\tconst url = new URL(options.serverUrl);\n\t\tif (url.username || url.password) throw new Error(\"The Server URL must not carry credentials\");\n\t\tthis.#baseUrl = url.origin;\n\t\tthis.#bearerToken = options.bearerToken;\n\t\tthis.#fetch = options.fetchImpl ?? fetch;\n\t\tthis.#logger = options.logger ?? createLogger(\"web-tools-client\");\n\t}\n\tsearch(input) {\n\t\treturn this.#call({\n\t\t\toperation: \"search\",\n\t\t\trequest: input.request,\n\t\t\t...input.remainingMs !== void 0 ? { remainingMs: input.remainingMs } : {},\n\t\t\t...input.signal ? { signal: input.signal } : {}\n\t\t});\n\t}\n\tfetch(input) {\n\t\treturn this.#call({\n\t\t\toperation: \"fetch\",\n\t\t\trequest: input.request,\n\t\t\t...input.remainingMs !== void 0 ? { remainingMs: input.remainingMs } : {},\n\t\t\t...input.signal ? { signal: input.signal } : {}\n\t\t});\n\t}\n\tasync #call(input) {\n\t\tconst startedAt = Date.now();\n\t\tconst budgetMs = effectiveWebBudgetMs(input.operation, input.remainingMs);\n\t\tif (budgetMs === 0) throw new WebToolsClientError(\"timeout\", \"The web call budget was exhausted before dispatch\", { retryable: true });\n\t\tconst path = input.operation === \"search\" ? RUNTIME_WEB_SEARCH_PATH : RUNTIME_WEB_FETCH_PATH;\n\t\tconst url = new URL(path, this.#baseUrl);\n\t\tif (url.origin !== this.#baseUrl) throw new WebToolsClientError(\"upstream_error\", \"The web route target is fixed\");\n\t\tconst deadline = new AbortController();\n\t\tconst timer = setTimeout(() => deadline.abort(/* @__PURE__ */ new Error(\"web call timed out\")), budgetMs);\n\t\ttimer.unref?.();\n\t\tconst signal = input.signal ? AbortSignal.any([input.signal, deadline.signal]) : deadline.signal;\n\t\ttry {\n\t\t\tlet response;\n\t\t\ttry {\n\t\t\t\tresponse = await this.#fetch(url, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\theaders: {\n\t\t\t\t\t\taccept: \"application/json\",\n\t\t\t\t\t\tauthorization: `Bearer ${this.#bearerToken}`,\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t[WEB_TIMEOUT_HEADER]: String(budgetMs)\n\t\t\t\t\t},\n\t\t\t\t\tbody: JSON.stringify(input.request),\n\t\t\t\t\tredirect: \"error\",\n\t\t\t\t\tsignal\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow abortOrUnavailable(input.signal, deadline.signal, error);\n\t\t\t}\n\t\t\tconst maxBytes = input.operation === \"search\" ? WEB_SEARCH_RESPONSE_MAX_BYTES : WEB_FETCH_RESPONSE_MAX_BYTES;\n\t\t\tconst body = await readBounded(response, maxBytes, signal, input.signal, deadline.signal);\n\t\t\tif (response.status !== 200) throw mapServerError(response.status, body, this.#logger);\n\t\t\tlet parsed;\n\t\t\ttry {\n\t\t\t\tparsed = JSON.parse(new TextDecoder().decode(body));\n\t\t\t} catch {\n\t\t\t\tthrow new WebToolsClientError(\"provider_protocol_error\", \"The Server web payload was malformed\");\n\t\t\t}\n\t\t\tconst result = (input.operation === \"search\" ? WebSearchResultSchema : WebFetchResultSchema).safeParse(parsed);\n\t\t\tif (!result.success) throw new WebToolsClientError(\"provider_protocol_error\", \"The Server web payload failed validation\");\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"web_call_completed\",\n\t\t\t\toperation: input.operation,\n\t\t\t\tdurationMs: Date.now() - startedAt\n\t\t\t}, \"Web call completed\");\n\t\t\treturn result.data;\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t}\n};\n/** Distinguish a caller cancellation from our own deadline after any transport rejection. */\nfunction abortOrUnavailable(callerSignal, deadlineSignal, error) {\n\tif (callerSignal?.aborted) return new WebToolsClientError(\"aborted\", \"The web call was aborted\");\n\tif (deadlineSignal.aborted || isTimeoutError(error)) return new WebToolsClientError(\"timeout\", \"The Server web call timed out\", { retryable: true });\n\treturn new WebToolsClientError(\"upstream_unavailable\", \"The Server web route could not be reached\", { retryable: true });\n}\n/** A bare DOM/fetch timeout (numeric code 23 / name TimeoutError) is still a timeout, not a fault. */\nfunction isTimeoutError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst candidate = error;\n\treturn candidate.name === \"TimeoutError\" || candidate.code === 23;\n}\nasync function readBounded(response, maxBytes, signal, callerSignal, deadlineSignal) {\n\tconst declared = Number(response.headers.get(\"content-length\"));\n\tif (Number.isFinite(declared) && declared > maxBytes) {\n\t\tawait response.body?.cancel().catch(() => void 0);\n\t\tthrow oversizedError();\n\t}\n\tif (!response.body) return readStreamlessBody(response, maxBytes, callerSignal, deadlineSignal);\n\treturn readStreamBounded(response.body, maxBytes, signal, callerSignal, deadlineSignal);\n}\nasync function readStreamlessBody(response, maxBytes, callerSignal, deadlineSignal) {\n\tlet buffer;\n\ttry {\n\t\tbuffer = new Uint8Array(await response.arrayBuffer());\n\t} catch (error) {\n\t\tthrow abortOrUnavailable(callerSignal, deadlineSignal, error);\n\t}\n\tif (buffer.byteLength > maxBytes) throw oversizedError();\n\treturn buffer;\n}\nasync function readStreamBounded(body, maxBytes, signal, callerSignal, deadlineSignal) {\n\tconst reader = body.getReader();\n\tconst chunks = [];\n\tlet total = 0;\n\tconst onAbort = () => void reader.cancel().catch(() => void 0);\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\ttry {\n\t\tfor (;;) {\n\t\t\tif (signal.aborted) throw abortOrUnavailable(callerSignal, deadlineSignal);\n\t\t\tconst read = await readChunk(reader, callerSignal, deadlineSignal);\n\t\t\tif (read.done) {\n\t\t\t\tif (signal.aborted) throw abortOrUnavailable(callerSignal, deadlineSignal);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst value = read.value;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\tawait reader.cancel().catch(() => void 0);\n\t\t\t\tthrow oversizedError();\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\treader.releaseLock();\n\t}\n\treturn mergeChunks(chunks, total);\n}\nasync function readChunk(reader, callerSignal, deadlineSignal) {\n\ttry {\n\t\treturn await reader.read();\n\t} catch (error) {\n\t\tthrow abortOrUnavailable(callerSignal, deadlineSignal, error);\n\t}\n}\nfunction mergeChunks(chunks, total) {\n\tconst merged = new Uint8Array(total);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tmerged.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn merged;\n}\nfunction oversizedError() {\n\treturn new WebToolsClientError(\"response_too_large\", \"The Server web response exceeds the bound\");\n}\n/** Map a non-200 Server response to the bounded error code; upstream text is never echoed. */\nfunction mapServerError(status, body, logger) {\n\tconst envelope = parseServerEnvelope(body, status, logger);\n\tif (envelope.code) return new WebToolsClientError(envelope.code, `The web call failed: ${envelope.code}`, { ...envelope.retryable !== void 0 ? { retryable: envelope.retryable } : {} });\n\treturn statusError(status);\n}\nfunction parseServerEnvelope(body, status, logger) {\n\tlet code;\n\tlet retryable;\n\ttry {\n\t\tconst parsed = JSON.parse(new TextDecoder().decode(body));\n\t\tconst envelope = parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed.error : void 0;\n\t\tif (typeof envelope?.code === \"string\" && KNOWN_ERROR_CODES.has(envelope.code)) code = envelope.code;\n\t\tif (typeof envelope?.retryable === \"boolean\") retryable = envelope.retryable;\n\t} catch {}\n\ttry {\n\t\tlogger.warn({\n\t\t\tcode: \"web_call_failed\",\n\t\t\tstatus,\n\t\t\terrorCode: code\n\t\t}, \"Server web call failed\");\n\t} catch {}\n\treturn {\n\t\t...code ? { code } : {},\n\t\t...retryable !== void 0 ? { retryable } : {}\n\t};\n}\nfunction statusError(status) {\n\tif (status === 401 || status === 403) return new WebToolsClientError(\"unauthenticated\", \"The web call was not authenticated\");\n\tif (status === 402) return new WebToolsClientError(\"insufficient_credit\", \"The web call has insufficient credit\");\n\tif (status === 429) return new WebToolsClientError(\"rate_limited\", \"The web call was rate limited\", { retryable: true });\n\tif (status === 504) return new WebToolsClientError(\"timeout\", \"The web call timed out\", { retryable: true });\n\tif (status === 410) return new WebToolsClientError(\"result_unavailable\", \"The web result is no longer available\");\n\tif (status >= 500) return new WebToolsClientError(\"upstream_unavailable\", \"The web route is unavailable\", { retryable: true });\n\treturn new WebToolsClientError(\"unknown\", \"The web call failed\");\n}\n//#endregion\n//#region src/runtime/web-tools-dispatch.ts\n/**\n* Bind one execution's Server web client to the Sandbox-facing gateway contract.\n*\n* Both trusted web boundaries need exactly this: the Local daemon per-execution Unix socket and the\n* Cloud Runner parent's per-execution `sandbox exec` duplex pipe. The execution identity is injected\n* here from the trusted parent — the Sandbox only ever supplies the runtime-generated `toolCallId`\n* and validated business parameters — and a bounded client failure is translated into the gateway's\n* own error type so the Sandbox sees one redacted vocabulary.\n*/\nfunction createExecutionWebDispatch(input) {\n\treturn async (dispatch, signal) => {\n\t\tconst request = {\n\t\t\tprotocolVersion: WEB_TOOLS_PROTOCOL_VERSION,\n\t\t\texecutionId: input.executionId,\n\t\t\ttoolCallId: dispatch.toolCallId,\n\t\t\t...dispatch.params\n\t\t};\n\t\ttry {\n\t\t\treturn dispatch.operation === \"search\" ? await input.client.search({\n\t\t\t\trequest,\n\t\t\t\tremainingMs: dispatch.remainingMs,\n\t\t\t\tsignal\n\t\t\t}) : await input.client.fetch({\n\t\t\t\trequest,\n\t\t\t\tremainingMs: dispatch.remainingMs,\n\t\t\t\tsignal\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof WebToolsClientError) throw new WebGatewayDispatchError(error.code, error.message, { ...error.retryable !== void 0 ? { retryable: error.retryable } : {} });\n\t\t\tthrow error;\n\t\t}\n\t};\n}\n//#endregion\n//#region src/runner/cloud-credential-connection.ts\nvar CloudCredentialConnection = class {\n\t#channel;\n\t#businessListeners = /* @__PURE__ */ new Set();\n\t#stateListeners = /* @__PURE__ */ new Set();\n\t#unsubscribers;\n\tconstructor(channel) {\n\t\tthis.#channel = channel;\n\t\tthis.#unsubscribers = [channel.onCredentialFrame((frame) => {\n\t\t\tfor (const listener of [...this.#businessListeners]) listener(frame);\n\t\t}), channel.onChannelState((state) => {\n\t\t\tconst mapped = state === \"registered\" ? \"registered\" : \"stopped\";\n\t\t\tfor (const listener of [...this.#stateListeners]) listener(mapped);\n\t\t})];\n\t}\n\t/** The exact surface `RuntimeCredentialRelayOptions.connection` requires. */\n\tget relayConnection() {\n\t\treturn {\n\t\t\tsend: (frame) => this.send(frame),\n\t\t\tsubscribeBusinessFrames: (listener) => this.subscribeBusinessFrames(listener),\n\t\t\tsubscribeState: (listener) => this.subscribeState(listener)\n\t\t};\n\t}\n\tsend(frame) {\n\t\tconst tunnel = {\n\t\t\ttype: \"credential:frame\",\n\t\t\tframe: RuntimeCredentialClientFrameSchema.parse(frame)\n\t\t};\n\t\tthis.#channel.sendFrame(tunnel);\n\t\treturn Promise.resolve();\n\t}\n\tsubscribeBusinessFrames(listener) {\n\t\tthis.#businessListeners.add(listener);\n\t\treturn () => this.#businessListeners.delete(listener);\n\t}\n\tsubscribeState(listener) {\n\t\tthis.#stateListeners.add(listener);\n\t\treturn () => this.#stateListeners.delete(listener);\n\t}\n\tclose() {\n\t\tfor (const unsubscribe of this.#unsubscribers.splice(0)) unsubscribe();\n\t\tthis.#businessListeners.clear();\n\t\tthis.#stateListeners.clear();\n\t}\n};\nvar WorkspaceArchiveError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.name = \"WorkspaceArchiveError\";\n\t\tthis.code = code;\n\t}\n};\nconst TAR_ENTRY_OVERHEAD_BYTES = 4096;\nconst TAR_STREAM_SLACK_BYTES = 65536;\nconst MEMBER_NAME_MAX_BYTES = 1024;\nconst MESSAGE_DETAIL_MAX_CHARS = 160;\n/** Same ceiling as Linux MAXSYMLINKS; a cycle or longer chain fails closed. */\nconst MAX_LINK_HOPS = 40;\nconst SHA256_HEX = /^[a-f0-9]{64}$/;\nconst MD5_BASE64 = /^[A-Za-z0-9+/]{22}==$/;\nfunction bounded(detail) {\n\treturn detail.length <= MESSAGE_DETAIL_MAX_CHARS ? detail : `${detail.slice(0, MESSAGE_DETAIL_MAX_CHARS)}...`;\n}\nfunction fail(code, message) {\n\tthrow new WorkspaceArchiveError(code, message);\n}\nfunction toArchiveError(error, code, context) {\n\tif (error instanceof WorkspaceArchiveError) return error;\n\treturn new WorkspaceArchiveError(code, `${context}: ${bounded(error instanceof Error ? error.message : String(error))}`);\n}\nfunction resolveLimits(limits) {\n\tconst maxArchiveBytes = limits?.maxArchiveBytes ?? 134217728;\n\tconst maxBytes = limits?.maxBytes ?? 268435456;\n\tconst maxEntries = limits?.maxEntries ?? 5e4;\n\tfor (const [label, value] of [\n\t\t[\"maxArchiveBytes\", maxArchiveBytes],\n\t\t[\"maxBytes\", maxBytes],\n\t\t[\"maxEntries\", maxEntries]\n\t]) if (!Number.isInteger(value) || value <= 0) fail(\"invalid-limits\", `${label} must be a positive integer`);\n\treturn {\n\t\tmaxArchiveBytes,\n\t\tmaxBytes,\n\t\tmaxEntries,\n\t\tmaxDecompressedBytes: maxBytes + maxEntries * TAR_ENTRY_OVERHEAD_BYTES + TAR_STREAM_SLACK_BYTES\n\t};\n}\n/**\n* Canonical absolute path: resolves the deepest existing ancestor (handling symlinked\n* ancestors such as /var on macOS) and re-appends the not-yet-existing tail lexically.\n*/\nasync function canonicalPath(path) {\n\tlet current = resolve(path);\n\tconst tail = [];\n\tfor (;;) try {\n\t\tconst real = await realpath(current);\n\t\treturn tail.length === 0 ? real : join(real, ...tail.reverse());\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw toArchiveError(error, \"io-failed\", \"Cannot canonicalize an archive path component\");\n\t\tconst parent = dirname(current);\n\t\tif (parent === current) throw toArchiveError(error, \"io-failed\", \"Cannot canonicalize an archive path component\");\n\t\ttail.push(basename(current));\n\t\tcurrent = parent;\n\t}\n}\n/** The archive must not be the workspace itself or live beneath it (canonical comparison). */\nasync function assertArchiveOutsideWorkspace(workspacePath, archivePath) {\n\tconst [workspaceCanonical, archiveCanonical] = await Promise.all([canonicalPath(workspacePath), canonicalPath(archivePath)]);\n\tconst suffix = relative(workspaceCanonical, archiveCanonical);\n\tif (!(suffix === \"..\" || suffix.startsWith(`..${sep}`) || isAbsolute(suffix))) fail(\"unsafe-archive-path\", \"Archive path must be outside the workspace\");\n}\nasync function assertRealWorkspaceRoot(workspacePath) {\n\tlet stats;\n\ttry {\n\t\tstats = await lstat(workspacePath);\n\t} catch (error) {\n\t\tthrow toArchiveError(error, \"invalid-workspace\", \"Workspace root is not accessible\");\n\t}\n\tif (stats.isSymbolicLink() || !stats.isDirectory()) fail(\"invalid-workspace\", \"Workspace root must be a real directory, not a symlink\");\n}\n/**\n* Normalizes an archive member name to a root-relative POSIX path, rejecting anything that is\n* absolute, ambiguous, or escapes the root. Returns \"\" for the root pseudo-entry (\"./\", \".\").\n*/\nfunction normalizeMemberName(rawName) {\n\tif (typeof rawName !== \"string\" || rawName.length === 0 || Buffer.byteLength(rawName) > MEMBER_NAME_MAX_BYTES) fail(\"unsafe-member\", \"Archive member name is missing or oversized\");\n\tif (rawName.includes(\"\\0\")) fail(\"unsafe-member\", \"Archive member name contains a NUL byte\");\n\tif (rawName.startsWith(\"/\") || /^[A-Za-z]:[\\\\/]?/.test(rawName) || rawName.includes(\"\\\\\")) fail(\"unsafe-member\", `Archive member name is absolute or ambiguous: ${bounded(rawName)}`);\n\tconst segments = [];\n\tfor (const segment of rawName.split(\"/\")) {\n\t\tif (segment === \"\" || segment === \".\") continue;\n\t\tif (segment === \"..\") fail(\"unsafe-member\", `Archive member escapes the workspace root: ${bounded(rawName)}`);\n\t\tsegments.push(segment);\n\t}\n\treturn segments.join(\"/\");\n}\n/**\n* Form check for a symlink target: relative, non-empty, and unambiguous. Containment is NOT\n* decided here — only full-graph resolution (assertLinksContained) can decide that.\n*/\nfunction assertLinkTargetForm(target, code, memberName) {\n\tif (target.length === 0 || Buffer.byteLength(target) > MEMBER_NAME_MAX_BYTES || target.includes(\"\\0\")) fail(code, `Link target is missing or oversized at ${bounded(memberName)}`);\n\tif (target.startsWith(\"/\") || /^[A-Za-z]:[\\\\/]?/.test(target) || target.includes(\"\\\\\")) fail(code, `Link target is absolute or ambiguous at ${bounded(memberName)}`);\n}\n/** Strips setuid/setgid/sticky and any non-permission bits; never trusts high mode bits. */\nfunction sanitizeMode(mode, fallback) {\n\tif (typeof mode !== \"number\" || !Number.isInteger(mode) || mode < 0) return fallback;\n\treturn mode & 511;\n}\nasync function drain(stream) {\n\tfor await (const chunk of stream);\n}\n/**\n* Resolves one symlink target with kernel path-component semantics against the recorded\n* namespace: the directory stack only ever holds REAL directories, a symlink component\n* substitutes its target in place (bounded hops catch cycles), and `..` past the root is an\n* escape. A component that is a file or missing makes traversal fail (ENOTDIR/ENOENT) — such\n* a link is broken and cannot escape, so only its final component may be non-directory.\n* Targets are never resolved to file contents; this is namespace metadata only.\n*/\nfunction assertTargetContained(namespace, startDir, target, code, linkName) {\n\tconst dirStack = [...startDir];\n\tlet components = target.split(\"/\");\n\tlet hops = 0;\n\tlet index = 0;\n\twhile (index < components.length) {\n\t\tconst component = components[index];\n\t\tindex += 1;\n\t\tif (!component || component === \".\") continue;\n\t\tif (component === \"..\") {\n\t\t\tif (dirStack.length === 0) fail(code, `Link target escapes the workspace root at ${bounded(linkName)}`);\n\t\t\tdirStack.pop();\n\t\t\tcontinue;\n\t\t}\n\t\tconst candidate = [...dirStack, component].join(\"/\");\n\t\tconst found = namespace.get(candidate);\n\t\tif (found?.kind === \"symlink\") {\n\t\t\thops += 1;\n\t\t\tcomponents = [...boundedLinkComponents(found.target ?? \"\", hops, code, linkName), ...components.slice(index)];\n\t\t\tindex = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (found?.kind === \"directory\") {\n\t\t\tdirStack.push(component);\n\t\t\tcontinue;\n\t\t}\n\t\treturn;\n\t}\n}\nfunction boundedLinkComponents(target, hops, code, name) {\n\tif (hops > MAX_LINK_HOPS) fail(code, `Link chain exceeds the ${MAX_LINK_HOPS} hop ceiling at ${bounded(name)}`);\n\treturn target.split(\"/\");\n}\n/** Validates every recorded symlink against the complete entry graph. */\nfunction assertLinksContained(namespace, code) {\n\tfor (const [name, entry] of namespace) {\n\t\tif (entry.kind !== \"symlink\") continue;\n\t\tassertTargetContained(namespace, name.split(\"/\").slice(0, -1), entry.target ?? \"\", code, name);\n\t}\n}\n/** Counts and hashes every compressed byte flowing through; fails closed on overflow. */\nfunction attachCompressedMeter(stream, limit, hashes) {\n\tlet bytes = 0;\n\tstream.on(\"data\", (chunk) => {\n\t\tbytes += chunk.length;\n\t\thashes.sha256.update(chunk);\n\t\thashes.md5.update(chunk);\n\t\tif (bytes > limit) stream.destroy(new WorkspaceArchiveError(\"archive-too-large\", `Compressed archive exceeds the ${limit} byte ceiling`));\n\t});\n\treturn { readCount: () => bytes };\n}\n/** Scans one entry; returns its record plus the child directory to enqueue, if any. */\nasync function scanWorkspaceEntry(workspacePath, dirRel, name, limits, state) {\n\tconst rel = dirRel === \"\" ? name : `${dirRel}/${name}`;\n\tif (name.includes(\"\\\\\") || /^[A-Za-z]:/.test(rel) || Buffer.byteLength(rel) > MEMBER_NAME_MAX_BYTES) fail(\"unsafe-entry\", `Workspace entry name is not portable: ${bounded(rel)}`);\n\tlet stats;\n\ttry {\n\t\tstats = await lstat(join(dirRel === \"\" ? workspacePath : join(workspacePath, ...dirRel.split(\"/\")), name));\n\t} catch (error) {\n\t\tthrow toArchiveError(error, \"io-failed\", `Cannot stat workspace entry ${bounded(rel)}`);\n\t}\n\tconst mode = sanitizeMode(stats.mode, stats.isDirectory() ? 493 : 420);\n\tif (stats.isSymbolicLink()) {\n\t\tlet target;\n\t\ttry {\n\t\t\ttarget = await readlink(join(workspacePath, ...rel.split(\"/\")));\n\t\t} catch (error) {\n\t\t\tthrow toArchiveError(error, \"io-failed\", `Cannot read workspace link ${bounded(rel)}`);\n\t\t}\n\t\tassertLinkTargetForm(target, \"unsafe-entry\", rel);\n\t\treturn { record: {\n\t\t\trel,\n\t\t\tkind: \"symlink\",\n\t\t\tsize: 0,\n\t\t\tmode: 511,\n\t\t\tmtime: stats.mtime,\n\t\t\ttarget\n\t\t} };\n\t}\n\tif (stats.isDirectory()) return {\n\t\trecord: {\n\t\t\trel,\n\t\t\tkind: \"directory\",\n\t\t\tsize: 0,\n\t\t\tmode,\n\t\t\tmtime: stats.mtime\n\t\t},\n\t\tchildDir: rel\n\t};\n\tif (stats.isFile()) {\n\t\tif (stats.nlink > 1) fail(\"unsafe-entry\", `Workspace entry has other hard links and is never archived: ${bounded(rel)}`);\n\t\tstate.bytes += stats.size;\n\t\tif (state.bytes > limits.maxBytes) fail(\"workspace-too-large\", `Workspace exceeds the ${limits.maxBytes} byte ceiling`);\n\t\treturn { record: {\n\t\t\trel,\n\t\t\tkind: \"file\",\n\t\t\tsize: stats.size,\n\t\t\tmode,\n\t\t\tmtime: stats.mtime\n\t\t} };\n\t}\n\tfail(\"unsupported-entry\", `Workspace entry is not a file, directory, or symlink: ${bounded(rel)}`);\n}\nasync function scanWorkspace(workspacePath, limits) {\n\tconst records = [];\n\tconst namespace = /* @__PURE__ */ new Map();\n\tconst state = { bytes: 0 };\n\tconst pendingDirs = [\"\"];\n\tlet cursor = 0;\n\twhile (cursor < pendingDirs.length) {\n\t\tconst dirRel = pendingDirs[cursor] ?? \"\";\n\t\tcursor += 1;\n\t\tconst absDir = dirRel === \"\" ? workspacePath : join(workspacePath, ...dirRel.split(\"/\"));\n\t\tlet names;\n\t\ttry {\n\t\t\tnames = await readdir(absDir);\n\t\t} catch (error) {\n\t\t\tthrow toArchiveError(error, \"io-failed\", `Cannot read workspace directory ${bounded(dirRel || \".\")}`);\n\t\t}\n\t\tnames.sort();\n\t\tfor (const name of names) {\n\t\t\tif (records.length >= limits.maxEntries) fail(\"too-many-entries\", `Workspace exceeds the ${limits.maxEntries} entry ceiling`);\n\t\t\tconst { record, childDir } = await scanWorkspaceEntry(workspacePath, dirRel, name, limits, state);\n\t\t\trecords.push(record);\n\t\t\tnamespace.set(record.rel, {\n\t\t\t\tkind: record.kind,\n\t\t\t\ttarget: record.target\n\t\t\t});\n\t\t\tif (childDir !== void 0) pendingDirs.push(childDir);\n\t\t}\n\t}\n\treturn {\n\t\trecords,\n\t\tnamespace\n\t};\n}\n/**\n* Pass 2 drift check, run immediately before each entry is streamed: kind, file size, and\n* link target must match the pass 1 scan that validated the link graph. Writers are required\n* to be stopped; any drift fails closed instead of archiving an unvalidated tree.\n*/\nasync function assertEntryUnchanged(workspacePath, record) {\n\tconst abs = join(workspacePath, ...record.rel.split(\"/\"));\n\tlet stats;\n\ttry {\n\t\tstats = await lstat(abs);\n\t} catch (error) {\n\t\tthrow toArchiveError(error, \"workspace-changed\", `Workspace entry changed while archiving: ${bounded(record.rel)}`);\n\t}\n\tif (!(record.kind === \"file\" && stats.isFile() || record.kind === \"directory\" && stats.isDirectory() && !stats.isSymbolicLink() || record.kind === \"symlink\" && stats.isSymbolicLink()) || record.kind === \"file\" && stats.size !== record.size) fail(\"workspace-changed\", `Workspace entry changed while archiving: ${bounded(record.rel)}`);\n\tif (record.kind === \"symlink\") {\n\t\tlet target;\n\t\ttry {\n\t\t\ttarget = await readlink(abs);\n\t\t} catch (error) {\n\t\t\tthrow toArchiveError(error, \"workspace-changed\", `Workspace link changed while archiving: ${bounded(record.rel)}`);\n\t\t}\n\t\tif (target !== record.target) fail(\"workspace-changed\", `Workspace link changed while archiving: ${bounded(record.rel)}`);\n\t}\n}\n/**\n* Streams one tar entry and resolves only after tar-stream has flushed it, keeping entry\n* production strictly sequential so memory stays bounded. A source whose size drifts mid-read\n* also fails closed via tar-stream's own size-mismatch check.\n*/\nfunction addArchiveEntry(pack, header, sourcePath) {\n\treturn new Promise((resolveEntry, rejectEntry) => {\n\t\tlet settled = false;\n\t\tconst done = (error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (error === void 0 || error === null) resolveEntry();\n\t\t\telse rejectEntry(error instanceof Error ? error : new Error(String(error)));\n\t\t};\n\t\tconst sink = pack.entry(header, (err) => done(err));\n\t\tif (sourcePath === void 0) {\n\t\t\tsink.end();\n\t\t\treturn;\n\t\t}\n\t\tpipeline(createReadStream(sourcePath), sink).then(() => done(), done);\n\t});\n}\nasync function writeWorkspaceEntries(pack, workspacePath, records) {\n\tfor (const record of records) {\n\t\tawait assertEntryUnchanged(workspacePath, record);\n\t\tif (record.kind === \"symlink\") await addArchiveEntry(pack, {\n\t\t\tname: record.rel,\n\t\t\ttype: \"symlink\",\n\t\t\tlinkname: record.target ?? \"\",\n\t\t\tmode: 511,\n\t\t\tmtime: record.mtime\n\t\t});\n\t\telse if (record.kind === \"directory\") await addArchiveEntry(pack, {\n\t\t\tname: record.rel,\n\t\t\ttype: \"directory\",\n\t\t\tmode: record.mode,\n\t\t\tmtime: record.mtime\n\t\t});\n\t\telse await addArchiveEntry(pack, {\n\t\t\tname: record.rel,\n\t\t\ttype: \"file\",\n\t\t\tsize: record.size,\n\t\t\tmode: record.mode,\n\t\t\tmtime: record.mtime\n\t\t}, join(workspacePath, ...record.rel.split(\"/\")));\n\t}\n}\nasync function createWorkspaceArchive(workspace, archivePath, limits) {\n\tconst resolvedLimits = resolveLimits(limits);\n\tconst workspacePath = resolve(workspace);\n\tconst archivePathResolved = resolve(archivePath);\n\tawait assertRealWorkspaceRoot(workspacePath);\n\tawait assertArchiveOutsideWorkspace(workspacePath, archivePathResolved);\n\tconst scan = await scanWorkspace(workspacePath, resolvedLimits);\n\tassertLinksContained(scan.namespace, \"unsafe-entry\");\n\tconst tempArchive = join(dirname(archivePathResolved), `.${basename(archivePathResolved)}.${randomUUID()}.tmp`);\n\tconst hashes = {\n\t\tsha256: createHash(\"sha256\"),\n\t\tmd5: createHash(\"md5\")\n\t};\n\tconst meter = new PassThrough();\n\tconst compressed = attachCompressedMeter(meter, resolvedLimits.maxArchiveBytes, hashes);\n\tconst pack$1 = pack();\n\tconst output = pipeline(pack$1, createGzip({ level: 1 }), meter, createWriteStream(tempArchive, {\n\t\tflags: \"wx\",\n\t\tmode: 384\n\t}));\n\toutput.catch(() => pack$1.destroy());\n\ttry {\n\t\tawait writeWorkspaceEntries(pack$1, workspacePath, scan.records);\n\t\tpack$1.finalize();\n\t\tawait output;\n\t} catch (error) {\n\t\tpack$1.destroy();\n\t\tawait output.catch(() => void 0);\n\t\tawait rm(tempArchive, { force: true });\n\t\tthrow toArchiveError(error, \"io-failed\", \"Archive creation failed\");\n\t}\n\ttry {\n\t\tawait rename(tempArchive, archivePathResolved);\n\t} catch (error) {\n\t\tawait rm(tempArchive, { force: true });\n\t\tthrow toArchiveError(error, \"io-failed\", \"Archive publish failed\");\n\t}\n\treturn {\n\t\tbytes: compressed.readCount(),\n\t\tsha256: hashes.sha256.digest(\"hex\"),\n\t\tmd5: hashes.md5.digest(\"base64\")\n\t};\n}\nfunction validateExpected(expected, limits) {\n\tif (!Number.isInteger(expected.bytes) || expected.bytes < 0 || expected.bytes > limits.maxArchiveBytes) fail(\"invalid-expected\", `Expected archive length must be an integer between 0 and ${limits.maxArchiveBytes}`);\n\tif (!SHA256_HEX.test(expected.sha256)) fail(\"invalid-expected\", \"Expected sha256 must be 64 lowercase hex characters\");\n\tif (!MD5_BASE64.test(expected.md5)) fail(\"invalid-expected\", \"Expected md5 must be base64 with padding\");\n}\n/**\n* Sequential archive-member validator and writer. Directories and files are written while\n* streaming; symlinks are only RECORDED and installed by `finalize`, after the stream ends,\n* the digests verify, and the complete link graph is validated. Directory modes are applied\n* last (deepest first) so restrictive modes cannot block their own children. Nothing here\n* follows symlinks, applies ownership, or trusts header modes.\n*/\nvar RestoreState = class {\n\tstaging;\n\tlimits;\n\tdeclared = /* @__PURE__ */ new Map();\n\timplicitDirs = /* @__PURE__ */ new Set();\n\tdirModes = /* @__PURE__ */ new Map();\n\tlinks = /* @__PURE__ */ new Map();\n\tentries = 0;\n\tbytes = 0;\n\tconstructor(staging, limits) {\n\t\tthis.staging = staging;\n\t\tthis.limits = limits;\n\t}\n\tasync handle(header, stream) {\n\t\tconst name = normalizeMemberName(header.name);\n\t\tthis.entries += 1;\n\t\tif (this.entries > this.limits.maxEntries) fail(\"too-many-entries\", `Archive exceeds the ${this.limits.maxEntries} entry ceiling`);\n\t\tif (name === \"\") {\n\t\t\tif (header.type !== \"directory\") fail(\"unsafe-member\", \"The archive root must be a directory\");\n\t\t\tawait drain(stream);\n\t\t\treturn;\n\t\t}\n\t\tif (this.declared.has(name)) fail(\"duplicate-member\", `Archive member is duplicated: ${bounded(name)}`);\n\t\tif (this.implicitDirs.has(name) && header.type !== \"directory\") fail(\"unsafe-member\", `Archive member collides with a directory: ${bounded(name)}`);\n\t\tconst segments = name.split(\"/\");\n\t\tawait this.ensureParents(segments, name);\n\t\tif (header.type === \"directory\") {\n\t\t\tthis.declared.set(name, \"directory\");\n\t\t\tif (!this.implicitDirs.delete(name)) await mkdir(this.dest(name));\n\t\t\tawait chmod(this.dest(name), 448);\n\t\t\tthis.dirModes.set(name, sanitizeMode(header.mode, 493));\n\t\t\tawait drain(stream);\n\t\t\treturn;\n\t\t}\n\t\tif (header.type === \"symlink\") {\n\t\t\tthis.declared.set(name, \"symlink\");\n\t\t\tconst target = typeof header.linkname === \"string\" ? header.linkname : \"\";\n\t\t\tassertLinkTargetForm(target, \"unsafe-member\", name);\n\t\t\tthis.links.set(name, target);\n\t\t\tawait drain(stream);\n\t\t\treturn;\n\t\t}\n\t\tif (header.type === \"file\") {\n\t\t\tthis.declared.set(name, \"file\");\n\t\t\tconst dest = this.dest(name);\n\t\t\tconst tap = new PassThrough();\n\t\t\ttap.on(\"data\", (chunk) => {\n\t\t\t\tthis.bytes += chunk.length;\n\t\t\t\tif (this.bytes > this.limits.maxBytes) tap.destroy(new WorkspaceArchiveError(\"workspace-too-large\", `Archive expands beyond the ${this.limits.maxBytes} byte ceiling`));\n\t\t\t});\n\t\t\tawait pipeline(stream, tap, createWriteStream(dest, {\n\t\t\t\tflags: \"wx\",\n\t\t\t\tmode: 384\n\t\t\t}));\n\t\t\tawait chmod(dest, sanitizeMode(header.mode, 420));\n\t\t\treturn;\n\t\t}\n\t\tif (header.type === \"link\") fail(\"unsafe-member\", `Hard-link members are never restorable: ${bounded(name)}`);\n\t\tfail(\"unsupported-member\", `Archive member has an unsupported type: ${bounded(name)}`);\n\t}\n\t/** Runs after the archive stream is fully consumed and both digests verify. */\n\tasync finalize() {\n\t\tconst namespace = /* @__PURE__ */ new Map();\n\t\tfor (const dir of this.implicitDirs) namespace.set(dir, { kind: \"directory\" });\n\t\tfor (const [name, kind] of this.declared) namespace.set(name, kind === \"symlink\" ? {\n\t\t\tkind,\n\t\t\ttarget: this.links.get(name) ?? \"\"\n\t\t} : { kind });\n\t\tassertLinksContained(namespace, \"unsafe-member\");\n\t\tfor (const [name, target] of this.links) await symlink(target, this.dest(name));\n\t\tconst deepestFirst = [...this.dirModes.keys()].sort((a, b) => b.split(\"/\").length - a.split(\"/\").length);\n\t\tfor (const dir of deepestFirst) await chmod(this.dest(dir), this.dirModes.get(dir) ?? 493);\n\t}\n\tdest(name) {\n\t\tconst dest = join(this.staging, ...name.split(\"/\"));\n\t\tconst suffix = relative(this.staging, dest);\n\t\tif (suffix === \"\" || suffix === \"..\" || suffix.startsWith(`..${sep}`) || isAbsolute(suffix)) fail(\"unsafe-member\", `Archive member escapes the staging root: ${bounded(name)}`);\n\t\treturn dest;\n\t}\n\t/** Creates missing parents on demand; a parent declared as a file/symlink rejects the child. */\n\tasync ensureParents(segments, memberName) {\n\t\tlet current = this.staging;\n\t\tlet rel = \"\";\n\t\tfor (const segment of segments.slice(0, -1)) {\n\t\t\trel = rel === \"\" ? segment : `${rel}/${segment}`;\n\t\t\tcurrent = join(current, segment);\n\t\t\tconst kind = this.declared.get(rel);\n\t\t\tif (kind !== void 0 && kind !== \"directory\") fail(\"unsafe-member\", `Archive member is nested beneath a non-directory: ${bounded(memberName)}`);\n\t\t\tif (kind === void 0 && !this.implicitDirs.has(rel)) {\n\t\t\t\tawait mkdir(current);\n\t\t\t\tawait chmod(current, 448);\n\t\t\t\tthis.implicitDirs.add(rel);\n\t\t\t}\n\t\t}\n\t}\n};\nasync function extractArchiveInto(archivePath, staging, expected, limits) {\n\tconst hashes = {\n\t\tsha256: createHash(\"sha256\"),\n\t\tmd5: createHash(\"md5\")\n\t};\n\tconst compressedMeter = new PassThrough();\n\tconst compressed = attachCompressedMeter(compressedMeter, limits.maxArchiveBytes, hashes);\n\tlet decompressedBytes = 0;\n\tconst decompressedMeter = new PassThrough();\n\tdecompressedMeter.on(\"data\", (chunk) => {\n\t\tdecompressedBytes += chunk.length;\n\t\tif (decompressedBytes > limits.maxDecompressedBytes) decompressedMeter.destroy(new WorkspaceArchiveError(\"decompression-limit\", \"Archive expands beyond the decompressed stream ceiling\"));\n\t});\n\tconst extractor = extract();\n\tconst state = new RestoreState(staging, limits);\n\textractor.on(\"entry\", (header, stream, next) => {\n\t\tstate.handle(header, stream).then(() => next(), (error) => next(error));\n\t});\n\ttry {\n\t\tawait pipeline(createReadStream(archivePath), compressedMeter, createGunzip(), decompressedMeter, extractor);\n\t} catch (error) {\n\t\tthrow toArchiveError(error, \"invalid-archive\", \"Archive cannot be unpacked\");\n\t}\n\tif (compressed.readCount() !== expected.bytes) fail(\"size-mismatch\", `Archive length ${compressed.readCount()} does not match the expected ${expected.bytes}`);\n\tconst sha256 = hashes.sha256.digest(\"hex\");\n\tconst md5 = hashes.md5.digest(\"base64\");\n\tif (sha256 !== expected.sha256 || md5 !== expected.md5) fail(\"hash-mismatch\", \"Archive digests do not match the expected integrity metadata\");\n\tawait state.finalize();\n}\n/**\n* Moves the fully validated staging tree onto an EMPTY or missing destination. A nonempty or\n* non-directory destination is refused untouched; on a rename failure the previous empty\n* destination is recreated best-effort so a failed restore never deletes user state.\n*/\nasync function replaceDestination(staging, workspacePath) {\n\tlet hadDestination = false;\n\ttry {\n\t\tconst stats = await lstat(workspacePath);\n\t\thadDestination = true;\n\t\tif (stats.isSymbolicLink() || !stats.isDirectory()) fail(\"invalid-destination\", \"Restore destination exists but is not a real directory\");\n\t\tif ((await readdir(workspacePath)).length > 0) fail(\"destination-not-empty\", \"Restore destination is not empty; refusing to overwrite a workspace\");\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t}\n\tif (hadDestination) await rmdir(workspacePath);\n\ttry {\n\t\tawait rename(staging, workspacePath);\n\t} catch (error) {\n\t\tif (hadDestination) await mkdir(workspacePath).catch(() => void 0);\n\t\tthrow toArchiveError(error, \"io-failed\", \"Failed to move the validated workspace into place\");\n\t}\n}\nasync function restoreWorkspaceArchive(archivePath, workspace, expected, limits) {\n\tconst resolvedLimits = resolveLimits(limits);\n\tvalidateExpected(expected, resolvedLimits);\n\tconst archivePathResolved = resolve(archivePath);\n\tconst workspacePath = resolve(workspace);\n\tawait assertArchiveOutsideWorkspace(workspacePath, archivePathResolved);\n\tlet archiveStats;\n\ttry {\n\t\tarchiveStats = await lstat(archivePathResolved);\n\t} catch (error) {\n\t\tthrow toArchiveError(error, \"io-failed\", \"Archive is not readable\");\n\t}\n\tif (archiveStats.isSymbolicLink() || !archiveStats.isFile()) fail(\"invalid-archive\", \"Archive path must be a regular file\");\n\tif (archiveStats.size !== expected.bytes) fail(\"size-mismatch\", `Archive length ${archiveStats.size} does not match the expected ${expected.bytes}`);\n\tconst parent = dirname(workspacePath);\n\ttry {\n\t\tawait mkdir(parent, { recursive: true });\n\t} catch (error) {\n\t\tthrow toArchiveError(error, \"io-failed\", \"Workspace parent directory is not writable\");\n\t}\n\tconst staging = await mkdtemp(join(parent, `.${basename(workspacePath)}.opentag-restore-`));\n\ttry {\n\t\tawait extractArchiveInto(archivePathResolved, staging, expected, resolvedLimits);\n\t\tawait replaceDestination(staging, workspacePath);\n\t} catch (error) {\n\t\tawait rm(staging, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t\tthrow error instanceof WorkspaceArchiveError ? error : toArchiveError(error, \"io-failed\", \"Workspace restore failed\");\n\t}\n}\n//#endregion\n//#region src/runner/cloud-workspace.ts\nvar CloudWorkspaceError = class extends Error {\n\tcode;\n\tretryable;\n\tconstructor(code, retryable = true) {\n\t\tsuper(`Cloud workspace ${code}`);\n\t\tthis.code = code;\n\t\tthis.retryable = retryable;\n\t\tthis.name = \"CloudWorkspaceError\";\n\t}\n};\nfunction outside(root, target) {\n\tconst path = relative(resolve(root), resolve(target));\n\treturn path === \"..\" || path.startsWith(`..${sep}`);\n}\nfunction workspaceOrigin(raw) {\n\tconst url = new URL(raw);\n\tif (url.username || url.password || url.search || url.hash) throw new CloudWorkspaceError(\"scope_unavailable\");\n\tif (url.protocol === \"wss:\") url.protocol = \"https:\";\n\tif (url.protocol === \"ws:\") url.protocol = \"http:\";\n\tconst host = url.hostname.replace(/^\\[|\\]$/g, \"\");\n\tconst local = host === \"localhost\" || host === \"::1\" || isIP(host) === 4 && host.startsWith(\"127.\");\n\tif (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && local)) throw new CloudWorkspaceError(\"scope_unavailable\");\n\treturn `${url.origin}${RUNNER_WORKSPACE_PATH}`;\n}\nasync function boundedJson(response) {\n\tif (!response.ok || !response.body) {\n\t\tawait response.body?.cancel();\n\t\tthrow new CloudWorkspaceError(\"save_failed\");\n\t}\n\tconst chunks = [];\n\tlet total = 0;\n\tconst reader = response.body.getReader();\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst item = await reader.read();\n\t\t\tif (item.done) break;\n\t\t\ttotal += item.value.byteLength;\n\t\t\tif (total > 16384) throw new CloudWorkspaceError(\"save_failed\");\n\t\t\tchunks.push(item.value);\n\t\t}\n\t\treturn JSON.parse(Buffer.concat(chunks).toString(\"utf8\"));\n\t} finally {\n\t\tawait reader.cancel().catch(() => void 0);\n\t\treader.releaseLock();\n\t}\n}\n/**\n* Latest-state transfer in the trusted parent. The caller exclusively owns the native namespace\n* and MUST stop every workspace writer before initialize/save. Reconnects retry unsaved local\n* bytes; they never re-extract an older archive over an initialized workspace.\n*/\nvar CloudWorkspace = class {\n\t#options;\n\t#url;\n\t#fetch;\n\t#object;\n\t#restored = false;\n\t#pendingSave = false;\n\t#terminalFailure = false;\n\t#serial = Promise.resolve();\n\tconstructor(options) {\n\t\tif (!outside(options.workspace, options.stateDirectory) || !outside(options.stateDirectory, options.workspace)) throw new CloudWorkspaceError(\"scope_unavailable\");\n\t\tthis.#options = options;\n\t\tthis.#url = workspaceOrigin(options.backendUrl);\n\t\tthis.#fetch = options.fetchImpl ?? fetch;\n\t}\n\tget initialized() {\n\t\treturn this.#restored;\n\t}\n\tget pendingSave() {\n\t\treturn this.#pendingSave;\n\t}\n\t/** An unchanged directory cannot recover from an archive format/size violation by retrying. */\n\tget terminalFailure() {\n\t\treturn this.#terminalFailure;\n\t}\n\tget sealed() {\n\t\treturn this.#object?.sealed === true;\n\t}\n\tinitialize() {\n\t\treturn this.#enqueue(async () => {\n\t\t\tif (this.sealed) return;\n\t\t\tif (this.#restored) {\n\t\t\t\tif (this.#pendingSave) await this.#save(false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst object = await this.#claim();\n\t\t\t\tthis.#object = object;\n\t\t\t\tif (object.sealed) return;\n\t\t\t\tawait mkdir(this.#options.workspace, {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tmode: 448\n\t\t\t\t});\n\t\t\t\tif ((await readdir(this.#options.workspace)).length !== 0) throw new CloudWorkspaceError(\"restore_failed\");\n\t\t\t\tif (object.saved) await this.#temporaryArchive(async (path) => {\n\t\t\t\t\tawait this.#download(object, path);\n\t\t\t\t\tawait restoreWorkspaceArchive(path, this.#options.workspace, object);\n\t\t\t\t});\n\t\t\t\tthis.#restored = true;\n\t\t\t\tawait this.#save(false);\n\t\t\t} catch {\n\t\t\t\tthrow new CloudWorkspaceError(\"restore_failed\");\n\t\t\t}\n\t\t});\n\t}\n\tsave(sealed = false) {\n\t\treturn this.#enqueue(() => this.#save(sealed));\n\t}\n\tasync #save(sealed) {\n\t\tif (this.#terminalFailure) throw new CloudWorkspaceError(\"save_failed\", false);\n\t\tif (this.sealed) {\n\t\t\tif (sealed) return;\n\t\t\tthrow new CloudWorkspaceError(\"save_failed\");\n\t\t}\n\t\tconst previous = this.#object;\n\t\tif (!previous || !this.#restored) throw new CloudWorkspaceError(\"restore_failed\");\n\t\tthis.#pendingSave = true;\n\t\ttry {\n\t\t\tawait this.#temporaryArchive(async (path) => {\n\t\t\t\tconst info = await createWorkspaceArchive(this.#options.workspace, path);\n\t\t\t\tthis.#object = await this.#upload(path, previous, info, sealed);\n\t\t\t});\n\t\t\tthis.#pendingSave = false;\n\t\t} catch (error) {\n\t\t\tif (error instanceof WorkspaceArchiveError && [\n\t\t\t\t\"too-many-entries\",\n\t\t\t\t\"workspace-too-large\",\n\t\t\t\t\"archive-too-large\",\n\t\t\t\t\"unsafe-entry\",\n\t\t\t\t\"unsupported-entry\"\n\t\t\t].includes(error.code)) this.#terminalFailure = true;\n\t\t\tthrow new CloudWorkspaceError(\"save_failed\", !this.#terminalFailure);\n\t\t}\n\t}\n\tasync #temporaryArchive(operation) {\n\t\tawait mkdir(this.#options.stateDirectory, {\n\t\t\trecursive: true,\n\t\t\tmode: 448\n\t\t});\n\t\tconst directory = await mkdtemp(join(this.#options.stateDirectory, \"workspace-\"));\n\t\ttry {\n\t\t\treturn await operation(join(directory, \"state.tar.gz\"));\n\t\t} finally {\n\t\t\tawait rm(directory, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t});\n\t\t}\n\t}\n\t#headers() {\n\t\tconst generation = this.#options.environmentGeneration();\n\t\tconst token = this.#options.token();\n\t\tif (!token || generation === void 0 || !Number.isSafeInteger(generation) || generation < 1) throw new CloudWorkspaceError(\"scope_unavailable\");\n\t\treturn { authorization: `Bearer ${token}` };\n\t}\n\t#signal() {\n\t\treturn AbortSignal.timeout(this.#options.timeoutMs ?? RUNNER_WORKSPACE_TIMEOUT_MS);\n\t}\n\t#parseObject(value) {\n\t\tconst object = RunnerWorkspaceObjectSchema.parse(value);\n\t\tif (object.ownerGeneration !== this.#options.environmentGeneration()) throw new CloudWorkspaceError(\"scope_unavailable\");\n\t\treturn object;\n\t}\n\tasync #claim() {\n\t\tconst response = await this.#fetch(`${this.#url}/claim`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...this.#headers(),\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t},\n\t\t\tbody: \"{}\",\n\t\t\tredirect: \"error\",\n\t\t\tsignal: this.#signal()\n\t\t});\n\t\treturn this.#parseObject(await boundedJson(response));\n\t}\n\tasync #download(object, path) {\n\t\tconst url = new URL(`${this.#url}/archive`);\n\t\turl.searchParams.set(\"generation\", object.generation);\n\t\turl.searchParams.set(\"metageneration\", object.metageneration);\n\t\tconst response = await this.#fetch(url, {\n\t\t\theaders: this.#headers(),\n\t\t\tredirect: \"error\",\n\t\t\tsignal: this.#signal()\n\t\t});\n\t\tif (!response.ok || !response.body) {\n\t\t\tawait response.body?.cancel();\n\t\t\tthrow new CloudWorkspaceError(\"restore_failed\");\n\t\t}\n\t\tconst reader = response.body.getReader();\n\t\tlet file;\n\t\tlet bytes = 0;\n\t\ttry {\n\t\t\tfile = await open(path, \"wx\", 384);\n\t\t\tfor (;;) {\n\t\t\t\tconst item = await reader.read();\n\t\t\t\tif (item.done) break;\n\t\t\t\tbytes += item.value.byteLength;\n\t\t\t\tif (bytes > object.bytes || bytes > RUNNER_WORKSPACE_ARCHIVE_MAX_BYTES) throw new CloudWorkspaceError(\"restore_failed\");\n\t\t\t\tawait file.writeFile(item.value);\n\t\t\t}\n\t\t\tif (bytes !== object.bytes) throw new CloudWorkspaceError(\"restore_failed\");\n\t\t\tawait file.sync();\n\t\t} finally {\n\t\t\tawait reader.cancel().catch(() => void 0);\n\t\t\treader.releaseLock();\n\t\t\tawait file?.close();\n\t\t}\n\t}\n\tasync #upload(path, previous, info, sealed) {\n\t\tconst body = createReadStream(path);\n\t\ttry {\n\t\t\tconst init = {\n\t\t\t\tmethod: \"PUT\",\n\t\t\t\theaders: {\n\t\t\t\t\t...this.#headers(),\n\t\t\t\t\t\"content-type\": \"application/octet-stream\",\n\t\t\t\t\t\"content-length\": String(info.bytes),\n\t\t\t\t\t\"x-opentag-storage-generation\": previous.generation,\n\t\t\t\t\t\"x-opentag-storage-metageneration\": previous.metageneration,\n\t\t\t\t\t\"x-opentag-workspace-sha256\": info.sha256,\n\t\t\t\t\t\"content-md5\": info.md5,\n\t\t\t\t\t\"x-opentag-workspace-sealed\": String(sealed)\n\t\t\t\t},\n\t\t\t\tbody,\n\t\t\t\tduplex: \"half\",\n\t\t\t\tredirect: \"error\",\n\t\t\t\tsignal: this.#signal()\n\t\t\t};\n\t\t\tconst object = this.#parseObject(await boundedJson(await this.#fetch(`${this.#url}/archive`, init)));\n\t\t\tif (!this.#confirmsWrite(object, previous, info, sealed)) throw new CloudWorkspaceError(\"save_failed\");\n\t\t\treturn object;\n\t\t} catch {\n\t\t\tconst current = await this.#claim();\n\t\t\tif (!this.#confirmsWrite(current, previous, info, sealed)) throw new CloudWorkspaceError(\"save_failed\");\n\t\t\treturn current;\n\t\t} finally {\n\t\t\tbody.destroy();\n\t\t}\n\t}\n\t#confirmsWrite(object, previous, info, sealed) {\n\t\treturn object.generation !== previous.generation && object.saved && object.sealed === sealed && object.bytes === info.bytes && object.sha256 === info.sha256 && object.md5 === info.md5;\n\t}\n\t#enqueue(operation) {\n\t\tconst pending = this.#serial.then(operation, operation);\n\t\tthis.#serial = pending.catch(() => void 0);\n\t\treturn pending;\n\t}\n};\nconst SANDBOX_ROOTFS = \"/opt/sandbox-root\";\nconst SANDBOX_WORKSPACE_DESTINATION = \"/workspace\";\nconst SANDBOX_WORKER_ENTRY = \"/opt/opentag/client/dist/runner/bin.mjs\";\nconst SANDBOX_NODE = \"/usr/local/bin/node\";\n/** Explicit PATH inside the sandbox; matches the image layout and nothing else. */\nconst SANDBOX_PATH = \"/usr/local/bin:/opt/opentag/tools/bin:/usr/bin:/bin\";\nconst SANDBOX_PI = \"/opt/opentag/tools/bin/pi\";\n/**\n* Directory the in-Sandbox web bridge may use for its fresh per-execution listener. The bridge\n* creates and removes its own short socket inside the Sandbox namespace; the parent never mounts\n* a socket or listener into the Sandbox, so the path is a nonsecret descriptor only.\n*/\nconst SANDBOX_WEB_BRIDGE_DIRECTORY = \"/tmp\";\nconst RESOLVER_DESTINATION = \"/etc/resolv.conf\";\nconst CAPTURE_LIMIT_BYTES = 262144;\nvar NativeSandboxError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.name = \"NativeSandboxError\";\n\t\tthis.code = code;\n\t}\n};\nfunction classifySpawnError(error) {\n\tconst errno = error;\n\tif (errno?.code === \"ENOENT\") return new NativeSandboxError(\"unavailable\", \"The native Cloud Run sandbox binary is absent; this is not a native Cloud Run Instance\");\n\tif (errno?.code === \"EACCES\" || errno?.code === \"EPERM\") return new NativeSandboxError(\"requires_root\", \"The native sandbox binary exists but cannot be executed by this user; the gcp sandbox may require root\");\n\treturn new NativeSandboxError(\"launch_failed\", \"Native sandbox process could not start\");\n}\n/** The exact PoC argv: run NAME --detach --write --allow-egress --rootfs ROOT --mount … --env PATH=… -- sleep infinity */\nfunction buildSandboxRunArgv(input) {\n\tassertSafeOperand(input.resolverCopy, \"resolver copy path\");\n\tif (!input.resolverCopy.startsWith(\"/\") || input.resolverCopy.includes(\",\") || input.resolverCopy.split(\"/\").includes(\"..\")) throw new NativeSandboxError(\"launch_failed\", \"Unsafe resolver copy mount\");\n\tfor (const mount of input.extraMounts ?? []) {\n\t\tassertSafeOperand(mount.source, \"extra mount source\");\n\t\tassertSafeOperand(mount.destination, \"extra mount destination\");\n\t\tif (!mount.source.startsWith(\"/\") || mount.source.includes(\",\") || mount.source.split(\"/\").includes(\"..\") || !mount.destination.startsWith(\"/\") || mount.destination.includes(\",\") || mount.destination.split(\"/\").includes(\"..\")) throw new NativeSandboxError(\"launch_failed\", \"Unsafe extra mount\");\n\t}\n\treturn [\n\t\tinput.sandboxBinary ?? \"/usr/local/gcp/bin/sandbox\",\n\t\t\"run\",\n\t\tinput.name,\n\t\t\"--detach\",\n\t\t\"--write\",\n\t\t\"--allow-egress\",\n\t\t\"--rootfs\",\n\t\tinput.rootfs ?? \"/opt/sandbox-root\",\n\t\t\"--mount\",\n\t\t`type=bind,source=${input.workspace},destination=${SANDBOX_WORKSPACE_DESTINATION}`,\n\t\t\"--mount\",\n\t\t`type=bind,source=${input.resolverCopy},destination=${RESOLVER_DESTINATION},readonly`,\n\t\t...(input.extraMounts ?? []).flatMap((mount) => [\"--mount\", `type=bind,source=${mount.source},destination=${mount.destination},readonly`]),\n\t\t\"--env\",\n\t\t`PATH=${SANDBOX_PATH}`,\n\t\t\"--\",\n\t\t\"/usr/local/bin/opentag-init\",\n\t\t\"/bin/sleep\",\n\t\t\"infinity\"\n\t];\n}\nfunction buildSandboxExecArgv(input) {\n\treturn [\n\t\tinput.sandboxBinary ?? \"/usr/local/gcp/bin/sandbox\",\n\t\t\"exec\",\n\t\tinput.name,\n\t\t\"--\",\n\t\tinput.command,\n\t\t...input.args ?? []\n\t];\n}\nfunction buildSandboxDeleteArgv(input) {\n\treturn [\n\t\tinput.sandboxBinary ?? \"/usr/local/gcp/bin/sandbox\",\n\t\t\"delete\",\n\t\t\"--force\",\n\t\tinput.name\n\t];\n}\n/** Assert that a value can never smuggle option/argv structure into the sandbox CLI. */\nfunction assertSafeOperand(value, what) {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > 512 || /[\\0\\n\\r]/.test(value)) throw new NativeSandboxError(\"launch_failed\", `Unsafe ${what} for the native sandbox`);\n}\n/** Read the platform resolver with a hard byte bound before anything is written to the private copy. */\nasync function readBoundedResolver(source) {\n\tlet sourceStats;\n\ttry {\n\t\tsourceStats = await stat(source);\n\t} catch {\n\t\tthrow new NativeSandboxError(\"launch_failed\", \"Platform resolver source cannot be read for the native sandbox\");\n\t}\n\tif (!sourceStats.isFile()) throw new NativeSandboxError(\"launch_failed\", \"Platform resolver source is not a regular file\");\n\tconst handle = await open(source, \"r\");\n\ttry {\n\t\tif (!(await handle.stat()).isFile()) throw new NativeSandboxError(\"launch_failed\", \"Platform resolver source is not a regular file\");\n\t\tconst buffer = Buffer.alloc(65537);\n\t\tlet total = 0;\n\t\twhile (total < buffer.length) {\n\t\t\tconst { bytesRead } = await handle.read(buffer, total, buffer.length - total, null);\n\t\t\tif (bytesRead === 0) break;\n\t\t\ttotal += bytesRead;\n\t\t}\n\t\tif (total === 0) throw new NativeSandboxError(\"launch_failed\", \"Platform resolver source is empty\");\n\t\tif (total > 65536) throw new NativeSandboxError(\"launch_failed\", \"Platform resolver source exceeds the snapshot bound\");\n\t\treturn buffer.subarray(0, total);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\nvar NativeSandbox = class {\n\t#name;\n\t#workspace;\n\t#rootfs;\n\t#binary;\n\t#spawn;\n\t#sleep;\n\t#resolverSource;\n\t#extraMounts;\n\t#rootfsCanary = `/tmp/opentag-rootfs-${randomUUID()}`;\n\t#resolverSnapshot;\n\t#sandboxAlive = false;\n\tconstructor(options) {\n\t\tif (!/^[a-z][a-z0-9-]{0,62}$/.test(options.name)) throw new NativeSandboxError(\"launch_failed\", \"Invalid sandbox name\");\n\t\tassertSafeOperand(options.workspace, \"workspace path\");\n\t\tif (!options.workspace.startsWith(\"/\") || options.workspace.includes(\",\") || options.workspace.split(\"/\").includes(\"..\")) throw new NativeSandboxError(\"launch_failed\", \"Unsafe workspace mount\");\n\t\tthis.#name = options.name;\n\t\tthis.#workspace = options.workspace;\n\t\tthis.#rootfs = options.rootfs ?? \"/opt/sandbox-root\";\n\t\tthis.#binary = options.sandboxBinary ?? \"/usr/local/gcp/bin/sandbox\";\n\t\tthis.#resolverSource = options.resolverSource ?? \"/etc/resolv.conf\";\n\t\tthis.#extraMounts = options.extraMounts ?? [];\n\t\tassertSafeOperand(this.#resolverSource, \"resolver source path\");\n\t\tif (!this.#resolverSource.startsWith(\"/\")) throw new NativeSandboxError(\"launch_failed\", \"Unsafe resolver source path\");\n\t\tthis.#spawn = options.spawnProcess ?? ((command, args, spawnOptions) => spawn(command, [...args], {\n\t\t\t...spawnOptions,\n\t\t\tstdio: \"pipe\"\n\t\t}));\n\t\tthis.#sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));\n\t}\n\tget name() {\n\t\treturn this.#name;\n\t}\n\t/** run --detach; resolves once the CLI accepted the launch, then verifies the sandbox answers exec. */\n\tasync launch() {\n\t\tconst resolver = await this.#ensureResolverSnapshot();\n\t\tconst [command, ...args] = buildSandboxRunArgv({\n\t\t\tname: this.#name,\n\t\t\tworkspace: this.#workspace,\n\t\t\tresolverCopy: resolver.copy,\n\t\t\trootfs: this.#rootfs,\n\t\t\tsandboxBinary: this.#binary,\n\t\t\textraMounts: this.#extraMounts\n\t\t});\n\t\ttry {\n\t\t\tconst result = await this.#runToExit(command, args, { timeoutMs: 3e4 });\n\t\t\tif (result.code !== 0) {\n\t\t\t\tconst stderr = result.stderr.trim();\n\t\t\t\tif (/permission denied|operation not permitted|must be run as root|requires root/i.test(stderr)) throw new NativeSandboxError(\"requires_root\", \"Native sandbox launch requires platform privileges\");\n\t\t\t\tthrow new NativeSandboxError(\"launch_failed\", `Sandbox launch failed (exit ${result.code})`);\n\t\t\t}\n\t\t\tthis.#sandboxAlive = true;\n\t\t} catch (error) {\n\t\t\tif (!this.#sandboxAlive) await this.#removeResolverSnapshot().catch(() => void 0);\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* The platform resolver lives on a sensitive parent path the native CLI refuses to mount.\n\t* Snapshot its bounded bytes into a fresh 0700 directory outside the workspace and rootfs, and\n\t* mount only that copy read-only. The copy exists until the native sandbox is deleted.\n\t*/\n\tasync #ensureResolverSnapshot() {\n\t\tif (this.#resolverSnapshot) return this.#resolverSnapshot;\n\t\tlet bytes;\n\t\ttry {\n\t\t\tbytes = await readBoundedResolver(this.#resolverSource);\n\t\t} catch (error) {\n\t\t\tif (error instanceof NativeSandboxError) throw error;\n\t\t\tthrow new NativeSandboxError(\"launch_failed\", \"Could not read the platform resolver for the native sandbox\");\n\t\t}\n\t\tconst directory = await mkdtemp(join(tmpdir(), \"opentag-resolver-\"));\n\t\tconst copy = join(directory, \"resolv.conf\");\n\t\ttry {\n\t\t\tawait writeFile(copy, bytes, {\n\t\t\t\tmode: 384,\n\t\t\t\tflag: \"wx\"\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tawait rm(directory, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t}).catch(() => void 0);\n\t\t\tthrow error instanceof NativeSandboxError ? error : new NativeSandboxError(\"launch_failed\", \"Could not write the private resolver copy for the native sandbox\");\n\t\t}\n\t\tthis.#resolverSnapshot = {\n\t\t\tdirectory,\n\t\t\tcopy\n\t\t};\n\t\treturn this.#resolverSnapshot;\n\t}\n\tasync #removeResolverSnapshot() {\n\t\tconst snapshot = this.#resolverSnapshot;\n\t\tif (!snapshot) return;\n\t\tawait rm(snapshot.directory, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t\tthis.#resolverSnapshot = void 0;\n\t}\n\t/** Native sandbox/tool readiness inside the sandbox: exact versions from the immutable rootfs. */\n\tasync probe() {\n\t\tconst node = await this.exec(SANDBOX_NODE, [\"--version\"], { timeoutMs: 3e4 });\n\t\tif (node.code !== 0 || !/^v\\d+\\.\\d+\\.\\d+$/.test(node.stdout.trim())) throw new NativeSandboxError(\"probe_failed\", \"The sandbox rootfs does not provide a working node runtime\");\n\t\tconst pi = await this.exec(SANDBOX_PI, [\"--version\"], { timeoutMs: 6e4 });\n\t\tif (pi.code !== 0 || pi.stdout.trim().length === 0) throw new NativeSandboxError(\"probe_failed\", \"The sandbox rootfs does not provide a working Pi toolchain\");\n\t\tconst identity = await this.exec(SANDBOX_NODE, [\"-e\", \"process.stdout.write(JSON.parse(require('node:fs').readFileSync('/opt/opentag/identity.json','utf8')).version)\"], { timeoutMs: 3e4 });\n\t\tif (identity.code !== 0 || !/^[0-9A-Za-z.+-]{1,64}$/.test(identity.stdout.trim())) throw new NativeSandboxError(\"probe_failed\", \"The sandbox provides no valid Runner version\");\n\t\tconst canaryRoot = await mkdtemp(join(tmpdir(), \"opentag-parent-canary-\"));\n\t\tconst canary = join(canaryRoot, \"parent-only\");\n\t\ttry {\n\t\t\tawait writeFile(canary, \"parent\", { mode: 384 });\n\t\t\tconst code = `const fs=require('node:fs'); const p=${JSON.stringify(canary)};\n        const rootfsCanary=${JSON.stringify(this.#rootfsCanary)};\n        if(fs.existsSync(rootfsCanary))process.exit(12);\n        fs.writeFileSync(rootfsCanary,'sandbox-layer');\n        if(fs.existsSync(p)||fs.existsSync('/opt/sandbox-root'))process.exit(10);\n        for(const file of ['/proc/self/environ','/proc/1/environ']) {\n          const value=fs.readFileSync(file,'utf8');\n          if(value.includes('OPENTAG_RUNNER_BOOTSTRAP_TOKEN')||value.includes('OPENTAG_RUNNER_CONTROL_TOKEN')||value.includes('OPENTAG_RUNNER_BACKEND_URL'))process.exit(11);\n        }\n        fs.mkdirSync(require('node:path').dirname(p),{recursive:true});fs.writeFileSync(p,'sandbox');\n        process.stdout.write('isolated');`;\n\t\t\tconst isolation = await this.exec(SANDBOX_NODE, [\"-e\", code], { timeoutMs: 3e4 });\n\t\t\tif (isolation.code !== 0 || isolation.stdout !== \"isolated\" || await readFile(canary, \"utf8\") !== \"parent\") throw new NativeSandboxError(\"probe_failed\", \"Native sandbox failed filesystem or credential isolation checks\");\n\t\t\tif (await lstat(join(this.#rootfs, this.#rootfsCanary)).catch((error) => {\n\t\t\t\tif (error.code === \"ENOENT\") return void 0;\n\t\t\t\tthrow error;\n\t\t\t})) throw new NativeSandboxError(\"probe_failed\", \"Native sandbox modified the immutable root filesystem\");\n\t\t} finally {\n\t\t\tawait rm(canaryRoot, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tnodeVersion: node.stdout.trim(),\n\t\t\tpiVersion: pi.stdout.trim().split(\"\\n\", 1)[0] ?? \"\",\n\t\t\trunnerVersion: identity.stdout.trim()\n\t\t};\n\t}\n\t/** Exec a command inside the sandbox with bounded capture and optional stdin payload. */\n\tasync exec(command, args, options) {\n\t\tassertSafeOperand(command, \"exec command\");\n\t\tconst [binary, ...rest] = buildSandboxExecArgv({\n\t\t\tname: this.#name,\n\t\t\tcommand,\n\t\t\targs,\n\t\t\tsandboxBinary: this.#binary\n\t\t});\n\t\treturn this.#runToExit(binary, rest, options);\n\t}\n\t/**\n\t* Long-lived duplex `sandbox exec` channel: stdin/stdout, no shell, no interpolation. This is\n\t* the verified native transport for the in-Sandbox web bridge — the parent process is the only\n\t* peer, so no network listener or credential ever enters the Sandbox. Callers own framing and\n\t* must close the handle on revocation.\n\t*/\n\topenDuplex(command, args) {\n\t\tassertSafeOperand(command, \"exec command\");\n\t\tconst [binary, ...rest] = buildSandboxExecArgv({\n\t\t\tname: this.#name,\n\t\t\tcommand,\n\t\t\targs,\n\t\t\tsandboxBinary: this.#binary\n\t\t});\n\t\tlet child;\n\t\ttry {\n\t\t\tchild = this.#spawn(binary, rest, { env: { PATH: \"/usr/local/bin:/usr/bin:/bin\" } });\n\t\t} catch (error) {\n\t\t\tthrow classifySpawnError(error);\n\t\t}\n\t\tlet firstError;\n\t\tconst errorListeners = /* @__PURE__ */ new Set();\n\t\tconst classifyPipeError = (error) => {\n\t\t\tif (error instanceof NativeSandboxError) return error;\n\t\t\tif (error?.code === \"EPIPE\") return new NativeSandboxError(\"exec_failed\", \"The sandbox duplex peer closed its input pipe\");\n\t\t\treturn new NativeSandboxError(\"exec_failed\", \"The sandbox duplex pipe failed\");\n\t\t};\n\t\tconst deliverError = (error) => {\n\t\t\tif (firstError) return;\n\t\t\tfirstError = classifyPipeError(error);\n\t\t\tfor (const listener of [...errorListeners]) try {\n\t\t\t\tlistener(firstError);\n\t\t\t} catch {}\n\t\t};\n\t\tchild.on(\"error\", deliverError);\n\t\tchild.stdin.on(\"error\", deliverError);\n\t\tchild.stdout.on(\"error\", deliverError);\n\t\tchild.stderr.on(\"error\", deliverError);\n\t\tlet pipe;\n\t\treturn {\n\t\t\tasStream() {\n\t\t\t\tconst fromStreams = Duplex.from;\n\t\t\t\tpipe ??= fromStreams({\n\t\t\t\t\treadable: child.stdout,\n\t\t\t\t\twritable: child.stdin\n\t\t\t\t});\n\t\t\t\treturn pipe;\n\t\t\t},\n\t\t\twrite(chunk) {\n\t\t\t\tif (child.stdin.destroyed) return;\n\t\t\t\ttry {\n\t\t\t\t\tchild.stdin.write(Buffer.from(chunk));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tdeliverError(error);\n\t\t\t\t}\n\t\t\t},\n\t\t\tend() {\n\t\t\t\tif (child.stdin.destroyed) return;\n\t\t\t\ttry {\n\t\t\t\t\tchild.stdin.end();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tdeliverError(error);\n\t\t\t\t}\n\t\t\t},\n\t\t\tkill(signal = \"SIGTERM\") {\n\t\t\t\ttry {\n\t\t\t\t\tchild.kill(signal);\n\t\t\t\t} catch {}\n\t\t\t},\n\t\t\tonData(listener) {\n\t\t\t\tchild.stdout.on(\"data\", listener);\n\t\t\t\treturn () => child.stdout.off(\"data\", listener);\n\t\t\t},\n\t\t\tonStderr(listener) {\n\t\t\t\tchild.stderr.on(\"data\", listener);\n\t\t\t\treturn () => child.stderr.off(\"data\", listener);\n\t\t\t},\n\t\t\tonError(listener) {\n\t\t\t\terrorListeners.add(listener);\n\t\t\t\tif (firstError) listener(firstError);\n\t\t\t\treturn () => errorListeners.delete(listener);\n\t\t\t},\n\t\t\tonExit(listener) {\n\t\t\t\tchild.once(\"close\", listener);\n\t\t\t\treturn () => child.off(\"close\", listener);\n\t\t\t}\n\t\t};\n\t}\n\t/**\n\t* Teardown/cancellation path: `delete --force`, and deletion must succeed — a failure is an\n\t* error, never a swallowed warning, because an alive sandbox is an alive untrusted workload.\n\t*/\n\tasync destroy(options = {}) {\n\t\tconst attempts = options.attempts ?? 3;\n\t\tfor (let attempt = 1; attempt <= attempts; attempt += 1) {\n\t\t\tconst [command, ...args] = buildSandboxDeleteArgv({\n\t\t\t\tname: this.#name,\n\t\t\t\tsandboxBinary: this.#binary\n\t\t\t});\n\t\t\tif ((await this.#runToExit(command, args, { timeoutMs: 3e4 })).code === 0) {\n\t\t\t\tthis.#sandboxAlive = false;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.#removeResolverSnapshot();\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new NativeSandboxError(\"delete_failed\", \"Native sandbox was deleted but its private resolver copy could not be removed\");\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (attempt < attempts) await this.#sleep(1e3 * attempt);\n\t\t}\n\t\tthrow new NativeSandboxError(\"delete_failed\", `Sandbox deletion failed after ${attempts} attempts`);\n\t}\n\t#runToExit(command, args, options) {\n\t\tif (options.signal?.aborted) return Promise.reject(new NativeSandboxError(\"exec_failed\", \"Sandbox execution cancelled before spawn\"));\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet child;\n\t\t\ttry {\n\t\t\t\tchild = this.#spawn(command, args, { env: { PATH: \"/usr/local/bin:/usr/bin:/bin\" } });\n\t\t\t} catch (error) {\n\t\t\t\treject(classifySpawnError(error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst stdout = [], stderr = [];\n\t\t\tlet stdoutBytes = 0, stderrBytes = 0;\n\t\t\tlet failure;\n\t\t\tlet settled = false;\n\t\t\tlet escalation;\n\t\t\tconst finish = (code) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tclearTimeout(escalation);\n\t\t\t\toptions.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tif (failure) reject(failure);\n\t\t\t\telse resolve({\n\t\t\t\t\tcode,\n\t\t\t\t\tstdout: Buffer.concat(stdout).toString(\"utf8\"),\n\t\t\t\t\tstderr: Buffer.concat(stderr).toString(\"utf8\")\n\t\t\t\t});\n\t\t\t};\n\t\t\tconst cancel = (message) => {\n\t\t\t\tif (settled || failure) return;\n\t\t\t\tfailure = new NativeSandboxError(\"exec_failed\", message);\n\t\t\t\tchild.kill(\"SIGTERM\");\n\t\t\t\tescalation = setTimeout(() => {\n\t\t\t\t\tif (!settled) child.kill(\"SIGKILL\");\n\t\t\t\t}, 2e3);\n\t\t\t};\n\t\t\tconst onAbort = () => cancel(\"Sandbox execution cancelled\");\n\t\t\tconst timer = setTimeout(() => cancel(\"Sandbox execution deadline exceeded\"), options.timeoutMs);\n\t\t\tchild.once(\"error\", (error) => {\n\t\t\t\tfailure = classifySpawnError(error);\n\t\t\t\tfinish(-1);\n\t\t\t});\n\t\t\tchild.once(\"close\", (code) => finish(code ?? -1));\n\t\t\tchild.stdout.on(\"data\", (chunk) => {\n\t\t\t\tconst kept = chunk.subarray(0, Math.max(0, CAPTURE_LIMIT_BYTES - stdoutBytes));\n\t\t\t\tif (kept.length > 0) stdout.push(Buffer.from(kept));\n\t\t\t\tstdoutBytes += kept.length;\n\t\t\t});\n\t\t\tchild.stderr.on(\"data\", (chunk) => {\n\t\t\t\tconst kept = chunk.subarray(0, Math.max(0, CAPTURE_LIMIT_BYTES - stderrBytes));\n\t\t\t\tif (kept.length > 0) stderr.push(Buffer.from(kept));\n\t\t\t\tstderrBytes += kept.length;\n\t\t\t});\n\t\t\tchild.stdin.on(\"error\", () => cancel(\"Sandbox worker stdin failed\"));\n\t\t\toptions.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tif (options.signal?.aborted) onAbort();\n\t\t\tif (options.stdin !== void 0) child.stdin.write(options.stdin);\n\t\t\tchild.stdin.end();\n\t\t});\n\t}\n};\nconst STARTUP_TIMEOUT_MS = 1e4;\nconst SHUTDOWN_TIMEOUT_MS = 2e3;\n/**\n* Native helper: two Sandbox-local TCP entries multiplexed over sandbox exec stdio. HTTP/2\n* runs only on the pipe; there is no parent network listener. CONNECT authorities are fixed\n* target enums, never addresses. EOF/termination removes both entries with the process.\n*/\nconst NATIVE_PROVIDER_BRIDGE_SOURCE = `\n\"use strict\";\nconst http2 = require(\"node:http2\");\nconst net = require(\"node:net\");\nconst { Duplex } = require(\"node:stream\");\nconst ports = process.argv.slice(1).map(Number);\nif (ports.length !== 2 || ports.some(p => !Number.isInteger(p) || p < 1 || p > 65535)) process.exit(2);\nconst clients = new Set();\nconst servers = [];\nlet closing = false;\nconst shutdown = code => {\n  if (closing) return;\n  closing = true;\n  for (const server of servers) server.close();\n  for (const client of clients) client.destroy();\n  process.exit(code);\n};\nconst session = http2.connect(\"http://native-provider\", {\n  createConnection: () => Duplex.from({ readable: process.stdin, writable: process.stdout }),\n  maxSessionMemory: 4,\n  maxHeaderListPairs: 8,\n});\nsession.on(\"error\", () => shutdown(3));\nsession.on(\"close\", () => shutdown(0));\nprocess.stdin.on(\"end\", () => shutdown(0));\nprocess.stdin.on(\"error\", () => shutdown(3));\nprocess.stdout.on(\"error\", () => shutdown(3));\nprocess.on(\"SIGTERM\", () => shutdown(0));\nprocess.on(\"SIGINT\", () => shutdown(0));\nconst listen = (port, target) => new Promise((resolve, reject) => {\n  const server = net.createServer({ allowHalfOpen: true }, client => {\n    if (closing || clients.size >= 64) { client.destroy(); return; }\n    clients.add(client);\n    let stream;\n    try { stream = session.request({ \":method\": \"CONNECT\", \":authority\": target }); }\n    catch { clients.delete(client); client.destroy(); return; }\n    client.on(\"error\", () => stream.close(http2.constants.NGHTTP2_CANCEL));\n    client.on(\"close\", () => { clients.delete(client); stream.close(http2.constants.NGHTTP2_CANCEL); });\n    stream.on(\"error\", () => client.destroy());\n    stream.on(\"aborted\", () => client.destroy());\n    stream.on(\"response\", headers => {\n      if (headers[\":status\"] !== 200) client.destroy();\n    });\n    // pipe preserves backpressure and sends FIN after queued data. Do not destroy on EOF.\n    client.pipe(stream);\n    stream.pipe(client);\n  });\n  servers.push(server);\n  server.once(\"error\", reject);\n  server.listen(port, \"127.0.0.1\", () => {\n    server.removeListener(\"error\", reject);\n    server.on(\"error\", () => shutdown(3));\n    resolve();\n  });\n});\nPromise.all([listen(ports[0], \"connect\"), listen(ports[1], \"slack\")]).then(() => {\n  const ready = session.request({ \":path\": \"/ready\" });\n  ready.on(\"error\", () => shutdown(3));\n  ready.on(\"response\", headers => { if (headers[\":status\"] !== 204) shutdown(3); });\n  ready.resume();\n  ready.end();\n}, () => shutdown(2));\n`;\n/** One execution owns the child, its HTTP/2 session and all adapter connections. No replay. */\nvar NativeProviderBridge = class NativeProviderBridge {\n\t#duplex;\n\t#targets;\n\t#sockets = /* @__PURE__ */ new Set();\n\t#abort = new AbortController();\n\t#resolveReady;\n\t#rejectReady;\n\t#ready = new Promise((resolve, reject) => {\n\t\tthis.#resolveReady = resolve;\n\t\tthis.#rejectReady = reject;\n\t});\n\t#resolveExit;\n\t#exit = new Promise((resolve) => {\n\t\tthis.#resolveExit = resolve;\n\t});\n\t#failure;\n\t#readySeen = false;\n\t#exited = false;\n\t#closing = false;\n\t#closePromise;\n\t#unsubscribeAbort;\n\tconstructor(duplex, targets) {\n\t\tthis.#duplex = duplex;\n\t\tthis.#targets = targets;\n\t\tduplex.onExit(() => {\n\t\t\tthis.#exited = true;\n\t\t\tthis.#resolveExit();\n\t\t\tif (!this.#closing) this.#fail(\"The native provider bridge exited unexpectedly\");\n\t\t});\n\t\tduplex.onError(() => this.#fail(\"The native provider bridge pipe failed\"));\n\t\tduplex.onStderr(() => void 0);\n\t\tconst server = createServer$2({\n\t\t\tmaxSessionMemory: 4,\n\t\t\tmaxHeaderListPairs: 8,\n\t\t\tsettings: { maxConcurrentStreams: 64 }\n\t\t});\n\t\tserver.on(\"session\", (session) => {\n\t\t\tsession.on(\"error\", () => this.#fail(\"The native provider bridge session failed\"));\n\t\t\tsession.on(\"close\", () => {\n\t\t\t\tif (!this.#closing) this.#fail(\"The native provider bridge session closed unexpectedly\");\n\t\t\t});\n\t\t});\n\t\tserver.on(\"sessionError\", () => this.#fail(\"The native provider bridge protocol failed\"));\n\t\tserver.on(\"error\", () => this.#fail(\"The native provider bridge failed\"));\n\t\tserver.on(\"stream\", (stream, headers) => {\n\t\t\tstream.on(\"error\", () => void 0);\n\t\t\tif (this.#closing) {\n\t\t\t\tstream.close(constants$1.NGHTTP2_CANCEL);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (headers[\":method\"] === \"GET\" && headers[\":path\"] === \"/ready\" && !this.#readySeen) {\n\t\t\t\tthis.#readySeen = true;\n\t\t\t\tstream.respond({ \":status\": 204 });\n\t\t\t\tstream.end();\n\t\t\t\tthis.#resolveReady();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst target = headers[\":authority\"];\n\t\t\tif (!this.#readySeen || headers[\":method\"] !== \"CONNECT\" || target !== \"connect\" && target !== \"slack\" || this.#sockets.size >= 64) {\n\t\t\t\tstream.close(constants$1.NGHTTP2_REFUSED_STREAM);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#connect(stream, this.#targets[target]);\n\t\t});\n\t\tserver.emit(\"connection\", duplex.asStream());\n\t}\n\tstatic async open(input) {\n\t\tinput.signal?.throwIfAborted();\n\t\tconst ports = input.entryPorts ?? {\n\t\t\tconnect: 18080,\n\t\t\tslack: 18443\n\t\t};\n\t\tfor (const port of [\n\t\t\tinput.targets.connect,\n\t\t\tinput.targets.slack,\n\t\t\tports.connect,\n\t\t\tports.slack\n\t\t]) if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(\"Invalid native provider bridge port\");\n\t\tconst duplex = input.sandbox.openDuplex(SANDBOX_NODE, [\n\t\t\t\"-e\",\n\t\t\tNATIVE_PROVIDER_BRIDGE_SOURCE,\n\t\t\tString(ports.connect),\n\t\t\tString(ports.slack)\n\t\t]);\n\t\tconst bridge = new NativeProviderBridge(duplex, input.targets);\n\t\tconst abort = () => {\n\t\t\tbridge.close().catch(() => void 0);\n\t\t};\n\t\tinput.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\tbridge.#unsubscribeAbort = () => input.signal?.removeEventListener(\"abort\", abort);\n\t\tlet timer;\n\t\ttry {\n\t\t\tif (input.signal?.aborted) abort();\n\t\t\tawait Promise.race([bridge.#ready, new Promise((_, reject) => {\n\t\t\t\ttimer = setTimeout(() => reject(/* @__PURE__ */ new Error(\"The native provider bridge did not become ready\")), input.startupTimeoutMs ?? STARTUP_TIMEOUT_MS);\n\t\t\t})]);\n\t\t\tinput.signal?.throwIfAborted();\n\t\t\tif (bridge.#failure || bridge.#closing) throw bridge.#failure ?? /* @__PURE__ */ new Error(\"The native provider bridge closed during startup\");\n\t\t\treturn bridge;\n\t\t} catch (error) {\n\t\t\tawait bridge.close();\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t\tif (bridge.#closing) bridge.#unsubscribeAbort?.();\n\t\t}\n\t}\n\tget failure() {\n\t\treturn this.#failure;\n\t}\n\tget failureSignal() {\n\t\treturn this.#abort.signal;\n\t}\n\tget closed() {\n\t\treturn this.#closing;\n\t}\n\t/** Observed exec process exit. close() also rejects forced supervisor termination. */\n\tget whenClosed() {\n\t\treturn this.#exit;\n\t}\n\t#connect(stream, port) {\n\t\tconst socket = connect$1({\n\t\t\thost: \"127.0.0.1\",\n\t\t\tport,\n\t\t\tallowHalfOpen: true\n\t\t});\n\t\tthis.#sockets.add(socket);\n\t\tsocket.on(\"connect\", () => {\n\t\t\tif (stream.destroyed || this.#closing) {\n\t\t\t\tsocket.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstream.respond({ \":status\": 200 });\n\t\t\tstream.pipe(socket);\n\t\t\tsocket.pipe(stream);\n\t\t});\n\t\tsocket.on(\"error\", () => stream.close(constants$1.NGHTTP2_CONNECT_ERROR));\n\t\tsocket.on(\"close\", (hadError) => {\n\t\t\tthis.#sockets.delete(socket);\n\t\t\tif (hadError) stream.close(constants$1.NGHTTP2_CONNECT_ERROR);\n\t\t});\n\t\tstream.on(\"aborted\", () => socket.destroy());\n\t\tstream.on(\"close\", () => socket.destroy());\n\t}\n\t#fail(message) {\n\t\tif (this.#closing || this.#failure) return;\n\t\tthis.#failure = new NativeSandboxError(\"exec_failed\", message);\n\t\tthis.#rejectReady(this.#failure);\n\t\tthis.#abort.abort(this.#failure);\n\t\tthis.close().catch(() => void 0);\n\t}\n\tclose() {\n\t\tthis.#closePromise ??= this.#close();\n\t\treturn this.#closePromise;\n\t}\n\tasync #close() {\n\t\tthis.#closing = true;\n\t\tthis.#unsubscribeAbort?.();\n\t\tthis.#rejectReady(/* @__PURE__ */ new Error(\"The native provider bridge closed before ready\"));\n\t\tfor (const socket of this.#sockets) socket.destroy();\n\t\tthis.#sockets.clear();\n\t\tthis.#duplex.asStream().destroy();\n\t\tif (await this.#waitForExit()) return;\n\t\tthis.#duplex.kill(\"SIGKILL\");\n\t\tawait this.#waitForExit();\n\t\tthrow new NativeSandboxError(\"delete_failed\", \"The native provider bridge helper termination was not confirmed\");\n\t}\n\tasync #waitForExit() {\n\t\tif (this.#exited) return true;\n\t\tlet timer;\n\t\ttry {\n\t\t\treturn await Promise.race([this.#exit.then(() => true), new Promise((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(false), SHUTDOWN_TIMEOUT_MS);\n\t\t\t})]);\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/runner/cloud-turns.ts\n/** Worker stdout is captured bounded by the native sandbox; still refuse anything larger. */\nconst CLOUD_TURN_WORKER_STDOUT_MAX_BYTES = 262144;\n/** Bounded Session queue: verified entries beyond this wait at `received` for re-verification. */\nconst CLOUD_TURN_MAX_QUEUED = 64;\n/**\n* Bounded grace on top of the persisted runtime budget for the native exec backstop, so the\n* in-sandbox worker's own deadline reports `turn_timeout` before the parent kills the wrapper.\n*/\nconst CLOUD_TURN_EXEC_TIMEOUT_GRACE_MS = 5e3;\n/** Strict validation of the in-sandbox worker completion before it can become a durable report. */\nconst CloudTurnCompletionSchema = z.object({\n\terrorReason: TurnFailureReasonSchema.optional(),\n\texecutionEffects: z.enum([\n\t\t\"completed\",\n\t\t\"may_have_occurred\",\n\t\t\"not_started\"\n\t]),\n\tfinalText: z.string().optional(),\n\toutcome: z.enum([\n\t\t\"completed\",\n\t\t\"failed\",\n\t\t\"cancelled\",\n\t\t\"unknown\"\n\t]),\n\tusage: RuntimeUsageSchema.optional()\n}).strict().superRefine((value, context) => {\n\tif (value.outcome === \"completed\" && value.errorReason) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"errorReason\"],\n\t\tmessage: \"Completed results cannot include an error\"\n\t});\n\tif (value.outcome !== \"completed\" && !value.errorReason) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"errorReason\"],\n\t\tmessage: \"Non-completed results require an error\"\n\t});\n\tif (value.finalText !== void 0 && utf8Length(value.finalText) > RUNTIME_FINAL_TEXT_MAX_BYTES) context.addIssue({\n\t\tcode: \"custom\",\n\t\tpath: [\"finalText\"],\n\t\tmessage: \"Final text exceeds the report bound\"\n\t});\n});\nconst UNKNOWN_COMPLETION = {\n\terrorReason: \"turn_state_unknown\",\n\texecutionEffects: \"may_have_occurred\",\n\toutcome: \"unknown\"\n};\nvar CloudTurnRunner = class {\n\t#options;\n\t#cancelRequested = /* @__PURE__ */ new Set();\n\t/** Verified entries waiting for the single Session-serial turn slot, keyed by request id. */\n\t#queue = /* @__PURE__ */ new Map();\n\t/** Monotonic control-channel generation; a close invalidates queued connection-scoped grants. */\n\t#channelGeneration = 0;\n\t#active;\n\t#closed = false;\n\t/**\n\t* Set for an interrupted Turn until its immediate verified cleanup succeeds. The next start\n\t* also checks it, so no delivery can ever observe a dirty namespace between turns.\n\t*/\n\t#needsSandboxReset = false;\n\t/** Set when native cleanup itself failed: the runner never starts another Cloud Turn. */\n\t#sandboxUnusable = false;\n\t#resetInFlight;\n\t/** Serializes control-state mutations only; the worker itself runs outside the queue. */\n\t#serial = Promise.resolve();\n\t#journalListeners = /* @__PURE__ */ new Set();\n\tconstructor(options) {\n\t\tthis.#options = options;\n\t}\n\tget activeDeliveryId() {\n\t\treturn this.#active?.kind === \"delivery\" ? this.#active.entryKey : void 0;\n\t}\n\tget activeMessageId() {\n\t\treturn this.#active?.kind === \"session-message\" ? this.#active.entryKey : void 0;\n\t}\n\tasync waitForActive() {\n\t\tawait this.#active?.settled;\n\t}\n\t/** True while a turn is running or verified work waits for the single turn slot. */\n\tget hasPendingWork() {\n\t\treturn this.#active !== void 0 || this.#queue.size > 0 || this.#needsSandboxReset || this.#sandboxUnusable;\n\t}\n\t/** True after a non-completed turn until the native namespace was verified clean again. */\n\tget needsSandboxReset() {\n\t\treturn this.#needsSandboxReset;\n\t}\n\t/** The occupation boundary reopened (e.g. native acceptance cleanup finished). */\n\tnotifyAvailable() {\n\t\tthis.#scheduleDrain();\n\t}\n\t/** Journal + fsync the input, THEN acknowledge receipt. Idempotent across duplicate dispatch. */\n\tasync handleDeliveryRun(frame) {\n\t\tawait this.#enqueue(async () => {\n\t\t\tif (this.#closed) return;\n\t\t\tconst delivery = frame.delivery;\n\t\t\tconst scope = this.#options.scope();\n\t\t\tif (!scope || delivery.sessionId !== scope.sessionId) {\n\t\t\t\tthis.#log(\"ignoring delivery:run outside the current Session scope\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst journalScope = this.#requireJournalScope();\n\t\t\tconst existing = await this.#options.journal.read(delivery.deliveryId);\n\t\t\tconst reusable = this.#reuseDeliveryEntry(existing, delivery, journalScope);\n\t\t\tif (existing && !reusable) return;\n\t\t\tconst entry = reusable ?? await this.#options.journal.recordReceived({\n\t\t\t\tdelivery,\n\t\t\t\tscope: journalScope,\n\t\t\t\tdeliveryId: delivery.deliveryId,\n\t\t\t\trequestId: delivery.requestId,\n\t\t\t\tturnId: randomUUID()\n\t\t\t});\n\t\t\tthis.#send({\n\t\t\t\ttype: \"delivery:received\",\n\t\t\t\tdeliveryId: entry.deliveryId,\n\t\t\t\trequestId: entry.requestId,\n\t\t\t\tturnId: entry.turnId\n\t\t\t});\n\t\t});\n\t}\n\t/** Reuse one already-journaled delivery, or undefined when the re-dispatch must be refused. */\n\t#reuseDeliveryEntry(existing, delivery, journalScope) {\n\t\tif (!existing) return void 0;\n\t\tif (existing.kind !== \"delivery\") {\n\t\t\tthis.#log(`refusing re-dispatch of ${delivery.deliveryId}: journal key belongs to a Session message`);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tassertCloudJournalScope(existing, journalScope);\n\t\t} catch {\n\t\t\tthis.#log(`refusing re-dispatch of ${delivery.deliveryId}: journaled under another allocation`);\n\t\t\treturn;\n\t\t}\n\t\tif (existing.requestId !== delivery.requestId || existing.inputHash !== computeCloudDeliveryInputHash(delivery)) {\n\t\t\tthis.#log(`refusing re-dispatch of ${delivery.deliveryId}: journaled dispatch identity or input differs`);\n\t\t\tthis.#reconcileSupersededReceipt(existing, delivery.requestId);\n\t\t\treturn;\n\t\t}\n\t\treturn existing;\n\t}\n\t/** Ask the Server to retire an expired old receipt before its replacement can be admitted. */\n\t#reconcileSupersededReceipt(entry, requestId) {\n\t\tif (entry.phase === \"received\" && entry.requestId !== requestId) this.#sendReceipt(entry);\n\t}\n\t/** Server persisted durable custody: execution may start (the model grant rides along). */\n\tasync handleVerified(frame) {\n\t\tconst generation = this.#channelGeneration;\n\t\tawait this.#enqueue(async () => {\n\t\t\tconst entry = await this.#entryByRequestId(frame.requestId);\n\t\t\tif (entry?.kind !== \"delivery\") return;\n\t\t\tif (generation !== this.#channelGeneration) {\n\t\t\t\tthis.#log(`ignoring delivery ${entry.deliveryId} verified on a closed channel generation`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (frame.status === \"rejected\") {\n\t\t\t\tif (entry.phase === \"received\") {\n\t\t\t\t\tawait this.#options.journal.clearRejected(entry.deliveryId, entry.scope);\n\t\t\t\t\tthis.#notifyJournalChanged();\n\t\t\t\t} else this.#log(`ignoring rejected receipt for ${entry.deliveryId} in phase ${entry.phase}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (entry.phase !== \"received\") return;\n\t\t\tif (this.#closed || this.#cancelRequested.delete(entry.deliveryId)) {\n\t\t\t\tawait this.#reportTerminal(entry, cancelledBeforeStart());\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst denial = this.#admit(entry.delivery, frame);\n\t\t\tif (denial) {\n\t\t\t\tawait this.#reportTerminal(entry, denial.completion);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.#queueVerified(entry, frame, generation);\n\t\t});\n\t}\n\t/** Journal + fsync one Session message, THEN acknowledge receipt. Idempotent across redispatch. */\n\tasync handleSessionMessageRun(frame) {\n\t\tawait this.#enqueue(async () => {\n\t\t\tif (this.#closed) return;\n\t\t\tconst message = frame.message;\n\t\t\tconst scope = this.#options.scope();\n\t\t\tif (!scope || message.targetSessionId !== scope.sessionId) {\n\t\t\t\tthis.#log(\"ignoring session:message:run outside the current Session scope\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst entry = await this.#journalSessionDispatch(frame, this.#requireJournalScope());\n\t\t\tif (!entry) return;\n\t\t\tif (entry.phase === \"reported\") {\n\t\t\t\tthis.#sendSessionSettled(entry);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#send({\n\t\t\t\ttype: \"session:message:received\",\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tmessageId: entry.messageId,\n\t\t\t\tturnId: entry.turnId,\n\t\t\t\tstatus: \"accepted\",\n\t\t\t\tphase: entry.phase === \"started\" ? \"started\" : \"received\"\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* Journal (or reuse) the entry for one Session run frame; undefined when the dispatch is\n\t* refused. Every write is fsynced before the caller may send the receipt.\n\t*/\n\tasync #journalSessionDispatch(frame, journalScope) {\n\t\tconst message = frame.message;\n\t\tconst existing = await this.#options.journal.read(message.messageId);\n\t\tconst decision = this.#sessionDispatchDecision(existing, frame, journalScope);\n\t\tif (decision.kind === \"refuse\") return void 0;\n\t\tif (decision.kind === \"reuse\") return decision.entry;\n\t\tif (decision.kind === \"rekey\") return this.#options.journal.updateSessionRequestId(message.messageId, journalScope, frame.requestId);\n\t\tconst input = {\n\t\t\tmessage,\n\t\t\tsessionKind: frame.sessionKind,\n\t\t\t...frame.outboxContext ? { outboxContext: frame.outboxContext } : {},\n\t\t\tscope: journalScope,\n\t\t\trequestId: frame.requestId,\n\t\t\tturnId: randomUUID()\n\t\t};\n\t\treturn decision.kind === \"replace\" ? this.#options.journal.replaceSessionReceived(input) : this.#options.journal.recordSessionReceived(input);\n\t}\n\t/**\n\t* How one Session run frame relates to the journaled entry, if any. The request id is the\n\t* per-attempt identity and the input hash ignores it, so a retry of the same logical message\n\t* reuses its entry, a changed snapshot supersedes a never-started entry, and any started or\n\t* reported entry is left to converge through its own settlement — never a second execution.\n\t*/\n\t#sessionDispatchDecision(existing, frame, journalScope) {\n\t\tconst messageId = frame.message.messageId;\n\t\tif (!existing) return { kind: \"fresh\" };\n\t\tif (existing.kind !== \"session-message\") {\n\t\t\tthis.#log(`refusing re-dispatch of ${messageId}: journal key belongs to a delivery`);\n\t\t\treturn { kind: \"refuse\" };\n\t\t}\n\t\ttry {\n\t\t\tassertCloudJournalScope(existing, journalScope);\n\t\t} catch {\n\t\t\tthis.#log(`refusing re-dispatch of ${messageId}: journaled under another allocation`);\n\t\t\treturn { kind: \"refuse\" };\n\t\t}\n\t\tconst sameAttempt = existing.requestId === frame.requestId;\n\t\tconst sameInput = existing.inputHash === computeCloudSessionInputHash(frame);\n\t\tif (sameAttempt && !sameInput) {\n\t\t\tthis.#log(`refusing re-dispatch of ${messageId}: journaled input differs for the same dispatch`);\n\t\t\treturn { kind: \"refuse\" };\n\t\t}\n\t\tif (sameInput) return existing.phase === \"received\" ? {\n\t\t\tkind: \"rekey\",\n\t\t\tentry: existing\n\t\t} : {\n\t\t\tkind: \"reuse\",\n\t\t\tentry: existing\n\t\t};\n\t\tif (existing.phase === \"received\") return { kind: \"replace\" };\n\t\tthis.#log(`refusing re-dispatch of ${messageId}: a ${existing.phase} entry with changed input settles through its own path`);\n\t\treturn { kind: \"refuse\" };\n\t}\n\t/** Server persisted durable custody for one Session message: execution may start. */\n\tasync handleSessionMessageVerified(frame) {\n\t\tconst generation = this.#channelGeneration;\n\t\tawait this.#enqueue(async () => {\n\t\t\tconst entry = await this.#entryByRequestId(frame.requestId);\n\t\t\tif (entry?.kind !== \"session-message\") return;\n\t\t\tif (generation !== this.#channelGeneration) {\n\t\t\t\tthis.#log(`ignoring Session message ${entry.messageId} verified on a closed channel generation`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (frame.status === \"rejected\") {\n\t\t\t\tif (entry.phase === \"received\") {\n\t\t\t\t\tawait this.#options.journal.clearSessionRejected(entry.messageId, entry.scope);\n\t\t\t\t\tthis.#notifyJournalChanged();\n\t\t\t\t} else this.#log(`ignoring rejected receipt for Session message ${entry.messageId} in phase ${entry.phase}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (entry.phase !== \"received\") return;\n\t\t\tif (this.#closed || this.#cancelRequested.delete(entry.messageId)) {\n\t\t\t\tawait this.#settleSessionTerminal(entry, \"cancelled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst denial = this.#admitSession(frame);\n\t\t\tif (denial) {\n\t\t\t\tawait this.#settleSessionTerminal(entry, denial);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.#queueSessionVerified(entry, frame, generation);\n\t\t});\n\t}\n\t/**\n\t* Queue a verified frame in FIFO order, then drain: a later verification can never overtake an\n\t* earlier queued entry. When this frame is the head and the slot is free, start it before\n\t* resolving (the established frame contract); otherwise a serialized drain picks it up in order.\n\t*/\n\tasync #queueVerified(entry, frame, generation) {\n\t\tif (this.#queue.size >= CLOUD_TURN_MAX_QUEUED) {\n\t\t\tthis.#log(`cloud turn queue is full; leaving ${entry.deliveryId} at the received boundary for re-verification`);\n\t\t\treturn;\n\t\t}\n\t\tconst queued = {\n\t\t\tkind: \"delivery\",\n\t\t\tdeliveryId: entry.deliveryId,\n\t\t\tframe: {\n\t\t\t\t...frame,\n\t\t\t\tmodel: frame.model\n\t\t\t},\n\t\t\tgeneration\n\t\t};\n\t\tthis.#queue.set(entry.requestId, queued);\n\t\tif (!this.#active && this.#queue.keys().next().value === entry.requestId) {\n\t\t\tawait this.#processQueued(queued);\n\t\t\treturn;\n\t\t}\n\t\tthis.#scheduleDrain();\n\t}\n\tasync #queueSessionVerified(entry, frame, generation) {\n\t\tif (this.#queue.size >= CLOUD_TURN_MAX_QUEUED) {\n\t\t\tthis.#log(`cloud turn queue is full; leaving ${entry.messageId} at the received boundary for re-verification`);\n\t\t\treturn;\n\t\t}\n\t\tconst queued = {\n\t\t\tkind: \"session-message\",\n\t\t\tmessageId: entry.messageId,\n\t\t\tframe: { ...frame },\n\t\t\tgeneration\n\t\t};\n\t\tthis.#queue.set(entry.requestId, queued);\n\t\tif (!this.#active && this.#queue.keys().next().value === entry.requestId) {\n\t\t\tawait this.#processQueued(queued);\n\t\t\treturn;\n\t\t}\n\t\tthis.#scheduleDrain();\n\t}\n\t/**\n\t* Explicit stop. An owned in-sandbox worker is aborted immediately; a not-yet-started entry\n\t* settles durably as a not-started cancellation instead of silently disappearing.\n\t*/\n\thandleCancel(deliveryId) {\n\t\tthis.#cancelEntry(\"delivery\", deliveryId);\n\t}\n\t/** Explicit stop of one journaled Session message (same FIFO slot and cancellation semantics). */\n\thandleSessionMessageCancel(messageId) {\n\t\tthis.#cancelEntry(\"session-message\", messageId);\n\t}\n\t#cancelEntry(kind, entryKey) {\n\t\tconst active = this.#active;\n\t\tif (active?.kind === kind && active.entryKey === entryKey) {\n\t\t\tactive.abort.abort();\n\t\t\treturn;\n\t\t}\n\t\tfor (const [requestId, queued] of this.#queue) {\n\t\t\tif (queued.kind !== kind) continue;\n\t\t\tif ((queued.kind === \"delivery\" ? queued.deliveryId : queued.messageId) === entryKey) this.#queue.delete(requestId);\n\t\t}\n\t\tthis.#cancelRequested.add(entryKey);\n\t\tthis.#enqueue(async () => {\n\t\t\tif (!this.#cancelRequested.delete(entryKey)) return;\n\t\t\tconst entry = await this.#options.journal.read(entryKey);\n\t\t\tif (!entry || entry.kind !== kind) return;\n\t\t\tthis.#assertCurrentScope(entry);\n\t\t\tif (entry.phase !== \"received\") return;\n\t\t\tif (entry.kind === \"delivery\") await this.#reportTerminal(entry, cancelledBeforeStart());\n\t\t\telse await this.#settleSessionTerminal(entry, \"cancelled\");\n\t\t}).catch((error) => this.#reportPersistenceError(error));\n\t}\n\t/** The Server durably recorded (or definitively refused) the report: retire the entry. */\n\tasync handleReportAck(frame) {\n\t\tawait this.#enqueue(async () => {\n\t\t\tconst entry = (await this.#options.journal.list()).find((candidate) => candidate.turnId === frame.turnId);\n\t\t\tif (entry?.kind !== \"delivery\") return;\n\t\t\tthis.#assertCurrentScope(entry);\n\t\t\tif (entry.phase !== \"reported\" || !entry.report) return;\n\t\t\tif (frame.status !== \"recorded\" && frame.status !== \"already_recorded\") {\n\t\t\t\tthis.#log(`retaining durable report for ${entry.deliveryId}: ack status ${frame.status}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (entry.report.resultHash !== frame.resultHash) {\n\t\t\t\tthis.#log(`retaining durable report for ${entry.deliveryId}: ack result hash mismatch`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.#options.journal.clearAcknowledged(entry.deliveryId, entry.scope, {\n\t\t\t\tresultHash: frame.resultHash,\n\t\t\t\tstatus: frame.status,\n\t\t\t\tturnId: frame.turnId\n\t\t\t});\n\t\t\tthis.#notifyJournalChanged();\n\t\t});\n\t}\n\t/** The Server durably committed the exact Session settlement: retire the immutable entry. */\n\tasync handleSessionMessageSettledAck(frame) {\n\t\tawait this.#enqueue(async () => {\n\t\t\tconst entry = await this.#entryByRequestId(frame.requestId);\n\t\t\tif (entry?.kind !== \"session-message\") return;\n\t\t\tthis.#assertCurrentScope(entry);\n\t\t\tif (entry.phase !== \"reported\" || !entry.settlement) return;\n\t\t\tif (frame.messageId !== entry.messageId || frame.turnId !== entry.turnId) {\n\t\t\t\tthis.#log(`retaining durable settlement for ${entry.messageId}: ack identity mismatch`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait this.#options.journal.clearSessionAcknowledged(entry.messageId, entry.scope, {\n\t\t\t\tstatus: frame.status,\n\t\t\t\tturnId: frame.turnId\n\t\t\t});\n\t\t\tthis.#notifyJournalChanged();\n\t\t});\n\t}\n\t/** Answer a Server recovery query from the durable journal; re-send a journaled report. */\n\tasync handleQuery(frame) {\n\t\tawait this.#enqueue(async () => {\n\t\t\tconst entry = await this.#options.journal.read(frame.deliveryId);\n\t\t\tif (entry) this.#assertCurrentScope(entry);\n\t\t\tconst phase = !entry || entry.turnId !== frame.turnId ? \"none\" : entry.phase;\n\t\t\tthis.#send({\n\t\t\t\ttype: \"delivery:query:result\",\n\t\t\t\tdeliveryId: frame.deliveryId,\n\t\t\t\tphase,\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tturnId: frame.turnId\n\t\t\t});\n\t\t\tif (phase === \"reported\" && entry?.kind === \"delivery\" && entry.report && !this.#isCheckpointing(entry.deliveryId)) this.#send({\n\t\t\t\ttype: \"delivery:report\",\n\t\t\t\treport: entry.report,\n\t\t\t\trequestId: randomUUID()\n\t\t\t});\n\t\t});\n\t}\n\t/**\n\t* After every (re)attach: retransmit durable state. Received entries re-announce their receipt\n\t* (the Server re-verifies idempotently); reported entries re-send until acked; started entries\n\t* report unknown exactly once and never re-execute — EXCEPT while this process still owns the\n\t* live execution, in which case only the durable receipt is re-announced.\n\t*\n\t* Every entry is scope-checked BEFORE any frame is sent, so a journal reopened under another\n\t* allocation fails closed without emitting a single stale frame.\n\t*/\n\tasync reconcile() {\n\t\tawait this.#enqueue(async () => {\n\t\t\tconst scope = this.#requireJournalScope();\n\t\t\tconst entries = await this.#options.journal.list();\n\t\t\tfor (const entry of entries) assertCloudJournalScope(entry, scope);\n\t\t\tfor (const entry of entries) await this.#reconcileEntry(entry);\n\t\t});\n\t}\n\tasync #reconcileEntry(entry) {\n\t\tif (entry.kind === \"session-message\") {\n\t\t\tawait this.#reconcileSessionEntry(entry);\n\t\t\treturn;\n\t\t}\n\t\tif (entry.phase === \"received\") {\n\t\t\tthis.#sendReceipt(entry);\n\t\t\treturn;\n\t\t}\n\t\tif (entry.phase === \"reported\" && entry.report) {\n\t\t\tif (this.#isCheckpointing(entry.deliveryId)) return;\n\t\t\tthis.#send({\n\t\t\t\ttype: \"delivery:report\",\n\t\t\t\treport: entry.report,\n\t\t\t\trequestId: randomUUID()\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (entry.phase !== \"started\") return;\n\t\tif (this.#active?.kind === \"delivery\" && this.#active.entryKey === entry.deliveryId) {\n\t\t\tthis.#sendReceipt(entry);\n\t\t\treturn;\n\t\t}\n\t\tawait this.#reportTerminal(entry, UNKNOWN_COMPLETION);\n\t}\n\tasync #reconcileSessionEntry(entry) {\n\t\tif (entry.phase === \"received\") {\n\t\t\tthis.#sendSessionProgress(entry);\n\t\t\treturn;\n\t\t}\n\t\tif (entry.phase === \"reported\") {\n\t\t\tthis.#sendSessionSettled(entry);\n\t\t\treturn;\n\t\t}\n\t\tif (this.#active?.kind === \"session-message\" && this.#active.entryKey === entry.messageId) {\n\t\t\tthis.#sendSessionProgress(entry);\n\t\t\treturn;\n\t\t}\n\t\tawait this.#settleSessionTerminal(entry, \"unknown\");\n\t}\n\t#isCheckpointing(deliveryId) {\n\t\treturn this.#options.checkpoint !== void 0 && this.#active?.kind === \"delivery\" && this.#active.entryKey === deliveryId;\n\t}\n\t#sendReceipt(entry) {\n\t\tthis.#send({\n\t\t\ttype: \"delivery:received\",\n\t\t\tdeliveryId: entry.deliveryId,\n\t\t\trequestId: entry.requestId,\n\t\t\tturnId: entry.turnId\n\t\t});\n\t}\n\t/** Re-announce one Session entry: its receipt, or its immutable terminal settlement. */\n\t#sendSessionProgress(entry) {\n\t\tif (entry.phase === \"reported\") {\n\t\t\tthis.#sendSessionSettled(entry);\n\t\t\treturn;\n\t\t}\n\t\tthis.#send({\n\t\t\ttype: \"session:message:received\",\n\t\t\trequestId: entry.requestId,\n\t\t\tmessageId: entry.messageId,\n\t\t\tturnId: entry.turnId,\n\t\t\tstatus: \"accepted\",\n\t\t\tphase: entry.phase === \"started\" ? \"started\" : \"received\"\n\t\t});\n\t}\n\t#sendSessionSettled(entry) {\n\t\tif (!entry.settlement) return;\n\t\tthis.#send({\n\t\t\ttype: \"session:message:settled\",\n\t\t\trequestId: entry.requestId,\n\t\t\tmessageId: entry.messageId,\n\t\t\tturnId: entry.turnId,\n\t\t\toutcome: entry.settlement.outcome\n\t\t});\n\t}\n\t/**\n\t* The control channel dropped. Connection-scoped grants are revoked by the Server with it, so\n\t* queued verified frames must never start afterwards; the journaled `received` entries are\n\t* re-announced by reconcile and re-verified with fresh grants. A live execution is not aborted\n\t* here (its report stays journaled and honest); only a full process restart reports `unknown`.\n\t*/\n\tonChannelClosed() {\n\t\tthis.#channelGeneration += 1;\n\t\tconst dropped = this.#queue.size;\n\t\tthis.#queue.clear();\n\t\tif (dropped > 0) this.#log(`dropped ${dropped} queued delivery grant(s) from the closed channel generation`);\n\t}\n\tasync close() {\n\t\tthis.#closed = true;\n\t\tthis.#active?.abort.abort();\n\t\tawait this.#active?.settled;\n\t\tawait this.#serial.catch(() => void 0);\n\t}\n\t/**\n\t* Quiesce execution and wait for durable Server report acknowledgments before the parent\n\t* seals storage. This wait never holds the control queue that must receive those acks.\n\t*/\n\tasync drainForRelease(timeoutMs) {\n\t\tawait this.close();\n\t\tconst deadline = Date.now() + timeoutMs;\n\t\tfor (;;) {\n\t\t\tlet notify = () => void 0;\n\t\t\tconst changed = new Promise((resolveChanged) => {\n\t\t\t\tnotify = resolveChanged;\n\t\t\t});\n\t\t\tthis.#journalListeners.add(notify);\n\t\t\tlet timer;\n\t\t\ttry {\n\t\t\t\tif (await this.#enqueue(async () => {\n\t\t\t\t\tconst entries = await this.#options.journal.list();\n\t\t\t\t\tfor (const entry of entries) await this.#drainReleaseEntry(entry);\n\t\t\t\t\treturn entries.length;\n\t\t\t\t}) === 0) return;\n\t\t\t\tconst waitMs = deadline - Date.now();\n\t\t\t\tif (waitMs <= 0) throw new CloudJournalError(\"store_failed\", \"Release reports were not acknowledged\");\n\t\t\t\tawait Promise.race([changed, new Promise((resolveRetry) => {\n\t\t\t\t\ttimer = setTimeout(resolveRetry, Math.min(waitMs, 5e3));\n\t\t\t\t})]);\n\t\t\t} finally {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tthis.#journalListeners.delete(notify);\n\t\t\t}\n\t\t}\n\t}\n\t#notifyJournalChanged() {\n\t\tfor (const listener of this.#journalListeners) listener();\n\t}\n\t/**\n\t* Re-announce one durable entry while releasing. A still-`received` input is re-announced so an\n\t* unaccepted attempt is rejected and retired; accepted custody is cancelled and reported.\n\t* Manufacturing a report before custody would strand the release on a conflict.\n\t*/\n\tasync #drainReleaseEntry(entry) {\n\t\tthis.#assertCurrentScope(entry);\n\t\tif (entry.kind === \"delivery\") {\n\t\t\tif (entry.phase === \"reported\" && entry.report) this.#send({\n\t\t\t\ttype: \"delivery:report\",\n\t\t\t\treport: entry.report,\n\t\t\t\trequestId: randomUUID()\n\t\t\t});\n\t\t\telse if (entry.phase === \"received\") this.#sendReceipt(entry);\n\t\t\telse await this.#reportTerminal(entry, UNKNOWN_COMPLETION);\n\t\t\treturn;\n\t\t}\n\t\tif (entry.phase === \"reported\") this.#sendSessionSettled(entry);\n\t\telse if (entry.phase === \"received\") this.#sendSessionProgress(entry);\n\t\telse await this.#settleSessionTerminal(entry, \"unknown\");\n\t}\n\t/** Reserve the single turn slot synchronously, then fsync the started boundary, then run. */\n\tasync #startTurn(entry, frame, generation) {\n\t\tif (this.#closed || this.#active) return \"wait\";\n\t\tif (!(this.#options.canStart?.() ?? true)) return \"wait\";\n\t\tlet settle = () => void 0;\n\t\tconst settled = new Promise((resolve) => {\n\t\t\tsettle = resolve;\n\t\t});\n\t\tconst active = {\n\t\t\tabort: new AbortController(),\n\t\t\tentryKey: entry.deliveryId,\n\t\t\tkind: \"delivery\",\n\t\t\tsettle,\n\t\t\tsettled\n\t\t};\n\t\tthis.#active = active;\n\t\ttry {\n\t\t\tif (this.#sandboxUnusable) throw new CloudJournalError(\"store_failed\", \"The native sandbox namespace could not be verified clean; the Runner must not start another Turn\");\n\t\t\tif (this.#needsSandboxReset) await this.#resetSandboxNamespace();\n\t\t\tconst current = await this.#options.journal.read(entry.deliveryId);\n\t\t\tif (this.#closed) return \"wait\";\n\t\t\tif (current?.kind !== \"delivery\" || current.phase !== \"received\") {\n\t\t\t\tthis.#queue.delete(entry.requestId);\n\t\t\t\treturn \"settled\";\n\t\t\t}\n\t\t\tif (generation !== this.#channelGeneration) {\n\t\t\t\tthis.#queue.delete(entry.requestId);\n\t\t\t\treturn \"settled\";\n\t\t\t}\n\t\t\tif (active.abort.signal.aborted) {\n\t\t\t\tthis.#queue.delete(entry.requestId);\n\t\t\t\tthis.#cancelRequested.delete(entry.deliveryId);\n\t\t\t\tawait this.#reportTerminal(current, cancelledBeforeStart());\n\t\t\t\treturn \"settled\";\n\t\t\t}\n\t\t\tconst started = await this.#options.journal.markStarted(current.deliveryId, current.scope);\n\t\t\tactive.execution = this.#executeTurn(started, frame, active.abort.signal, generation).catch((error) => this.#reportPersistenceError(error)).finally(() => {\n\t\t\t\tthis.#completeActive(active);\n\t\t\t\tthis.#scheduleDrain();\n\t\t\t});\n\t\t\treturn \"started\";\n\t\t} finally {\n\t\t\tif (!active.execution) this.#completeActive(active);\n\t\t}\n\t}\n\t/**\n\t* The Session-message counterpart of `#startTurn`: same synchronous slot reservation, namespace\n\t* reset, cancel re-check, and durable `started` marker, but the terminal evidence is the\n\t* immutable Session settlement instead of a delivery report.\n\t*/\n\tasync #startSessionTurn(entry, frame, generation) {\n\t\tif (this.#closed || this.#active) return \"wait\";\n\t\tif (!(this.#options.canStart?.() ?? true)) return \"wait\";\n\t\tlet settle = () => void 0;\n\t\tconst settled = new Promise((resolve) => {\n\t\t\tsettle = resolve;\n\t\t});\n\t\tconst active = {\n\t\t\tabort: new AbortController(),\n\t\t\tentryKey: entry.messageId,\n\t\t\tkind: \"session-message\",\n\t\t\tsettle,\n\t\t\tsettled\n\t\t};\n\t\tthis.#active = active;\n\t\ttry {\n\t\t\tif (this.#sandboxUnusable) throw new CloudJournalError(\"store_failed\", \"The native sandbox namespace could not be verified clean; the Runner must not start another Turn\");\n\t\t\tif (this.#needsSandboxReset) await this.#resetSandboxNamespace();\n\t\t\tconst current = await this.#options.journal.read(entry.messageId);\n\t\t\tif (this.#closed) return \"wait\";\n\t\t\tif (current?.kind !== \"session-message\" || current.phase !== \"received\") {\n\t\t\t\tthis.#queue.delete(entry.requestId);\n\t\t\t\treturn \"settled\";\n\t\t\t}\n\t\t\tif (generation !== this.#channelGeneration) {\n\t\t\t\tthis.#queue.delete(entry.requestId);\n\t\t\t\treturn \"settled\";\n\t\t\t}\n\t\t\tif (active.abort.signal.aborted) {\n\t\t\t\tthis.#queue.delete(entry.requestId);\n\t\t\t\tthis.#cancelRequested.delete(entry.messageId);\n\t\t\t\tawait this.#settleSessionTerminal(current, \"cancelled\");\n\t\t\t\treturn \"settled\";\n\t\t\t}\n\t\t\tconst started = await this.#options.journal.markSessionStarted(current.messageId, current.scope);\n\t\t\tactive.execution = this.#executeSessionTurn(started, frame, active.abort.signal, generation).catch((error) => this.#reportPersistenceError(error)).finally(() => {\n\t\t\t\tthis.#completeActive(active);\n\t\t\t\tthis.#scheduleDrain();\n\t\t\t});\n\t\t\treturn \"started\";\n\t\t} finally {\n\t\t\tif (!active.execution) this.#completeActive(active);\n\t\t}\n\t}\n\t/**\n\t* Serialized, non-reentrant drain: only this path starts queued work, so a new verification or\n\t* an extra availability signal can never overtake the FIFO head. Enqueuing from inside a drain\n\t* (e.g. `#startTurn`'s finally) only chains a later no-op drain; it never awaits itself.\n\t*/\n\t#scheduleDrain() {\n\t\tthis.#enqueue(() => this.#drain()).catch((error) => this.#reportPersistenceError(error));\n\t}\n\t/**\n\t* Verify a clean native namespace after an interrupted Turn and before any next start. The reset\n\t* callback must throw when native `delete --force`/relaunch/probe cannot be verified; a failure\n\t* permanently disables Cloud Turns in this process instead of silently reusing a namespace that\n\t* may still own processes.\n\t*/\n\tasync #resetSandboxNamespace() {\n\t\tif (this.#resetInFlight) return this.#resetInFlight;\n\t\tconst reset = this.#options.sandboxReset;\n\t\tif (!reset) {\n\t\t\tthis.#needsSandboxReset = false;\n\t\t\treturn;\n\t\t}\n\t\tconst run = Promise.resolve().then(async () => {\n\t\t\ttry {\n\t\t\t\tawait reset();\n\t\t\t\tthis.#needsSandboxReset = false;\n\t\t\t} catch (error) {\n\t\t\t\tthis.#sandboxUnusable = true;\n\t\t\t\tthrow new CloudJournalError(\"store_failed\", `The native sandbox namespace cleanup could not be verified: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t} finally {\n\t\t\t\tthis.#resetInFlight = void 0;\n\t\t\t}\n\t\t});\n\t\tthis.#resetInFlight = run;\n\t\treturn run;\n\t}\n\t/** A non-completed Turn may have left namespace processes; require verified cleanup. */\n\t#markSandboxDirty() {\n\t\tif (this.#options.sandboxReset) this.#needsSandboxReset = true;\n\t}\n\tasync #drain() {\n\t\tfor (;;) {\n\t\t\tif (this.#closed || this.#active || this.#sandboxUnusable) return;\n\t\t\tconst first = this.#queue.values().next().value;\n\t\t\tif (!first) return;\n\t\t\tif (await this.#processQueued(first) !== \"continue\") return;\n\t\t}\n\t}\n\t/**\n\t* Process the FIFO head. The entry stays queued until it is actually started, so losing the\n\t* occupation race can never drop verified work, and cancellation is re-checked after every\n\t* await so a delivery cancelled mid-drain is never started.\n\t*/\n\tasync #processQueued(next) {\n\t\treturn next.kind === \"session-message\" ? this.#processQueuedSession(next) : this.#processQueuedDelivery(next);\n\t}\n\t/**\n\t* Process the FIFO head. The entry stays queued until it is actually started, so losing the\n\t* occupation race can never drop verified work, and cancellation is re-checked after every\n\t* await so a delivery cancelled mid-drain is never started.\n\t*/\n\tasync #processQueuedDelivery(next) {\n\t\tif (this.#cancelRequested.delete(next.deliveryId)) {\n\t\t\tthis.#queue.delete(next.frame.requestId);\n\t\t\tawait this.#settleCancelled(next.deliveryId);\n\t\t\treturn \"continue\";\n\t\t}\n\t\tconst entry = await this.#entryByRequestId(next.frame.requestId);\n\t\tif (entry?.kind !== \"delivery\" || entry.phase !== \"received\") {\n\t\t\tthis.#queue.delete(next.frame.requestId);\n\t\t\treturn \"continue\";\n\t\t}\n\t\tif (this.#cancelRequested.delete(next.deliveryId)) {\n\t\t\tthis.#queue.delete(next.frame.requestId);\n\t\t\tawait this.#settleCancelled(next.deliveryId);\n\t\t\treturn \"continue\";\n\t\t}\n\t\tif (next.generation !== this.#channelGeneration) {\n\t\t\tthis.#queue.delete(next.frame.requestId);\n\t\t\treturn \"continue\";\n\t\t}\n\t\tconst denial = this.#admit(entry.delivery, next.frame);\n\t\tif (denial) {\n\t\t\tthis.#queue.delete(next.frame.requestId);\n\t\t\tawait this.#reportTerminal(entry, denial.completion);\n\t\t\treturn \"continue\";\n\t\t}\n\t\tif (!(this.#options.canStart?.() ?? true)) return \"stop\";\n\t\tconst outcome = await this.#startTurn(entry, next.frame, next.generation);\n\t\tif (outcome === \"wait\") return \"stop\";\n\t\tthis.#queue.delete(next.frame.requestId);\n\t\treturn outcome === \"started\" ? \"started\" : \"continue\";\n\t}\n\t/** Session-message FIFO head: identical discipline, terminal evidence is the settlement. */\n\tasync #processQueuedSession(next) {\n\t\tif (this.#cancelRequested.delete(next.messageId)) {\n\t\t\tthis.#queue.delete(next.frame.requestId);\n\t\t\tawait this.#settleCancelledSession(next.messageId);\n\t\t\treturn \"continue\";\n\t\t}\n\t\tconst entry = await this.#entryByRequestId(next.frame.requestId);\n\t\tif (entry?.kind !== \"session-message\" || entry.phase !== \"received\") {\n\t\t\tthis.#queue.delete(next.frame.requestId);\n\t\t\treturn \"continue\";\n\t\t}\n\t\tif (this.#cancelRequested.delete(next.messageId)) {\n\t\t\tthis.#queue.delete(next.frame.requestId);\n\t\t\tawait this.#settleCancelledSession(next.messageId);\n\t\t\treturn \"continue\";\n\t\t}\n\t\tif (next.generation !== this.#channelGeneration) {\n\t\t\tthis.#queue.delete(next.frame.requestId);\n\t\t\treturn \"continue\";\n\t\t}\n\t\tconst denial = this.#admitSession(next.frame);\n\t\tif (denial) {\n\t\t\tthis.#queue.delete(next.frame.requestId);\n\t\t\tawait this.#settleSessionTerminal(entry, denial);\n\t\t\treturn \"continue\";\n\t\t}\n\t\tif (!(this.#options.canStart?.() ?? true)) return \"stop\";\n\t\tconst outcome = await this.#startSessionTurn(entry, next.frame, next.generation);\n\t\tif (outcome === \"wait\") return \"stop\";\n\t\tthis.#queue.delete(next.frame.requestId);\n\t\treturn outcome === \"started\" ? \"started\" : \"continue\";\n\t}\n\tasync #settleCancelled(deliveryId) {\n\t\tconst entry = await this.#options.journal.read(deliveryId);\n\t\tif (!entry) return;\n\t\tthis.#assertCurrentScope(entry);\n\t\tif (entry.kind === \"delivery\" && entry.phase === \"received\") await this.#reportTerminal(entry, cancelledBeforeStart());\n\t}\n\tasync #settleCancelledSession(messageId) {\n\t\tconst entry = await this.#options.journal.read(messageId);\n\t\tif (!entry) return;\n\t\tthis.#assertCurrentScope(entry);\n\t\tif (entry.kind === \"session-message\" && entry.phase === \"received\") await this.#settleSessionTerminal(entry, \"cancelled\");\n\t}\n\t#completeActive(active) {\n\t\tif (this.#active === active) this.#active = void 0;\n\t\tactive.settle();\n\t}\n\tasync #executeTurn(entry, frame, signal, generation) {\n\t\tconst current = await this.#options.journal.read(entry.deliveryId);\n\t\tif (current?.kind !== \"delivery\" || current.phase !== \"started\") return;\n\t\tif (generation !== this.#channelGeneration) {\n\t\t\tawait this.#reportTerminal(current, cancelledBeforeStart());\n\t\t\treturn;\n\t\t}\n\t\tif (signal.aborted) {\n\t\t\tawait this.#reportTerminal(current, cancelledBeforeStart());\n\t\t\treturn;\n\t\t}\n\t\tconst model = frame.model;\n\t\tif (!model) return;\n\t\tlet completion;\n\t\ttry {\n\t\t\tcompletion = await this.#runInSandbox(current.delivery, model, current, signal, generation);\n\t\t} catch {\n\t\t\tcompletion = {\n\t\t\t\terrorReason: \"turn_state_unknown\",\n\t\t\t\texecutionEffects: \"may_have_occurred\",\n\t\t\t\toutcome: \"unknown\"\n\t\t\t};\n\t\t}\n\t\tif (signal.aborted && completion.executionEffects !== \"not_started\" && completion.outcome !== \"completed\") completion = {\n\t\t\terrorReason: \"client_shutdown\",\n\t\t\texecutionEffects: \"may_have_occurred\",\n\t\t\toutcome: \"cancelled\"\n\t\t};\n\t\tconst cleanup = await this.#cleanupInterrupted(completion);\n\t\tawait this.#reportTerminal(current, cleanup.completion, true);\n\t\tif (cleanup.failure !== void 0) this.#reportPersistenceError(cleanup.failure);\n\t}\n\t/**\n\t* Verified namespace cleanup after an interrupted Turn. A failed reset makes the completion an\n\t* honest unknown and keeps the failure for the caller to surface after the terminal evidence.\n\t*/\n\tasync #cleanupInterrupted(completion) {\n\t\tif (!isInterrupted(completion) || !this.#options.sandboxReset || this.#options.checkpoint) return { completion };\n\t\tthis.#markSandboxDirty();\n\t\ttry {\n\t\t\tawait this.#resetSandboxNamespace();\n\t\t\treturn { completion };\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tcompletion: {\n\t\t\t\t\terrorReason: \"sandbox_unavailable\",\n\t\t\t\t\texecutionEffects: \"may_have_occurred\",\n\t\t\t\t\toutcome: \"unknown\"\n\t\t\t\t},\n\t\t\t\tfailure: error\n\t\t\t};\n\t\t}\n\t}\n\t/** Build the fsynced report and send it; the entry retires only on the Server's durable ack. */\n\tasync #reportTerminal(entry, completion, checkpoint = false) {\n\t\tlet checkpointError;\n\t\tif (checkpoint) try {\n\t\t\tawait this.#options.checkpoint?.();\n\t\t} catch (error) {\n\t\t\tcheckpointError = error;\n\t\t\tcompletion = workspaceSaveFailure(completion);\n\t\t}\n\t\tconst report = entry.report ?? this.#buildReport(entry.delivery, entry, completion);\n\t\tconst recorded = await this.#options.journal.recordReport(entry.deliveryId, entry.scope, report);\n\t\tif (!recorded.report) return;\n\t\tthis.#notifyJournalChanged();\n\t\tthis.#send({\n\t\t\ttype: \"delivery:report\",\n\t\t\treport: recorded.report,\n\t\t\trequestId: randomUUID()\n\t\t});\n\t\tif (checkpointError !== void 0 && !(checkpointError instanceof CloudWorkspaceError && !checkpointError.retryable)) this.#reportPersistenceError(checkpointError);\n\t}\n\t#buildReport(delivery, entry, completion) {\n\t\tconst base = {\n\t\t\ttype: \"turn:report\",\n\t\t\tagentId: delivery.agentId,\n\t\t\tdeliveryId: delivery.deliveryId,\n\t\t\texecutionEffects: completion.executionEffects,\n\t\t\tplacementGeneration: delivery.placementGeneration,\n\t\t\toutcome: completion.outcome,\n\t\t\trequestId: randomUUID(),\n\t\t\tsessionId: delivery.sessionId,\n\t\t\ttraceSummary: {\n\t\t\t\tdroppedEvents: 0,\n\t\t\t\tlastSequence: 0\n\t\t\t},\n\t\t\tturnId: entry.turnId,\n\t\t\t...completion.errorReason ? { errorReason: completion.errorReason } : {},\n\t\t\t...completion.finalText ? { finalText: completion.finalText } : {},\n\t\t\t...completion.usage ? { usage: completion.usage } : {}\n\t\t};\n\t\tconst report = {\n\t\t\t...base,\n\t\t\tresultHash: computeTurnResultHash(base)\n\t\t};\n\t\tconst validated = TurnReportRequestSchema.safeParse(report);\n\t\tif (!validated.success) throw new CloudJournalError(\"store_failed\", `The Turn report for ${entry.deliveryId} failed schema validation`);\n\t\treturn validated.data;\n\t}\n\t/**\n\t* Deadline/grant admission BEFORE any native or Pi effect. An expired persisted runtime deadline\n\t* or an expired/absent model grant settles durably as `not_started` with zero sandbox work and\n\t* never extends the budget.\n\t*/\n\t#admit(delivery, frame) {\n\t\tconst now = Date.now();\n\t\tconst model = frame.model;\n\t\tif (!model) return { completion: {\n\t\t\terrorReason: \"credential_unavailable\",\n\t\t\texecutionEffects: \"not_started\",\n\t\t\toutcome: \"failed\"\n\t\t} };\n\t\tif (!Number.isFinite(Date.parse(model.expiresAt)) || Date.parse(model.expiresAt) <= now) return { completion: {\n\t\t\terrorReason: \"credential_unavailable\",\n\t\t\texecutionEffects: \"not_started\",\n\t\t\toutcome: \"failed\"\n\t\t} };\n\t\tif (delivery.deadlineAt) {\n\t\t\tconst deadline = Date.parse(delivery.deadlineAt);\n\t\t\tif (!Number.isFinite(deadline) || deadline <= now) return { completion: {\n\t\t\t\terrorReason: \"turn_timeout\",\n\t\t\t\texecutionEffects: \"not_started\",\n\t\t\t\toutcome: \"failed\"\n\t\t\t} };\n\t\t}\n\t}\n\tasync #runInSandbox(delivery, model, entry, signal, generation) {\n\t\tconst scope = this.#options.scope();\n\t\tif (!scope) throw new Error(\"The Runner scope is not established\");\n\t\tif (signal.aborted) return cancelledBeforeStart();\n\t\tconst execution = await (this.#options.openExecution ?? ((input) => this.#openBridgeExecution(input)))({\n\t\t\tdelivery,\n\t\t\tscope,\n\t\t\tturnId: entry.turnId,\n\t\t\tsignal\n\t\t});\n\t\ttry {\n\t\t\tif (signal.aborted || generation !== this.#channelGeneration) return cancelledBeforeStart();\n\t\t\tconst stdin = serializeRunnerCloudTurnWorkerStdin({\n\t\t\t\tdelivery,\n\t\t\t\texecutionDir: execution.executionDir,\n\t\t\t\t...execution.mcpGateway ? { mcpGateway: execution.mcpGateway } : {},\n\t\t\t\t...execution.webTools ? { webTools: execution.webTools } : {},\n\t\t\t\tmodel,\n\t\t\t\t...execution.sessionCliProof ? { sessionCollaboration: {\n\t\t\t\t\tproof: execution.sessionCliProof,\n\t\t\t\t\tserverUrl: this.#options.serverUrl\n\t\t\t\t} } : {},\n\t\t\t\t...this.#options.piSessionDirectory ? { piSessionDirectory: this.#options.piSessionDirectory } : {}\n\t\t\t});\n\t\t\tconst timeoutMs = turnTimeoutMs(delivery, Date.now()) + CLOUD_TURN_EXEC_TIMEOUT_GRACE_MS;\n\t\t\treturn await this.#runWorker({\n\t\t\t\tstdin,\n\t\t\t\ttimeoutMs\n\t\t\t}, signal, execution);\n\t\t} finally {\n\t\t\tawait execution.close().catch((error) => this.#reportPersistenceError(error));\n\t\t}\n\t}\n\t/**\n\t* Session-message execution: same durable `started` boundary and namespace discipline as an IM\n\t* Turn, but the terminal evidence is the immutable Session settlement. The execution-open result\n\t* carries the ephemeral Session CLI proof, which is forwarded to the worker via stdin.\n\t*/\n\tasync #executeSessionTurn(entry, frame, signal, generation) {\n\t\tconst current = await this.#options.journal.read(entry.messageId);\n\t\tif (current?.kind !== \"session-message\" || current.phase !== \"started\") return;\n\t\tif (generation !== this.#channelGeneration || signal.aborted) {\n\t\t\tawait this.#settleSessionTerminal(current, \"cancelled\");\n\t\t\treturn;\n\t\t}\n\t\tconst model = frame.model;\n\t\tif (!model) {\n\t\t\tawait this.#settleSessionTerminal(current, \"failed\");\n\t\t\treturn;\n\t\t}\n\t\tlet completion;\n\t\ttry {\n\t\t\tcompletion = await this.#runSessionInSandbox(current.message, model, current, signal, generation);\n\t\t} catch {\n\t\t\tcompletion = {\n\t\t\t\terrorReason: \"turn_state_unknown\",\n\t\t\t\texecutionEffects: \"may_have_occurred\",\n\t\t\t\toutcome: \"unknown\"\n\t\t\t};\n\t\t}\n\t\tif (signal.aborted && completion.executionEffects !== \"not_started\" && completion.outcome !== \"completed\") completion = {\n\t\t\terrorReason: \"client_shutdown\",\n\t\t\texecutionEffects: \"may_have_occurred\",\n\t\t\toutcome: \"cancelled\"\n\t\t};\n\t\tconst cleanup = await this.#cleanupInterrupted(completion);\n\t\tawait this.#settleSessionTerminal(current, sessionSettlementOutcome(cleanup.completion), true);\n\t\tif (cleanup.failure !== void 0) this.#reportPersistenceError(cleanup.failure);\n\t}\n\t/** Deadline/grant admission BEFORE any native or Pi effect, mirroring the IM Turn gate. */\n\t#admitSession(frame) {\n\t\tconst model = frame.model;\n\t\tif (!model) return \"failed\";\n\t\tif (!Number.isFinite(Date.parse(model.expiresAt)) || Date.parse(model.expiresAt) <= Date.now()) return \"failed\";\n\t}\n\t/**\n\t* Record the immutable settlement after the same save boundary as an IM report, then send (or\n\t* replay) it; the entry retires only on the Server's exact settlement ack.\n\t*/\n\tasync #settleSessionTerminal(entry, outcome, checkpoint = false) {\n\t\tlet effective = outcome;\n\t\tlet checkpointError;\n\t\tif (checkpoint) try {\n\t\t\tawait this.#options.checkpoint?.();\n\t\t} catch (error) {\n\t\t\tcheckpointError = error;\n\t\t\teffective = \"failed\";\n\t\t}\n\t\tconst recorded = await this.#options.journal.recordSessionSettled(entry.messageId, entry.scope, effective);\n\t\tif (!recorded.settlement) return;\n\t\tthis.#notifyJournalChanged();\n\t\tthis.#sendSessionSettled(recorded);\n\t\tif (checkpointError !== void 0 && !(checkpointError instanceof CloudWorkspaceError && !checkpointError.retryable)) this.#reportPersistenceError(checkpointError);\n\t}\n\tasync #runSessionInSandbox(message, model, entry, signal, generation) {\n\t\tconst scope = this.#options.scope();\n\t\tif (!scope) throw new Error(\"The Runner scope is not established\");\n\t\tif (signal.aborted) return cancelledBeforeStart();\n\t\tconst budgetMs = Math.max(1, message.runtime.budget?.maxDurationMs ?? RUNTIME_DEFAULT_MAX_DURATION_MS);\n\t\tconst deadlineAt = new Date(Date.now() + budgetMs).toISOString();\n\t\tconst execution = await (this.#options.openSessionExecution ?? ((input) => this.#openSessionBridgeExecution(input)))({\n\t\t\tmessage,\n\t\t\tscope,\n\t\t\tturnId: entry.turnId,\n\t\t\tsignal\n\t\t});\n\t\ttry {\n\t\t\tif (signal.aborted || generation !== this.#channelGeneration) return cancelledBeforeStart();\n\t\t\tconst stdin = serializeRunnerCloudSessionWorkerStdin({\n\t\t\t\tmessage,\n\t\t\t\texecutionDir: execution.executionDir,\n\t\t\t\t...execution.mcpGateway ? { mcpGateway: execution.mcpGateway } : {},\n\t\t\t\t...execution.webTools ? { webTools: execution.webTools } : {},\n\t\t\t\tmodel,\n\t\t\t\tsessionKind: entry.sessionKind,\n\t\t\t\tdeadlineAt,\n\t\t\t\t...entry.outboxContext ? { outboxContext: entry.outboxContext } : {},\n\t\t\t\t...execution.sessionCliProof ? { sessionCollaboration: {\n\t\t\t\t\tproof: execution.sessionCliProof,\n\t\t\t\t\tserverUrl: this.#options.serverUrl\n\t\t\t\t} } : {},\n\t\t\t\t...this.#options.piSessionDirectory ? { piSessionDirectory: this.#options.piSessionDirectory } : {}\n\t\t\t});\n\t\t\tconst timeoutMs = Math.max(1, Date.parse(deadlineAt) - Date.now()) + CLOUD_TURN_EXEC_TIMEOUT_GRACE_MS;\n\t\t\treturn await this.#runWorker({\n\t\t\t\tstdin,\n\t\t\t\ttimeoutMs\n\t\t\t}, signal, execution);\n\t\t} finally {\n\t\t\tawait execution.close().catch((error) => this.#reportPersistenceError(error));\n\t\t}\n\t}\n\t/** Both execution paths use the same transport-failure and completion boundary. */\n\tasync #runWorker(input, signal, execution) {\n\t\tconst workerSignal = execution.bridgeFailureSignal ? AbortSignal.any([signal, execution.bridgeFailureSignal]) : signal;\n\t\tconst runWorker = this.#options.runWorker ?? ((input, workerSignal) => this.#options.sandbox.exec(\"/usr/local/bin/node\", [\"/opt/opentag/client/dist/runner/bin.mjs\", \"worker\"], {\n\t\t\tsignal: workerSignal,\n\t\t\tstdin: input.stdin,\n\t\t\ttimeoutMs: input.timeoutMs\n\t\t}));\n\t\ttry {\n\t\t\tconst exec = await runWorker(input, workerSignal);\n\t\t\tif (signal.aborted) return {\n\t\t\t\terrorReason: \"client_shutdown\",\n\t\t\t\texecutionEffects: \"may_have_occurred\",\n\t\t\t\toutcome: \"cancelled\"\n\t\t\t};\n\t\t\tif (execution.bridgeFailure?.()) return {\n\t\t\t\terrorReason: \"turn_state_unknown\",\n\t\t\t\texecutionEffects: \"may_have_occurred\",\n\t\t\t\toutcome: \"unknown\"\n\t\t\t};\n\t\t\tconst completion = parseWorkerCompletion(exec.stdout);\n\t\t\tif (exec.code !== 0 && completion.outcome === \"completed\") return {\n\t\t\t\terrorReason: \"provider_failed\",\n\t\t\t\texecutionEffects: \"may_have_occurred\",\n\t\t\t\toutcome: \"failed\"\n\t\t\t};\n\t\t\treturn completion;\n\t\t} catch (error) {\n\t\t\tif (execution.bridgeFailure?.() && !signal.aborted) return {\n\t\t\t\terrorReason: \"turn_state_unknown\",\n\t\t\t\texecutionEffects: \"may_have_occurred\",\n\t\t\t\toutcome: \"unknown\"\n\t\t\t};\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/**\n\t* Default per-turn credential bridge: open a #633 execution through the Runner channel tunnel,\n\t* start the trusted loopback adapter, publish ONLY the per-turn public material the native\n\t* Sandbox mounts, and open the per-execution HTTP/2 provider bridge (`sandbox exec` duplex)\n\t* whose in-Sandbox helper owns the two fixed loopback entry ports. The parent side of the\n\t* bridge dials exactly two enumerated targets — this execution's own adapter ports — and no\n\t* parent Unix socket is ever mounted. The private CA/journal/bootstrap material stays in the\n\t* unmounted private root. Nothing runs in this parent beyond credential relaying; the worker\n\t* executes inside the Sandbox.\n\t*/\n\tasync #openBridgeExecution(input) {\n\t\treturn this.#openRelayExecution({\n\t\t\tagentId: input.delivery.agentId,\n\t\t\tplacementGeneration: input.delivery.placementGeneration,\n\t\t\tsessionId: input.delivery.sessionId,\n\t\t\tsignal: input.signal,\n\t\t\tsource: {\n\t\t\t\tkind: \"delivery\",\n\t\t\t\tdeliveryId: input.delivery.deliveryId,\n\t\t\t\tturnId: input.turnId\n\t\t\t},\n\t\t\tscope: input.scope\n\t\t});\n\t}\n\tasync #openSessionBridgeExecution(input) {\n\t\treturn this.#openRelayExecution({\n\t\t\tagentId: input.message.agentId,\n\t\t\tplacementGeneration: input.message.placementGeneration,\n\t\t\tsessionId: input.message.targetSessionId,\n\t\t\tsignal: input.signal,\n\t\t\tsource: {\n\t\t\t\tkind: \"session-message\",\n\t\t\t\tmessageId: input.message.messageId\n\t\t\t},\n\t\t\tscope: input.scope\n\t\t});\n\t}\n\tasync #openRelayExecution(input) {\n\t\tconst scope = input.scope;\n\t\tif (!scope.resourceUid) throw new Error(\"The Sandbox allocation UID is not tracked yet\");\n\t\tconst connection = new CloudCredentialConnection(this.#options.credentialChannel());\n\t\tlet relay;\n\t\tlet adapter;\n\t\tlet bridge;\n\t\tlet webChannel;\n\t\tlet privateDirectory;\n\t\tlet publicDirectory;\n\t\tlet cleaned = false;\n\t\t/**\n\t\t* Idempotent local cleanup: every acquired handle is released exactly once and one failing\n\t\t* step never stops the remaining ones. Failures are logged here and returned so the caller\n\t\t* can decide whether the original open/close error is the one that surfaces.\n\t\t*/\n\t\tconst cleanup = async (reason) => {\n\t\t\tif (cleaned) return [];\n\t\t\tcleaned = true;\n\t\t\tconst failures = [];\n\t\t\tconst step = async (operation) => {\n\t\t\t\ttry {\n\t\t\t\t\tawait operation();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfailures.push(error);\n\t\t\t\t}\n\t\t\t};\n\t\t\tawait releaseRelayExecutionResources({\n\t\t\t\tstep,\n\t\t\t\tconnection,\n\t\t\t\treason,\n\t\t\t\tonBridgeCloseFailure: () => {\n\t\t\t\t\tthis.#sandboxUnusable = true;\n\t\t\t\t},\n\t\t\t\twebChannel,\n\t\t\t\tbridge,\n\t\t\t\tadapter,\n\t\t\t\trelay,\n\t\t\t\tpublicDirectory,\n\t\t\t\tprivateDirectory\n\t\t\t});\n\t\t\tfor (const failure of failures) this.#log(`cloud bridge ${reason} cleanup step failed: ${errorMessage(failure)}`);\n\t\t\treturn failures;\n\t\t};\n\t\ttry {\n\t\t\trelay = await RuntimeCredentialRelay.open({\n\t\t\t\tconnection: connection.relayConnection,\n\t\t\t\tserverUrl: this.#options.serverUrl,\n\t\t\t\t...this.#options.relayOptions ?? {}\n\t\t\t}, {\n\t\t\t\tagentId: input.agentId,\n\t\t\t\tplacementGeneration: input.placementGeneration,\n\t\t\t\trunId: randomUUID(),\n\t\t\t\tsandbox: {\n\t\t\t\t\tenvironmentGeneration: scope.environmentGeneration,\n\t\t\t\t\tresourceUid: scope.resourceUid,\n\t\t\t\t\tsandboxId: scope.sandboxId\n\t\t\t\t},\n\t\t\t\tsessionId: input.sessionId,\n\t\t\t\tsource: input.source,\n\t\t\t\tservices: [\"mcp\", \"web\"]\n\t\t\t}, input.signal);\n\t\t\tconst openRelay = relay;\n\t\t\tconst mcpGrant = openRelay.services?.some((service) => service.service === \"mcp\" && service.scopes.includes(\"mcp:tools\")) ? await openRelay.acquireMcpGatewayToken(input.signal) : void 0;\n\t\t\tprivateDirectory = await mkdtemp(join(this.#options.stateDirectory, \"turn-private-\"));\n\t\t\tconst publicRoot = this.#options.publicDirectory ?? join(this.#options.stateDirectory, \"public\");\n\t\t\tawait mkdir(publicRoot, {\n\t\t\t\trecursive: true,\n\t\t\t\tmode: 448\n\t\t\t});\n\t\t\tpublicDirectory = await mkdtemp(join(publicRoot, \"turn-\"));\n\t\t\tadapter = await RuntimeProxyLoopbackAdapter.start({\n\t\t\t\texecutionId: openRelay.executionId,\n\t\t\t\tlocalHandleFor: (provider) => openRelay.providers.some((entryPoint) => entryPoint.provider === provider) ? openRelay.localHandleFor(provider) : void 0,\n\t\t\t\tmaterialDir: join(privateDirectory, \"adapter\"),\n\t\t\t\topenStream: (request) => openRelay.openProviderStream(request),\n\t\t\t\tverifyHandle: (provider, handle) => openRelay.verifyLocalHandle(provider, handle)\n\t\t\t});\n\t\t\tconst inSandboxExecutionDir = `${CLOUD_EXECUTION_MOUNT}/${basename(publicDirectory)}`;\n\t\t\tawait publishExecutionMaterial({\n\t\t\t\tadapter,\n\t\t\t\trelay: openRelay\n\t\t\t}, publicDirectory, {\n\t\t\t\tincludeEntryPrograms: false,\n\t\t\t\tpublicMountPath: inSandboxExecutionDir\n\t\t\t});\n\t\t\tconst openAdapter = adapter;\n\t\t\tbridge = await NativeProviderBridge.open({\n\t\t\t\tsandbox: this.#options.sandbox,\n\t\t\t\tsignal: input.signal,\n\t\t\t\ttargets: {\n\t\t\t\t\tconnect: loopbackPortOf(openAdapter.connectProxyUrl),\n\t\t\t\t\tslack: loopbackPortOf(openAdapter.slackApiHost)\n\t\t\t\t}\n\t\t\t});\n\t\t\tconst openBridge = bridge;\n\t\t\tconst webTools = await this.#openGrantedWebChannel({\n\t\t\t\trelay: openRelay,\n\t\t\t\tsignal: input.signal,\n\t\t\t\tonOpened: (channel) => {\n\t\t\t\t\twebChannel = channel;\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn {\n\t\t\t\texecutionDir: inSandboxExecutionDir,\n\t\t\t\t...mcpGrant ? { mcpGateway: {\n\t\t\t\t\turl: new URL(MCP_GATEWAY_PATH, this.#options.serverUrl).toString(),\n\t\t\t\t\ttoken: mcpGrant.token\n\t\t\t\t} } : {},\n\t\t\t\t...webTools ? { webTools } : {},\n\t\t\t\t...openRelay.sessionCliProof ? { sessionCliProof: openRelay.sessionCliProof } : {},\n\t\t\t\tbridgeFailure: () => openBridge.failure,\n\t\t\t\tbridgeFailureSignal: openBridge.failureSignal,\n\t\t\t\tclose: async () => {\n\t\t\t\t\tconst failures = await cleanup(\"execution_closed\");\n\t\t\t\t\tif (failures.length > 0) throw new Error(`Cloud execution cleanup failed: ${failures.map((failure) => errorMessage(failure)).join(\"; \")}`);\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof NativeSandboxError && error.code === \"delete_failed\") {\n\t\t\t\tthis.#sandboxUnusable = true;\n\t\t\t\tthis.#reportPersistenceError(error);\n\t\t\t}\n\t\t\tconst cleanupFailures = await cleanup(\"open_failed\");\n\t\t\tif (cleanupFailures.length > 0) this.#reportPersistenceError(/* @__PURE__ */ new Error(`Cloud bridge open-failure cleanup left ${cleanupFailures.length} unresolved step(s): ${cleanupFailures.map((failure) => errorMessage(failure)).join(\"; \")}`));\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/** A withheld grant leaves web off; a granted service must be usable or fail this execution. */\n\tasync #openGrantedWebChannel(input) {\n\t\tif (!input.relay.services?.some((service) => service.service === \"web\" && service.scopes.length > 0)) return void 0;\n\t\tconst token = await input.relay.acquireWebGatewayToken(input.signal);\n\t\tif (!token) throw new Error(\"The granted Cloud web service did not provide an execution credential\");\n\t\treturn this.#openExecutionWebChannel({\n\t\t\texecutionId: input.relay.executionId,\n\t\t\tsignal: input.signal,\n\t\t\ttoken: token.token,\n\t\t\tonOpened: input.onOpened\n\t\t});\n\t}\n\t/** Open the native channel after a grant; missing Runner components fail the execution. */\n\tasync #openExecutionWebChannel(input) {\n\t\tconst gateway = this.#options.webGateway;\n\t\tconst extensionPath = this.#options.webExtensionPath;\n\t\tif (!gateway || !extensionPath) throw new Error(\"The Cloud web tools extension or gateway is unavailable\");\n\t\tconst client = new WebToolsServerClient({\n\t\t\tserverUrl: this.#options.serverUrl,\n\t\t\tbearerToken: input.token,\n\t\t\t...this.#options.fetchImpl ? { fetchImpl: this.#options.fetchImpl } : {}\n\t\t});\n\t\ttry {\n\t\t\tconst channel = await gateway.openExecution({\n\t\t\t\tsandbox: this.#options.sandbox,\n\t\t\t\tauthority: {\n\t\t\t\t\texecutionIdentity: input.executionId,\n\t\t\t\t\tsignal: input.signal,\n\t\t\t\t\tdispatch: createExecutionWebDispatch({\n\t\t\t\t\t\tclient,\n\t\t\t\t\t\texecutionId: input.executionId\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t});\n\t\t\tinput.onOpened(channel);\n\t\t\treturn {\n\t\t\t\textensionPath,\n\t\t\t\tsocketPath: channel.socketPath\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthis.#log(`cloud web channel did not open: ${errorMessage(error)}`);\n\t\t\tthrow error;\n\t\t}\n\t}\n\tasync #entryByRequestId(requestId) {\n\t\tconst entry = (await this.#options.journal.list()).find((candidate) => candidate.requestId === requestId);\n\t\tif (!entry) return void 0;\n\t\tthis.#assertCurrentScope(entry);\n\t\treturn entry;\n\t}\n\t#assertCurrentScope(entry) {\n\t\tassertCloudJournalScope(entry, this.#requireJournalScope());\n\t}\n\t#requireJournalScope() {\n\t\tconst scope = this.#options.scope();\n\t\tif (!scope) throw new CloudJournalError(\"scope_unbound\", \"The Runner has no negotiated Cloud allocation scope\");\n\t\tif (!scope.resourceUid) throw new CloudJournalError(\"scope_unbound\", \"The Sandbox allocation UID is not tracked yet\");\n\t\treturn {\n\t\t\tenvironmentGeneration: scope.environmentGeneration,\n\t\t\tresourceName: scope.resourceName,\n\t\t\tresourceUid: scope.resourceUid,\n\t\t\tsandboxId: scope.sandboxId,\n\t\t\tsessionId: scope.sessionId\n\t\t};\n\t}\n\tasync #enqueue(operation) {\n\t\tconst run = this.#serial.then(operation, operation);\n\t\tthis.#serial = run.then(() => void 0, () => void 0);\n\t\treturn run;\n\t}\n\t#reportPersistenceError(error) {\n\t\tthis.#log(`cloud delivery durable boundary failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\tthis.#options.onPersistenceError?.(error);\n\t}\n\t#send(frame) {\n\t\ttry {\n\t\t\tthis.#options.send(frame);\n\t\t} catch {\n\t\t\tthis.#log(\"cloud delivery frame could not be sent (channel closed)\");\n\t\t}\n\t}\n\t#log(message) {\n\t\tthis.#options.log?.(message);\n\t}\n};\nfunction cancelledBeforeStart() {\n\treturn {\n\t\terrorReason: \"client_shutdown\",\n\t\texecutionEffects: \"not_started\",\n\t\toutcome: \"cancelled\"\n\t};\n}\n/**\n* Release every resource one relay execution acquired, in the order the teardown requires.\n*\n* The web channel goes first: its in-Sandbox bridge process and its request listener are removed\n* while the trusted parent still owns the execution, so no successor execution can observe a stale\n* socket or an inherited authority. Then the provider bridge, whose helper and every in-flight\n* parent connection stop before the trusted adapter/relay they dialed. One failing step never stops\n* the remaining ones; the caller records the failures.\n*/\nasync function releaseRelayExecutionResources(input) {\n\tif (input.webChannel) await input.step(() => input.webChannel?.close());\n\tif (input.bridge) {\n\t\tconst bridge = input.bridge;\n\t\tawait input.step(async () => {\n\t\t\ttry {\n\t\t\t\tawait bridge.close();\n\t\t\t} catch (error) {\n\t\t\t\tinput.onBridgeCloseFailure();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t});\n\t}\n\tif (input.adapter) await input.step(() => input.adapter?.close());\n\tif (input.relay) await input.step(() => input.relay?.close(input.reason));\n\tawait input.step(() => input.connection.close());\n\tif (input.publicDirectory) {\n\t\tconst directory = input.publicDirectory;\n\t\tawait input.step(() => rm(directory, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t}));\n\t}\n\tif (input.privateDirectory) {\n\t\tconst directory = input.privateDirectory;\n\t\tawait input.step(() => rm(directory, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t}));\n\t}\n}\n/**\n* One conservative Session settlement outcome. A Turn may only be reported `completed` when the\n* worker reported complete execution effects; anything else stays distinguishable as failed,\n* cancelled, or unknown.\n*/\nfunction sessionSettlementOutcome(completion) {\n\tif (completion.outcome === \"cancelled\") return \"cancelled\";\n\tif (completion.outcome === \"unknown\") return \"unknown\";\n\tif (completion.outcome === \"completed\") return completion.executionEffects === \"completed\" ? \"completed\" : \"unknown\";\n\treturn \"failed\";\n}\nfunction workspaceSaveFailure(completion) {\n\tconst message = \"Workspace save failed. Execution effects may already exist, but these files are not durably saved. Further execution is blocked. If saving cannot recover, explicitly discard unsaved changes to release the environment. Do not repeat completed external actions.\\n\\n\";\n\treturn {\n\t\t...completion,\n\t\toutcome: \"failed\",\n\t\terrorReason: \"workspace_failed\",\n\t\tfinalText: message + truncateUtf8(completion.finalText ?? \"\", RUNTIME_FINAL_TEXT_MAX_BYTES - Buffer.byteLength(message)).text\n\t};\n}\n/** A Turn that did not verifiably complete may have left native processes behind. */\nfunction isInterrupted(completion) {\n\treturn completion.outcome !== \"completed\" || completion.executionEffects !== \"completed\";\n}\n/**\n* Enumerated bridge target extraction: the parent maps the two bridge entries to exactly the two\n* loopback TCP ports of its own per-execution adapter. Anything that is not a numeric 127.0.0.1\n* port is a composition bug and fails before any helper is spawned; no address or path is ever\n* taken from the Sandbox or from a caller.\n*/\nfunction loopbackPortOf(endpoint) {\n\tconst url = new URL(endpoint);\n\tif (url.hostname !== \"127.0.0.1\") throw new Error(\"The execution adapter endpoint is not a fixed loopback address\");\n\tconst port = Number(url.port);\n\tif (!Number.isInteger(port) || port <= 0 || port > 65535) throw new Error(\"The execution adapter endpoint has no valid loopback port\");\n\treturn port;\n}\n/** One-line error text for logs and aggregate cleanup errors. */\nfunction errorMessage(error) {\n\treturn error instanceof Error ? error.message : String(error);\n}\n/** Parse exactly one bounded in-sandbox result line; malformed output is an explicit unknown. */\nfunction parseWorkerCompletion(stdout) {\n\tif (utf8Length(stdout) > CLOUD_TURN_WORKER_STDOUT_MAX_BYTES) return {\n\t\terrorReason: \"output_too_large\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\toutcome: \"unknown\"\n\t};\n\tconst line = stdout.split(\"\\n\").filter((candidate) => candidate.startsWith(\"{\")).at(-1);\n\tlet parsed;\n\ttry {\n\t\tparsed = line ? JSON.parse(line) : void 0;\n\t} catch {\n\t\treturn providerProtocolError();\n\t}\n\tif (typeof parsed !== \"object\" || parsed === null || parsed.kind !== \"result\" || typeof parsed.completion !== \"object\") return providerProtocolError();\n\tconst completion = CloudTurnCompletionSchema.safeParse(parsed.completion);\n\tif (!completion.success) return providerProtocolError();\n\treturn completion.data;\n}\nfunction providerProtocolError() {\n\treturn {\n\t\terrorReason: \"provider_protocol_error\",\n\t\texecutionEffects: \"may_have_occurred\",\n\t\toutcome: \"unknown\"\n\t};\n}\n/** UTF-8 byte length without depending on a Shared-internal helper. */\nfunction utf8Length(value) {\n\treturn Buffer.byteLength(value, \"utf8\");\n}\n//#endregion\n//#region src/runner/health.ts\nconst DEFAULT_MAX_CONNECTIONS = 128;\nconst DEFAULT_SOCKET_TIMEOUT_MS = 5e3;\nasync function startRunnerHealthListener(options) {\n\tconst sockets = /* @__PURE__ */ new Set();\n\tconst onError = options.onError ?? (() => void 0);\n\tconst server = createServer$1((socket) => {\n\t\tsockets.add(socket);\n\t\tsocket.setTimeout(options.socketTimeoutMs ?? DEFAULT_SOCKET_TIMEOUT_MS, () => socket.destroy());\n\t\tsocket.once(\"close\", () => sockets.delete(socket));\n\t\tsocket.once(\"error\", () => socket.destroy());\n\t\tsocket.end();\n\t});\n\tserver.maxConnections = options.maxConnections ?? DEFAULT_MAX_CONNECTIONS;\n\tserver.on(\"error\", (error) => onError(error instanceof Error ? error.message : String(error)));\n\tconst port = await new Promise((resolve, reject) => {\n\t\tconst onListenError = (error) => reject(error);\n\t\tserver.once(\"error\", onListenError);\n\t\tserver.listen({\n\t\t\tport: options.port,\n\t\t\thost: options.host ?? \"0.0.0.0\"\n\t\t}, () => {\n\t\t\tserver.off(\"error\", onListenError);\n\t\t\tconst address = server.address();\n\t\t\tif (address === null || typeof address !== \"object\") {\n\t\t\t\treject(/* @__PURE__ */ new Error(\"Runner health listener bound no address\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve(address.port);\n\t\t});\n\t}).catch((error) => {\n\t\tserver.close(() => void 0);\n\t\tthrow error;\n\t});\n\tlet closed = false;\n\treturn {\n\t\tport,\n\t\tasync close() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tfor (const socket of sockets) socket.destroy();\n\t\t\tsockets.clear();\n\t\t\tawait new Promise((resolve) => {\n\t\t\t\tserver.close(() => resolve());\n\t\t\t});\n\t\t}\n\t};\n}\n//#endregion\n//#region src/runner/serve-workspace.ts\n/** Serializes the existing native occupation boundary with archive I/O, without another lifecycle. */\nvar ServeWorkspace = class {\n\t#workspace;\n\t#sandbox;\n\t#state;\n\t#turns;\n\t#blocked = true;\n\t#sealing = false;\n\t#serial = Promise.resolve();\n\t#sealInFlight;\n\tconstructor(input) {\n\t\tthis.#workspace = input.workspace;\n\t\tthis.#sandbox = input.sandbox;\n\t\tthis.#state = input.state;\n\t\tthis.#turns = input.turns;\n\t}\n\tget ready() {\n\t\treturn !this.#blocked && !this.#sealing && !this.#workspace.sealed && !this.#workspace.pendingSave;\n\t}\n\tget sealing() {\n\t\treturn this.#sealing;\n\t}\n\tasync prepare() {\n\t\tif (this.#sealing || this.#workspace.sealed || this.#workspace.terminalFailure) return false;\n\t\tif (this.#workspace.initialized && !this.#workspace.pendingSave && this.#state().present && !this.#blocked) return true;\n\t\tthis.#blocked = true;\n\t\tawait this.#turns.waitForActive();\n\t\tawait this.#state().active?.done;\n\t\treturn this.#enqueue(async () => {\n\t\t\tawait this.#quiesce();\n\t\t\tawait this.#workspace.initialize();\n\t\t\tif (this.#workspace.sealed || this.#sealing || this.#state().stopping) return false;\n\t\t\tawait this.#launch();\n\t\t\tthis.#blocked = false;\n\t\t\treturn true;\n\t\t});\n\t}\n\tcheckpoint() {\n\t\tthis.#blocked = true;\n\t\treturn this.#enqueue(async () => {\n\t\t\tawait this.#quiesce();\n\t\t\tawait this.#workspace.save();\n\t\t\tawait this.#launch();\n\t\t\tthis.#blocked = this.#sealing || this.#state().stopping;\n\t\t});\n\t}\n\tseal() {\n\t\tif (this.#sealInFlight) return this.#sealInFlight;\n\t\tthis.#blocked = true;\n\t\tthis.#sealing = true;\n\t\tconst run = this.#seal().finally(() => {\n\t\t\tthis.#sealInFlight = void 0;\n\t\t});\n\t\tthis.#sealInFlight = run;\n\t\treturn run;\n\t}\n\tasync #seal() {\n\t\tthis.#state().active?.abort.abort();\n\t\tawait this.#state().active?.done;\n\t\tawait this.#turns.drainForRelease(RUNNER_WORKSPACE_TIMEOUT_MS);\n\t\tawait this.#enqueue(async () => {\n\t\t\tawait this.#quiesce();\n\t\t\tawait this.#workspace.save(true);\n\t\t});\n\t}\n\tasync #quiesce() {\n\t\tconst state = this.#state();\n\t\tif (!state.present) return;\n\t\ttry {\n\t\t\tawait this.#sandbox.destroy();\n\t\t\tstate.present = false;\n\t\t} catch (error) {\n\t\t\tstate.fatal = true;\n\t\t\tthrow error;\n\t\t}\n\t}\n\tasync #launch() {\n\t\tconst state = this.#state();\n\t\tif (this.#sealing || state.stopping) return;\n\t\tstate.present = true;\n\t\ttry {\n\t\t\tawait this.#sandbox.launch();\n\t\t\tstate.probe = await this.#sandbox.probe();\n\t\t} catch (error) {\n\t\t\tstate.fatal = true;\n\t\t\tthrow error;\n\t\t}\n\t}\n\t#enqueue(operation) {\n\t\tconst pending = this.#serial.then(operation, operation);\n\t\tthis.#serial = pending.catch(() => void 0);\n\t\treturn pending;\n\t}\n};\n/** Strict hop-budget grammar shared with the parent gateway: 1..7 ASCII digits, positive. */\nconst WEB_BRIDGE_BUDGET_PATTERN = /^[0-9]{1,7}$/;\nconst WEB_BRIDGE_SOURCE = `\n\"use strict\";\nconst http = require(\"node:http\");\nconst fs = require(\"node:fs\");\nconst socketPath = process.argv[1];\nif (typeof socketPath !== \"string\" || socketPath[0] !== \"/\" || socketPath.includes(\"\\\\n\")) {\n  process.stderr.write(\"web bridge socket path is required\\\\n\");\n  process.exit(2);\n}\nconst MAX_FRAME = 6291456;\nconst MAX_REQUEST = 16384;\nconst SEARCH_CAP = ${WEB_SEARCH_TIMEOUT_CAP_MS};\nconst FETCH_CAP = ${WEB_FETCH_TIMEOUT_CAP_MS};\nconst BUDGET_PATTERN = /^[0-9]{1,7}$/;\nlet socketIdentity;\ntry {\n  socketIdentity = fs.statSync(socketPath);\n} catch (error) {\n  if (error.code !== \"ENOENT\") {\n    process.stderr.write(\"web bridge socket path is unreadable\\\\n\");\n    process.exit(2);\n  }\n}\nif (socketIdentity) {\n  process.stderr.write(\"web bridge socket path is occupied\\\\n\");\n  process.exit(2);\n}\nlet input = Buffer.alloc(0);\nlet nextId = 1;\nlet closing = false;\nconst pending = new Map();\nconst writeFrame = (value) => {\n  const body = Buffer.from(JSON.stringify(value), \"utf8\");\n  const frame = Buffer.allocUnsafe(4 + body.length);\n  frame.writeUInt32BE(body.length, 0);\n  body.copy(frame, 4);\n  process.stdout.write(frame);\n};\nconst sendLocal = (response, status, code, message, retryable) => {\n  if (response.headersSent || response.destroyed) return;\n  response.writeHead(status, { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" });\n  response.end(\n    JSON.stringify({ error: { code, message, ...(retryable === undefined ? {} : { retryable }) } }),\n  );\n};\nconst shutdown = (code) => {\n  if (closing) return;\n  closing = true;\n  try {\n    server.close(() => {});\n  } catch (error) {\n    /* Listener already closed. */\n  }\n  for (const entry of pending.values()) {\n    try {\n      entry.response.destroy();\n    } catch (error) {\n      /* Response already gone. */\n    }\n  }\n  pending.clear();\n  try {\n    const current = fs.lstatSync(socketPath);\n    if (\n      socketIdentity &&\n      current.isSocket() &&\n      current.dev === socketIdentity.dev &&\n      current.ino === socketIdentity.ino\n    ) {\n      fs.unlinkSync(socketPath);\n    }\n  } catch (error) {\n    /* The socket is already gone or belongs to a successor. */\n  }\n  process.exit(code);\n};\nconst handleFrame = (frame) => {\n  if (!frame || typeof frame !== \"object\") return;\n  if (frame.t === \"response\" && Number.isSafeInteger(frame.id)) {\n    const entry = pending.get(frame.id);\n    if (!entry) return;\n    pending.delete(frame.id);\n    if (entry.response.writableEnded || entry.response.destroyed) return;\n    entry.response.writeHead(\n      Number.isSafeInteger(frame.status) ? frame.status : 500,\n      { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" },\n    );\n    entry.response.end(typeof frame.body === \"string\" ? frame.body : \"\");\n    return;\n  }\n  if (frame.t === \"cancel\" && Number.isSafeInteger(frame.id)) {\n    const entry = pending.get(frame.id);\n    if (!entry) return;\n    pending.delete(frame.id);\n    entry.response.destroy();\n  }\n};\n/**\n * One request under the strict monotonic ingress budget. The deadline starts before the body is\n * read; an unfinished body yields a bounded 504 instead of hanging until the parent safety\n * timeout, and the forwarded frame carries only the budget that is actually left.\n */\nconst onRequest = (request, response) => {\n  const pathName = request.url;\n  const operation = pathName === \"/web/search\" ? \"search\" : pathName === \"/web/fetch\" ? \"fetch\" : undefined;\n  if (!operation) {\n    sendLocal(response, 404, \"invalid_request\", \"Unknown web gateway operation\");\n    request.resume();\n    return;\n  }\n  const cap = operation === \"search\" ? SEARCH_CAP : FETCH_CAP;\n  const rawRemaining = request.headers[\"x-web-remaining-ms\"];\n  let budget = cap;\n  if (rawRemaining !== undefined) {\n    const value = Array.isArray(rawRemaining) ? rawRemaining[0] : rawRemaining;\n    if (typeof value !== \"string\" || !BUDGET_PATTERN.test(value) || Number(value) < 1) {\n      sendLocal(response, 400, \"invalid_request\", \"The web bridge request budget is invalid\");\n      request.resume();\n      return;\n    }\n    budget = Math.min(Number(value), cap);\n  }\n  const deadlineAt = Date.now() + budget;\n  const chunks = [];\n  let total = 0;\n  let settled = false;\n  const settle = (callback) => {\n    if (settled) return;\n    settled = true;\n    clearTimeout(timer);\n    callback();\n  };\n  const timer = setTimeout(() => {\n    settle(() => {\n      sendLocal(response, 504, \"timeout\", \"The web request budget was exhausted\", true);\n      request.pause();\n    });\n  }, budget);\n  timer.unref?.();\n  request.on(\"data\", (chunk) => {\n    if (settled) return;\n    total += chunk.length;\n    if (total > MAX_REQUEST) {\n      settle(() => {\n        sendLocal(response, 413, \"invalid_request\", \"The web bridge request exceeds the bound\");\n        request.pause();\n      });\n      return;\n    }\n    chunks.push(chunk);\n  });\n  request.on(\"end\", () => {\n    settle(() => {\n      const remaining = deadlineAt - Date.now();\n      if (remaining <= 0) {\n        sendLocal(response, 504, \"timeout\", \"The web request budget was exhausted\", true);\n        return;\n      }\n      const id = nextId++;\n      pending.set(id, { response });\n      response.on(\"close\", () => {\n        if (!response.writableFinished && pending.delete(id)) writeFrame({ t: \"cancel\", id });\n      });\n      writeFrame({\n        t: \"request\",\n        id,\n        path: pathName,\n        body: Buffer.concat(chunks).toString(\"base64\"),\n        remaining: String(remaining),\n      });\n    });\n  });\n  request.on(\"aborted\", () => settle(() => {}));\n  request.on(\"error\", () => settle(() => {}));\n};\nconst server = http.createServer((request, response) => {\n  if (request.method !== \"POST\") {\n    sendLocal(response, 404, \"invalid_request\", \"Unknown web bridge operation\");\n    request.resume();\n    return;\n  }\n  onRequest(request, response);\n});\nserver.on(\"error\", (error) => {\n  process.stderr.write(\"web bridge listener failed: \" + (error && error.code ? error.code : \"error\") + \"\\\\n\");\n  process.exit(2);\n});\nprocess.on(\"SIGTERM\", () => shutdown(0));\nprocess.on(\"SIGINT\", () => shutdown(0));\nprocess.stdin.on(\"data\", (chunk) => {\n  input = Buffer.concat([input, chunk]);\n  for (;;) {\n    if (input.length < 4) return;\n    const size = input.readUInt32BE(0);\n    if (size > MAX_FRAME) {\n      process.stderr.write(\"web bridge frame exceeds the bound\\\\n\");\n      shutdown(3);\n      return;\n    }\n    if (input.length < 4 + size) return;\n    const payload = input.subarray(4, 4 + size);\n    input = input.subarray(4 + size);\n    try {\n      handleFrame(JSON.parse(payload.toString(\"utf8\")));\n    } catch (error) {\n      shutdown(3);\n      return;\n    }\n  }\n});\nprocess.stdin.on(\"end\", () => shutdown(0));\nprocess.stdin.resume();\nserver.listen(socketPath, () => {\n  try {\n    fs.chmodSync(socketPath, 0o600);\n  } catch (error) {\n    /* Best-effort permission tightening inside the Sandbox namespace. */\n  }\n  socketIdentity = fs.statSync(socketPath);\n  writeFrame({ t: \"ready\" });\n});\n`;\n//#endregion\n//#region src/runner/web-gateway.ts\n/** Kernel-bound Unix socket path used by the in-Sandbox bridge; leave headroom below 104. */\nconst BRIDGE_SOCKET_PATH_MAX_BYTES = 90;\nconst DEFAULT_BRIDGE_STARTUP_TIMEOUT_MS = 1e4;\nconst BRIDGE_SHUTDOWN_TIMEOUT_MS = 2e3;\n/** One live execution channel: a dedicated bridge process and its own in-Sandbox listener. */\nvar NativeWebExecutionChannel = class NativeWebExecutionChannel {\n\t#authority;\n\t#duplex;\n\t#logger;\n\t#now;\n\t#inflight = /* @__PURE__ */ new Map();\n\t#decoder = new FrameDecoder();\n\t#closed = false;\n\t#terminated = false;\n\t#closeNotified = false;\n\t#closePromise;\n\t#readySettled = false;\n\t#readyResolve = () => void 0;\n\t#readyReject = () => void 0;\n\t#readyPromise;\n\t#closedPromise;\n\t#onClosed;\n\t#closedResolve = () => void 0;\n\t/** Nonsecret descriptor for Pi's `OPENTAG_WEB_TOOLS_SOCKET` inside the Sandbox. */\n\tsocketPath;\n\tconstructor(socketPath, duplex, authority, logger, now, onClosed) {\n\t\tthis.socketPath = socketPath;\n\t\tthis.#duplex = duplex;\n\t\tthis.#authority = authority;\n\t\tthis.#logger = logger;\n\t\tthis.#now = now;\n\t\tthis.#onClosed = onClosed;\n\t\tthis.#readyPromise = new Promise((resolve, reject) => {\n\t\t\tthis.#readyResolve = resolve;\n\t\t\tthis.#readyReject = reject;\n\t\t});\n\t\tthis.#closedPromise = new Promise((resolve) => {\n\t\t\tthis.#closedResolve = resolve;\n\t\t});\n\t\tthis.#duplex.onData((chunk) => this.#onData(chunk));\n\t\tthis.#duplex.onStderr((chunk) => {\n\t\t\ttry {\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tcode: \"native_web_bridge_stderr\",\n\t\t\t\t\tbytes: chunk.byteLength\n\t\t\t\t}, \"Sandbox web bridge wrote to stderr\");\n\t\t\t} catch {}\n\t\t});\n\t\tthis.#duplex.onError((error) => this.#fail(error));\n\t\tthis.#duplex.onExit((code, signal) => {\n\t\t\tthis.#fail(new NativeSandboxError(\"exec_failed\", `Sandbox web bridge exited (${code ?? signal ?? \"unknown\"})`));\n\t\t});\n\t}\n\tstatic async open(input) {\n\t\tif (!input.authority.executionIdentity) throw new NativeSandboxError(\"launch_failed\", \"A web execution authority needs a nonempty identity\");\n\t\tif (input.authority.signal?.aborted) throw new NativeSandboxError(\"exec_failed\", \"The web execution authority is already revoked\");\n\t\tconst socketPath = `${SANDBOX_WEB_BRIDGE_DIRECTORY}/opentag-web-${randomBytes(8).toString(\"hex\")}.sock`;\n\t\tif (Buffer.byteLength(socketPath) > BRIDGE_SOCKET_PATH_MAX_BYTES) throw new NativeSandboxError(\"launch_failed\", \"The sandbox web bridge socket path exceeds the platform bound\");\n\t\tconst duplex = input.sandbox.openDuplex(SANDBOX_NODE, [\n\t\t\t\"-e\",\n\t\t\tWEB_BRIDGE_SOURCE,\n\t\t\tsocketPath\n\t\t]);\n\t\tconst logger = input.logger ?? createLogger(\"native-web-gateway\");\n\t\tconst channel = new NativeWebExecutionChannel(socketPath, duplex, input.authority, logger, input.now ?? Date.now, input.onClosed);\n\t\ttry {\n\t\t\tawait channel.#waitForReady(input.startupTimeoutMs ?? DEFAULT_BRIDGE_STARTUP_TIMEOUT_MS);\n\t\t} catch (error) {\n\t\t\tawait channel.close();\n\t\t\tthrow error;\n\t\t}\n\t\tinput.authority.signal?.addEventListener(\"abort\", () => void channel.close(), { once: true });\n\t\tif (input.authority.signal?.aborted) await channel.close();\n\t\treturn channel;\n\t}\n\tget closed() {\n\t\treturn this.#closed;\n\t}\n\t/** Resolves once the channel is closed by any path (explicit close, exit, or revocation). */\n\tget whenClosed() {\n\t\treturn this.#closedPromise;\n\t}\n\t/**\n\t* Cancel in-flight work, stop the bridge, and let the bridge remove only its own listener.\n\t* Concurrent/repeated calls await the same in-progress close instead of falsely reporting\n\t* completion before the listener and bridge process are actually gone.\n\t*/\n\tclose() {\n\t\tthis.#closePromise ??= this.#close();\n\t\treturn this.#closePromise;\n\t}\n\tasync #close() {\n\t\tthis.#closed = true;\n\t\tfor (const controller of this.#inflight.values()) controller.abort(/* @__PURE__ */ new Error(\"web execution channel closed\"));\n\t\tthis.#inflight.clear();\n\t\tthis.#failReadyIfPending(new NativeSandboxError(\"exec_failed\", \"The sandbox web bridge closed before ready\"));\n\t\tif (this.#terminated) {\n\t\t\tthis.#notifyClosed();\n\t\t\tthis.#closedResolve();\n\t\t\treturn;\n\t\t}\n\t\tthis.#terminated = true;\n\t\tthis.#duplex.end();\n\t\tif (!await this.#waitForExit(BRIDGE_SHUTDOWN_TIMEOUT_MS)) {\n\t\t\tthis.#duplex.kill(\"SIGKILL\");\n\t\t\tawait this.#waitForExit(BRIDGE_SHUTDOWN_TIMEOUT_MS);\n\t\t}\n\t\tthis.#notifyClosed();\n\t\tthis.#closedResolve();\n\t}\n\t#onData(chunk) {\n\t\tif (this.#closed) return;\n\t\tlet frames;\n\t\ttry {\n\t\t\tframes = this.#decoder.push(chunk);\n\t\t} catch {\n\t\t\tthis.#duplex.kill(\"SIGKILL\");\n\t\t\tthis.#fail(new NativeSandboxError(\"exec_failed\", \"The sandbox web bridge sent an invalid frame\"));\n\t\t\treturn;\n\t\t}\n\t\tfor (const frame of frames) this.#handleFrame(frame);\n\t}\n\t#handleFrame(frame) {\n\t\tif (!frame || typeof frame !== \"object\" || Array.isArray(frame)) return;\n\t\tconst record = frame;\n\t\tif (record.t === \"ready\") {\n\t\t\tif (!this.#readySettled) {\n\t\t\t\tthis.#readySettled = true;\n\t\t\t\tthis.#readyResolve();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (record.t === \"request\") {\n\t\t\tthis.#handleRequest(record).catch(() => void 0);\n\t\t\treturn;\n\t\t}\n\t\tif (record.t === \"cancel\" && Number.isSafeInteger(record.id)) this.#inflight.get(record.id)?.abort(/* @__PURE__ */ new Error(\"web request cancelled\"));\n\t}\n\tasync #handleRequest(frame) {\n\t\tif (this.#closed) return;\n\t\tconst id = frame.id;\n\t\tif (!Number.isSafeInteger(id)) return;\n\t\tconst path = frame.path;\n\t\tconst operation = path === \"/web/search\" ? \"search\" : path === \"/web/fetch\" ? \"fetch\" : void 0;\n\t\tif (operation === void 0) {\n\t\t\tthis.#writeResponse(id, 404, JSON.stringify({ error: {\n\t\t\t\tcode: \"invalid_request\",\n\t\t\t\tmessage: \"Unknown web gateway operation\"\n\t\t\t} }));\n\t\t\treturn;\n\t\t}\n\t\tconst rawBody = decodeBridgeBody(frame.body);\n\t\tif (!rawBody) {\n\t\t\tthis.#writeResponse(id, 400, JSON.stringify({ error: {\n\t\t\t\tcode: \"invalid_request\",\n\t\t\t\tmessage: \"The web gateway request is not valid base64\"\n\t\t\t} }));\n\t\t\treturn;\n\t\t}\n\t\tconst remaining = frame.remaining;\n\t\tif (typeof remaining !== \"string\" || !WEB_BRIDGE_BUDGET_PATTERN.test(remaining) || Number(remaining) < 1) {\n\t\t\tthis.#writeResponse(id, 400, JSON.stringify({ error: {\n\t\t\t\tcode: \"invalid_request\",\n\t\t\t\tmessage: \"The web bridge request budget is invalid\"\n\t\t\t} }));\n\t\t\treturn;\n\t\t}\n\t\tconst controller = new AbortController();\n\t\tthis.#inflight.set(id, controller);\n\t\ttry {\n\t\t\tconst outcome = await executeGatewayCall({\n\t\t\t\toperation,\n\t\t\t\trawBody,\n\t\t\t\tremainingHeader: remaining,\n\t\t\t\tdispatch: (input, signal) => this.#authority.dispatch(input, signal),\n\t\t\t\tsignal: controller.signal,\n\t\t\t\tnow: this.#now,\n\t\t\t\tlogger: this.#logger\n\t\t\t});\n\t\t\tthis.#writeResponse(id, outcome.status, outcome.body);\n\t\t} finally {\n\t\t\tthis.#inflight.delete(id);\n\t\t}\n\t}\n\t#writeResponse(id, status, body) {\n\t\tif (this.#closed) return;\n\t\tthis.#duplex.write(encodeFrame({\n\t\t\tt: \"response\",\n\t\t\tid,\n\t\t\tstatus,\n\t\t\tbody\n\t\t}));\n\t}\n\tasync #waitForReady(startupTimeoutMs) {\n\t\tlet timer;\n\t\ttry {\n\t\t\tawait Promise.race([this.#readyPromise, new Promise((_resolve, reject) => {\n\t\t\t\ttimer = setTimeout(() => reject(new NativeSandboxError(\"exec_failed\", \"The sandbox web bridge did not become ready\")), startupTimeoutMs);\n\t\t\t\ttimer.unref?.();\n\t\t\t})]);\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t}\n\t#failReadyIfPending(error) {\n\t\tif (this.#readySettled) return;\n\t\tthis.#readySettled = true;\n\t\tthis.#readyReject(error);\n\t}\n\t#fail(error) {\n\t\tconst normalized = error instanceof Error ? error : new Error(String(error));\n\t\tthis.#failReadyIfPending(normalized);\n\t\tthis.#duplex.kill(\"SIGKILL\");\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tfor (const controller of this.#inflight.values()) controller.abort(normalized);\n\t\tthis.#inflight.clear();\n\t\tthis.#notifyClosed();\n\t\tthis.#closedResolve();\n\t}\n\t#notifyClosed() {\n\t\tif (this.#closeNotified) return;\n\t\tthis.#closeNotified = true;\n\t\ttry {\n\t\t\tthis.#onClosed?.();\n\t\t} catch {}\n\t}\n\t#exitPromise;\n\t#waitForExit(timeoutMs) {\n\t\tthis.#exitPromise ??= new Promise((resolve) => {\n\t\t\tthis.#duplex.onExit(() => resolve());\n\t\t\tthis.#duplex.onError(() => resolve());\n\t\t});\n\t\treturn Promise.race([this.#exitPromise.then(() => true), new Promise((resolve) => {\n\t\t\tsetTimeout(() => resolve(false), timeoutMs).unref?.();\n\t\t})]);\n\t}\n};\n/** Strict length-prefixed frame decoder; any malformed size is a fatal channel condition. */\nvar FrameDecoder = class {\n\t#buffer = Buffer.alloc(0);\n\tpush(chunk) {\n\t\tthis.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk]);\n\t\tconst frames = [];\n\t\tfor (;;) {\n\t\t\tif (this.#buffer.length < 4) break;\n\t\t\tconst size = this.#buffer.readUInt32BE(0);\n\t\t\tif (size > 6291456) throw new Error(\"The sandbox web bridge frame exceeds the bound\");\n\t\t\tif (this.#buffer.length < 4 + size) break;\n\t\t\tconst payload = this.#buffer.subarray(4, 4 + size);\n\t\t\tthis.#buffer = this.#buffer.subarray(4 + size);\n\t\t\tframes.push(JSON.parse(payload.toString(\"utf8\")));\n\t\t}\n\t\treturn frames;\n\t}\n};\nfunction encodeFrame(value) {\n\tconst body = Buffer.from(JSON.stringify(value), \"utf8\");\n\tconst frame = Buffer.allocUnsafe(4 + body.length);\n\tframe.writeUInt32BE(body.length, 0);\n\tbody.copy(frame, 4);\n\treturn frame;\n}\nfunction decodeBridgeBody(raw) {\n\tif (typeof raw !== \"string\" || raw.length > 6291456) return void 0;\n\tconst decoded = Buffer.from(raw, \"base64\");\n\tif (decoded.toString(\"base64\").replace(/=+$/, \"\") !== raw.replace(/=+$/, \"\")) return void 0;\n\treturn decoded;\n}\n/**\n* Native Sandbox parent boundary for web tools. There is no parent-side or network listener:\n* one verified `sandbox exec` duplex pipe per exact execution carries strict bounded frames to a\n* listener inside the Sandbox namespace. Because every execution opens its own bridge process\n* and socket descriptor, an old process can never reach a successor execution, and revocation\n* cancels in-flight dispatches and lets the bridge remove only its own listener.\n*/\nvar NativeSandboxWebGateway = class NativeSandboxWebGateway {\n\t#sandboxName;\n\t#logger;\n\t#now;\n\t#active;\n\t#opening = false;\n\t#closePromise;\n\t#closed = false;\n\tconstructor(options, now) {\n\t\tthis.#sandboxName = options.sandboxName;\n\t\tthis.#logger = options.logger ?? createLogger(\"native-web-gateway\");\n\t\tthis.#now = now;\n\t}\n\tget sandboxName() {\n\t\treturn this.#sandboxName;\n\t}\n\t/** No listener is created at start; production stays fail-closed until an execution opens one. */\n\tstatic async start(options) {\n\t\treturn new NativeSandboxWebGateway(options, options.now ?? Date.now);\n\t}\n\t/**\n\t* Open the dedicated channel for one exact execution: a fresh bridge process and a fresh\n\t* nonsecret socket descriptor inside the Sandbox. One gateway holds at most one channel, so\n\t* replacing an authority requires closing the predecessor first; there is no retarget path.\n\t* A close/revoke fully releases the slot (synchronously, before `close()` resolves) so the same\n\t* long-lived gateway can serve a successor execution; a second overlapping open or an\n\t* already-revoked authority fails before any bridge process is spawned.\n\t*/\n\tasync openExecution(input) {\n\t\tif (this.#closed) throw new NativeSandboxError(\"exec_failed\", \"The native web gateway is closed\");\n\t\tif (this.#active || this.#opening) throw new NativeSandboxError(\"exec_failed\", \"The native web gateway already has an active execution channel; close it before opening a successor\");\n\t\tif (input.sandbox.name !== this.#sandboxName) throw new NativeSandboxError(\"exec_failed\", \"The web execution channel must target this Sandbox\");\n\t\tif (input.authority.signal?.aborted) throw new NativeSandboxError(\"exec_failed\", \"The web execution authority is already revoked\");\n\t\tthis.#opening = true;\n\t\tlet channel;\n\t\ttry {\n\t\t\tchannel = await NativeWebExecutionChannel.open({\n\t\t\t\tsandbox: input.sandbox,\n\t\t\t\tauthority: input.authority,\n\t\t\t\tlogger: this.#logger,\n\t\t\t\tnow: this.#now,\n\t\t\t\tonClosed: () => {\n\t\t\t\t\tif (this.#active === channel) this.#active = void 0;\n\t\t\t\t},\n\t\t\t\t...input.startupTimeoutMs !== void 0 ? { startupTimeoutMs: input.startupTimeoutMs } : {}\n\t\t\t});\n\t\t\tthis.#active = channel;\n\t\t\treturn channel;\n\t\t} finally {\n\t\t\tthis.#opening = false;\n\t\t}\n\t}\n\t/** Close the active execution channel (when any) and refuse all future openings. Idempotent. */\n\tclose() {\n\t\tthis.#closePromise ??= this.#close();\n\t\treturn this.#closePromise;\n\t}\n\tasync #close() {\n\t\tthis.#closed = true;\n\t\tconst active = this.#active;\n\t\tthis.#active = void 0;\n\t\tawait active?.close().catch(() => void 0);\n\t}\n};\n//#endregion\n//#region src/runner/serve.ts\nconst DEFAULT_AUTH_TIMEOUT_MS = 5e3;\nconst PERSISTENT_AUTH_TIMEOUT_MS = 45e3;\nconst DEFAULT_MAX_RECONNECT_ATTEMPTS = 8;\nfunction logLine(io, message) {\n\tio.write(`[opentag-runner serve] ${message}\\n`);\n}\nfunction isLoopbackHostname(hostname) {\n\tconst value = hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n\treturn value === \"localhost\" || value === \"::1\" || isIP(value) === 4 && value.startsWith(\"127.\");\n}\n/** wss only outside loopback; TLS verification is the library default and is never relaxed. */\nfunction resolveRunnerBackendUrl(raw) {\n\tlet url;\n\ttry {\n\t\turl = new URL(raw);\n\t} catch {\n\t\tthrow new Error(\"OPENTAG_RUNNER_BACKEND_URL is not a valid URL\");\n\t}\n\tif (url.protocol === \"https:\") url.protocol = \"wss:\";\n\tif (url.protocol === \"ws:\" && !isLoopbackHostname(url.hostname)) throw new Error(\"OPENTAG_RUNNER_BACKEND_URL must use wss:// outside loopback\");\n\tif (url.protocol !== \"wss:\" && url.protocol !== \"ws:\") throw new Error(\"OPENTAG_RUNNER_BACKEND_URL must be a WebSocket URL\");\n\tif (url.username || url.password || url.search || url.hash) throw new Error(\"OPENTAG_RUNNER_BACKEND_URL must not carry credentials, query, or fragment\");\n\treturn url.toString();\n}\n/**\n* The Runner image and the Cloud Run Instance declare exactly this single container port, and the\n* platform's default startup TCP probe targets it. An injected `PORT` stays the strict override;\n* absence must not disable the listener.\n*/\nconst DECLARED_CONTAINER_PORT = 8080;\nfunction loadRunnerServeConfig(env) {\n\tconst backendRaw = env.OPENTAG_RUNNER_BACKEND_URL;\n\tif (!backendRaw) throw new Error(\"OPENTAG_RUNNER_BACKEND_URL is required for serve mode\");\n\tconst token = env.OPENTAG_RUNNER_BOOTSTRAP_TOKEN;\n\tif (!token) throw new Error(\"OPENTAG_RUNNER_BOOTSTRAP_TOKEN is required for serve mode (env only, never argv)\");\n\tconst sandboxName = env.OPENTAG_RUNNER_SANDBOX_NAME ?? \"ots-runner\";\n\tif (!/^[a-z][a-z0-9-]{0,62}$/.test(sandboxName)) throw new Error(\"OPENTAG_RUNNER_SANDBOX_NAME is not a safe sandbox name\");\n\tconst healthPort = parseRunnerHealthPort(env.PORT) ?? DECLARED_CONTAINER_PORT;\n\tconst persistence = env.OPENTAG_RUNNER_WORKSPACE_PERSISTENCE;\n\tif (persistence !== void 0 && persistence !== \"1\" && persistence !== \"0\") throw new Error(\"OPENTAG_RUNNER_WORKSPACE_PERSISTENCE must be 1 or 0\");\n\tconst controlToken = env.OPENTAG_RUNNER_CONTROL_TOKEN;\n\tif (controlToken !== void 0 && (controlToken.length === 0 || controlToken.length > 8192)) throw new Error(\"OPENTAG_RUNNER_CONTROL_TOKEN is not a valid credential\");\n\treturn {\n\t\tbackendUrl: resolveRunnerBackendUrl(backendRaw),\n\t\tbootstrapToken: token,\n\t\t...controlToken ? { controlToken } : {},\n\t\tsandboxName,\n\t\tworkspace: env.OPENTAG_RUNNER_WORKSPACE ?? join(tmpdir(), \"opentag-runner-workspaces\", sandboxName),\n\t\tstateDir: env.OPENTAG_RUNNER_STATE_DIR ?? defaultRunnerStateDir(sandboxName),\n\t\thealthPort,\n\t\t...persistence === \"1\" ? { workspacePersistence: true } : {}\n\t};\n}\n/**\n* Only an exact integer 1..65535 is accepted; absence falls back to the declared container port\n* in `loadRunnerServeConfig`, while 0 and out-of-range values remain configuration errors (the\n* helper itself accepts 0 so tests can request an ephemeral port directly).\n*/\nfunction parseRunnerHealthPort(value) {\n\tif (value === void 0) return void 0;\n\tconst port = Number(value);\n\tif (!Number.isInteger(port) || port < 1 || port > 65535 || String(port) !== value) throw new Error(\"PORT must be an integer between 1 and 65535\");\n\treturn port;\n}\n/** Bound on queued Cloud control work per connection; overflow is a protocol anomaly, not memory. */\nconst MAX_PENDING_CLOUD_CONTROL = 128;\n/**\n* Trusted E4 state layout. The public root is the ONLY directory that becomes a Sandbox mount;\n* the journal and per-turn private material (adapter CA private key) stay disjoint from it.\n*/\nfunction cloudRunnerDirectories(stateDir) {\n\treturn {\n\t\tjournalDir: join(stateDir, \"journal\"),\n\t\tprivateTurnRoot: join(stateDir, \"turn-material\"),\n\t\tpublicRoot: join(stateDir, \"bridge-public\")\n\t};\n}\n/**\n* Longest per-Sandbox state directory segment. Long names keep the first 32 characters plus a\n* `-<8 hex digest>` suffix (41 characters), keeping per-turn public material paths short and\n* stable even for the 63-character maximum valid Sandbox name.\n*/\nconst RUNNER_STATE_SEGMENT_MAX = 32;\n/**\n* Per-Sandbox state directory segment. Bounded so public material paths stay short and stable\n* for any accepted Sandbox name, while the deterministic hash\n* keeps one distinct durable journal/private root per Sandbox.\n*/\nfunction runnerStateDirectorySegment(sandboxName) {\n\tif (sandboxName.length <= RUNNER_STATE_SEGMENT_MAX) return sandboxName;\n\tconst digest = createHash(\"sha256\").update(sandboxName).digest(\"hex\").slice(0, 8);\n\treturn `${sandboxName.slice(0, RUNNER_STATE_SEGMENT_MAX)}-${digest}`;\n}\n/**\n* Default trusted Runner state root. `temporaryRoot` is injectable so tests can compute the exact\n* production path length; production always uses the platform temp root.\n*/\nfunction defaultRunnerStateDir(sandboxName, temporaryRoot = tmpdir()) {\n\treturn join(temporaryRoot, \"ots\", runnerStateDirectorySegment(sandboxName));\n}\n/** Assignment identity used to bind a Session bearer to the welcome that produced it. */\nfunction assignmentKey(scope) {\n\treturn `${scope.sandboxId}:${scope.environmentGeneration}`;\n}\n/** Apply one credential frame: bind the Session bearer to the assignment that received it. */\nfunction applyCredential(state, bridge, credentials) {\n\tif (credentials.token) {\n\t\tstate.token = credentials.token;\n\t\tstate.tokenScope = bridge.scope ? assignmentKey(bridge.scope) : void 0;\n\t}\n\tif (credentials.controlToken) state.controlToken = credentials.controlToken;\n\tstate.credentialEpoch += 1;\n\tfor (const waiter of state.credentialWaiters.splice(0)) waiter();\n}\n/**\n* Wait for a `server:credential` that arrives after `epoch`. A credential received before this\n* call resolves immediately. A timeout REJECTS: preparing against a bearer that is not proven to\n* belong to the current assignment must fail closed, never proceed on the expectation that the\n* old token might still work.\n*/\nfunction waitForCredentialAfter(state, epoch, timeoutMs) {\n\tif (state.credentialEpoch > epoch) return Promise.resolve();\n\tif (state.credentialInterrupt) return Promise.reject(state.credentialInterrupt);\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst finish = (error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timer);\n\t\t\tstate.credentialWaiters = state.credentialWaiters.filter((waiter) => waiter !== finish);\n\t\t\tif (error) reject(error);\n\t\t\telse resolve();\n\t\t};\n\t\tconst timer = setTimeout(() => finish(/* @__PURE__ */ new Error(\"the assignment credential was not received before the deadline\")), timeoutMs);\n\t\ttimer.unref?.();\n\t\tstate.credentialWaiters.push(finish);\n\t});\n}\n/**\n* The Session bearer for the CURRENT assignment. A fresh first bind may use the bearer minted for\n* it at Instance creation; a restart or a changed assignment must receive the Server's bearer for\n* the holder before any workspace HTTP claim. The check also covers the case where the credential\n* arrived before the serialized restore operation ran.\n*/\nasync function ensureAssignmentCredential(state, scope, timeoutMs, options) {\n\tif (state.tokenScope === assignmentKey(scope)) return;\n\tif (!options.required && !state.assignmentRequired) return;\n\tconst baseline = state.credentialEpoch;\n\tawait waitForCredentialAfter(state, baseline, timeoutMs);\n\tif (state.tokenScope !== assignmentKey(scope)) throw new Error(\"the received credential does not belong to the current assignment\");\n}\n/**\n* The single per-process Cloud Turn controller. `canStart` composes the shared native occupation\n* boundary with the E3 acceptance run so Cloud Turns wait instead of racing a destroy/relaunch.\n*/\nfunction createCloudTurnRunner(input) {\n\tconst server = new URL(input.serverUrl);\n\tserver.protocol = server.protocol === \"wss:\" ? \"https:\" : \"http:\";\n\treturn new CloudTurnRunner({\n\t\tcanStart: () => {\n\t\t\tconst current = input.state();\n\t\t\treturn current !== void 0 && !current.stopping && current.active === void 0 && (!input.workspacePersistence || current.workspace?.ready === true);\n\t\t},\n\t\tcredentialChannel: () => input.bridge,\n\t\tjournal: input.journal,\n\t\tonPersistenceError: (error) => input.state()?.persistenceFailure?.(error),\n\t\tpublicDirectory: input.publicRoot,\n\t\tsandbox: input.sandbox,\n\t\t...input.webGateway ? { webGateway: input.webGateway } : {},\n\t\t...input.webExtensionPath ? { webExtensionPath: input.webExtensionPath } : {},\n\t\tsandboxReset: async () => {\n\t\t\tconst current = input.state();\n\t\t\tif (!current) throw new Error(\"The Runner sandbox state is not established\");\n\t\t\tawait recycleNativeSandbox(input.sandbox, current);\n\t\t},\n\t\t...input.workspacePersistence ? { checkpoint: async () => {\n\t\t\tconst workspace = input.state()?.workspace;\n\t\t\tif (!workspace) throw new Error(\"Workspace persistence is not initialized\");\n\t\t\tawait workspace.checkpoint();\n\t\t} } : {},\n\t\tscope: () => input.bridge.scope,\n\t\tsend: (frame) => input.bridge.sendFrame(frame),\n\t\tserverUrl: server.origin,\n\t\tstateDirectory: input.privateTurnRoot,\n\t\tlog: (message) => logLine(input.options.stderr, message),\n\t\t...input.options.cloudTurnSeams ?? {}\n\t});\n}\n/**\n* Per-process E4 channel bridge: the current connection's send function plus the credential\n* tunnel dispatch. A dropped connection removes its send function; journal-backed retransmission\n* happens on the next welcome, so a frame written to a dead connection is never lost silently —\n* it simply waits for the next reconcile.\n*/\nvar RunnerChannelBridge = class {\n\tsendFn;\n\tscope;\n\t/** True only after a negotiated `cloudDeliveryVersion: 1` welcome. Legacy E3 stays Cloud-free. */\n\tcloudEnabled = false;\n\t/** True only when the Server echoed the E8 Session-collaboration capability at the same welcome. */\n\tsessionCollaborationEnabled = false;\n\tcredentialListeners = /* @__PURE__ */ new Set();\n\tstateListeners = /* @__PURE__ */ new Set();\n\tsendFrame(frame) {\n\t\tif (!this.sendFn) throw new Error(\"The Runner control channel is not connected\");\n\t\tthis.sendFn(frame);\n\t}\n\tonCredentialFrame(listener) {\n\t\tthis.credentialListeners.add(listener);\n\t\treturn () => this.credentialListeners.delete(listener);\n\t}\n\tonChannelState(listener) {\n\t\tthis.stateListeners.add(listener);\n\t\treturn () => this.stateListeners.delete(listener);\n\t}\n\temitCredential(frame) {\n\t\tfor (const listener of [...this.credentialListeners]) listener(frame);\n\t}\n\temitState(state) {\n\t\tfor (const listener of [...this.stateListeners]) listener(state);\n\t}\n};\nasync function resetDirectory(directory) {\n\tawait rm(directory, {\n\t\trecursive: true,\n\t\tforce: true\n\t});\n\tawait mkdir(directory, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n}\nfunction attachWorkspace(config, options, current, sandbox, bridge, web) {\n\tcurrent.turns = createCloudTurnRunner({\n\t\tbridge,\n\t\tjournal: current.journal,\n\t\toptions,\n\t\tprivateTurnRoot: current.privateTurnRoot,\n\t\tpublicRoot: current.publicRoot,\n\t\tsandbox,\n\t\tserverUrl: config.backendUrl,\n\t\tstate: () => current,\n\t\twebExtensionPath: web.extensionPath,\n\t\twebGateway: web.gateway,\n\t\tworkspacePersistence: config.workspacePersistence === true\n\t});\n\tif (!config.workspacePersistence) return;\n\tcurrent.workspace = new ServeWorkspace({\n\t\tworkspace: new CloudWorkspace({\n\t\t\tbackendUrl: config.backendUrl,\n\t\t\tworkspace: config.workspace,\n\t\t\tstateDirectory: join(config.stateDir, \"workspace-private\"),\n\t\t\ttoken: () => current.token,\n\t\t\tenvironmentGeneration: () => bridge.scope?.environmentGeneration,\n\t\t\t...options.workspaceFetchImpl ? { fetchImpl: options.workspaceFetchImpl } : {}\n\t\t}),\n\t\tsandbox,\n\t\tstate: () => current,\n\t\tturns: current.turns\n\t});\n}\n/**\n* Gate for replacing the current assignment: a previous marker may be discarded only when it\n* recorded a successful seal; without a marker nothing may look like it could hold unsaved work.\n*/\nasync function assignmentReplacementAllowed(input) {\n\tif (input.assignment) {\n\t\tif (input.assignment.sealed) return true;\n\t\tlogLine(input.options.stderr, \"refusing a new assignment: the previous workspace was not sealed\");\n\t\treturn false;\n\t}\n\tif (!await hasUnmarkedAssignmentState({\n\t\tworkspace: input.config.workspace,\n\t\tjournalDir: input.current.journalDir,\n\t\tprivateTurnRoot: input.current.privateTurnRoot,\n\t\tpublicRoot: input.current.publicRoot\n\t})) return true;\n\tlogLine(input.options.stderr, \"refusing a new assignment: unmarked local workspace state exists\");\n\treturn false;\n}\n/**\n* E7 sealed-assignment discard: the previous assignment's durable work is settled, so its local\n* workspace, private credential material, public execution material and completed journal entries are\n* removed before a fresh controller/workspace is built. Every step is required; a failure fails\n* closed for the new assignment rather than executing over unproven local state.\n*/\nasync function discardSealedAssignment(input) {\n\tconst { config, options, current, sandbox, bridge, web, assignment } = input;\n\tawait current.turns.close();\n\tawait current.webExecution?.close();\n\tcurrent.webExecution = void 0;\n\tif (current.present) {\n\t\ttry {\n\t\t\tawait sandbox.destroy();\n\t\t} catch (error) {\n\t\t\tcurrent.fatal = true;\n\t\t\tthrow error;\n\t\t}\n\t\tcurrent.present = false;\n\t}\n\tawait current.journal.resetScope({\n\t\tsandboxId: assignment.sandboxId,\n\t\tsessionId: assignment.sessionId,\n\t\tenvironmentGeneration: assignment.environmentGeneration,\n\t\tresourceName: assignment.resourceName,\n\t\tresourceUid: assignment.resourceUid\n\t});\n\tawait resetDirectory(config.workspace);\n\tawait resetDirectory(current.privateTurnRoot);\n\tawait resetDirectory(current.publicRoot);\n\tcurrent.workspace = void 0;\n\tcurrent.journal = await CloudJournal.open(current.journalDir);\n\tattachWorkspace(config, options, current, sandbox, bridge, web);\n\tawait prepareServeWebExecution(current, web.gateway, sandbox, options);\n}\nasync function runRunnerServe(config, options) {\n\tconst gatewayStartup = await startServeWebGateway(config.sandboxName, options);\n\tif (gatewayStartup.exitCode !== void 0) return gatewayStartup.exitCode;\n\tconst web = {\n\t\tgateway: gatewayStartup.gateway,\n\t\textensionPath: await resolveServeWebExtensionPath(options)\n\t};\n\tconst webGateway = web.gateway;\n\tconst { journalDir, privateTurnRoot, publicRoot } = cloudRunnerDirectories(config.stateDir);\n\tawait mkdir(privateTurnRoot, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tawait mkdir(publicRoot, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tconst journal = await CloudJournal.open(journalDir);\n\tconst bridge = new RunnerChannelBridge();\n\tlet sandbox;\n\ttry {\n\t\tsandbox = (options.sandboxFactory ?? ((name, workspace) => new NativeSandbox({\n\t\t\tname,\n\t\t\tworkspace,\n\t\t\textraMounts: [{\n\t\t\t\tsource: publicRoot,\n\t\t\t\tdestination: \"/run/opentag-execution\"\n\t\t\t}]\n\t\t})))(config.sandboxName, config.workspace);\n\t} catch (error) {\n\t\tawait webGateway?.close();\n\t\treportStartupError(error, options);\n\t\treturn startupExitCode(error);\n\t}\n\tlet state;\n\tlet health;\n\tlet stopping = false, exitCode = 143, launchAttempted = false;\n\tconst stopListeners = /* @__PURE__ */ new Set();\n\t/**\n\t* E7 assignment bind. A welcome for the SAME assignment keeps all local unsaved bytes. A welcome\n\t* for a DIFFERENT assignment is accepted only when the previous assignment proved its workspace\n\t* sealed; then old native/controller/workspace/journal/private/public state is destroyed and a\n\t* fresh controller + workspace is built for the new Session before any restore or readiness.\n\t*/\n\tconst rebindAssignment = async () => {\n\t\tconst current = state;\n\t\tconst scope = bridge.scope;\n\t\tif (!current || !scope) return false;\n\t\tconst assignment = current.assignment;\n\t\tif (assignment && assignmentsMatch(assignment, scope)) return true;\n\t\tif (!await assignmentReplacementAllowed({\n\t\t\tconfig,\n\t\t\toptions,\n\t\t\tcurrent,\n\t\t\tassignment\n\t\t})) return false;\n\t\tif (assignment) {\n\t\t\tawait discardSealedAssignment({\n\t\t\t\tconfig,\n\t\t\t\toptions,\n\t\t\t\tcurrent,\n\t\t\t\tsandbox,\n\t\t\t\tbridge,\n\t\t\t\tweb,\n\t\t\t\tassignment\n\t\t\t});\n\t\t\tcurrent.assignmentRequired = true;\n\t\t}\n\t\tconst proposed = {\n\t\t\tsandboxId: scope.sandboxId,\n\t\t\tsessionId: scope.sessionId,\n\t\t\tenvironmentGeneration: scope.environmentGeneration,\n\t\t\tresourceName: scope.resourceName,\n\t\t\tresourceUid: scope.resourceUid ?? \"\",\n\t\t\tsealed: false\n\t\t};\n\t\tawait writeRunnerAssignment(config.stateDir, proposed);\n\t\tcurrent.assignment = proposed;\n\t\treturn true;\n\t};\n\tconst requestStop = (code) => {\n\t\tstopping = true;\n\t\texitCode = code;\n\t\tif (state) {\n\t\t\tstate.stopping = true;\n\t\t\tstate.active?.abort.abort();\n\t\t}\n\t\tstate?.turns.onChannelClosed();\n\t\tfor (const listener of stopListeners) listener();\n\t};\n\tconst removeSignals = installRunnerSignals(requestStop, options);\n\tlet result = 1;\n\ttry {\n\t\tawait mkdir(config.workspace, {\n\t\t\trecursive: true,\n\t\t\tmode: 448\n\t\t});\n\t\tif (stopping) return exitCode;\n\t\tlaunchAttempted = true;\n\t\tawait sandbox.launch();\n\t\tstate = {\n\t\t\tprobe: await sandbox.probe(),\n\t\t\tstopping,\n\t\t\tfatal: false,\n\t\t\tpresent: true,\n\t\t\ttoken: config.bootstrapToken,\n\t\t\t...config.controlToken ? { controlToken: config.controlToken } : {},\n\t\t\tjournal,\n\t\t\tjournalDir,\n\t\t\tprivateTurnRoot,\n\t\t\tpublicRoot,\n\t\t\tcredentialEpoch: 0,\n\t\t\tassignmentRequired: false,\n\t\t\tcredentialWaiters: [],\n\t\t\tassignment: await readRunnerAssignment(config.stateDir),\n\t\t\tturns: void 0\n\t\t};\n\t\tattachWorkspace(config, options, state, sandbox, bridge, web);\n\t\tawait prepareServeWebExecution(state, webGateway, sandbox, options);\n\t\thealth = await startServeHealthListener(config, options, stopping);\n\t\tawait maintainConnections(config, state, sandbox, options, stopListeners, bridge, rebindAssignment);\n\t\tresult = stopping ? exitCode : state.fatal ? 5 : 1;\n\t} catch (error) {\n\t\treportStartupError(error, options);\n\t\tif (error instanceof NativeSandboxError && error.code === \"unavailable\") launchAttempted = false;\n\t\tresult = startupExitCode(error);\n\t} finally {\n\t\tawait settleCloudController(state);\n\t\ttry {\n\t\t\tif (!await cleanupRunner(sandbox, state, launchAttempted, options)) result = 5;\n\t\t} finally {\n\t\t\tawait webGateway?.close();\n\t\t\tawait health?.close();\n\t\t\tremoveSignals();\n\t\t}\n\t}\n\treturn result;\n}\n/** Acceptance-harness path: opens the acceptance run's own channel when an authority was injected. */\nasync function prepareServeWebExecution(state, webGateway, sandbox, options) {\n\tconst open = () => openServeWebExecution(state, webGateway, sandbox, options);\n\tif (state.workspace) state.afterWorkspaceRestore = open;\n\telse await open();\n}\nasync function openServeWebExecution(state, webGateway, sandbox, options) {\n\tif (state.stopping || !webGateway || !options.webAuthority) return;\n\tawait state.webExecution?.close();\n\tstate.webExecution = void 0;\n\tconst channel = await webGateway.openExecution({\n\t\tsandbox,\n\t\tauthority: options.webAuthority\n\t});\n\tstate.webExecution = channel;\n\toptions.onWebExecution?.(channel);\n}\n/** Platform TCP startup probe: started after native readiness when a health port is configured. */\nasync function startServeHealthListener(config, options, stopping) {\n\tif (stopping || config.healthPort === void 0) return void 0;\n\tconst health = await startRunnerHealthListener({\n\t\tport: config.healthPort,\n\t\tonError: (message) => logLine(options.stderr, `startup health listener error: ${message}`)\n\t});\n\tlogLine(options.stderr, `startup health listener ready on port ${health.port}`);\n\treturn health;\n}\n/** No listener exists until a Server-granted execution opens its own channel. */\nasync function startServeWebGateway(sandboxName, options) {\n\ttry {\n\t\tconst gateway = await NativeSandboxWebGateway.start({ sandboxName });\n\t\toptions.onWebGateway?.(gateway);\n\t\treturn { gateway };\n\t} catch (error) {\n\t\treportStartupError(error, options);\n\t\treturn { exitCode: 4 };\n\t}\n}\n/**\n* Fixed packaged location of the Pi web-tools extension in the Runner image. `scripts/runner`\n* assembles `packages/client/dist` to `/opt/opentag/client/dist`, and the Client build emits the\n* extension to `dist/pi-extensions/web-tools.mjs`. It is named here as well as resolved\n* automatically because the running module may be a shared build chunk.\n*/\nconst PACKAGED_WEB_EXTENSION_PATH = \"/opt/opentag/client/dist/pi-extensions/web-tools.mjs\";\n/**\n* Resolve the fixed packaged Pi web-tools extension for Cloud turns. The packaged path is tried\n* first, then the artifact's own resolution (which covers development and a relocated build);\n* `resolveWebToolsExtensionPath` verifies the result is a real file and never follows environment\n* variables or cwd, so an Agent cannot substitute its own extension. A missing artifact is a logged\n* fail-closed (web tools stay off), never a guessed path.\n*/\nasync function resolveServeWebExtensionPath(options) {\n\tconst path = await resolveWebToolsExtensionPath({ explicitPath: PACKAGED_WEB_EXTENSION_PATH }) ?? await resolveWebToolsExtensionPath();\n\tif (path) return path;\n\toptions.stderr.write(\"[opentag-runner serve] the trusted web tools extension artifact is missing\\n\");\n}\nasync function serveOnce(config, state, sandbox, options, stopListeners, bridge, rebind) {\n\tstate.credentialInterrupt = void 0;\n\tconst socket = (options.webSocketFactory ?? ((url, settings) => new WebSocket(url, settings)))(config.backendUrl, {\n\t\tmaxPayload: 262144,\n\t\thandshakeTimeout: options.authTimeoutMs ?? DEFAULT_AUTH_TIMEOUT_MS\n\t});\n\treturn new Promise((resolve) => {\n\t\tlet closed = false, authenticated = false, welcome, healthy = false;\n\t\tlet heartbeatTimer, silenceTimer;\n\t\tlet welcomeAt = 0;\n\t\tlet controlTail = Promise.resolve();\n\t\tlet controlPending = 0;\n\t\tconst enqueueCloudControl = (label, operation) => {\n\t\t\tif (closed) return;\n\t\t\tif (controlPending >= MAX_PENDING_CLOUD_CONTROL) {\n\t\t\t\tlogLine(options.stderr, `too many queued cloud control operations (${label})`);\n\t\t\t\tfinish();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcontrolPending += 1;\n\t\t\tcontrolTail = controlTail.then(async () => {\n\t\t\t\tif (closed) {\n\t\t\t\t\tlogLine(options.stderr, `skipping cloud ${label} queued on a closed connection`);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tawait operation();\n\t\t\t}).then(() => {\n\t\t\t\tcontrolPending -= 1;\n\t\t\t}, (error) => {\n\t\t\t\tcontrolPending -= 1;\n\t\t\t\tlogLine(options.stderr, `cloud delivery ${label} failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t\tfinish();\n\t\t\t});\n\t\t};\n\t\tstate.persistenceFailure = (error) => {\n\t\t\tlogLine(options.stderr, `cloud delivery durable boundary failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tfinish();\n\t\t};\n\t\tconst finish = (kind = \"closed\") => {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tstate.persistenceFailure = void 0;\n\t\t\tclearTimeout(authTimer);\n\t\t\tclearInterval(heartbeatTimer);\n\t\t\tclearTimeout(silenceTimer);\n\t\t\tstopListeners.delete(stop);\n\t\t\tbridge.sendFn = void 0;\n\t\t\tbridge.scope = void 0;\n\t\t\tbridge.cloudEnabled = false;\n\t\t\tbridge.sessionCollaborationEnabled = false;\n\t\t\tbridge.emitState(\"closed\");\n\t\t\tstate.turns.onChannelClosed();\n\t\t\tstate.active?.abort.abort();\n\t\t\tconst interrupted = /* @__PURE__ */ new Error(\"the control channel closed before the assignment credential arrived\");\n\t\t\tstate.credentialInterrupt = interrupted;\n\t\t\tfor (const waiter of state.credentialWaiters.splice(0)) waiter(interrupted);\n\t\t\tconst drain = controlTail;\n\t\t\tsocket.terminate();\n\t\t\tPromise.all([Promise.resolve(state.active?.done), drain]).then(() => resolve({\n\t\t\t\tkind,\n\t\t\t\thealthy\n\t\t\t}));\n\t\t};\n\t\tconst send = (frame) => {\n\t\t\tif (closed || socket.readyState !== WebSocket.OPEN) return;\n\t\t\ttry {\n\t\t\t\tsocket.send(JSON.stringify(frame), (error) => {\n\t\t\t\t\tif (error) finish();\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\tfinish();\n\t\t\t}\n\t\t};\n\t\tconst armSilence = () => {\n\t\t\tif (!welcome) return;\n\t\t\tclearTimeout(silenceTimer);\n\t\t\tsilenceTimer = setTimeout(() => finish(), welcome.heartbeatTimeoutMs);\n\t\t};\n\t\tconst stop = () => finish();\n\t\tstopListeners.add(stop);\n\t\tconst authTimer = setTimeout(() => finish(\"auth_timeout\"), options.authTimeoutMs ?? (config.workspacePersistence ? PERSISTENT_AUTH_TIMEOUT_MS : DEFAULT_AUTH_TIMEOUT_MS));\n\t\tconst ready = () => {\n\t\t\tif (state.workspace && !state.workspace.ready) return;\n\t\t\tsend({\n\t\t\t\ttype: \"runner:ready\",\n\t\t\t\trequestId: randomUUID(),\n\t\t\t\treadiness: {\n\t\t\t\t\tsandboxName: config.sandboxName,\n\t\t\t\t\trootfs: SANDBOX_ROOTFS,\n\t\t\t\t\t...state.probe\n\t\t\t\t},\n\t\t\t\t...state.workspace?.ready ? { workspaceRestored: true } : {}\n\t\t\t});\n\t\t};\n\t\tsocket.on(\"open\", () => send({\n\t\t\ttype: \"auth\",\n\t\t\trequestId: randomUUID(),\n\t\t\ttoken: state.token,\n\t\t\tcloudDeliveryVersion: RUNNER_CLOUD_DELIVERY_VERSION,\n\t\t\tsessionCollaborationVersion: RUNNER_SESSION_COLLABORATION_VERSION,\n\t\t\t...config.workspacePersistence ? {\n\t\t\t\tworkspaceVersion: RUNNER_WORKSPACE_VERSION,\n\t\t\t\trenewExpired: true\n\t\t\t} : {},\n\t\t\t...state.controlToken && config.workspacePersistence ? {\n\t\t\t\tcontrolToken: state.controlToken,\n\t\t\t\treuseVersion: RUNNER_REUSE_VERSION\n\t\t\t} : {}\n\t\t}));\n\t\tconst onWelcome = (data) => {\n\t\t\tif (welcome || data.protocolVersion !== RUNNER_WS_PROTOCOL_VERSION || !data.resourceName.endsWith(`/instances/${config.sandboxName}`)) {\n\t\t\t\tfinish();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst cloudCapable = data.cloudDeliveryVersion === RUNNER_CLOUD_DELIVERY_VERSION;\n\t\t\tif (config.workspacePersistence && data.workspaceVersion !== RUNNER_WORKSPACE_VERSION) {\n\t\t\t\tlogLine(options.stderr, \"Server does not support required workspace persistence\");\n\t\t\t\tfinish(\"auth_failed\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (cloudCapable && !data.resourceUid) {\n\t\t\t\tlogLine(options.stderr, \"cloud welcome has no tracked allocation UID; retrying attachment\");\n\t\t\t\tfinish();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\twelcome = data;\n\t\t\twelcomeAt = Date.now();\n\t\t\tclearTimeout(authTimer);\n\t\t\tbridge.scope = {\n\t\t\t\tsandboxId: data.sandboxId,\n\t\t\t\tsessionId: data.sessionId,\n\t\t\t\tenvironmentGeneration: data.environmentGeneration,\n\t\t\t\tresourceName: data.resourceName,\n\t\t\t\tresourceUid: data.resourceUid ?? null\n\t\t\t};\n\t\t\tbridge.cloudEnabled = cloudCapable;\n\t\t\tbridge.sessionCollaborationEnabled = data.sessionCollaborationVersion === RUNNER_SESSION_COLLABORATION_VERSION;\n\t\t\tbridge.sendFn = send;\n\t\t\tbridge.emitState(\"registered\");\n\t\t\tarmSilence();\n\t\t\theartbeatTimer = setInterval(() => send({\n\t\t\t\ttype: \"heartbeat\",\n\t\t\t\trequestId: randomUUID()\n\t\t\t}), data.heartbeatIntervalMs);\n\t\t\tprepareRunnerConnection(state, cloudCapable, {\n\t\t\t\tready,\n\t\t\t\tisClosed: () => closed,\n\t\t\t\tenqueue: enqueueCloudControl,\n\t\t\t\trebind,\n\t\t\t\tensureCredential: () => ensureAssignmentCredential(state, data, options.authTimeoutMs ?? PERSISTENT_AUTH_TIMEOUT_MS, { required: data.reuseVersion === RUNNER_REUSE_VERSION })\n\t\t\t});\n\t\t\tlogLine(options.stderr, \"authenticated control channel ready\");\n\t\t};\n\t\tconst onAcceptance = (data) => {\n\t\t\tif (state.active || state.turns.hasPendingWork || state.workspace && !state.workspace.ready) {\n\t\t\t\tsend({\n\t\t\t\t\ttype: \"acceptance:result\",\n\t\t\t\t\trequestId: data.requestId,\n\t\t\t\t\toutcome: \"failed\",\n\t\t\t\t\tfailure: {\n\t\t\t\t\t\tcode: \"runner_busy\",\n\t\t\t\t\t\tmessage: \"A Cloud Turn or acceptance run already owns the sandbox\"\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (data.deadlineAtMs <= Date.now()) {\n\t\t\t\tsend({\n\t\t\t\t\ttype: \"acceptance:result\",\n\t\t\t\t\trequestId: data.requestId,\n\t\t\t\t\toutcome: \"cancelled\"\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstartAcceptance(data, state, sandbox, {\n\t\t\t\tsend,\n\t\t\t\tready,\n\t\t\t\tfinish,\n\t\t\t\tisClosed: () => closed,\n\t\t\t\tturnSlotAvailable: () => state.turns.notifyAvailable()\n\t\t\t});\n\t\t};\n\t\tconst handle = (data) => dispatchFrame(data, {\n\t\t\tclosed,\n\t\t\tauthenticated,\n\t\t\twelcomed: welcome !== void 0,\n\t\t\trenewExpired: config.workspacePersistence === true,\n\t\t\tfinish,\n\t\t\tarmSilence,\n\t\t\tonWelcome,\n\t\t\tonAcceptance,\n\t\t\tonWorkspaceSeal: (frame) => {\n\t\t\t\tconst workspace = state.workspace;\n\t\t\t\tif (!workspace) {\n\t\t\t\t\tfinish();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tworkspace.seal().then(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait markAssignmentSealed(state, config);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tsend({\n\t\t\t\t\t\t\ttype: \"workspace:seal:result\",\n\t\t\t\t\t\t\trequestId: frame.requestId,\n\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\tcode: \"workspace_save_failed\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tsend({\n\t\t\t\t\t\ttype: \"workspace:seal:result\",\n\t\t\t\t\t\trequestId: frame.requestId,\n\t\t\t\t\t\tok: true\n\t\t\t\t\t});\n\t\t\t\t}, () => send({\n\t\t\t\t\ttype: \"workspace:seal:result\",\n\t\t\t\t\trequestId: frame.requestId,\n\t\t\t\t\tok: false,\n\t\t\t\t\tcode: \"workspace_save_failed\"\n\t\t\t\t}));\n\t\t\t},\n\t\t\tturns: state.turns,\n\t\t\tbridge,\n\t\t\tenqueueCloudControl,\n\t\t\tauthResult: (ok) => {\n\t\t\t\tif (!ok) finish(\"auth_failed\");\n\t\t\t\telse authenticated = true;\n\t\t\t},\n\t\t\theartbeat: () => {\n\t\t\t\tif (welcome && Date.now() - welcomeAt >= welcome.heartbeatTimeoutMs) healthy = true;\n\t\t\t},\n\t\t\tcredential: (credentials) => applyCredential(state, bridge, credentials),\n\t\t\tcancel: (requestId) => {\n\t\t\t\tif (state.active?.requestId === requestId) state.active.abort.abort();\n\t\t\t},\n\t\t\terror: () => logLine(options.stderr, \"Server reported a control protocol error\")\n\t\t});\n\t\tsocket.on(\"message\", (raw, isBinary) => {\n\t\t\tif (closed) return;\n\t\t\tif (isBinary) {\n\t\t\t\tfinish();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet parsed;\n\t\t\ttry {\n\t\t\t\tparsed = JSON.parse(String(raw));\n\t\t\t} catch {\n\t\t\t\tfinish();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst frame = RunnerServerFrameSchema.safeParse(parsed);\n\t\t\tif (!frame.success) {\n\t\t\t\tfinish();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thandle(frame.data);\n\t\t});\n\t\tsocket.on(\"close\", () => finish());\n\t\tsocket.on(\"error\", () => finish());\n\t\tif (state.stopping) finish();\n\t});\n}\nfunction prepareRunnerConnection(state, cloudCapable, callbacks) {\n\tif (!state.workspace) {\n\t\tcallbacks.ready();\n\t\tif (cloudCapable) callbacks.enqueue(\"reconcile\", () => state.turns.reconcile());\n\t\treturn;\n\t}\n\tcallbacks.enqueue(\"restore\", async () => {\n\t\tif (!await callbacks.rebind() || callbacks.isClosed()) return;\n\t\tif (cloudCapable) await state.turns.reconcile();\n\t\tawait callbacks.ensureCredential();\n\t\tconst currentWorkspace = state.workspace;\n\t\tif (!currentWorkspace || !await currentWorkspace.prepare() || callbacks.isClosed()) return;\n\t\tawait state.afterWorkspaceRestore?.();\n\t\tstate.afterWorkspaceRestore = void 0;\n\t\tcallbacks.ready();\n\t\tif (cloudCapable) await state.turns.reconcile();\n\t\tstate.turns.notifyAvailable();\n\t});\n}\nasync function runAcceptanceInSandbox(sandbox, command, signal) {\n\tconst remaining = Math.min(command.deadlineAtMs - Date.now(), 18e5);\n\tif (remaining <= 0 || signal.aborted) return { outcome: \"cancelled\" };\n\tlet exec;\n\ttry {\n\t\texec = await sandbox.exec(SANDBOX_NODE, [SANDBOX_WORKER_ENTRY, \"worker\"], {\n\t\t\ttimeoutMs: remaining,\n\t\t\tsignal,\n\t\t\tstdin: serializeRunnerAcceptanceWorkerStdin({\n\t\t\t\tmode: command.mode,\n\t\t\t\t...command.piConfig ? { piConfig: command.piConfig } : {}\n\t\t\t})\n\t\t});\n\t} catch {\n\t\treturn signal.aborted ? { outcome: \"cancelled\" } : {\n\t\t\toutcome: \"failed\",\n\t\t\tfailure: {\n\t\t\t\tcode: \"worker_exec_failed\",\n\t\t\t\tmessage: \"The in-sandbox worker did not complete\"\n\t\t\t}\n\t\t};\n\t}\n\tif (signal.aborted) return { outcome: \"cancelled\" };\n\tconst line = exec.stdout.split(\"\\n\").filter((l) => l.startsWith(\"{\")).at(-1);\n\tlet raw;\n\ttry {\n\t\traw = JSON.parse(line ?? \"\");\n\t} catch {\n\t\treturn {\n\t\t\toutcome: \"failed\",\n\t\t\tfailure: {\n\t\t\t\tcode: \"worker_output_invalid\",\n\t\t\t\tmessage: \"The worker produced no valid result\"\n\t\t\t}\n\t\t};\n\t}\n\tif (typeof raw !== \"object\" || raw === null || !(\"kind\" in raw) || raw.kind !== \"result\" || !(\"report\" in raw)) return {\n\t\toutcome: \"failed\",\n\t\tfailure: {\n\t\t\tcode: \"worker_failed\",\n\t\t\tmessage: \"The in-sandbox worker failed\"\n\t\t}\n\t};\n\tconst text = sanitizeWorkerReport(raw.report, command);\n\tconst report = RunnerAcceptanceReportWireSchema.safeParse(JSON.parse(text));\n\tif (!report.success) return {\n\t\toutcome: \"failed\",\n\t\tfailure: {\n\t\t\tcode: \"worker_report_invalid\",\n\t\t\tmessage: \"The worker report failed validation\"\n\t\t}\n\t};\n\treturn {\n\t\toutcome: exec.code === 0 && !report.data.failed ? \"passed\" : \"failed\",\n\t\treport: report.data\n\t};\n}\nasync function maintainConnections(config, state, sandbox, options, stopListeners, bridge, rebind) {\n\tlet failures = 0;\n\twhile (!state.stopping && !state.fatal) {\n\t\tconst outcome = await serveOnce(config, state, sandbox, options, stopListeners, bridge, rebind);\n\t\tawait state.active?.done;\n\t\tif (state.stopping || state.fatal) break;\n\t\tif (shouldExitRejectedRunner(config, options, outcome)) break;\n\t\tfailures = outcome.healthy ? 0 : failures + 1;\n\t\tif (reconnectLimitReached(config, options, failures)) break;\n\t\tawait waitReconnect(Math.min(1e3 * 2 ** failures, 3e4) + (options.randomJitter ?? randomInt)(500), state, options, stopListeners);\n\t}\n}\nfunction shouldExitRejectedRunner(config, options, outcome) {\n\tif (outcome.kind === \"auth_timeout\") logLine(options.stderr, \"Runner authentication timed out; reconnecting\");\n\tif (outcome.kind !== \"auth_failed\") return false;\n\tlogLine(options.stderr, \"Runner authentication rejected\");\n\treturn !config.workspacePersistence;\n}\nfunction reconnectLimitReached(config, options, failures) {\n\treturn !config.workspacePersistence && failures >= (options.maxReconnectAttempts ?? DEFAULT_MAX_RECONNECT_ATTEMPTS);\n}\nasync function waitReconnect(delay, state, options, stopListeners) {\n\tawait new Promise((resolve) => {\n\t\tlet timer;\n\t\tconst finish = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tstopListeners.delete(finish);\n\t\t\tresolve();\n\t\t};\n\t\tstopListeners.add(finish);\n\t\tif (state.stopping) finish();\n\t\telse if (options.sleep) options.sleep(delay).then(finish);\n\t\telse timer = setTimeout(finish, delay);\n\t});\n}\n/** Mark the exit as a stop, then settle (abort + await) the live Cloud controller first. */\nasync function settleCloudController(state) {\n\tif (state) state.stopping = true;\n\tawait state?.turns.close().catch(() => void 0);\n}\n/** Persist the seal-complete assignment marker; a failure must keep the Server's seal retryable. */\nasync function markAssignmentSealed(state, config) {\n\tconst assignment = state.assignment;\n\tif (!assignment) return;\n\tconst sealed = {\n\t\t...assignment,\n\t\tsealed: true\n\t};\n\tawait writeRunnerAssignment(config.stateDir, sealed);\n\tstate.assignment = sealed;\n}\nasync function cleanupRunner(sandbox, state, launchAttempted, options) {\n\tif (state) {\n\t\tstate.stopping = true;\n\t\tstate.active?.abort.abort();\n\t\tawait state.active?.done;\n\t}\n\tif (launchAttempted && (!state || state.present)) try {\n\t\tawait sandbox.destroy();\n\t\tlogLine(options.stderr, \"native sandbox deleted\");\n\t} catch {\n\t\tlogLine(options.stderr, \"FATAL: native sandbox deletion failed\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n/**\n* Verified native namespace cleanup shared by E3 acceptance and E4 Cloud Turns: native\n* `delete --force`, relaunch, and a fresh readiness probe. Killing the `sandbox exec` wrapper\n* proves nothing about the process tree it started, so only this reset may reopen the single\n* Sandbox occupation boundary. A failure marks the Runner fatal instead of reusing the namespace.\n*/\nasync function recycleNativeSandbox(sandbox, state) {\n\ttry {\n\t\tawait sandbox.destroy();\n\t\tstate.present = false;\n\t\tif (state.stopping) return;\n\t\tstate.present = true;\n\t\tawait sandbox.launch();\n\t\tstate.probe = await sandbox.probe();\n\t} catch (error) {\n\t\tstate.fatal = true;\n\t\tthrow error;\n\t}\n}\nfunction startAcceptance(data, state, sandbox, callbacks) {\n\tconst abort = new AbortController();\n\tconst deadline = setTimeout(() => abort.abort(), Math.min(data.deadlineAtMs - Date.now(), 18e5));\n\tconst done = (async () => {\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await runAcceptanceInSandbox(sandbox, data, abort.signal);\n\t\t} catch {\n\t\t\tresult = {\n\t\t\t\toutcome: \"failed\",\n\t\t\t\tfailure: {\n\t\t\t\t\tcode: \"worker_failed\",\n\t\t\t\t\tmessage: \"The sandbox worker failed\"\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tclearTimeout(deadline);\n\t\ttry {\n\t\t\tif (state.workspace) await state.workspace.checkpoint();\n\t\t\telse await recycleNativeSandbox(sandbox, state);\n\t\t} catch {\n\t\t\tresult = {\n\t\t\t\toutcome: \"failed\",\n\t\t\t\tfailure: {\n\t\t\t\t\tcode: \"sandbox_cleanup_failed\",\n\t\t\t\t\tmessage: \"Native sandbox cleanup could not be verified\"\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tif (!callbacks.isClosed()) {\n\t\t\tcallbacks.send({\n\t\t\t\ttype: \"acceptance:result\",\n\t\t\t\trequestId: data.requestId,\n\t\t\t\t...result\n\t\t\t});\n\t\t\tif (!state.fatal && !state.stopping) callbacks.ready();\n\t\t}\n\t\tstate.active = void 0;\n\t\tif (state.fatal || state.workspace && !state.workspace.ready && !state.workspace.sealing) callbacks.finish();\n\t\tcallbacks.turnSlotAvailable();\n\t})();\n\tstate.active = {\n\t\trequestId: data.requestId,\n\t\tabort,\n\t\tdone\n\t};\n}\nfunction sanitizeWorkerReport(value, command) {\n\tconst secrets = [];\n\tconst collect = (v) => {\n\t\tif (typeof v === \"string\" && v.length >= 8) secrets.push(v);\n\t\telse if (v && typeof v === \"object\") for (const x of Object.values(v)) collect(x);\n\t};\n\tfor (const document of Object.values(command.piConfig ?? {})) try {\n\t\tcollect(JSON.parse(document));\n\t} catch {}\n\tlet text = JSON.stringify(redactAcceptanceRecord(value));\n\tfor (const secret of secrets) text = text.split(secret).join(\"[redacted]\");\n\treturn text;\n}\nfunction reportStartupError(error, options) {\n\tlogLine(options.stderr, `Runner unavailable (${error instanceof NativeSandboxError ? error.code : \"startup_failed\"})`);\n}\nfunction startupExitCode(error) {\n\treturn error instanceof NativeSandboxError && error.code === \"unavailable\" ? 3 : 4;\n}\nfunction installRunnerSignals(requestStop, options) {\n\tconst term = () => requestStop(143), int = () => requestStop(130);\n\tif (options.installSignalHandlers !== false) {\n\t\tprocess.on(\"SIGTERM\", term);\n\t\tprocess.on(\"SIGINT\", int);\n\t}\n\toptions.signal?.addEventListener(\"abort\", term, { once: true });\n\tif (options.signal?.aborted) term();\n\treturn () => {\n\t\tprocess.off(\"SIGTERM\", term);\n\t\tprocess.off(\"SIGINT\", int);\n\t\toptions.signal?.removeEventListener(\"abort\", term);\n\t};\n}\n/**\n* Renewal-only reply: a fresh Session bearer, a fresh physical control credential, or both. An\n* authenticated connection never accepts it (the Server only sends it for an expired credential).\n*/\nfunction dispatchRenewedFrame(data, c) {\n\tif (!c.authenticated && c.renewExpired && (data.token !== void 0 || data.controlToken !== void 0)) {\n\t\tc.credential({\n\t\t\t...data.token !== void 0 ? { token: data.token } : {},\n\t\t\t...data.controlToken !== void 0 ? { controlToken: data.controlToken } : {}\n\t\t});\n\t\tc.finish(\"renewed\");\n\t\treturn;\n\t}\n\tc.finish();\n}\n/** Post-welcome frames that are neither Cloud delivery nor renewal. */\nfunction dispatchEstablishedFrame(data, c) {\n\tswitch (data.type) {\n\t\tcase \"workspace:seal\":\n\t\t\tc.onWorkspaceSeal(data);\n\t\t\tbreak;\n\t\tcase \"server:heartbeat\":\n\t\t\tc.heartbeat();\n\t\t\tbreak;\n\t\tcase \"server:credential\":\n\t\t\tc.credential({\n\t\t\t\ttoken: data.token,\n\t\t\t\t...data.controlToken ? { controlToken: data.controlToken } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"acceptance:cancel\":\n\t\t\tc.cancel(data.requestId);\n\t\t\tbreak;\n\t\tcase \"acceptance:run\":\n\t\t\tc.onAcceptance(data);\n\t\t\tbreak;\n\t\tcase \"error\": c.error();\n\t}\n}\nfunction dispatchFrame(data, c) {\n\tif (c.closed) return;\n\tif (data.type === \"auth:renewed\") {\n\t\tdispatchRenewedFrame(data, c);\n\t\treturn;\n\t}\n\tif (data.type === \"auth:result\") {\n\t\tc.authResult(data.ok);\n\t\treturn;\n\t}\n\tif (!c.authenticated) {\n\t\tc.finish();\n\t\treturn;\n\t}\n\tif (data.type === \"server:welcome\") {\n\t\tc.onWelcome(data);\n\t\treturn;\n\t}\n\tif (!c.welcomed) {\n\t\tc.finish();\n\t\treturn;\n\t}\n\tc.armSilence();\n\tif (isCloudServerFrame(data)) {\n\t\tdispatchCloudFrame(data, c);\n\t\treturn;\n\t}\n\tdispatchEstablishedFrame(data, c);\n}\nfunction isCloudServerFrame(frame) {\n\treturn frame.type === \"delivery:run\" || frame.type === \"delivery:verified\" || frame.type === \"delivery:cancel\" || frame.type === \"delivery:report:ack\" || frame.type === \"delivery:query\" || frame.type === \"session:message:run\" || frame.type === \"session:message:verified\" || frame.type === \"session:message:cancel\" || frame.type === \"session:message:settled:ack\" || frame.type === \"credential:frame\";\n}\n/**\n* Cloud delivery frames exist only on a negotiated `cloudDeliveryVersion: 1` channel. Session\n* collaboration frames additionally require the E8 echo, so a Server that never negotiated the\n* capability can never cause a session Turn to run. On a legacy channel the frame is a protocol\n* violation: the connection cycles instead of touching Cloud state. Cancellation stays synchronous\n* so it never waits behind queued durable work.\n*/\nfunction dispatchCloudFrame(data, c) {\n\tif (!c.bridge.cloudEnabled) {\n\t\tc.finish();\n\t\treturn;\n\t}\n\tif (data.type.startsWith(\"session:message:\") && !c.bridge.sessionCollaborationEnabled) {\n\t\tc.finish();\n\t\treturn;\n\t}\n\tswitch (data.type) {\n\t\tcase \"delivery:run\":\n\t\t\tc.enqueueCloudControl(\"delivery:run\", () => c.turns.handleDeliveryRun(data));\n\t\t\tbreak;\n\t\tcase \"delivery:verified\":\n\t\t\tc.enqueueCloudControl(\"delivery:verified\", () => c.turns.handleVerified(data));\n\t\t\tbreak;\n\t\tcase \"delivery:cancel\":\n\t\t\tc.turns.handleCancel(data.deliveryId);\n\t\t\tbreak;\n\t\tcase \"delivery:report:ack\":\n\t\t\tc.enqueueCloudControl(\"delivery:report:ack\", () => c.turns.handleReportAck(data));\n\t\t\tbreak;\n\t\tcase \"delivery:query\":\n\t\t\tc.enqueueCloudControl(\"delivery:query\", () => c.turns.handleQuery(data));\n\t\t\tbreak;\n\t\tcase \"session:message:run\":\n\t\t\tc.enqueueCloudControl(\"session:message:run\", () => c.turns.handleSessionMessageRun(data));\n\t\t\tbreak;\n\t\tcase \"session:message:verified\":\n\t\t\tc.enqueueCloudControl(\"session:message:verified\", () => c.turns.handleSessionMessageVerified(data));\n\t\t\tbreak;\n\t\tcase \"session:message:cancel\":\n\t\t\tc.turns.handleSessionMessageCancel(data.messageId);\n\t\t\tbreak;\n\t\tcase \"session:message:settled:ack\":\n\t\t\tc.enqueueCloudControl(\"session:message:settled:ack\", () => c.turns.handleSessionMessageSettledAck(data));\n\t\t\tbreak;\n\t\tcase \"credential:frame\": c.bridge.emitCredential(data.frame);\n\t}\n}\n//#endregion\n//#region src/runner/signals.ts\nlet signalCleanup;\nfunction registerRunnerSignalCleanup(cleanup) {\n\tsignalCleanup = cleanup;\n}\nfunction installRunnerSignalHandlers(exit = (code) => {\n\tprocess.exit(code);\n}) {\n\tlet stopping = false;\n\tfor (const [signal, code] of [[\"SIGINT\", 130], [\"SIGTERM\", 143]]) process.on(signal, () => {\n\t\tif (stopping) return;\n\t\tstopping = true;\n\t\tconst cleanup = signalCleanup;\n\t\tsignalCleanup = void 0;\n\t\tPromise.resolve().then(() => cleanup?.()).catch((error) => {\n\t\t\tprocess.stderr.write(`[opentag-runner] signal cleanup failed: ${error instanceof Error ? error.message : String(error)}\\n`);\n\t\t}).finally(() => exit(code));\n\t});\n}\n//#endregion\n//#region src/cloud-runtime/sandbox-ca.ts\n/**\n* Real-module form of the generated `sandbox-ca.mjs` program (#633): the mounted public CA is\n* root-owned and native CLIs refuse a CA not owned by the current Sandbox uid, so the worker\n* copies the public certificate into its own 0700 home as a 0600 file and rewrites every CA\n* environment path to that copy. Only the public certificate is copied; the CA private key never\n* leaves the trusted Runner.\n*/\nfunction prepareSandboxCa(input) {\n\tconst source = `${input.mount}/${CLOUD_SANDBOX_CA_FILE}`;\n\tconst directory = dirname(input.destination);\n\tmkdirSync(directory, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tchmodSync(directory, 448);\n\twriteFileSync(input.destination, readFileSync(source), {\n\t\tflag: \"wx\",\n\t\tmode: 384\n\t});\n\tchmodSync(input.destination, 384);\n\tconst rewritten = { ...input.environment };\n\tfor (const key of CLOUD_SANDBOX_CA_ENVIRONMENT_KEYS) if (rewritten[key] === source) rewritten[key] = input.destination;\n\treturn {\n\t\tdestination: input.destination,\n\t\tenvironment: rewritten\n\t};\n}\n//#endregion\n//#region src/runner/cloud-context-tree.ts\n/**\n* In-Sandbox Context Tree preparation for one Cloud Turn (E8).\n*\n* The packaged CLI anchors managed trees below its process HOME and places write worktrees in\n* `$TMPDIR`; both are pinned at `.opentag/context-tree/{home,tmp}` inside the Session workspace,\n* so the checkout, connection record and prepared writes persist with E5 while the scratch HOME\n* stays disposable. The record stores linkage only; proxy credentials and Git helper config stay\n* in the per-execution environment.\n*\n* Every Turn re-evaluates the current snapshot selection and execution grant. Revoked grants are detached locally without\n* network preparation; a failed connect/sync is reported `stale` with the preserved\n* in-workspace checkout still addressable through the pinned CLI; nothing is forced, reset or\n* discarded, and drafts of an unselected or rebinding tree stay on disk. A killed first clone can\n* leave a partial managed directory that the pinned CLI thereafter reports as unusable; it is\n* indistinguishable from preserved work, so it is reported rather than deleted. Failures never\n* throw into Turn execution, and no CLI child is left writing once preparation settles.\n*/\n/** Per-Session Context Tree subtree inside the Session workspace; saved and restored with it. */\nconst CLOUD_CONTEXT_TREE_SUBDIRECTORY = \".opentag/context-tree\";\n/** Bound for Context Tree preparation inside a Turn; optional memory never delays the task long. */\nconst CLOUD_CONTEXT_TREE_PREPARATION_BUDGET_MS = 3e4;\nconst FALLBACK_AGENT_IDENTITY = \"opentag-cloud-agent\";\n/**\n* Extract the current Agent slug from the rendered platform instructions. The Server renders\n* them through `renderPlatformInstructions` (`OpenTag Agent slug: <slug>`) and fails closed on a\n* malformed name, so an anchored, charset-strict match is exactly the identity the Server vetted.\n*/\nfunction cloudAgentSlug(platformInstructions) {\n\treturn /(?:^|\\n)OpenTag Agent slug: ([a-z0-9][a-z0-9-]*)(?=\\n|$)/.exec(platformInstructions)?.[1];\n}\n/**\n* Prepare the Session's Context Tree for one Cloud Turn. Total by contract: every failure is\n* reported in the returned status and nothing throws into Turn execution.\n*/\nconst prepareCloudContextTree = async (input, internals = {}) => {\n\ttry {\n\t\treturn await prepare({\n\t\t\t...input,\n\t\t\tsignal: AbortSignal.any([...input.signal ? [input.signal] : [], AbortSignal.timeout(CLOUD_CONTEXT_TREE_PREPARATION_BUDGET_MS)])\n\t\t}, internals);\n\t} catch {\n\t\treturn failedPreparation(input.contextTrees, \"PREPARATION_FAILED\");\n\t}\n};\nasync function prepare(input, internals) {\n\tconst workspace = resolve(input.workspace);\n\tconst treeHome = join(workspace, CLOUD_CONTEXT_TREE_SUBDIRECTORY, \"home\");\n\tconst treeTmp = join(workspace, CLOUD_CONTEXT_TREE_SUBDIRECTORY, \"tmp\");\n\tconst contextTreePackage = internals.contextTreePackage === void 0 ? resolveContextTreePackage() : internals.contextTreePackage ?? void 0;\n\tconst run = (pack, args, network) => runContextTreeCli(pack, args, {\n\t\tcwd: workspace,\n\t\tenv: {\n\t\t\t...input.environment,\n\t\t\tHOME: treeHome,\n\t\t\tLANG: \"C.UTF-8\",\n\t\t\tPATH: input.path,\n\t\t\tTMPDIR: treeTmp\n\t\t},\n\t\tnetwork,\n\t\t...internals.execFile ? { execFile: internals.execFile } : {},\n\t\t...internals.nodePath ? { nodePath: internals.nodePath } : {},\n\t\t...input.signal ? { signal: input.signal } : {}\n\t});\n\tif (!contextTreePackage) return input.contextTrees.length ? failedPreparation(input.contextTrees, \"PACKAGE_MISSING\") : { status: { status: \"unconfigured\" } };\n\tif (!await directoryExists(workspace)) return failedPreparation(input.contextTrees, \"WORKSPACE_MISSING\");\n\tawait mkdir(treeHome, {\n\t\tmode: 448,\n\t\trecursive: true\n\t});\n\tawait mkdir(treeTmp, {\n\t\tmode: 448,\n\t\trecursive: true\n\t});\n\tconst runCli = (args, network) => run(contextTreePackage, args, network);\n\tconst reconciliation = await reconcileContextTreeConnections(runCli, workspace, input.contextTrees.filter((entry) => managedRepositoryAllowed(input.environment, entry.repository)));\n\tif (reconciliation.failureCode) return failedPreparation(input.contextTrees, reconciliation.failureCode);\n\tif (!input.contextTrees.length) return { status: { status: \"unconfigured\" } };\n\tconst connections = [];\n\tfor (const connection of input.contextTrees) connections.push(await prepareConnection(runCli, input, workspace, treeHome, connection));\n\tconst status = {\n\t\tstatus: \"configured\",\n\t\tconnections\n\t};\n\tif (!connections.some((entry) => entry.status === \"ready\" || entry.status === \"stale\")) return { status };\n\ttry {\n\t\treturn {\n\t\t\tbinDirectory: await writeContextTreeShim({\n\t\t\t\tagentSlug: input.agentSlug ?? FALLBACK_AGENT_IDENTITY,\n\t\t\t\tcliPath: contextTreePackage.cliPath,\n\t\t\t\thome: treeHome,\n\t\t\t\tnodePath: internals.nodePath ?? process.execPath,\n\t\t\t\tscratch: input.scratch,\n\t\t\t\ttmp: treeTmp\n\t\t\t}),\n\t\t\tstatus\n\t\t};\n\t} catch {\n\t\treturn failedPreparation(input.contextTrees, \"SHIM_UNAVAILABLE\");\n\t}\n}\nasync function prepareConnection(run, input, workspace, treeHome, connection) {\n\tif (!managedRepositoryAllowed(input.environment, connection.repository)) return {\n\t\t...connection,\n\t\tstatus: \"unavailable\",\n\t\treason: \"GITHUB_PERMISSION\"\n\t};\n\tif (input.signal?.aborted) return {\n\t\t...connection,\n\t\tstatus: \"unavailable\",\n\t\treason: \"TIMEOUT\"\n\t};\n\ttry {\n\t\treturn {\n\t\t\t...connection,\n\t\t\t...await connectAndSync(run, workspace, treeHome, connection)\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\t...connection,\n\t\t\tstatus: \"unavailable\",\n\t\t\treason: input.signal?.aborted ? \"TIMEOUT\" : \"PREPARATION_FAILED\"\n\t\t};\n\t}\n}\nfunction failedPreparation(connections, reason) {\n\treturn { status: connections.length ? {\n\t\tstatus: \"configured\",\n\t\tconnections: connections.map((entry) => ({\n\t\t\t...entry,\n\t\t\tstatus: \"unavailable\",\n\t\t\treason\n\t\t}))\n\t} : {\n\t\tstatus: \"unavailable\",\n\t\treason\n\t} };\n}\n/**\n* One `connect` (clone, reattach, or rebind) and, on success, one `sync`. Connect failures fall\n* back to the preserved checkout only for this exact repository and workspace.\n*/\nasync function connectAndSync(run, workspace, treeHome, connection) {\n\tconst connected = await run([\n\t\t\"connect\",\n\t\tconnection.repository,\n\t\t\"--as\",\n\t\tconnection.alias,\n\t\t\"--project-path\",\n\t\tworkspace,\n\t\t\"--json\"\n\t], true);\n\tconst treePath = connected.failureCode === void 0 ? connectedTree(connected.payload, connection)?.path : void 0;\n\tif (treePath === void 0) {\n\t\tif (connected.failureCode === void 0) return {\n\t\t\tstatus: \"unavailable\",\n\t\t\treason: \"CONNECT_FAILED\"\n\t\t};\n\t\tconst preserved = await preservedCheckout(treeHome, workspace, connection);\n\t\treturn preserved === void 0 ? {\n\t\t\tstatus: \"unavailable\",\n\t\t\treason: connected.failureCode\n\t\t} : {\n\t\t\tstatus: \"stale\",\n\t\t\ttreePath: preserved,\n\t\t\treason: connected.failureCode\n\t\t};\n\t}\n\tif (!isWithin(await realpath(workspace), await realpath(treePath).catch(() => treePath))) return {\n\t\tstatus: \"unavailable\",\n\t\treason: \"TREE_OUTSIDE_WORKSPACE\"\n\t};\n\tconst synced = await run([\n\t\t\"sync\",\n\t\t\"--tree\",\n\t\tconnection.alias,\n\t\t\"--project-path\",\n\t\tworkspace\n\t], true);\n\tconst entry = syncedTree(synced.payload, connection);\n\tif (!entry) return {\n\t\tstatus: \"stale\",\n\t\ttreePath,\n\t\treason: synced.failureCode ?? \"SYNC_FAILED\"\n\t};\n\treturn entry.ok ? readyStatus(treePath, entry) : {\n\t\tstatus: \"stale\",\n\t\ttreePath,\n\t\treason: entry.error?.code ?? \"SYNC_FAILED\"\n\t};\n}\n/** Recover only the exact workspace/alias/repository record from the current upstream format. */\nasync function preservedCheckout(treeHome, workspace, connection) {\n\ttry {\n\t\tconst parsed = StoredConnectionsSchema.safeParse(JSON.parse(await readFile(join(treeHome, \".context-tree\", \"connections.json\"), \"utf8\")));\n\t\tif (!parsed.success) return void 0;\n\t\tconst canonical = await realpath(workspace);\n\t\tconst record = parsed.data.connections.find((entry) => (entry.projectPath === canonical || entry.projectPath === resolve(workspace)) && entry.alias === connection.alias && entry.tree.kind === \"github\" && entry.tree.repository.toLowerCase() === connection.repository.toLowerCase());\n\t\tif (!record) return void 0;\n\t\tconst path = await realpath(record.tree.path);\n\t\treturn isWithin(canonical, path) && await directoryExists(path) ? path : void 0;\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction readyStatus(treePath, payload) {\n\tconst record = payload;\n\treturn {\n\t\tstatus: \"ready\",\n\t\ttreePath,\n\t\t...typeof record?.branch === \"string\" ? { branch: record.branch } : {},\n\t\t...typeof record?.sha === \"string\" ? { sha: record.sha } : {}\n\t};\n}\n/**\n* The agent-facing `context-tree` command for one Turn. It pins the packaged CLI entrypoint and\n* Node runtime (so PATH resolution cannot substitute another install), the in-workspace tree\n* HOME/TMPDIR (so skill-driven commands operate on this Session's preserved checkout and\n* prepared writes land in the saved workspace), and a commit identity (the Sandbox has no user\n* Git identity, and the execution GIT_CONFIG_GLOBAL is a read-only mount). Proxy and grant\n* variables flow from the Pi process environment, never from this file: the shim carries no\n* secrets.\n*/\nasync function writeContextTreeShim(input) {\n\tconst bin = join(input.scratch, \"context-tree-bin\");\n\tawait mkdir(bin, {\n\t\tmode: 448,\n\t\trecursive: true\n\t});\n\tconst quote = (value) => `'${value.replaceAll(\"'\", `'\\\\''`)}'`;\n\tconst shim = join(bin, \"context-tree\");\n\tawait writeFile(shim, `${[\n\t\t\"#!/bin/sh\",\n\t\t\"# Generated by OpenTag for this Cloud Turn; edits are overwritten.\",\n\t\t`HOME=${quote(input.home)}`,\n\t\t`TMPDIR=${quote(input.tmp)}`,\n\t\t`GIT_AUTHOR_NAME=${quote(input.agentSlug)}`,\n\t\t`GIT_AUTHOR_EMAIL=${quote(`${input.agentSlug}@localhost`)}`,\n\t\t`GIT_COMMITTER_NAME=${quote(input.agentSlug)}`,\n\t\t`GIT_COMMITTER_EMAIL=${quote(`${input.agentSlug}@localhost`)}`,\n\t\t\"export HOME TMPDIR GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_COMMITTER_NAME GIT_COMMITTER_EMAIL\",\n\t\t`exec ${quote(input.nodePath)} ${quote(input.cliPath)} \"$@\"`\n\t].join(\"\\n\")}\\n`, { mode: 448 });\n\tawait chmod(shim, 448);\n\treturn bin;\n}\nasync function directoryExists(path) {\n\ttry {\n\t\treturn (await stat(path)).isDirectory();\n\t} catch {\n\t\treturn false;\n\t}\n}\nfunction isWithin(root, candidate) {\n\tconst rel = relative(resolve(root), resolve(candidate));\n\treturn rel !== \"\" && rel !== \"..\" && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);\n}\n//#endregion\n//#region src/runtime/runtime-durability.ts\nvar RuntimeDurabilityFailure = class extends Error {\n\tcategory;\n\tcode;\n\tphase;\n\trequestId;\n\tretryability;\n\tstructuredError;\n\tconstructor(failure) {\n\t\tconst structured = StructuredErrorSchema.parse(failure);\n\t\tsuper(structured.message, structured.cause ? { cause: structured.cause } : void 0);\n\t\tthis.name = \"RuntimeDurabilityFailure\";\n\t\tthis.category = structured.category;\n\t\tthis.code = structured.code;\n\t\tthis.phase = structured.phase;\n\t\tthis.requestId = structured.requestId ?? \"unknown\";\n\t\tthis.retryability = structured.retryability;\n\t\tthis.structuredError = structured;\n\t}\n};\n/**\n* Convert an operation failure into the shared, bounded taxonomy used by the durable state machines.\n* Legacy `retryable`/`terminal` values are accepted while old on-disk records drain.\n*/\nfunction durableFailureFromUnknown(requestId, phase, error, fallbackCode) {\n\tconst source = structuredFailureCandidate(error);\n\tconst normalizedPhase = normalizePhase(typeof source.phase === \"string\" ? source.phase : phase);\n\tconst normalizedRetryability = normalizeRetryability(source.retryability);\n\tconst normalizedCategory = normalizeCategory(source.category, normalizedPhase);\n\tconst code = typeof source.code === \"string\" && source.code.length > 0 ? source.code : fallbackCode;\n\tconst message = boundedFailureMessage(typeof source.message === \"string\" ? source.message : error instanceof Error ? error.message : \"Runtime operation failed\");\n\tconst candidate = {\n\t\tcode,\n\t\tcategory: normalizedCategory,\n\t\tretryability: normalizedRetryability,\n\t\tphase: normalizedPhase,\n\t\trequestId: boundedRequestId(typeof source.requestId === \"string\" && source.requestId.length > 0 ? source.requestId : requestId),\n\t\tmessage,\n\t\t...source.cause && typeof source.cause === \"object\" ? { cause: source.cause } : {}\n\t};\n\tconst parsed = StructuredErrorSchema.safeParse(candidate);\n\tif (parsed.success) return parsed.data;\n\treturn StructuredErrorSchema.parse({\n\t\tcode: fallbackCode,\n\t\tcategory: \"internal\",\n\t\tretryability: \"backoff\",\n\t\tphase: \"unknown\",\n\t\trequestId: boundedRequestId(requestId),\n\t\tmessage: \"Runtime operation failed\"\n\t});\n}\nfunction structuredFailureCandidate(error) {\n\tif (error && typeof error === \"object\") {\n\t\tconst candidate = error;\n\t\tif (candidate.structuredError && typeof candidate.structuredError === \"object\") return candidate.structuredError;\n\t\treturn candidate;\n\t}\n\treturn {};\n}\nfunction normalizeRetryability(value) {\n\tif (value === \"never\" || value === \"immediate\" || value === \"backoff\" || value === \"after_auth\") return value;\n\tif (value === \"terminal\") return \"never\";\n\treturn \"backoff\";\n}\nfunction normalizePhase(value) {\n\tif (StructuredErrorPhaseSchema.safeParse(value).success) return value;\n\treturn {\n\t\tcredential: \"authentication\",\n\t\tconfirmation: \"request\",\n\t\tpersist: \"persistence\",\n\t\tprompt: \"provider\",\n\t\truntime: \"transport\",\n\t\tserver: \"transport\"\n\t}[value] ?? \"unknown\";\n}\nfunction normalizeCategory(value, phase) {\n\tif (StructuredErrorCategorySchema.safeParse(value).success) return value;\n\tif (value === \"credential\") return \"auth\";\n\tif (value === \"provider\" || value === \"server\") return \"dependency\";\n\tif (value === \"transport\" || value === \"runtime\") return \"unavailable\";\n\tif (phase === \"authentication\") return \"auth\";\n\tif (phase === \"provider\") return \"dependency\";\n\tif (phase === \"transport\") return \"unavailable\";\n\tif (phase === \"persistence\") return \"dependency\";\n\treturn \"internal\";\n}\nfunction boundedRequestId(value) {\n\treturn value.slice(0, 256) || \"unknown\";\n}\nfunction boundedFailureMessage(value) {\n\tconst redacted = redactSensitive(value);\n\treturn (typeof redacted === \"string\" ? redacted : \"Runtime operation failed\").slice(0, 256) || \"Runtime operation failed\";\n}\nvar MemoryRuntimeDurabilityStore = class {\n\t#records = /* @__PURE__ */ new Map();\n\tasync list(kind) {\n\t\treturn [...this.#records.values()].filter((record) => record.kind === kind).map((record) => ({ ...record }));\n\t}\n\tasync write(record) {\n\t\tthis.#records.set(`${record.kind}:${record.key}`, { ...record });\n\t}\n};\nvar FileRuntimeDurabilityStore = class {\n\t#directory;\n\t#tails = /* @__PURE__ */ new Map();\n\tconstructor(home) {\n\t\tthis.#directory = resolve(resolveOpenTagHomeLayout(home).runtime, \"durability\");\n\t}\n\tasync list(kind) {\n\t\treturn await readDurableJson(durabilityPath(this.#directory, kind), (value) => parseRecords(value, kind)) ?? [];\n\t}\n\tasync write(record) {\n\t\tawait this.#withKindLock(record.kind, async () => {\n\t\t\tawait ensurePrivateDirectory(dirname(this.#directory), this.#directory);\n\t\t\tconst path = durabilityPath(this.#directory, record.kind);\n\t\t\tconst next = (await readDurableJson(path, (value) => parseRecords(value, record.kind)) ?? []).filter((candidate) => candidate.key !== record.key);\n\t\t\tnext.push(record);\n\t\t\tawait writeDurableJson(path, next);\n\t\t});\n\t}\n\tasync #withKindLock(kind, task) {\n\t\tconst previous = this.#tails.get(kind) ?? Promise.resolve();\n\t\tlet release;\n\t\tconst tail = new Promise((resolveTail) => {\n\t\t\trelease = resolveTail;\n\t\t});\n\t\tthis.#tails.set(kind, tail);\n\t\tawait previous;\n\t\ttry {\n\t\t\treturn await task();\n\t\t} finally {\n\t\t\trelease();\n\t\t\t/* v8 ignore else -- the tail map still holds this task while it unwinds. */\n\t\t\tif (this.#tails.get(kind) === tail) this.#tails.delete(kind);\n\t\t}\n\t}\n};\nconst DEFAULT_RUNTIME_RETRY_POLICY = {\n\tbaseDelayMs: 1e3,\n\tmaxAgeMs: 9e5,\n\tmaxAttempts: 5,\n\tmaxDelayMs: 3e4\n};\nconst defaultRuntimeRetryScheduler = { schedule(delayMs, task) {\n\tconst timer = setTimeout(task, delayMs);\n\ttimer.unref();\n\treturn { cancel: () => clearTimeout(timer) };\n} };\nfunction retryDelay(policy, attempts) {\n\tconst exponent = Math.max(0, Math.min(attempts - 1, 30));\n\treturn Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** exponent);\n}\nfunction retryExhausted(policy, record, now) {\n\treturn record.attempts >= policy.maxAttempts || now - record.acceptedAt >= policy.maxAgeMs;\n}\nvar RuntimeDurabilityMetrics = class {\n\t#deadLetters = 0;\n\t#retries = 0;\n\t#transitions = /* @__PURE__ */ new Map();\n\ttransition(kind, from, to) {\n\t\tconst key = `${kind}:${from ?? \"new\"}->${to}`;\n\t\tthis.#transitions.set(key, (this.#transitions.get(key) ?? 0) + 1);\n\t\tif (to === \"retryable\") this.#retries += 1;\n\t\tif (to === \"dead-letter\") this.#deadLetters += 1;\n\t}\n\tsnapshot() {\n\t\treturn {\n\t\t\tdeadLetters: this.#deadLetters,\n\t\t\tretries: this.#retries,\n\t\t\ttransitions: Object.fromEntries(this.#transitions)\n\t\t};\n\t}\n};\nfunction durabilityPath(directory, kind) {\n\treturn resolve(directory, `${kind}.json`);\n}\nfunction parseRecords(value, kind) {\n\tif (!Array.isArray(value)) throw new Error(\"Runtime durability records must be an array\");\n\treturn value.filter((record) => {\n\t\tif (!record || typeof record !== \"object\") return false;\n\t\tconst candidate = record;\n\t\treturn candidate.kind === kind && typeof candidate.key === \"string\" && typeof candidate.payload === \"object\";\n\t});\n}\n//#endregion\n//#region src/runtime/session-message-inbox.ts\nvar SessionMessageInbox = class {\n\t#admission;\n\t#cliCommand;\n\t#credentialEnvironment;\n\t#turnPlan;\n\t#imCredentialGrantVersion;\n\t#logger;\n\t#maxQueuedPerSession;\n\t#maxQueuedTotal;\n\t#maxRememberedMessages;\n\t#metrics;\n\t#now;\n\t#onFailure;\n\t#persistence;\n\t#retryPolicy;\n\t#scheduler;\n\t#timeoutScheduler;\n\t#reconciler;\n\t#runtimeManager;\n\t#queues = /* @__PURE__ */ new Map();\n\t#drains = /* @__PURE__ */ new Map();\n\t#records = /* @__PURE__ */ new Map();\n\t#remembered = /* @__PURE__ */ new Map();\n\t#abort = new AbortController();\n\t#retryTimers = /* @__PURE__ */ new Map();\n\t#readyPromise;\n\t#queuedTotal = 0;\n\tconstructor(options) {\n\t\tthis.#admission = options.admission;\n\t\tthis.#cliCommand = options.cliCommand ?? \"opentag\";\n\t\tthis.#credentialEnvironment = options.credentialEnvironment;\n\t\tthis.#turnPlan = options.turnPlan;\n\t\tthis.#imCredentialGrantVersion = options.imCredentialGrantVersion;\n\t\tthis.#logger = options.logger ?? createLogger(\"session-message-inbox\");\n\t\tthis.#maxQueuedPerSession = positive(options.maxQueuedPerSession ?? 64, \"maxQueuedPerSession\");\n\t\tthis.#maxQueuedTotal = positive(options.maxQueuedTotal ?? 256, \"maxQueuedTotal\");\n\t\tthis.#maxRememberedMessages = positive(options.maxRememberedMessages ?? 512, \"maxRememberedMessages\");\n\t\tthis.#metrics = options.metrics;\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#onFailure = options.onFailure;\n\t\tthis.#persistence = options.persistence;\n\t\tthis.#retryPolicy = normalizeRetryPolicy(options.retryPolicy);\n\t\tthis.#scheduler = options.scheduler ?? defaultRuntimeRetryScheduler;\n\t\tthis.#timeoutScheduler = options.timeoutScheduler ?? defaultRuntimeRetryScheduler;\n\t\tthis.#reconciler = options.reconciler;\n\t\tthis.#runtimeManager = options.runtimeManager;\n\t\tthis.#readyPromise = this.#hydrate();\n\t}\n\tready() {\n\t\treturn this.#readyPromise;\n\t}\n\tgetState(messageId) {\n\t\treturn [...this.#records.values()].find((record) => record.payload.messageId === messageId);\n\t}\n\tmetricsSnapshot() {\n\t\treturn this.#metrics?.snapshot();\n\t}\n\tasync accept(input) {\n\t\tawait this.#readyPromise;\n\t\tconst request = SessionMessageDeliveryRequestSchema.parse(input);\n\t\tconst key = `${request.targetSessionId}:${request.messageId}`;\n\t\tconst hash = hashTuple([\n\t\t\trequest.sourceSessionId,\n\t\t\trequest.targetSessionId,\n\t\t\trequest.agentId,\n\t\t\trequest.content\n\t\t]);\n\t\treturn this.#reconciler.withAgentLock(request.agentId, () => this.#acceptLocked(request, key, hash));\n\t}\n\tasync #acceptLocked(request, key, hash) {\n\t\tconst remembered = this.#rememberedResult(request, key, hash);\n\t\tif (remembered) return remembered;\n\t\tif (this.#abort.signal.aborted) return deliveryResult(request, \"rejected\", \"client_busy\");\n\t\tconst reason = this.#acceptanceReason(request);\n\t\tif (reason) {\n\t\t\tthis.#remember(key, retryableAuthorityReason(reason) ? {\n\t\t\t\thash,\n\t\t\t\tstatus: \"retryable\"\n\t\t\t} : {\n\t\t\t\thash,\n\t\t\t\tstatus: \"rejected\",\n\t\t\t\treason\n\t\t\t});\n\t\t\treturn deliveryResult(request, \"rejected\", reason);\n\t\t}\n\t\treturn this.#enqueueAccepted(request, key, hash);\n\t}\n\t#rememberedResult(request, key, hash) {\n\t\tconst remembered = this.#remembered.get(key);\n\t\tif (!remembered) return void 0;\n\t\tif (remembered.hash !== hash) return deliveryResult(request, \"rejected\", \"input_conflict\");\n\t\tif (remembered.status === \"dead-letter\" || remembered.status === \"failed\") return deliveryResult(request, \"rejected\", remembered.reason ?? \"provider_unavailable\");\n\t\treturn remembered.status === \"retryable\" ? void 0 : deliveryResult(request, \"accepted\");\n\t}\n\t#acceptanceReason(request) {\n\t\tif (this.#admission.paused) return \"client_busy\";\n\t\tconst authorityReason = this.#reconciler.checkSessionMessageDelivery(request);\n\t\tif (authorityReason) return authorityReason;\n\t\tif (this.#runtimeManager.sessionKind(request.targetSessionId) === \"visible\" && this.#imCredentialGrantVersion() !== 2) return \"session_not_ready\";\n\t}\n\tasync #enqueueAccepted(request, key, hash) {\n\t\tconst queue = this.#queues.get(request.targetSessionId) ?? [];\n\t\tif (queue.length >= this.#maxQueuedPerSession || this.#queuedTotal >= this.#maxQueuedTotal) return deliveryResult(request, \"rejected\", \"client_busy\");\n\t\tqueue.push({\n\t\t\trequest,\n\t\t\thash\n\t\t});\n\t\tthis.#queues.set(request.targetSessionId, queue);\n\t\tthis.#queuedTotal += 1;\n\t\ttry {\n\t\t\tawait this.#persist({\n\t\t\t\tacceptedAt: this.#now(),\n\t\t\t\tattempts: 0,\n\t\t\t\tkey,\n\t\t\t\tkind: \"session-message\",\n\t\t\t\tpayload: request,\n\t\t\t\tstatus: \"accepted\",\n\t\t\t\tupdatedAt: this.#now()\n\t\t\t});\n\t\t} catch {\n\t\t\tqueue.pop();\n\t\t\tthis.#queuedTotal -= 1;\n\t\t\tthis.#records.delete(key);\n\t\t\tthis.#remember(key, {\n\t\t\t\thash,\n\t\t\t\tstatus: \"rejected\",\n\t\t\t\treason: \"provider_unavailable\"\n\t\t\t});\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"SESSION_MESSAGE_PERSISTENCE_FAILED\",\n\t\t\t\tmessageId: request.messageId\n\t\t\t}, \"Session message persistence failed\");\n\t\t\treturn deliveryResult(request, \"rejected\", \"provider_unavailable\");\n\t\t}\n\t\tthis.#remember(key, {\n\t\t\thash,\n\t\t\tstatus: \"accepted\"\n\t\t});\n\t\tthis.#startDrain(request.targetSessionId);\n\t\treturn deliveryResult(request, \"accepted\");\n\t}\n\tstop() {\n\t\tif (this.#abort.signal.aborted) return;\n\t\tthis.#abort.abort(/* @__PURE__ */ new Error(\"Session message inbox stopped\"));\n\t\tfor (const timer of this.#retryTimers.values()) timer.cancel();\n\t\tthis.#retryTimers.clear();\n\t\tthis.#queues.clear();\n\t\tthis.#queuedTotal = 0;\n\t}\n\t/** Accepted Session messages still waiting in an in-memory delivery queue. */\n\tget queuedCount() {\n\t\treturn this.#queuedTotal;\n\t}\n\t/**\n\t* Every accepted Session message that has not reached a terminal durable state. Unlike\n\t* `queuedCount`, this includes a message that is running or waiting behind retry backoff.\n\t*/\n\tget pendingCount() {\n\t\tlet count = 0;\n\t\tfor (const record of this.#records.values()) if (record.status === \"accepted\" || record.status === \"running\" || record.status === \"retryable\") count += 1;\n\t\treturn count;\n\t}\n\tasync settled() {\n\t\tawait Promise.allSettled([...this.#drains.values()]);\n\t}\n\t#startDrain(sessionId) {\n\t\tif (this.#drains.has(sessionId) || this.#abort.signal.aborted) return;\n\t\tconst drain = this.#drain(sessionId).finally(() => {\n\t\t\tif (this.#drains.get(sessionId) === drain) this.#drains.delete(sessionId);\n\t\t\tif ((this.#queues.get(sessionId)?.length ?? 0) > 0) this.#startDrain(sessionId);\n\t\t});\n\t\tthis.#drains.set(sessionId, drain);\n\t\tdrain.catch(() => void 0);\n\t}\n\tasync #drain(sessionId) {\n\t\twhile (!this.#abort.signal.aborted) {\n\t\t\tconst queue = this.#queues.get(sessionId);\n\t\t\tconst next = queue?.[0];\n\t\t\tif (!next) {\n\t\t\t\tthis.#queues.delete(sessionId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet reservation = this.#admission.reserve(sessionId, next.request.agentId, { acceptedWork: true });\n\t\t\twhile (!reservation.accepted) {\n\t\t\t\tawait this.#admission.waitForRelease(this.#abort.signal);\n\t\t\t\treservation = this.#admission.reserve(sessionId, next.request.agentId, { acceptedWork: true });\n\t\t\t}\n\t\t\tqueue?.shift();\n\t\t\tthis.#queuedTotal -= 1;\n\t\t\treservation.reservation.markActive();\n\t\t\tawait this.#runMessage(sessionId, next, reservation.reservation);\n\t\t}\n\t}\n\tasync #runMessage(sessionId, next, reservation) {\n\t\tconst runId = `session-message-${next.request.messageId}`;\n\t\tconst key = `${next.request.targetSessionId}:${next.request.messageId}`;\n\t\tlet current = this.#records.get(key);\n\t\tlet credentialPrepared = false;\n\t\tlet preparedExecutionId;\n\t\tlet turnPlanInput;\n\t\tlet phase = \"runtime\";\n\t\tconst timeout = new AbortController();\n\t\tlet timer;\n\t\tlet runSignal;\n\t\tlet executionSignal;\n\t\tconst ensureRunSignal = () => {\n\t\t\tif (runSignal) return runSignal;\n\t\t\ttimer = this.#timeoutScheduler.schedule(next.request.runtime.budget?.maxDurationMs ?? RUNTIME_DEFAULT_MAX_DURATION_MS, () => timeout.abort(/* @__PURE__ */ new Error(\"Session message Run timed out\")));\n\t\t\trunSignal = executionSignal ? AbortSignal.any([\n\t\t\t\tthis.#abort.signal,\n\t\t\t\ttimeout.signal,\n\t\t\t\texecutionSignal\n\t\t\t]) : AbortSignal.any([this.#abort.signal, timeout.signal]);\n\t\t\treturn runSignal;\n\t\t};\n\t\ttry {\n\t\t\tif (current) current = await this.#transition(current, \"running\");\n\t\t\tawait this.#reconciler.withAgentLock(next.request.agentId, async () => {\n\t\t\t\tthis.#reconciler.setActivity(sessionId, {\n\t\t\t\t\tphase: \"running\",\n\t\t\t\t\tdeliveryId: next.request.messageId,\n\t\t\t\t\tturnId: runId\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst sessionKind = this.#runtimeManager.sessionKind(sessionId);\n\t\t\tlet outboxContext;\n\t\t\tif (sessionKind === \"visible\") {\n\t\t\t\tphase = \"credential\";\n\t\t\t\tconst prepared = await this.#prepareCredentials(sessionId, next.request);\n\t\t\t\tcredentialPrepared = true;\n\t\t\t\tpreparedExecutionId = prepared.executionId;\n\t\t\t\texecutionSignal = prepared.signal;\n\t\t\t\tif (!prepared.outboxContext) {\n\t\t\t\t\tthis.#logger.warn({\n\t\t\t\t\t\tcode: \"SESSION_MESSAGE_OUTBOX_PREPARATION_FAILED\",\n\t\t\t\t\t\tmessageId: next.request.messageId,\n\t\t\t\t\t\tsessionId\n\t\t\t\t\t}, \"Visible Session collaboration outbox context was missing\");\n\t\t\t\t\tthrow new Error(\"The credential grant did not include visible Session outbox context\");\n\t\t\t\t}\n\t\t\t\toutboxContext = prepared.outboxContext;\n\t\t\t\tturnPlanInput = await this.#prepareTurnPlan(sessionId, runId, prepared, ensureRunSignal());\n\t\t\t}\n\t\t\tphase = \"runtime\";\n\t\t\tconst runtimeSignal = sessionKind === \"visible\" ? ensureRunSignal() : this.#abort.signal;\n\t\t\truntimeSignal.throwIfAborted();\n\t\t\tconst runtime = await this.#runtimeManager.ensureRuntime(sessionId, runtimeSignal);\n\t\t\tawait runtime.waitForIdle();\n\t\t\tphase = \"prompt\";\n\t\t\tensureRunSignal().throwIfAborted();\n\t\t\tconst result = await runtime.prompt({\n\t\t\t\trunId,\n\t\t\t\tinput: buildSessionMessageInput(next.request, this.#cliCommand, sessionKind === \"visible\" ? {\n\t\t\t\t\tsessionKind,\n\t\t\t\t\toutboxContext: requireOutboxContext(outboxContext)\n\t\t\t\t} : { sessionKind }),\n\t\t\t\tsignal: ensureRunSignal()\n\t\t\t});\n\t\t\tif (result.status !== \"completed\") throw new Error(result.error?.message ?? `Session message Run ended with status ${result.status}`);\n\t\t\tif (current && !this.#abort.signal.aborted) {\n\t\t\t\tawait this.#transition(current, \"succeeded\");\n\t\t\t\tthis.#remember(key, {\n\t\t\t\t\thash: next.hash,\n\t\t\t\t\tstatus: \"succeeded\"\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (current) await this.#handleFailure(current, next.hash, phase, error);\n\t\t} finally {\n\t\t\ttimer?.cancel();\n\t\t\tawait this.#cleanupTurnPlan(turnPlanInput);\n\t\t\tif (credentialPrepared) await this.#credentialEnvironment.cleanup(sessionId, preparedExecutionId).catch(() => void 0);\n\t\t\tawait this.#reconciler.withAgentLock(next.request.agentId, async () => {\n\t\t\t\tthis.#reconciler.clearActivity(sessionId, runId);\n\t\t\t\treservation.release();\n\t\t\t});\n\t\t}\n\t}\n\tasync #prepareCredentials(sessionId, request) {\n\t\ttry {\n\t\t\treturn await this.#credentialEnvironment.prepare({\n\t\t\t\tsessionId,\n\t\t\t\tagentId: request.agentId,\n\t\t\t\tplacementGeneration: request.placementGeneration,\n\t\t\t\trun: {\n\t\t\t\t\trunId: request.requestId,\n\t\t\t\t\tsource: {\n\t\t\t\t\t\tkind: \"session-message\",\n\t\t\t\t\t\tmessageId: request.messageId\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, this.#abort.signal);\n\t\t} catch (error) {\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"SESSION_MESSAGE_OUTBOX_PREPARATION_FAILED\",\n\t\t\t\terrorCode: error instanceof Error && \"code\" in error ? error.code : void 0,\n\t\t\t\tmessageId: request.messageId,\n\t\t\t\tsessionId\n\t\t\t}, \"Visible Session collaboration outbox preparation failed\");\n\t\t\tthrow error;\n\t\t}\n\t}\n\tasync #prepareTurnPlan(sessionId, runId, prepared, signal) {\n\t\tif (!this.#turnPlan) return void 0;\n\t\tif (!prepared.provider) throw new Error(\"Visible Session collaboration requires an IM provider grant\");\n\t\tconst input = {\n\t\t\tprovider: prepared.provider,\n\t\t\tsessionId,\n\t\t\trunId,\n\t\t\t...prepared.slackConfigDir ? { configDir: prepared.slackConfigDir } : {},\n\t\t\t...prepared.environmentManifest ? { environmentManifest: prepared.environmentManifest } : {},\n\t\t\t...prepared.slackApiHost ? { slackApiHost: prepared.slackApiHost } : {}\n\t\t};\n\t\tawait this.#turnPlan.prepare(input, signal);\n\t\treturn input;\n\t}\n\tasync #cleanupTurnPlan(input) {\n\t\tif (!input) return;\n\t\tawait this.#turnPlan?.cleanup(input).catch(() => void 0);\n\t}\n\tasync #hydrate() {\n\t\tif (!this.#persistence) return;\n\t\tconst records = await this.#persistence.list(\"session-message\");\n\t\tfor (const stored of records) {\n\t\t\tconst request = SessionMessageDeliveryRequestSchema.safeParse(stored.payload);\n\t\t\tif (!request.success) continue;\n\t\t\tconst hash = hashTuple([\n\t\t\t\trequest.data.sourceSessionId,\n\t\t\t\trequest.data.targetSessionId,\n\t\t\t\trequest.data.agentId,\n\t\t\t\trequest.data.content\n\t\t\t]);\n\t\t\tconst key = stored.key;\n\t\t\tlet record = {\n\t\t\t\t...stored,\n\t\t\t\tpayload: request.data\n\t\t\t};\n\t\t\tthis.#records.set(key, record);\n\t\t\tif (record.status === \"succeeded\") {\n\t\t\t\tthis.#remember(key, {\n\t\t\t\t\thash,\n\t\t\t\t\tstatus: \"succeeded\"\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (record.status === \"dead-letter\" || record.status === \"failed\") {\n\t\t\t\tthis.#remember(key, {\n\t\t\t\t\thash,\n\t\t\t\t\tstatus: record.status,\n\t\t\t\t\treason: \"provider_unavailable\"\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (retryExhausted(this.#retryPolicy, record, this.#now())) {\n\t\t\t\trecord = await this.#transition(record, \"dead-letter\", { nextAttemptAt: void 0 });\n\t\t\t\tthis.#remember(key, {\n\t\t\t\t\thash,\n\t\t\t\t\tstatus: \"dead-letter\",\n\t\t\t\t\treason: \"provider_unavailable\"\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (record.status === \"running\") {\n\t\t\t\trecord = {\n\t\t\t\t\t...record,\n\t\t\t\t\tstatus: \"retryable\",\n\t\t\t\t\tnextAttemptAt: this.#now(),\n\t\t\t\t\tupdatedAt: this.#now()\n\t\t\t\t};\n\t\t\t\tawait this.#persist(record);\n\t\t\t}\n\t\t\tthis.#remember(key, {\n\t\t\t\thash,\n\t\t\t\tstatus: \"retryable\"\n\t\t\t});\n\t\t\tthis.#enqueue(record.payload, hash);\n\t\t}\n\t}\n\t#enqueue(request, hash) {\n\t\tconst queue = this.#queues.get(request.targetSessionId) ?? [];\n\t\tif (queue.some((candidate) => candidate.request.messageId === request.messageId)) return;\n\t\tif (queue.length >= this.#maxQueuedPerSession || this.#queuedTotal >= this.#maxQueuedTotal) {\n\t\t\tthis.#logger.warn({\n\t\t\t\tmessageId: request.messageId,\n\t\t\t\tsessionId: request.targetSessionId\n\t\t\t}, \"Durable inbox capacity delayed recovery\");\n\t\t\treturn;\n\t\t}\n\t\tqueue.push({\n\t\t\trequest,\n\t\t\thash\n\t\t});\n\t\tthis.#queues.set(request.targetSessionId, queue);\n\t\tthis.#queuedTotal += 1;\n\t\tthis.#startDrain(request.targetSessionId);\n\t}\n\tasync #transition(record, status, fields = {}) {\n\t\tconst next = {\n\t\t\t...record,\n\t\t\t...fields,\n\t\t\tstatus,\n\t\t\tupdatedAt: this.#now()\n\t\t};\n\t\tthis.#metrics?.transition(\"session-message\", record.status, status);\n\t\tawait this.#persist(next);\n\t\treturn next;\n\t}\n\tasync #handleFailure(record, hash, phase, error) {\n\t\tconst failure = durableFailureFromUnknown(record.payload.requestId, phase, error, phase === \"credential\" ? \"credential_unavailable\" : phase === \"prompt\" ? \"provider_failed\" : \"runtime_failed\");\n\t\tthis.#emitFailure(failure);\n\t\tconst attempts = record.attempts + 1;\n\t\tconst now = this.#now();\n\t\tconst candidate = {\n\t\t\t...record,\n\t\t\tattempts,\n\t\t\tlastError: failure,\n\t\t\tupdatedAt: now\n\t\t};\n\t\tif (failure.retryability === \"never\") {\n\t\t\tawait this.#transition(candidate, \"failed\", { nextAttemptAt: void 0 }).catch(() => void 0);\n\t\t\tthis.#remember(record.key, {\n\t\t\t\thash,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treason: \"provider_unavailable\"\n\t\t\t});\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: failure.code,\n\t\t\t\tmessageId: record.payload.messageId,\n\t\t\t\tphase,\n\t\t\t\tstatus: \"failed\"\n\t\t\t}, \"Session message failed permanently\");\n\t\t\treturn;\n\t\t}\n\t\tif (retryExhausted(this.#retryPolicy, candidate, now)) {\n\t\t\tawait this.#transition(candidate, \"dead-letter\", { nextAttemptAt: void 0 }).catch(() => void 0);\n\t\t\tthis.#remember(record.key, {\n\t\t\t\thash,\n\t\t\t\tstatus: \"dead-letter\",\n\t\t\t\treason: \"provider_unavailable\"\n\t\t\t});\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: failure.code,\n\t\t\t\tmessageId: record.payload.messageId,\n\t\t\t\tphase,\n\t\t\t\tstatus: \"dead-letter\"\n\t\t\t}, \"Session message moved to dead letter\");\n\t\t\treturn;\n\t\t}\n\t\tconst nextAttemptAt = now + retryDelay(this.#retryPolicy, attempts);\n\t\tlet retryable;\n\t\ttry {\n\t\t\tretryable = await this.#transition(candidate, \"retryable\", { nextAttemptAt });\n\t\t} catch {\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"SESSION_MESSAGE_PERSISTENCE_FAILED\",\n\t\t\t\tmessageId: record.payload.messageId,\n\t\t\t\tstatus: \"retryable\"\n\t\t\t}, \"Session message retry state could not be persisted\");\n\t\t\treturn;\n\t\t}\n\t\tthis.#remember(record.key, {\n\t\t\thash,\n\t\t\tstatus: \"retryable\"\n\t\t});\n\t\tthis.#scheduleRetry(retryable, hash);\n\t}\n\t#emitFailure(failure) {\n\t\ttry {\n\t\t\tthis.#onFailure?.(failure);\n\t\t} catch {}\n\t}\n\t#scheduleRetry(record, hash) {\n\t\tif (this.#abort.signal.aborted || this.#retryTimers.has(record.key)) return;\n\t\tconst delay = Math.max(0, (record.nextAttemptAt ?? this.#now()) - this.#now());\n\t\tconst timer = this.#scheduler.schedule(delay, () => {\n\t\t\tthis.#retryTimers.delete(record.key);\n\t\t\tif (this.#abort.signal.aborted) return;\n\t\t\tconst current = this.#records.get(record.key);\n\t\t\tif (current?.status !== \"retryable\") return;\n\t\t\tthis.#transition(current, \"accepted\").then(() => this.#enqueue(current.payload, hash)).catch(() => void 0);\n\t\t});\n\t\tthis.#retryTimers.set(record.key, timer);\n\t}\n\tasync #persist(record) {\n\t\tawait this.#persistence?.write(record);\n\t\tthis.#records.set(record.key, record);\n\t}\n\t#remember(key, value) {\n\t\tthis.#remembered.set(key, value);\n\t\twhile (this.#remembered.size > this.#maxRememberedMessages) {\n\t\t\tconst oldest = this.#remembered.keys().next().value;\n\t\t\tif (oldest === void 0) break;\n\t\t\tthis.#remembered.delete(oldest);\n\t\t}\n\t}\n};\nfunction retryableAuthorityReason(reason) {\n\treturn reason === \"stale_generation\" || reason === \"session_not_ready\" || reason === \"stale_configuration\" || reason === \"session_recovery_required\";\n}\nfunction normalizeRetryPolicy(overrides) {\n\tconst policy = {\n\t\t...DEFAULT_RUNTIME_RETRY_POLICY,\n\t\t...overrides\n\t};\n\tfor (const [name, value] of Object.entries(policy)) if (!Number.isSafeInteger(value) || value < 1) throw new Error(`Runtime retry ${name} must be a positive safe integer`);\n\treturn policy;\n}\nfunction buildSessionMessageInput(request, cliCommand = \"opentag\", turnContext = { sessionKind: \"internal\" }) {\n\treturn { items: [{\n\t\ttype: \"text\",\n\t\ttext: (turnContext.sessionKind === \"visible\" ? [\n\t\t\t\"<opentag-session-message-context source=\\\"managed\\\">\",\n\t\t\tGITHUB_NATIVE_CLI_INSTRUCTIONS,\n\t\t\t\"OpenTag internal collaboration message continuing the visible Session's existing work.\",\n\t\t\t`Message ID: ${request.messageId}`,\n\t\t\t`Source Session: ${request.sourceSessionId}`,\n\t\t\t`Target Session: ${request.targetSessionId}`,\n\t\t\t\"This message is not an IM provider event, but the target visible Session retains its IM outbox authority.\",\n\t\t\t...buildProviderOutboxInstructions({\n\t\t\t\tactionInstruction: \"When this collaboration message contains a user-visible result, question, or blocker, synthesize it and deliver it through the provider CLI in this Turn before ending. Do not wait for another IM message. Do not automatically forward the source text verbatim.\",\n\t\t\t\tprovider: turnContext.outboxContext.provider,\n\t\t\t\ttarget: turnContext.outboxContext,\n\t\t\t\ttargetLabel: \"Default provider outbox context\"\n\t\t\t}),\n\t\t\t...turnContext.outboxContext.sessionKind === \"thread\" ? turnContext.outboxContext.provider === \"slack\" ? [\"Keep this collaboration continuation in the supplied Slack threadTs scope.\"] : [\"Keep this collaboration continuation in the supplied Feishu threadId scope. Use lark-cli to inspect the thread when a native message reply target is required.\"] : [],\n\t\t\t`Use ${cliCommand} session send <target-session-id> to continue Session collaboration when needed.`,\n\t\t\t\"Ordinary final text remains Runtime console output and is not published automatically.\",\n\t\t\t\"</opentag-session-message-context>\"\n\t\t] : [\n\t\t\t\"<opentag-session-message-context source=\\\"managed\\\">\",\n\t\t\tGITHUB_NATIVE_CLI_INSTRUCTIONS,\n\t\t\t\"OpenTag internal collaboration message.\",\n\t\t\t`Message ID: ${request.messageId}`,\n\t\t\t`Source Session: ${request.sourceSessionId}`,\n\t\t\t`Target Session: ${request.targetSessionId}`,\n\t\t\t\"This message is not an IM provider event.\",\n\t\t\t\"Your final text is not returned automatically.\",\n\t\t\t`Use ${cliCommand} session send <target-session-id> to report progress or results, ask a question, or continue collaboration.`,\n\t\t\t\"No IM provider reference or credential is attached to this message.\",\n\t\t\t\"</opentag-session-message-context>\"\n\t\t]).join(\"\\n\")\n\t}, {\n\t\ttype: \"text\",\n\t\ttext: request.content.text\n\t}] };\n}\nfunction requireOutboxContext(context) {\n\tif (!context) throw new Error(\"Visible Session collaboration requires outbox context\");\n\treturn context;\n}\nfunction deliveryResult(request, status, reason) {\n\treturn {\n\t\ttype: \"session:message:deliver:result\",\n\t\trequestId: request.requestId,\n\t\tmessageId: request.messageId,\n\t\ttargetSessionId: request.targetSessionId,\n\t\tplacementGeneration: request.placementGeneration,\n\t\tstatus,\n\t\t...reason ? { reason } : {}\n\t};\n}\nfunction positive(value, field) {\n\tif (!Number.isSafeInteger(value) || value < 1) throw new Error(`${field} must be a positive safe integer`);\n\treturn value;\n}\n//#endregion\n//#region src/runner/cloud-worker-input.ts\nfunction cloudWorkerRuntime(request) {\n\treturn request.kind === \"turn\" ? request.delivery.runtime : request.message.runtime;\n}\nfunction cloudWorkerInput(request) {\n\tif (request.kind === \"turn\") return buildAgentInput(request.delivery);\n\tif (request.sessionKind === \"internal\") return buildSessionMessageInput(request.message);\n\tif (!request.outboxContext) throw new Error(\"Visible Cloud Session collaboration requires outbox context\");\n\treturn buildSessionMessageInput(request.message, \"opentag\", {\n\t\tsessionKind: \"visible\",\n\t\toutboxContext: request.outboxContext\n\t});\n}\nfunction cloudWorkerTimeout(request, now) {\n\tif (request.kind === \"turn\") return turnTimeoutMs(request.delivery, now);\n\tif (request.deadlineAt) return Math.max(1, Date.parse(request.deadlineAt) - now);\n\treturn Math.max(1, request.message.runtime.budget?.maxDurationMs ?? RUNTIME_DEFAULT_MAX_DURATION_MS);\n}\n/** Proofs and endpoint discovery belong to execution scratch, never restored Session storage. */\nasync function cloudSessionCliEnvironment(request, scratch) {\n\tconst material = request.sessionCollaboration;\n\tif (!material) return {};\n\tconst directory = join(scratch, \"session-cli\");\n\tawait mkdir(directory, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tconst proofPath = join(directory, \"proof.json\");\n\tawait writeFile(proofPath, `${JSON.stringify(material.proof)}\\n`, { mode: 384 });\n\treturn {\n\t\tOPENTAG_SESSION_PROOF_FILE: proofPath,\n\t\tOPENTAG_SESSION_SERVER_URL: material.serverUrl\n\t};\n}\n//#endregion\n//#region src/runner/cloud-turn-worker.ts\n/**\n* In-sandbox Cloud worker: one IM Turn or Session message inside the disposable Sandbox. The\n* bounded stdin document is the only control input; model grants, proxy handles and Session\n* proofs land only in disposable scratch or the disposable Pi home — never in argv, logs, the\n* workspace, or parent-visible storage. stdout carries exactly one JSON result line.\n*\n* Continuity: the Pi conversation and persisted binding live under the Session workspace's\n* private `.opentag/pi-session` subtree (or the supplied allocation-stable directory), so a\n* same-Session next message resumes the exact history instead of a blank Pi session; E5 restores\n* that directory before a replacement allocation becomes ready. Grants and scratch files are\n* per-message and never persist.\n*\n* The per-execution proxy manifest is the only credential source for Pi and its tools; platform\n* keys and raw IM tokens never enter the Sandbox, and routing/CA variables reach only the\n* provider shell that sources them. NATIVE TRANSPORT BOUNDARY: before Pi starts, production\n* proves the per-execution HTTP/2 provider bridge with a bounded readiness check of both fixed\n* loopback entries — the execution adapter's fixed CONNECT refusal and a TLS exchange pinned to\n* THIS execution's published CA — so a missing or stale transport fails the Turn honestly. The\n* explicit `localProxyLoopbackSeam` test seam skips that probe for local fixtures only; it is\n* never set by production composition and is never evidence that the native bridge works.\n* Cancellation kills every Pi child this worker owns.\n*/\n/** Pi custom provider name for the Server-mediated model path. */\nconst CLOUD_MODEL_PI_PROVIDER = \"opentag\";\n/** The locked adapter lives with the Cloud image's Pi installation. */\nconst CLOUD_PI_MCP_ADAPTER_ENTRY = \"/opt/opentag/pi/node_modules/pi-mcp-adapter/index.ts\";\nconst TURN_POLICY = {\n\tapprovals: \"never\",\n\tfileSystem: \"unrestricted\",\n\tnetwork: \"enabled\",\n\ttools: { mode: \"provider-default\" }\n};\nconst BINDING_FILE_NAME = \"pi-binding.json\";\nconst ProxyEnvironmentManifestSchema = { parse(value) {\n\tif (typeof value !== \"object\" || value === null) throw new Error(\"The proxy environment manifest is invalid\");\n\tconst record = value;\n\tif (typeof record.executionId !== \"string\" || typeof record.environment !== \"object\" || record.environment === null) throw new Error(\"The proxy environment manifest is invalid\");\n\tconst environment = {};\n\tfor (const [key, entry] of Object.entries(record.environment)) if (typeof entry === \"string\") environment[key] = entry;\n\treturn {\n\t\texecutionId: record.executionId,\n\t\tenvironment\n\t};\n} };\nconst PersistedBindingSchema = { parse(value) {\n\tif (typeof value !== \"object\" || value === null) throw new Error(\"The persisted Pi binding is invalid\");\n\tconst record = value;\n\tif (typeof record.providerId !== \"string\" || typeof record.schemaVersion !== \"number\" || typeof record.payload !== \"object\" || record.payload === null) throw new Error(\"The persisted Pi binding is invalid\");\n\treturn {\n\t\tpayload: record.payload,\n\t\tproviderId: record.providerId,\n\t\tschemaVersion: record.schemaVersion\n\t};\n} };\nfunction trackedSpawn(pids) {\n\treturn (command, args, spawnOptions) => {\n\t\tconst child = spawn(command, [...args], {\n\t\t\t...spawnOptions,\n\t\t\tstdio: \"pipe\"\n\t\t});\n\t\tif (typeof child.pid === \"number\") pids.add(child.pid);\n\t\treturn child;\n\t};\n}\n/** Terminate every Pi child this worker owns; SIGKILL escalation is bounded and unref'd. */\nfunction terminateTrackedProcesses(pids, options = {}) {\n\tconst signalled = [];\n\tfor (const pid of pids) try {\n\t\tprocess.kill(pid, \"SIGTERM\");\n\t\tsignalled.push(pid);\n\t} catch {\n\t\tpids.delete(pid);\n\t}\n\tif (signalled.length === 0) return;\n\tconst escalate = () => {\n\t\tfor (const pid of signalled) {\n\t\t\t/* v8 ignore next -- signal races are expected while terminating. */\n\t\t\ttry {\n\t\t\t\tprocess.kill(pid, \"SIGKILL\");\n\t\t\t} catch {}\n\t\t\tpids.delete(pid);\n\t\t}\n\t};\n\tif (options.immediate) {\n\t\tescalate();\n\t\treturn;\n\t}\n\tsetTimeout(escalate, 2e3).unref?.();\n}\n/**\n* Cloud-accurate managed system prompt. It never reuses the Local renderer's persistent Agent\n* Home / shared-workspace wording; the Context Tree and Session sections appear only with real\n* per-Turn state.\n*/\nfunction renderCloudSystemPrompt(snapshot, context) {\n\treturn [\n\t\t\"# OpenTag managed instructions\",\n\t\t\"\",\n\t\t\"These trusted instructions are injected through the Agent Runtime Provider's native system prompt.\",\n\t\t\"\",\n\t\t\"## Cloud execution context\",\n\t\t\"\",\n\t\t\"- You run inside a Session-scoped Cloud Sandbox. The workspace is this Session's own; it is not shared with other Sessions.\",\n\t\t\"- The workspace and Pi conversation for this Session recover from the last successful save when the environment is replaced. Unsaved changes can be lost; running processes and background services do not survive Turn cleanup or replacement.\",\n\t\t\"- Saved workspaces are limited to 256 MiB of file content, 50,000 entries and a 128 MiB compressed archive. Hard links, sockets, FIFOs and links outside the workspace cannot be saved. Keep dependency caches, large installs and disposable build output outside the workspace (for example /tmp); recreate them on later Turns. Exceeding these limits blocks further execution and requires recovery or explicit discard of unsaved changes.\",\n\t\t\"- Credentials are execution-scoped and short-lived; the managed IM/Git CLIs reach providers through the platform proxy. Never ask the user for tokens and never persist credential material.\",\n\t\t\"\",\n\t\t...renderCloudContextTree(snapshot, context?.contextTree),\n\t\t...context?.sessionCollaboration ? [\n\t\t\t\"## Session collaboration\",\n\t\t\t\"\",\n\t\t\t\"Use `opentag session create`, `opentag session send`, and `opentag session list` to coordinate authorized Sessions of this Agent. Use `--help` for command options.\",\n\t\t\t\"Each Cloud Session has its own workspace and history. Send relevant information explicitly; another Session cannot read this workspace. Only published Context Tree knowledge is shared.\",\n\t\t\t\"Your source Session identity is supplied by this execution. Do not copy or persist its temporary proof. A child Session reports through `opentag session send`; its final text is not automatically returned to its parent.\",\n\t\t\t\"\"\n\t\t] : [],\n\t\t\"## Platform\",\n\t\t\"\",\n\t\tsnapshot.instructions.platform,\n\t\t\"\",\n\t\t\"## Agent\",\n\t\t\"\",\n\t\tsnapshot.instructions.agent,\n\t\t\"\",\n\t\t...snapshot.instructions.session ? [\n\t\t\t\"## Session\",\n\t\t\t\"\",\n\t\t\tsnapshot.instructions.session,\n\t\t\t\"\"\n\t\t] : []\n\t].join(\"\\n\");\n}\n/**\n* The Context Tree section the Cloud Sandbox can truthfully offer. The Agent is told plainly when\n* durable memory is absent or stale, so it cannot mistake a failed connection for an empty tree or\n* a failed synchronization for the newest published state.\n*/\nfunction renderCloudContextTree(snapshot, status) {\n\tif (!status) return [];\n\tif (status.status === \"configured\") return [\n\t\t\"## Context Trees\",\n\t\t\"Trees have no implied precedence. Use the upstream skills to select relevant trees, attribute disagreements to aliases, and choose an explicit write destination.\",\n\t\t...status.connections.flatMap((entry) => [`Alias ${entry.alias} — ${entry.repository}:`, ...renderCloudTreeFacts(entry)]),\n\t\t...new Set(status.connections.flatMap((entry) => renderCloudTreeGuidance(snapshot, entry)))\n\t];\n\treturn [\n\t\t\"## Context Tree\",\n\t\t\"\",\n\t\t...renderCloudTreeFacts(status),\n\t\t...renderCloudTreeGuidance(snapshot, status)\n\t];\n}\nfunction renderCloudTreeFacts(status) {\n\tif (status.status === \"ready\") return [`Context Tree: ${status.treePath} — synchronized at the start of this Turn${status.branch && status.sha ? ` (branch ${status.branch}, commit ${status.sha.slice(0, 12)})` : \"\"}.`];\n\tif (status.status === \"stale\") return [`Context Tree: ${status.treePath} — ${status.reason === \"DIRTY_TREE\" ? \"the preserved checkout has unpublished changes\" : `this Turn's synchronization failed (${status.reason})`}.`];\n\tif (status.status === \"unconfigured\") return [\"Context Tree: disabled for this Agent (no Context Tree repository is selected on the Agent's Context Tree page).\"];\n\treturn [`Context Tree unavailable (${status.reason}).`];\n}\nfunction renderCloudTreeGuidance(snapshot, status) {\n\tif (status.status === \"ready\") {\n\t\tconst slug = cloudAgentSlug(snapshot.instructions.platform);\n\t\treturn [\n\t\t\t\"Ready Context Trees are connected on this Agent's Context Tree page. Each checkout lives inside this Session's own workspace and is saved and restored with it, including unpublished drafts. Only the published tree is shared with other Agents that select the same repository; your files and Pi conversation stay private to this Session.\",\n\t\t\t\"Read the decisions that bear on a task before planning or changing code, and record durable decisions there. Use the context-tree-read and context-tree-write skills; the `context-tree` command is on PATH.\",\n\t\t\tslug ? `Your Agent slug is \\`${slug}\\` (also stated in the Platform section): \\`members/${slug}/\\` is your own private working memory in the tree. Do not write to another Agent's member directory.` : \"`members/<your Agent slug>/` is your own private working memory in the tree; the Agent slug is stated in the Platform section below. Do not write to another Agent's member directory.\",\n\t\t\t\"\"\n\t\t];\n\t}\n\tif (status.status === \"stale\") return [...status.reason === \"DIRTY_TREE\" ? [\"For stale trees with unpublished changes: the changes were left untouched. Inspect them with the `context-tree` command (`context-tree read --tree-path <tree> …`, `context-tree verify --tree-path <tree>`) or with `git`, and continue any prepared write worktree. Synchronizing or publishing will keep failing until the changes are committed or otherwise resolved; do not reset or discard them silently.\"] : [\"For other stale trees, the on-disk copy may be outdated: it is not confirmed to be the newest published state. Unpublished drafts were left untouched. You may read the local copy as potentially stale context, and expect synchronizing or publishing to fail until a later Turn succeeds.\"], \"\"];\n\tif (status.status === \"unconfigured\") return [\"Durable memory is not active. Do not assume earlier decisions were recorded, and do not create or connect a tree yourself.\", \"\"];\n\treturn [\n\t\t\"Unavailable trees are not active for this Turn; other ready trees remain usable. Continue the task without those trees. Do not assume earlier decisions were recorded, and do not attempt to repair, create, or connect a tree yourself. Any unpublished drafts from earlier Turns remain preserved in this Session's workspace.\",\n\t\t...status.reason === \"GITHUB_PERMISSION\" ? [\"The current execution does not grant this Session the selected repository, so the managed connection stays detached until the grant returns.\"] : [],\n\t\t...status.reason === \"DIRTY_TREE\" ? [\"The preserved checkout contains unpublished changes from an earlier Turn. They were left untouched; do not commit, reset, or discard them silently — report their presence.\"] : [],\n\t\t\"\"\n\t];\n}\n/** The model grant becomes exactly one disposable Pi provider document set. */\nfunction cloudTurnPiDocuments(request) {\n\tconst model = request.model;\n\treturn {\n\t\tauthJson: `${JSON.stringify({ [CLOUD_MODEL_PI_PROVIDER]: {\n\t\t\ttype: \"api_key\",\n\t\t\tkey: model.token\n\t\t} }, null, 2)}\\n`,\n\t\tmodelsJson: `${JSON.stringify({ providers: { [CLOUD_MODEL_PI_PROVIDER]: {\n\t\t\tapi: \"openai-completions\",\n\t\t\tbaseUrl: model.baseUrl,\n\t\t\tmodels: [{\n\t\t\t\tid: model.model,\n\t\t\t\tname: model.model,\n\t\t\t\tcontextWindow: model.contextWindow,\n\t\t\t\tmaxTokens: model.maxTokens,\n\t\t\t\tcompat: { supportsStore: false }\n\t\t\t}]\n\t\t} } }, null, 2)}\\n`,\n\t\tsettingsJson: `${JSON.stringify({\n\t\t\tcompaction: { enabled: true },\n\t\t\tdefaultModel: `${CLOUD_MODEL_PI_PROVIDER}/${model.model}`,\n\t\t\tdefaultProvider: CLOUD_MODEL_PI_PROVIDER\n\t\t}, null, 2)}\\n`\n\t};\n}\n/**\n* Pi's provider block for one Cloud execution. Only the services the trusted parent actually opened\n* appear here: a missing `webTools`/`mcpGateway` field means the corresponding extension is not\n* registered at all, and Pi's own `--no-extensions` default keeps implicit discovery off.\n*/\nfunction cloudPiConfiguration(request) {\n\treturn {\n\t\tmodel: `${CLOUD_MODEL_PI_PROVIDER}/${request.model.model}`,\n\t\t...request.mcpGateway || request.webTools ? { provider: {\n\t\t\t...request.mcpGateway ? { mcpGateway: request.mcpGateway } : {},\n\t\t\t...request.webTools ? { webTools: request.webTools } : {}\n\t\t} } : {},\n\t\t...cloudWorkerRuntime(request).reasoningEffort ? { reasoningEffort: cloudWorkerRuntime(request).reasoningEffort } : {}\n\t};\n}\nfunction createTurnExecutionContext(request, options) {\n\tconst deadline = AbortSignal.timeout(Math.max(1, cloudWorkerTimeout(request, options.now?.() ?? Date.now())));\n\treturn {\n\t\tsignal: options.signal ? AbortSignal.any([options.signal, deadline]) : deadline,\n\t\tstopReason: () => options.signal?.aborted ? \"client_shutdown\" : deadline.aborted ? \"turn_timeout\" : void 0\n\t};\n}\n/**\n* Optional pre-run memory with its own small budget on top of the Turn execution bounds. It is\n* fully awaited, so a stop leaves no CLI child or `git` writing after the Turn stopped waiting.\n*/\nfunction prepareTurnContextTree(request, options, execution, scratch, environment) {\n\tconst budget = AbortSignal.timeout(Math.max(1, options.contextTreePreparationBudgetMs ?? 3e4));\n\treturn (options.prepareContextTree ?? prepareCloudContextTree)({\n\t\tagentSlug: cloudAgentSlug(cloudWorkerRuntime(request).instructions.platform),\n\t\tenvironment,\n\t\tpath: `${request.executionDir}/bin:/usr/local/bin:/opt/opentag/tools/bin:/usr/bin:/bin`,\n\t\tcontextTrees: cloudWorkerRuntime(request).contextTrees,\n\t\tscratch,\n\t\tsignal: AbortSignal.any([execution.signal, budget]),\n\t\tworkspace: options.workspace\n\t});\n}\nasync function runCloudTurnWorker(request, options) {\n\tassertSafeInSandboxPath(request.executionDir, \"execution directory\");\n\tconst executionMount = options.executionMount ?? \"/run/opentag-execution\";\n\tif (!request.executionDir.startsWith(`${executionMount}/`)) throw new Error(\"The Turn execution directory is outside the Sandbox mount\");\n\tconst continuityDirectory = assertSafeInSandboxPath(request.piSessionDirectory ?? options.continuityDirectory ?? join(assertSafeInSandboxPath(options.workspace, \"workspace\"), \".opentag/pi-session\"), \"continuity directory\");\n\tconst scratch = await mkdtemp(join(tmpdir(), \"opentag-cloud-turn-\"));\n\tconst pids = /* @__PURE__ */ new Set();\n\tlet runtime;\n\tregisterRunnerSignalCleanup(async () => {\n\t\tterminateTrackedProcesses(pids, { immediate: true });\n\t\tconst failures = [];\n\t\tawait runtime?.close().catch((error) => failures.push(error));\n\t\tawait rm(scratch, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t}).catch((error) => failures.push(error));\n\t\tif (failures.length > 0) throw new Error(`Cloud Turn signal cleanup failed: ${failures.map((error) => String(error)).join(\"; \")}`);\n\t});\n\ttry {\n\t\tconst home = join(scratch, \"home\");\n\t\tconst piHome = join(scratch, \"pi-agent\");\n\t\tconst sessionDirectory = join(continuityDirectory, \"sessions\");\n\t\tawait mkdir(home, {\n\t\t\trecursive: true,\n\t\t\tmode: 448\n\t\t});\n\t\tawait mkdir(piHome, {\n\t\t\trecursive: true,\n\t\t\tmode: 448\n\t\t});\n\t\tawait mkdir(sessionDirectory, {\n\t\t\trecursive: true,\n\t\t\tmode: 448\n\t\t});\n\t\tconst bindingFile = join(continuityDirectory, BINDING_FILE_NAME);\n\t\tconst manifest = ProxyEnvironmentManifestSchema.parse(JSON.parse(await readFile(join(request.executionDir, \"environment.json\"), \"utf8\")));\n\t\tawait verifyProxyTransport(request.executionDir, manifest.environment, options);\n\t\tawait prepareCliDirectories(manifest.environment, scratch);\n\t\tconst execution = createTurnExecutionContext(request, options);\n\t\tconst contextTree = await prepareTurnContextTree(request, options, execution, scratch, manifest.environment);\n\t\tif (execution.signal.aborted) return completionForError(/* @__PURE__ */ new Error(\"The Turn stopped during Context Tree preparation\"), execution.stopReason());\n\t\tconst documents = cloudTurnPiDocuments(request);\n\t\tawait writeFile(join(piHome, \"auth.json\"), documents.authJson, { mode: 384 });\n\t\tawait writeFile(join(piHome, \"models.json\"), documents.modelsJson, { mode: 384 });\n\t\tawait writeFile(join(piHome, \"settings.json\"), documents.settingsJson, { mode: 384 });\n\t\tconst baseEnvironment = {\n\t\t\tHOME: home,\n\t\t\tLANG: \"C.UTF-8\",\n\t\t\tPATH: [\n\t\t\t\t...contextTree.binDirectory ? [contextTree.binDirectory] : [],\n\t\t\t\t`${request.executionDir}/bin`,\n\t\t\t\t\"/usr/local/bin\",\n\t\t\t\t\"/opt/opentag/tools/bin\",\n\t\t\t\t\"/usr/bin\",\n\t\t\t\t\"/bin\"\n\t\t\t].join(\":\"),\n\t\t\tPI_CODING_AGENT_DIR: piHome,\n\t\t\tPI_CODING_AGENT_SESSION_DIR: sessionDirectory,\n\t\t\tTMPDIR: tmpdir(),\n\t\t\t...manifest.environment\n\t\t};\n\t\tconst { environment } = prepareSandboxCa({\n\t\t\tdestination: join(home, \".opentag\", \"ca.pem\"),\n\t\t\tenvironment: baseEnvironment,\n\t\t\tmount: request.executionDir\n\t\t});\n\t\tconst runtimeEnvironment = environment;\n\t\tObject.assign(runtimeEnvironment, await cloudSessionCliEnvironment(request, scratch));\n\t\tif (request.kind === \"turn\" || request.sessionKind === \"visible\") {\n\t\t\tconst providerEnvironmentPath = join(scratch, \"provider-environment.sh\");\n\t\t\tawait writeFile(providerEnvironmentPath, serializeEnvironment({\n\t\t\t\t...environment,\n\t\t\t\t...providerRoutingEnvironment(environment)\n\t\t\t}, process.platform), { mode: 384 });\n\t\t\truntimeEnvironment.OPENTAG_PROVIDER_ENV_FILE = providerEnvironmentPath;\n\t\t}\n\t\tconst contextTreeSkills = await assembleContextTreeSkills().catch(() => void 0);\n\t\tconst toolSkills = await assembleRunnerToolSkills();\n\t\tconst skillPaths = [...contextTreeSkills?.skillPaths ?? [], ...toolSkills.skills.map((skill) => skill.directory)];\n\t\tconst factory = options.createPiFactory?.({\n\t\t\tenvironment: runtimeEnvironment,\n\t\t\tpids,\n\t\t\tsessionDirectory\n\t\t}) ?? new PiAgentRuntimeFactory({\n\t\t\tmcpAdapterEntry: CLOUD_PI_MCP_ADAPTER_ENTRY,\n\t\t\tprocess: {\n\t\t\t\targs: skillArgsOf(skillPaths),\n\t\t\t\tcommand: \"pi\",\n\t\t\t\tenv: environment,\n\t\t\t\tsessionDirectory,\n\t\t\t\tprobeTimeoutMs: 3e4,\n\t\t\t\tspawnProcess: trackedSpawn(pids)\n\t\t\t}\n\t\t});\n\t\tconst configuration = cloudPiConfiguration(request);\n\t\tconst common = {\n\t\t\tconfiguration,\n\t\t\teventSink: async (event) => {\n\t\t\t\tif (event.type === \"binding_changed\") await persistBinding(bindingFile, event.binding);\n\t\t\t},\n\t\t\tpolicy: TURN_POLICY,\n\t\t\tsystemPrompt: renderCloudSystemPrompt(cloudWorkerRuntime(request), {\n\t\t\t\tcontextTree: contextTree.status,\n\t\t\t\tsessionCollaboration: request.sessionCollaboration !== void 0\n\t\t\t}),\n\t\t\tworkspace: {\n\t\t\t\tcwd: options.workspace,\n\t\t\t\tenvironment: runtimeEnvironment\n\t\t\t}\n\t\t};\n\t\tconst persisted = await readPersistedBinding(bindingFile);\n\t\tconst activeRuntime = persisted ? await factory.resume({\n\t\t\t...common,\n\t\t\tbinding: persisted\n\t\t}) : await factory.create(common);\n\t\truntime = activeRuntime;\n\t\tconst onAbort = () => terminateTrackedProcesses(pids);\n\t\texecution.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tlet completion;\n\t\ttry {\n\t\t\tconst result = await activeRuntime.prompt({\n\t\t\t\trunId: randomTurnRunId(request),\n\t\t\t\tconfiguration,\n\t\t\t\tinput: cloudWorkerInput(request),\n\t\t\t\tsignal: execution.signal\n\t\t\t});\n\t\t\tcompletion = result.status === \"completed\" ? completionForResult(result, void 0) : completionForResult(result, execution.stopReason());\n\t\t} catch (error) {\n\t\t\tcompletion = completionForError(error, execution.stopReason());\n\t\t} finally {\n\t\t\texecution.signal.removeEventListener(\"abort\", onAbort);\n\t\t\tawait activeRuntime.close().catch(() => void 0);\n\t\t\tterminateTrackedProcesses(pids);\n\t\t}\n\t\treturn completion;\n\t} finally {\n\t\tregisterRunnerSignalCleanup(void 0);\n\t\tawait rm(scratch, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n/** Bounded total deadline for both readiness probes; the bridge is ready before the worker starts. */\nconst CLOUD_PROXY_READINESS_TIMEOUT_MS = 1e4;\n/** Each probe needs only the adapter's fixed status line; anything larger is a violation. */\nconst READINESS_RESPONSE_MAX_BYTES = 4096;\n/** Fixed probe target the allowlisted-hosts check always refuses without any upstream work. */\nconst READINESS_CONNECT_TARGET = \"opentag-transport-check.invalid:443\";\n/**\n* Meaningful per-execution transport proof, replacing the old isSocket-only mount check. The\n* manifest must name the fixed loopback endpoint; then both entries must answer through the\n* HTTP/2 bridge within one bounded deadline:\n*\n* - CONNECT entry: `CONNECT <invalid-host>:443` must return the execution adapter's fixed 403\n*   refusal — a response that exists only because the byte path reaches the trusted adapter of\n*   this execution (no relay, provider, or credential work happens for a refused host).\n* - Slack entry: a TLS handshake pinned to THIS execution's published CA plus a request must\n*   return the adapter's 401 credential challenge. The per-execution CA ties the proof to the\n*   current execution: a stale or foreign listener cannot complete the handshake.\n*\n* Any failure throws BEFORE Pi starts, so a broken transport can never degrade into a Turn that\n* silently has no provider access. The explicit local seam skips both probes for local fixtures.\n*/\nasync function verifyProxyTransport(executionDir, environment, options) {\n\tconst expected = `http://127.0.0.1:${CLOUD_CONNECT_PROXY_PORT}`;\n\tfor (const key of [RUNTIME_PROXY_PROVIDER_URL_KEY, \"LARKSUITE_CLI_PROXY_ADDRESS\"]) if (environment[key] !== void 0 && environment[key] !== expected) throw new Error(\"The proxy manifest does not name the fixed execution loopback endpoint\");\n\tif (options.localProxyLoopbackSeam === true) return;\n\tconst ports = options.proxyReadinessPorts ?? {\n\t\tconnect: 18080,\n\t\tslack: 18443\n\t};\n\tconst deadline = Date.now() + Math.max(1, options.proxyReadinessTimeoutMs ?? CLOUD_PROXY_READINESS_TIMEOUT_MS);\n\ttry {\n\t\tif (!(await probeStatusLine({\n\t\t\tdeadline,\n\t\t\tport: ports.connect,\n\t\t\trequest: `CONNECT ${READINESS_CONNECT_TARGET} HTTP/1.1\\r\\nHost: ${READINESS_CONNECT_TARGET}\\r\\nConnection: close\\r\\n\\r\\n`\n\t\t})).startsWith(\"HTTP/1.1 403\")) throw new Error(\"the CONNECT entry did not answer with the execution adapter refusal\");\n\t\tif (!(await probeStatusLine({\n\t\t\tca: await readFile(join(executionDir, \"ca.pem\")),\n\t\t\tdeadline,\n\t\t\tport: ports.slack,\n\t\t\trequest: \"GET / HTTP/1.1\\r\\nHost: localhost\\r\\nConnection: close\\r\\n\\r\\n\",\n\t\t\tservername: \"localhost\"\n\t\t})).startsWith(\"HTTP/1.1 401\")) throw new Error(\"the Slack entry did not answer with the execution adapter challenge\");\n\t} catch (error) {\n\t\tthrow new Error(`The per-execution proxy transport readiness check failed: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n}\n/** One bounded request/response exchange against a loopback entry; resolves with the status line. */\nasync function probeStatusLine(input) {\n\tconst remaining = input.deadline - Date.now();\n\tif (remaining <= 0) throw new Error(\"the readiness deadline was exceeded\");\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet received = 0;\n\t\tlet buffered = \"\";\n\t\tconst finish = (error, line) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timer);\n\t\t\tsocket.destroy();\n\t\t\tif (error) reject(error);\n\t\t\telse resolve(line);\n\t\t};\n\t\tconst timer = setTimeout(() => finish(/* @__PURE__ */ new Error(\"the readiness probe timed out\")), remaining);\n\t\ttimer.unref?.();\n\t\tconst socket = input.ca ? connect({\n\t\t\tca: input.ca,\n\t\t\thost: \"127.0.0.1\",\n\t\t\tport: input.port,\n\t\t\trejectUnauthorized: true,\n\t\t\t...input.servername ? { servername: input.servername } : {}\n\t\t}) : connect$1({\n\t\t\thost: \"127.0.0.1\",\n\t\t\tport: input.port\n\t\t});\n\t\tsocket.once(\"error\", (error) => finish(/* @__PURE__ */ new Error(`the readiness connection failed: ${error.message}`)));\n\t\tsocket.once(\"close\", () => finish(/* @__PURE__ */ new Error(\"the readiness connection closed without a response\")));\n\t\tsocket.on(\"data\", (chunk) => {\n\t\t\treceived += chunk.byteLength;\n\t\t\tif (received > READINESS_RESPONSE_MAX_BYTES) {\n\t\t\t\tfinish(/* @__PURE__ */ new Error(\"the readiness response exceeded the bound\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbuffered += chunk.toString(\"latin1\");\n\t\t\tconst newline = buffered.indexOf(\"\\r\\n\");\n\t\t\tif (newline < 0) return;\n\t\t\tconst line = buffered.slice(0, newline);\n\t\t\tif (!/^HTTP\\/1\\.[01] \\d{3}( |$)/.test(line)) {\n\t\t\t\tfinish(/* @__PURE__ */ new Error(\"the readiness response is not an HTTP status line\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfinish(void 0, line);\n\t\t});\n\t\tsocket.once(input.ca ? \"secureConnect\" : \"connect\", () => socket.write(input.request));\n\t});\n}\nasync function readPersistedBinding(path) {\n\tlet raw;\n\ttry {\n\t\traw = await readFile(path, \"utf8\");\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return void 0;\n\t\tthrow error;\n\t}\n\treturn PersistedBindingSchema.parse(JSON.parse(raw));\n}\n/** Atomic binding persistence: the next Turn resumes exactly this provider binding. */\nasync function persistBinding(path, binding) {\n\tconst temporary = `${path}.${process.pid}.tmp`;\n\tawait writeFile(temporary, `${JSON.stringify(binding)}\\n`, { mode: 384 });\n\tawait rename(temporary, path);\n}\n/** An in-sandbox path only; the trusted parent never supplies a host path here. */\nfunction assertSafeInSandboxPath(value, label) {\n\tif (typeof value !== \"string\" || value.length === 0 || value.length > 512 || !value.startsWith(\"/\") || value.split(\"/\").includes(\"..\") || /[\\0\\n\\r]/.test(value)) throw new Error(`Unsafe ${label} for the Cloud Turn worker`);\n\treturn value;\n}\nfunction randomTurnRunId(request) {\n\treturn request.kind === \"turn\" ? `cloud-turn-${request.delivery.deliveryId}` : `cloud-session-${request.message.messageId}`;\n}\n/** Keep CLI writes in the existing per-execution scratch lifetime. */\nasync function prepareCliDirectories(environment, scratch) {\n\tif (environment.OPENTAG_SLACK_CONFIG_DIR || environment.SLACK_CONFIG_DIR) {\n\t\tconst directory = join(scratch, \"slack\");\n\t\tawait mkdir(directory, { mode: 448 });\n\t\tenvironment.OPENTAG_SLACK_CONFIG_DIR = directory;\n\t\tenvironment.SLACK_CONFIG_DIR = directory;\n\t}\n\tif (environment.LARKSUITE_CLI_CONFIG_DIR) {\n\t\tconst directory = join(scratch, \"lark\");\n\t\tawait mkdir(directory, { mode: 448 });\n\t\tenvironment.LARKSUITE_CLI_CONFIG_DIR = directory;\n\t}\n}\n//#endregion\n//#region src/runner/worker.ts\n/**\n* In-sandbox acceptance worker. Runs INSIDE the native sandbox (launched via `sandbox exec`).\n* The bounded stdin document is the only input: real-mode Pi credentials travel through stdin\n* and land only in a disposable Pi home inside the disposable sandbox filesystem — never in\n* argv, env, logs, or any parent-visible storage. stdout carries exactly one JSON result line;\n* the report is already redacted by the acceptance runner.\n*\n* E8 adds the Cloud kinds: one IM Turn or Session-collaboration message through the same\n* disposable-home discipline, with the execution-scoped model grant and proxy manifest instead\n* of a raw account-supplied Pi config, plus an optional Session proof in per-message scratch.\n*/\nconst WORKER_STDIN_MAX_BYTES = Math.max(RUNNER_ACCEPTANCE_WORKER_STDIN_MAX_BYTES, RUNNER_CLOUD_TURN_WORKER_STDIN_MAX_BYTES);\nconst WorkerRequestSchema = z.discriminatedUnion(\"kind\", [\n\tz.object({\n\t\tkind: z.literal(\"acceptance\"),\n\t\tmode: z.enum([\"offline\", \"real\"]),\n\t\tpiConfig: RunnerPiConfigInputSchema.optional()\n\t}).strict().superRefine((value, context) => {\n\t\tif (value.mode === \"real\" && !value.piConfig) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"piConfig\"],\n\t\t\tmessage: \"Real acceptance requires piConfig\"\n\t\t});\n\t\tif (value.mode === \"offline\" && value.piConfig) context.addIssue({\n\t\t\tcode: \"custom\",\n\t\t\tpath: [\"piConfig\"],\n\t\t\tmessage: \"Offline acceptance must not carry piConfig\"\n\t\t});\n\t}),\n\tRunnerCloudTurnWorkerRequestSchema,\n\tRunnerCloudSessionWorkerRequestSchema\n]);\nasync function readStdinBounded(stdin, limit) {\n\treturn new Promise((resolve, reject) => {\n\t\tlet received = 0;\n\t\tconst chunks = [];\n\t\tstdin.on(\"data\", (chunk) => {\n\t\t\treceived += chunk.byteLength;\n\t\t\tif (received > limit) {\n\t\t\t\treject(/* @__PURE__ */ new Error(\"Worker stdin payload exceeded bounds\"));\n\t\t\t\tstdin.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tchunks.push(chunk);\n\t\t});\n\t\tstdin.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n\t\tstdin.on(\"error\", (error) => reject(error));\n\t});\n}\nasync function writeDisposablePiConfig(piHome, config) {\n\tawait writeFile(join(piHome, \"auth.json\"), config.authJson, {\n\t\tencoding: \"utf8\",\n\t\tmode: 384\n\t});\n\tif (config.modelsJson !== void 0) await writeFile(join(piHome, \"models.json\"), config.modelsJson, {\n\t\tencoding: \"utf8\",\n\t\tmode: 384\n\t});\n\tif (config.settingsJson !== void 0) await writeFile(join(piHome, \"settings.json\"), config.settingsJson, {\n\t\tencoding: \"utf8\",\n\t\tmode: 384\n\t});\n}\nasync function runRunnerWorker(io, options = {}) {\n\tconst emit = (value) => io.stdout.write(`${JSON.stringify(value)}\\n`);\n\tlet scratch;\n\ttry {\n\t\tconst raw = await readStdinBounded(io.stdin, WORKER_STDIN_MAX_BYTES);\n\t\tlet parsed;\n\t\ttry {\n\t\t\tparsed = WorkerRequestSchema.parse(JSON.parse(raw));\n\t\t} catch {\n\t\t\temit({\n\t\t\t\tkind: \"error\",\n\t\t\t\tcode: \"worker_request_invalid\",\n\t\t\t\tmessage: \"The worker stdin payload is invalid\"\n\t\t\t});\n\t\t\treturn 2;\n\t\t}\n\t\tif (parsed.kind === \"turn\" || parsed.kind === \"session-message\") return await runCloudTurn(parsed, emit, options);\n\t\tscratch = await mkdtemp(join(tmpdir(), \"opentag-runner-worker-\"));\n\t\tregisterRunnerSignalCleanup(async () => {\n\t\t\tif (scratch) await rm(scratch, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t});\n\t\t});\n\t\tconst home = join(scratch, \"home\");\n\t\tlet piHome = join(scratch, \"pi-agent\");\n\t\tconst sessionDirectory = join(scratch, \"sessions\");\n\t\tif (parsed.piConfig) {\n\t\t\tconst rawPiHome = piHome;\n\t\t\tawait mkdir(rawPiHome, {\n\t\t\t\trecursive: true,\n\t\t\t\tmode: 448\n\t\t\t});\n\t\t\tawait writeDisposablePiConfig(rawPiHome, parsed.piConfig);\n\t\t\tpiHome = await copyIsolatedPiConfig({\n\t\t\t\tsource: rawPiHome,\n\t\t\t\tdestination: join(scratch, \"filtered-pi\"),\n\t\t\t\tproviders: [\"deepseek\"]\n\t\t\t});\n\t\t\tawait rm(rawPiHome, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t});\n\t\t}\n\t\tawait mkdir(home, {\n\t\t\trecursive: true,\n\t\t\tmode: 448\n\t\t});\n\t\tconst report = await (options.runAcceptance ?? runRunnerAcceptance)({\n\t\t\tmode: parsed.mode,\n\t\t\tpiHome,\n\t\t\truntimeHome: home,\n\t\t\tpath: io.env?.PATH ?? process.env.PATH,\n\t\t\tsessionDirectory,\n\t\t\tworkspace: options.workspace ?? \"/workspace\"\n\t\t});\n\t\temit({\n\t\t\tkind: \"result\",\n\t\t\treport\n\t\t});\n\t\treturn report.failed ? 1 : 0;\n\t} catch {\n\t\temit({\n\t\t\tkind: \"error\",\n\t\t\tcode: \"worker_failed\",\n\t\t\tmessage: \"The in-sandbox worker failed\"\n\t\t});\n\t\treturn 1;\n\t} finally {\n\t\tregisterRunnerSignalCleanup(void 0);\n\t\tif (scratch) await rm(scratch, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n/** One Cloud delivery (IM Turn or Session message): emits the completion and maps it to an exit code. */\nasync function runCloudTurn(request, emit, options) {\n\ttry {\n\t\tconst completion = await (options.runCloudTurn ?? runCloudTurnWorker)(request, { workspace: options.workspace ?? \"/workspace\" });\n\t\temit({\n\t\t\tkind: \"result\",\n\t\t\tcompletion\n\t\t});\n\t\treturn completion.outcome === \"completed\" ? 0 : 1;\n\t} catch {\n\t\temit({\n\t\t\tkind: \"error\",\n\t\t\tcode: \"worker_failed\",\n\t\t\tmessage: \"The in-sandbox Turn worker failed\"\n\t\t});\n\t\treturn 1;\n\t}\n}\n//#endregion\n//#region src/runner/cli.ts\nconst IDENTITY_CANDIDATES = [\"/opt/opentag/identity.json\", \"identity.json\"];\nasync function loadIdentity(cwd) {\n\tfor (const candidate of IDENTITY_CANDIDATES) {\n\t\tconst path = isAbsolute(candidate) ? candidate : resolve(cwd, candidate);\n\t\ttry {\n\t\t\treturn parseRunnerIdentity(JSON.parse(await readFile(path, \"utf8\")));\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") continue;\n\t\t\tthrow error;\n\t\t}\n\t}\n}\nfunction writeJson(io, value) {\n\tio.stdout.write(`${JSON.stringify(redactAcceptanceRecord(value))}\\n`);\n}\nfunction writeText(io, value) {\n\tio.stdout.write(value.endsWith(\"\\n\") ? value : `${value}\\n`);\n}\nasync function runIdentity(invocation, io, cwd) {\n\tconst identity = await loadIdentity(cwd);\n\tif (!identity) {\n\t\tio.stderr.write(\"runner identity file is missing\\n\");\n\t\treturn 1;\n\t}\n\tif (invocation.json) writeJson(io, identity);\n\telse writeText(io, `${identity.version} ${identity.sourceSha}${identity.sourceDirty ? \" dirty\" : \"\"}`);\n\treturn 0;\n}\nasync function runProbe(invocation, io, cwd) {\n\tconst identity = await loadIdentity(cwd);\n\tconst probes = await probeRunnerTools({\n\t\tenv: io.env,\n\t\t...identity ? { expected: expectedFromIdentity(identity) } : {}\n\t});\n\tif (invocation.json) writeJson(io, probes);\n\telse for (const probe of probes) writeText(io, `${probe.ok ? \"ok\" : \"FAIL\"} ${probe.name}${probe.detail ? ` ${probe.detail}` : \"\"}`);\n\treturn runnerToolsReady(probes) ? 0 : 1;\n}\nasync function runSkills(invocation, io) {\n\tconst assembled = await assembleContextTreeSkills();\n\tif (invocation.json) writeJson(io, {\n\t\tskills: assembled.skills.map((skill) => skill.name),\n\t\tskillsPath: assembled.skillsPath\n\t});\n\telse writeText(io, assembled.skills.map((skill) => skill.name).join(\"\\n\"));\n\treturn 0;\n}\nfunction checkSupportedProvider(invocation, io) {\n\tif (invocation.provider !== void 0 && invocation.provider !== \"deepseek\") {\n\t\tio.stderr.write(`unsupported provider for real acceptance: ${invocation.provider} (only ${RUNNER_DEEPSEEK_PROVIDER} is currently supported)\\n`);\n\t\treturn 2;\n\t}\n}\nfunction writeAcceptReport(invocation, io, report) {\n\tif (invocation.json) {\n\t\twriteJson(io, report);\n\t\treturn;\n\t}\n\tfor (const item of report.events) writeText(io, `${item.status} ${item.name}${item.detail ? ` ${item.detail}` : \"\"}`);\n\twriteText(io, `offline=${report.offline} model=${report.model}`);\n}\nasync function acceptPiHome(invocation, runtimeHome, scratch) {\n\tif (invocation.piConfigDir && invocation.provider) return copyIsolatedPiConfig({\n\t\tdestination: join(scratch, \"pi-config\"),\n\t\tsource: invocation.piConfigDir,\n\t\tproviders: [invocation.provider]\n\t});\n\treturn resolve(runtimeHome, \".pi\", \"agent\");\n}\nasync function runAccept(invocation, io, cwd) {\n\tconst unsupported = checkSupportedProvider(invocation, io);\n\tif (unsupported !== void 0) return unsupported;\n\tconst workspace = invocation.workspace ?? resolve(cwd, \"workspace\");\n\tconst runtimeHome = io.env?.HOME ?? resolve(cwd, \"home\");\n\tconst scratch = await mkdtemp(join(tmpdir(), \"opentag-runner-accept-\"));\n\tconst cleanupScratch = async () => {\n\t\tawait rm(scratch, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t};\n\tregisterRunnerSignalCleanup(cleanupScratch);\n\ttry {\n\t\tconst identity = await loadIdentity(cwd);\n\t\tconst report = await runRunnerAcceptance({\n\t\t\tmode: invocation.mode,\n\t\t\tpiHome: await acceptPiHome(invocation, runtimeHome, scratch),\n\t\t\truntimeHome,\n\t\t\tpath: io.env?.PATH,\n\t\t\tsessionDirectory: join(scratch, \"sessions\"),\n\t\t\tworkspace,\n\t\t\t...identity ? { identity } : {}\n\t\t});\n\t\twriteAcceptReport(invocation, io, report);\n\t\treturn report.failed ? 1 : 0;\n\t} finally {\n\t\tregisterRunnerSignalCleanup(void 0);\n\t\tawait cleanupScratch();\n\t}\n}\nasync function runServe(invocation, io) {\n\tconst env = io.env ?? process.env;\n\tif (invocation.workspace) io.stderr.write(\"--workspace is ignored in serve mode; OPENTAG_RUNNER_WORKSPACE applies\\n\");\n\tconst config = loadRunnerServeConfig(env);\n\tconst stop = new AbortController();\n\tconst running = runRunnerServe(config, {\n\t\tenv,\n\t\tstderr: io.stderr,\n\t\tsignal: stop.signal,\n\t\tinstallSignalHandlers: false\n\t});\n\tregisterRunnerSignalCleanup(async () => {\n\t\tstop.abort();\n\t\tawait running;\n\t});\n\ttry {\n\t\treturn await running;\n\t} finally {\n\t\tregisterRunnerSignalCleanup(void 0);\n\t}\n}\nasync function runWorker(invocation, io) {\n\tif (invocation.workspace) io.stderr.write(\"--workspace is ignored in worker mode; the sandbox workspace is fixed\\n\");\n\treturn runRunnerWorker({\n\t\tstdin: process.stdin,\n\t\tstdout: io.stdout,\n\t\tstderr: io.stderr,\n\t\t...io.env ? { env: io.env } : {}\n\t}, {});\n}\nconst COMMANDS = {\n\tidentity: runIdentity,\n\tprobe: runProbe,\n\tskills: runSkills,\n\taccept: runAccept,\n\tserve: runServe,\n\tworker: runWorker\n};\nasync function runRunnerCli(argv, io, cwd = process.cwd()) {\n\tconst parsed = parseRunnerCliArgv(argv);\n\tif (!parsed.ok) {\n\t\tio.stderr.write(parsed.error);\n\t\treturn parsed.exitCode;\n\t}\n\ttry {\n\t\tconst command = COMMANDS[parsed.invocation.command];\n\t\treturn await command(parsed.invocation, io, cwd);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tio.stderr.write(`${redactAcceptanceRecord(message)}\\n`);\n\t\treturn 1;\n\t}\n}\n//#endregion\nexport { isProviderCliSessionKey as $, writeDurableFile as $n, closeBridgeSockets as $t, PROVIDER_CLI_OUTGOING_REPLY_STDOUT_CAPTURE_MAX_BYTES as A, RUNTIME_PROVIDER_PROXY_CAPABILITY as An, runContextTreeCli as At, MAX_PROVIDER_CLI_TURN_IDENTITY_BYTES as B, parseRuntimeCredentialServerFrame as Bn, requireProviderCliCatalogEntry as Bt, TURN_TRACE_MAX_BUFFER_BYTES as C, RuntimeProxyDataConnection as Cn, runRunnerAcceptance as Ct, ClientRuntimeProviderStartError as D, RUNTIME_EXECUTION_MAX_LIFETIME_MS as Dn, managedRepositoryAllowed as Dt, TurnTraceBuffer as E, RUNTIME_CREDENTIAL_CAPABILITY as En, ContextTreeManager as Et, cleanupOutgoingReplyRun as F, RUNTIME_PROXY_DATA_INITIAL_CREDIT_BYTES as Fn, linuxAmd64ProviderCliPlans as Ft, assertPlanWithinRoot as G, assertRealDirectory as Gn, PI_RPC_MAX_LINE_BYTES as Gt, PROVIDER_CLI_TURN_PLAN_SCHEMA_VERSION as H, resolveOpenTagHome as Hn, PiAgentRuntime as Ht, collectOutgoingReplyReceipts as I, RUNTIME_PROXY_DATA_MAX_STREAMS as In, PROVIDER_CLI_CATALOG as It, deriveProviderCliHomeNamespace as J, readDurableJson as Jn, PiRpcError as Jt, assertProviderCliSlackConfigDir as K, assertWithin as Kn, PI_RPC_MAX_STDERR_BYTES as Kt, listPrivateFiles as L, RUNTIME_PROXY_PROVIDERS as Ln, catalogExecutableDigests as Lt, classifyLarkOutgoingMutation as M, RUNTIME_PROXY_DATA_BINARY_FRAME_MAX_BYTES as Mn, resolveContextTreeHome as Mt, withOutgoingReplyInflight as N, RUNTIME_PROXY_DATA_CHUNK_BYTES as Nn, redactAcceptanceRecord as Nt, SessionRuntimeManager as O, RUNTIME_MCP_GATEWAY_CAPABILITY as On, mergeContextTreeEnvironment as Ot, assertPrivateAncestry as P, RUNTIME_PROXY_DATA_HEADER_MAX_BYTES as Pn, probeRunnerTools as Pt, isProviderCliRunKey as Q, validatePrivateDirectory as Qn, composeRuntimeEnvironment as Qt, markOutgoingReplyCaptureStatus as R, RUNTIME_PROXY_TICKET_TTL_MS as Rn, findCatalogArtifact as Rt, TURN_TRACE_BATCH_SOFT_LIMIT_BYTES as S, defaultRuntimeProxyDataConnectionFactory as Sn, RUNNER_IDENTITY_SCHEMA_VERSION as St, TURN_TRACE_SEND_DEADLINE_MS as T, MCP_GATEWAY_PATH$1 as Tn, assembleContextTreeSkills as Tt, ProviderCliTurnPlanError as U, resolveOpenTagHomeLayout as Un, PiAgentRuntimeFactory as Ut, MAX_PROVIDER_CLI_TURN_PLAN_BYTES as V, runtimeProxyErrorReason as Vn, PI_AGENT_RUNTIME_MANIFEST as Vt, assertIdentity as W, RuntimeStorageError as Wn, piAgentRuntimeEnvironment as Wt, deriveProviderCliSessionKey as X, removeDurableFile as Xn, signalWatchedProcess as Xt, deriveProviderCliRunKey as Y, readSecureFile as Yn, PiRpcProcess as Yt, isProviderCliHomeNamespace as Z, syncDurableDirectory as Zn, spawnWatchedProcess as Zt, WebGatewayDispatchError as _, RuntimeProxyLoopbackAdapter as _n, createRunnerIdentity as _t, FileRuntimeDurabilityStore as a, RUNTIME_PROXY_SHIM_MARKER as an, assertSystemPrompt as ar, providerCliPlanSessionDir as at, AgentTurnRunner as b, RuntimeCredentialRelay as bn, parseRunnerCliArgv as bt, RuntimeDurabilityMetrics as c, providerRoutingEnvironment as cn, AGENT_RUNTIME_CONTRACT_VERSION as cr, publishProviderCliTurnPlanExclusive as ct, retryDelay as d, runtimeProxyOutboxContext as dn, AGENT_RUNTIME_TEXT_MAX_BYTES as dr, spawnCapturedProcess as dt, createBridgeSocketResources as en, writeDurableJson as er, managedArtifactDigest as et, retryExhausted as f, ImCredentialEnvironmentError as fn, AgentProviderError as fr, spawnInheritedProcess as ft, WebToolsServerClient as g, RUNTIME_PROXY_HANDLE_PATH_PREFIX as gn, createLogger as gr, resolveWebToolsExtensionPath as gt, WebToolsClientError as h, RUNTIME_PROXY_ALLOWED_CONNECT_HOSTS as hn, configureClientLoggerForService as hr, isAgentRuntimeProviderId as ht, DEFAULT_RUNTIME_RETRY_POLICY as i, RUNTIME_PROXY_GIT_HELPER_MARKER as in, assertJsonValue as ir, providerCliPlanHomeDir as it, captureFeishuOutgoingReply as j, RUNTIME_PROVIDER_PROXY_PATH as jn, prepareContextTreeHome as jt, renderManagedSystemPrompt as k, RUNTIME_PROVIDER_ORIGIN_HEADER as kn, resolveContextTreePackage as kt, defaultRuntimeRetryScheduler as l, renderRuntimeProxyGitCredentialHelper as ln, AGENT_RUNTIME_DESCRIPTION_MAX_BYTES as lr, readProviderCliTurnPlan as lt, createExecutionWebDispatch as m, serializeEnvironment as mn, configureClientLoggerContext as mr, AgentRuntimeProviderUnavailableError as mt, SessionMessageInbox as n, publishExecutionMaterial as nn, assertBinding as nr, planCapturesOutgoingReplies as nt, MemoryRuntimeDurabilityStore as o, RuntimeProxyMaterialStore as on, runWithAbortSignal as or, providerCliTurnLauncherPath as ot, installRunnerSignalHandlers as p, ImCredentialEnvironmentManager as pn, AgentRuntimeError as pr, AgentRuntimeProviderRegistry as pt, assertProviderCliTurnPlanConfigDir as q, ensurePrivateDirectory as qn, PI_RPC_REQUEST_TIMEOUT_MS as qt, buildSessionMessageInput as r, CLOUD_EXECUTION_MOUNT as rn, assertHostedTools as rr, providerCliCommandForProvider as rt, RuntimeDurabilityFailure as s, buildRuntimeProxyEnvironment as sn, AGENT_RUNTIME_BINDING_MAX_BYTES as sr, providerCliTurnPlanPath as st, runRunnerCli as t, listenBridgeProxySockets as tn, BaseAgentRuntime as tr, parseProviderCliTurnPlan as tt, durableFailureFromUnknown as u, renderRuntimeProxyShim as un, AGENT_RUNTIME_ID_MAX_BYTES as ur, flushStdout as ut, WebToolsGatewayServer as v, RuntimeProxyLoopbackError as vn, parseRunnerIdentity as vt, TURN_TRACE_MAX_BUFFER_EVENTS as w, RuntimeProxyDataError as wn, CONTEXT_TREE_PACKAGED_SKILL_DIRECTORIES as wt, buildAgentInput as x, RuntimeCredentialRelayError as xn, RUNNER_CLI_NAME as xt, allocateWebGatewaySocket as y, generateExecutionCa as yn, copyIsolatedPiConfig as yt, recoverSessionOutgoingReplyEvidence as z, RUNTIME_WEB_TOOLS_CAPABILITY as zn, findProviderCliCatalogEntry as zt };\n\n//# sourceMappingURL=cli-PfvjQunU.mjs.map","import { $ as isProviderCliSessionKey, $n as writeDurableFile, $t as closeBridgeSockets, A as PROVIDER_CLI_OUTGOING_REPLY_STDOUT_CAPTURE_MAX_BYTES, An as RUNTIME_PROVIDER_PROXY_CAPABILITY, At as runContextTreeCli, B as MAX_PROVIDER_CLI_TURN_IDENTITY_BYTES, Bn as parseRuntimeCredentialServerFrame, Bt as requireProviderCliCatalogEntry, C as TURN_TRACE_MAX_BUFFER_BYTES, Cn as RuntimeProxyDataConnection, Ct as runRunnerAcceptance, D as ClientRuntimeProviderStartError, Dn as RUNTIME_EXECUTION_MAX_LIFETIME_MS, Dt as managedRepositoryAllowed, E as TurnTraceBuffer, En as RUNTIME_CREDENTIAL_CAPABILITY, Et as ContextTreeManager, F as cleanupOutgoingReplyRun, Fn as RUNTIME_PROXY_DATA_INITIAL_CREDIT_BYTES, Ft as linuxAmd64ProviderCliPlans, G as assertPlanWithinRoot, Gn as assertRealDirectory, Gt as PI_RPC_MAX_LINE_BYTES, H as PROVIDER_CLI_TURN_PLAN_SCHEMA_VERSION, Hn as resolveOpenTagHome, Ht as PiAgentRuntime, I as collectOutgoingReplyReceipts, In as RUNTIME_PROXY_DATA_MAX_STREAMS, It as PROVIDER_CLI_CATALOG, J as deriveProviderCliHomeNamespace, Jn as readDurableJson, Jt as PiRpcError, K as assertProviderCliSlackConfigDir, Kn as assertWithin, Kt as PI_RPC_MAX_STDERR_BYTES, L as listPrivateFiles, Ln as RUNTIME_PROXY_PROVIDERS, Lt as catalogExecutableDigests, M as classifyLarkOutgoingMutation, Mn as RUNTIME_PROXY_DATA_BINARY_FRAME_MAX_BYTES, Mt as resolveContextTreeHome, N as withOutgoingReplyInflight, Nn as RUNTIME_PROXY_DATA_CHUNK_BYTES, Nt as redactAcceptanceRecord, O as SessionRuntimeManager, On as RUNTIME_MCP_GATEWAY_CAPABILITY, Ot as mergeContextTreeEnvironment, P as assertPrivateAncestry, Pn as RUNTIME_PROXY_DATA_HEADER_MAX_BYTES, Pt as probeRunnerTools, Q as isProviderCliRunKey, Qn as validatePrivateDirectory, Qt as composeRuntimeEnvironment, R as markOutgoingReplyCaptureStatus, Rn as RUNTIME_PROXY_TICKET_TTL_MS, Rt as findCatalogArtifact, S as TURN_TRACE_BATCH_SOFT_LIMIT_BYTES, Sn as defaultRuntimeProxyDataConnectionFactory, St as RUNNER_IDENTITY_SCHEMA_VERSION, T as TURN_TRACE_SEND_DEADLINE_MS, Tn as MCP_GATEWAY_PATH$1, Tt as assembleContextTreeSkills, U as ProviderCliTurnPlanError, Un as resolveOpenTagHomeLayout, Ut as PiAgentRuntimeFactory, V as MAX_PROVIDER_CLI_TURN_PLAN_BYTES, Vn as runtimeProxyErrorReason, Vt as PI_AGENT_RUNTIME_MANIFEST, W as assertIdentity, Wn as RuntimeStorageError, Wt as piAgentRuntimeEnvironment, X as deriveProviderCliSessionKey, Xn as removeDurableFile, Xt as signalWatchedProcess, Y as deriveProviderCliRunKey, Yn as readSecureFile, Yt as PiRpcProcess, Z as isProviderCliHomeNamespace, Zn as syncDurableDirectory, Zt as spawnWatchedProcess, _ as WebGatewayDispatchError, _n as RuntimeProxyLoopbackAdapter, _t as createRunnerIdentity, a as FileRuntimeDurabilityStore, an as RUNTIME_PROXY_SHIM_MARKER, ar as assertSystemPrompt, at as providerCliPlanSessionDir, b as AgentTurnRunner, bn as RuntimeCredentialRelay, bt as parseRunnerCliArgv, c as RuntimeDurabilityMetrics, cn as providerRoutingEnvironment, cr as AGENT_RUNTIME_CONTRACT_VERSION, ct as publishProviderCliTurnPlanExclusive, d as retryDelay, dn as runtimeProxyOutboxContext, dr as AGENT_RUNTIME_TEXT_MAX_BYTES, dt as spawnCapturedProcess, en as createBridgeSocketResources, er as writeDurableJson, et as managedArtifactDigest, f as retryExhausted, fn as ImCredentialEnvironmentError, fr as AgentProviderError, ft as spawnInheritedProcess, g as WebToolsServerClient, gn as RUNTIME_PROXY_HANDLE_PATH_PREFIX, gr as createLogger, gt as resolveWebToolsExtensionPath, h as WebToolsClientError, hn as RUNTIME_PROXY_ALLOWED_CONNECT_HOSTS, hr as configureClientLoggerForService, ht as isAgentRuntimeProviderId, i as DEFAULT_RUNTIME_RETRY_POLICY, in as RUNTIME_PROXY_GIT_HELPER_MARKER, ir as assertJsonValue, it as providerCliPlanHomeDir, j as captureFeishuOutgoingReply, jn as RUNTIME_PROVIDER_PROXY_PATH, jt as prepareContextTreeHome, k as renderManagedSystemPrompt, kn as RUNTIME_PROVIDER_ORIGIN_HEADER, kt as resolveContextTreePackage, l as defaultRuntimeRetryScheduler, ln as renderRuntimeProxyGitCredentialHelper, lr as AGENT_RUNTIME_DESCRIPTION_MAX_BYTES, lt as readProviderCliTurnPlan, m as createExecutionWebDispatch, mn as serializeEnvironment, mr as configureClientLoggerContext, mt as AgentRuntimeProviderUnavailableError, n as SessionMessageInbox, nn as publishExecutionMaterial, nr as assertBinding, nt as planCapturesOutgoingReplies, o as MemoryRuntimeDurabilityStore, on as RuntimeProxyMaterialStore, or as runWithAbortSignal, ot as providerCliTurnLauncherPath, pn as ImCredentialEnvironmentManager, pr as AgentRuntimeError, pt as AgentRuntimeProviderRegistry, q as assertProviderCliTurnPlanConfigDir, qn as ensurePrivateDirectory, qt as PI_RPC_REQUEST_TIMEOUT_MS, r as buildSessionMessageInput, rn as CLOUD_EXECUTION_MOUNT, rr as assertHostedTools, rt as providerCliCommandForProvider, s as RuntimeDurabilityFailure, sn as buildRuntimeProxyEnvironment, sr as AGENT_RUNTIME_BINDING_MAX_BYTES, st as providerCliTurnPlanPath, t as runRunnerCli, tn as listenBridgeProxySockets, tr as BaseAgentRuntime, tt as parseProviderCliTurnPlan, u as durableFailureFromUnknown, un as renderRuntimeProxyShim, ur as AGENT_RUNTIME_ID_MAX_BYTES, ut as flushStdout, v as WebToolsGatewayServer, vn as RuntimeProxyLoopbackError, vt as parseRunnerIdentity, w as TURN_TRACE_MAX_BUFFER_EVENTS, wn as RuntimeProxyDataError, wt as CONTEXT_TREE_PACKAGED_SKILL_DIRECTORIES, x as buildAgentInput, xn as RuntimeCredentialRelayError, xt as RUNNER_CLI_NAME, y as allocateWebGatewaySocket, yn as generateExecutionCa, yt as copyIsolatedPiConfig, z as recoverSessionOutgoingReplyEvidence, zn as RUNTIME_WEB_TOOLS_CAPABILITY, zt as findProviderCliCatalogEntry } from \"./cli-PfvjQunU.mjs\";\nimport { basename, delimiter, dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from \"node:path\";\nimport { AgentAdminConfigSchema, AgentDetailSchema, AgentRuntimeTestResponseSchema, AgentRuntimeTestResultFrameSchema, AgentUsageDetailSchema, ComputerConnectCodeExchangeResponseSchema, ComputerConnectCodeIssueResponseSchema, ComputerConnectCodeStatusSchema, ConnectCodeExchangeResponseSchema, ContextTreeOperationResponseSchema, ContextTreeOperationResultFrameSchema, EffectiveRuntimeSnapshotSchema, ErrorEnvelopeSchema, FeishuSetupAttemptSchema, HTTP_PATHS, IM_CLI_PROVIDERS, ImBindingAdminDetailSchema, ImBindingDiagnosticsSchema, ImBindingSummarySchema, ImMessageDeliveryResultSchema, ListAccountComputersResponseSchema, ListAgentMCPServersResponseSchema, ListAgentSkillsResponseSchema, ListAgentsResponseSchema, ListAvailableMCPServersResponseSchema, ListMCPServersResponseSchema, MCPAgentServerSchema, MCPProbeResponseSchema, MCPServerDetailSchema, MCPServerSchema, MCP_GATEWAY_ALLOWED_TOOL_RULE, MCP_GATEWAY_SERVER_NAME, MeResponseSchema, PROVIDER_CLI_REASON_V2_HEADER, PROVIDER_READINESS_V1_HEADER, PROVIDER_READINESS_V2_HEADER, ProviderCliCancelFrameSchema, ProviderCliPrewarmFrameSchema, ProviderCliPrewarmResultFrameSchema, ProviderCliRequirementFrameSchema, ProviderCliValidationGrantFrameSchema, ProviderCliValidationRunFrameSchema, RUNTIME_AGENT_MCP_SERVERS_AVAILABLE_PATH, RUNTIME_AGENT_MCP_SERVERS_PATH, RUNTIME_AGENT_PATH, RUNTIME_AGENT_RUNTIME_TEST_CLEANUP_MS, RUNTIME_AGENT_RUNTIME_TEST_TIMEOUT_MS, RUNTIME_CAPABILITY, RUNTIME_CLIENT_CAPABILITY_OFFERS, RUNTIME_CLIENT_CAPABILITY_TTL_MS, RUNTIME_MAX_FRAME_BYTES, RUNTIME_MVP_RETAINED_REPORT_LIMIT, RUNTIME_PROTOCOL_V1, RUNTIME_PROTOCOL_V2, RUNTIME_PROTOCOL_VERSION, RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES, RUNTIME_PROVIDER_CLI_VALIDATION_TIMEOUT_MS, RUNTIME_REQUIRED_SERVER_CAPABILITIES, RUNTIME_SKILLS_PATH, RUNTIME_SUPPORTED_PROTOCOL_VERSIONS, RefreshTokenResponseSchema, RuntimeCredentialServerFrameSchema, RuntimeDurableWorkKindSchema, RuntimeDurableWorkListResponseSchema, RuntimeDurableWorkRecordSchema, RuntimeFrameEnvelopeSchema, RuntimeImSteerResultSchema, RuntimeRequestIdSchema, RuntimeSha256Schema, RuntimeSkillManifestSchema, SESSION_CLI_PROOF_HEADER, SKILL_ARCHIVE_MAX_BYTES, SKILL_FORMAT_HEADER, SKILL_MANIFEST_FILE, SKILL_MARKER_FILE, SKILL_MAX_ENTRIES, SKILL_MAX_PATH_BYTES, SKILL_REPLACE_HEADER, SKILL_SHA256_HEADER, SKILL_UNPACKED_MAX_BYTES, SKILL_UPLOAD_CONTENT_TYPE, ServerHealthSchema, ServerRuntimeBusinessFrameSchema, ServerRuntimeFrameSchema, SessionCliCommandResponseSchema, SessionCliListResponseSchema, SessionMessageDeliveryResultSchema, SessionReconcileRequestSchema, SessionReconcileResultSchema, SkillDetailSchema, SkillInstallMarkerSchema, SkillSchema, StartMCPOAuthResponseSchema, StartSlackOAuthResponseSchema, StructuredErrorCategorySchema, StructuredErrorPhaseSchema, StructuredErrorSchema, TurnReportRequestSchema, TurnReportResultSchema, accountComputerConnectCodePath, agentByIdPath, agentComputerRebindPath, agentConfigPath, agentFeishuSetupAttemptsPath, agentImBindingConfigPath, agentImBindingPath, agentMcpAuthorizationOAuthPath, agentMcpAuthorizationPath, agentMcpProbePath, agentMcpServerPath, agentMcpServersPath, agentReactivatePath, agentRuntimeTestPath, agentSkillBundlePath, agentSkillPath, agentSkillsPath, agentSlackOAuthStartPath, agentSuspendPath, agentUsagePath, compareSemVer, computeDirectInputHash, computeReconcilePayloadHash, computeRuntimeImMessageSemanticHash, computeRuntimeImSteerInputHash, computeRuntimeSnapshotHashes, computeTurnResultHash, computerAgentSkillBundlePath, computerAgentSkillsPath, createErrorReport, feishuSetupAttemptPath, getRuntimeConfigurationOptions, hashTuple, imBindingDiagnosticsPath, imBindingDisablePath, isReservedSkillName, mcpServerPath, mcpServersPath, missingRuntimeCapabilities, negotiateRuntimeCapabilities, parseSkillManifest, providerCliArtifactFailureIsManual, publicProviderCliArtifactReason, redactForLog, redactSensitive, runtimeAgentMcpServerPath, runtimeDurableWorkPath, runtimeFrameByteLength, runtimeImResourcePath, runtimeNegotiatedCapabilitiesEqual, runtimeSkillBundlePath, runtimeWebSocketUrl } from \"@opentag/shared\";\nimport { constants, createReadStream, createWriteStream, readdirSync, readlinkSync, realpathSync } from \"node:fs\";\nimport { createHash, randomBytes, randomUUID } from \"node:crypto\";\nimport { z } from \"zod\";\nimport { access, chmod, copyFile, cp, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from \"node:fs/promises\";\nimport { homedir, tmpdir, userInfo } from \"node:os\";\nimport { execFile, spawn } from \"node:child_process\";\nimport WebSocket from \"ws\";\nimport { createServer } from \"node:http\";\nimport { inspect, promisify } from \"node:util\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport semver from \"semver\";\nimport { PassThrough, Readable, Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport { createGunzip, createGzip, gunzipSync } from \"node:zlib\";\nimport { extract, pack } from \"tar-stream\";\nconst REQUEST_ID_HEADER = \"x-request-id\";\nfunction defaultRetryability(category) {\n\tswitch (category) {\n\t\tcase \"transient\":\n\t\tcase \"rate_limit\": return \"backoff\";\n\t\tcase \"credential\": return \"after_auth\";\n\t\tdefault: return \"never\";\n\t}\n}\nfunction defaultPhase(category) {\n\tswitch (category) {\n\t\tcase \"credential\": return \"authentication\";\n\t\tcase \"validation\": return \"validation\";\n\t\tdefault: return \"request\";\n\t}\n}\nfunction createRequestId() {\n\treturn randomUUID();\n}\nfunction safeCause(error, seen = /* @__PURE__ */ new WeakSet(), depth = 0) {\n\tif (error === void 0) return void 0;\n\tif (depth >= 8) return { message: \"Cause chain exceeded the diagnostic depth limit\" };\n\tif (error instanceof Error) {\n\t\tif (seen.has(error)) return { message: \"Cause chain contained a circular reference\" };\n\t\tseen.add(error);\n\t\tconst code = \"code\" in error && typeof error.code === \"string\" ? error.code : void 0;\n\t\tconst category = \"category\" in error ? canonicalCategory(error.category) : void 0;\n\t\tconst retryability = \"retryability\" in error ? canonicalRetryability(error.retryability) : void 0;\n\t\tconst phase = \"phase\" in error ? canonicalPhase(error.phase) : void 0;\n\t\tconst nested = \"cause\" in error ? safeCause(error.cause, seen, depth + 1) : void 0;\n\t\treturn {\n\t\t\t...code ? { code } : {},\n\t\t\t...category ? { category } : {},\n\t\t\t...retryability ? { retryability } : {},\n\t\t\t...phase ? { phase } : {},\n\t\t\tmessage: sanitizeCauseMessage(error.message),\n\t\t\t...nested ? { cause: nested } : {}\n\t\t};\n\t}\n\treturn { message: sanitizeCauseMessage(String(error)) };\n}\nfunction sanitizeCauseMessage(message) {\n\tconst sanitized = redactSensitive(message);\n\treturn (typeof sanitized === \"string\" ? sanitized : \"[REDACTED]\").slice(0, 2048);\n}\nfunction canonicalCategory(value) {\n\tif (StructuredErrorCategorySchema.safeParse(value).success) return value;\n\tif (value === \"credential\") return \"auth\";\n\tif (value === \"deterministic\") return \"conflict\";\n\tif (value === \"transient\") return \"unavailable\";\n}\nfunction canonicalRetryability(value) {\n\treturn value === \"never\" || value === \"immediate\" || value === \"backoff\" || value === \"after_auth\" ? value : value === \"retryable\" ? \"backoff\" : value === \"terminal\" ? \"never\" : void 0;\n}\nfunction canonicalPhase(value) {\n\treturn StructuredErrorPhaseSchema.safeParse(value).success ? value : void 0;\n}\nfunction statusFallback(status) {\n\tif (status === 400) return {\n\t\tcode: \"VALIDATION_ERROR\",\n\t\tcategory: \"validation\",\n\t\tmessage: \"The request payload is invalid\"\n\t};\n\tif (status === 404) return {\n\t\tcode: \"RESOURCE_NOT_FOUND\",\n\t\tcategory: \"deterministic\",\n\t\tmessage: \"The requested resource was not found\"\n\t};\n\tif (status === 409) return {\n\t\tcode: \"VALIDATION_ERROR\",\n\t\tcategory: \"deterministic\",\n\t\tmessage: \"The request conflicts with current state\"\n\t};\n\tif (status === 429) return {\n\t\tcode: \"RATE_LIMITED\",\n\t\tcategory: \"rate_limit\",\n\t\tmessage: \"The OpenTag server rate limit was reached\"\n\t};\n\tif (status >= 500) return {\n\t\tcode: \"SERVICE_UNAVAILABLE\",\n\t\tcategory: \"transient\",\n\t\tmessage: \"The OpenTag server is unavailable\"\n\t};\n\tif (status === 401 || status === 403) return {\n\t\tcode: \"AUTH_INVALID_TOKEN\",\n\t\tcategory: \"credential\",\n\t\tmessage: \"Authentication failed\"\n\t};\n\treturn {\n\t\tcode: \"VALIDATION_ERROR\",\n\t\tcategory: \"validation\",\n\t\tmessage: \"The request was rejected\"\n\t};\n}\nfunction validTimeout(timeoutMs) {\n\tif (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) throw new Error(\"timeoutMs must be a positive safe integer\");\n\treturn timeoutMs;\n}\nfunction prepareRequest(init, options, defaultTimeoutMs) {\n\tconst normalizedOptions = isAbortSignal(options) ? { signal: options } : options;\n\tconst requestId = normalizedOptions.requestId?.trim() || createRequestId();\n\tconst timeoutMs = validTimeout(normalizedOptions.timeoutMs ?? defaultTimeoutMs);\n\tconst controller = new AbortController();\n\tlet abortReason;\n\tlet timer;\n\tconst callerSignal = normalizedOptions.signal;\n\tconst abortFromCaller = () => {\n\t\tabortReason = \"caller\";\n\t\tcontroller.abort(callerSignal?.reason);\n\t};\n\tif (callerSignal?.aborted) abortFromCaller();\n\telse callerSignal?.addEventListener(\"abort\", abortFromCaller, { once: true });\n\ttimer = setTimeout(() => {\n\t\tabortReason = \"deadline\";\n\t\tcontroller.abort(/* @__PURE__ */ new Error(`OpenTag request deadline exceeded after ${timeoutMs}ms`));\n\t}, timeoutMs);\n\tconst headers = new Headers(init.headers);\n\tif (!headers.has(\"x-request-id\")) headers.set(REQUEST_ID_HEADER, requestId);\n\treturn {\n\t\tinit: {\n\t\t\t...init,\n\t\t\theaders,\n\t\t\tsignal: controller.signal\n\t\t},\n\t\trequestId,\n\t\tsignal: controller.signal,\n\t\tcleanup() {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tcallerSignal?.removeEventListener(\"abort\", abortFromCaller);\n\t\t},\n\t\treason: () => abortReason\n\t};\n}\nfunction isAbortSignal(value) {\n\treturn typeof value === \"object\" && value !== null && \"aborted\" in value && typeof value.addEventListener === \"function\";\n}\nasync function awaitWithAbort(promise, signal) {\n\tif (signal.aborted) throw signal.reason;\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst cleanup = () => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(signal.reason);\n\t\t};\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then((value) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tresolve(value);\n\t\t}, (error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t});\n\t});\n}\n//#endregion\n//#region src/api.ts\nvar OpenTagApiError = class extends Error {\n\tcode;\n\tcategory;\n\tstatus;\n\tissues;\n\tstructuredError;\n\tconstructor(code, category, message, status, issues, options = {}) {\n\t\tsuper(message, options.cause === void 0 ? void 0 : { cause: options.cause });\n\t\tthis.code = code;\n\t\tthis.category = category;\n\t\tthis.status = status;\n\t\tthis.issues = issues;\n\t\tthis.name = \"OpenTagApiError\";\n\t\tthis.retryability = options.retryability ?? defaultRetryability(category);\n\t\tthis.phase = options.phase ?? defaultPhase(category);\n\t\tthis.requestId = options.requestId;\n\t\tthis.safeCause = options.safeCause ?? safeCause(options.cause);\n\t\tthis.structuredError = StructuredErrorSchema.parse({\n\t\t\tcode: this.code,\n\t\t\tcategory: structuredCategory(category, this.code, status),\n\t\t\tretryability: this.retryability,\n\t\t\tphase: this.phase,\n\t\t\t...this.requestId ? { requestId: this.requestId.slice(0, 256) } : {},\n\t\t\tmessage: message.slice(0, 2048),\n\t\t\t...this.safeCause ? { cause: this.safeCause } : {}\n\t\t});\n\t}\n\tretryability;\n\tphase;\n\trequestId;\n\tsafeCause;\n\ttoStructuredError() {\n\t\treturn this.structuredError;\n\t}\n};\nfunction structuredCategory(category, code, status) {\n\tif (category === \"credential\") return \"auth\";\n\tif (category === \"validation\") return \"validation\";\n\tif (category === \"rate_limit\") return \"rate_limit\";\n\tif (category === \"transient\") return \"unavailable\";\n\tif (code === \"REQUEST_CANCELLED\") return \"cancelled\";\n\tif (code === \"RESOURCE_NOT_FOUND\" || status === 404) return \"not_found\";\n\tif (status === 409 || /(?:CONFLICT|_CONFLICT)$/u.test(code)) return \"conflict\";\n\treturn \"internal\";\n}\nvar OpenTagApi = class {\n\t#baseUrl;\n\t#fetch;\n\t#timeoutMs;\n\t#responseRequestIds = /* @__PURE__ */ new WeakMap();\n\tconstructor(serverUrl, fetchOrOptions = fetch, options = {}) {\n\t\tthis.#baseUrl = new URL(normalizeServerUrl(serverUrl));\n\t\tconst constructorOptions = typeof fetchOrOptions === \"function\" ? options : fetchOrOptions;\n\t\tthis.#fetch = typeof fetchOrOptions === \"function\" ? fetchOrOptions : constructorOptions.fetchImpl ?? fetch;\n\t\tthis.#timeoutMs = constructorOptions.timeoutMs ?? 3e4;\n\t}\n\texchangeConnectCode(code, expectedUserId, options) {\n\t\treturn this.#request(HTTP_PATHS.authConnectExchange, ConnectCodeExchangeResponseSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\tcode,\n\t\t\t\t...expectedUserId ? { expectedUserId } : {}\n\t\t\t}),\n\t\t\theaders: { \"content-type\": \"application/json\" }\n\t\t}, options);\n\t}\n\texchangeComputerConnectCode(input, options) {\n\t\treturn this.#request(HTTP_PATHS.computerConnectExchange, ComputerConnectCodeExchangeResponseSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: { \"content-type\": \"application/json\" }\n\t\t}, options);\n\t}\n\trefresh(refreshToken, options) {\n\t\treturn this.#request(HTTP_PATHS.authRefresh, RefreshTokenResponseSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({ refreshToken }),\n\t\t\theaders: { \"content-type\": \"application/json\" }\n\t\t}, options);\n\t}\n\tme(accessToken, options) {\n\t\treturn this.#request(HTTP_PATHS.me, MeResponseSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tissueComputerConnectCode(accessToken, options) {\n\t\treturn this.#request(HTTP_PATHS.accountComputerConnectCodes, ComputerConnectCodeIssueResponseSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\tgetComputerConnectCodeStatus(accessToken, connectCodeId, options) {\n\t\treturn this.#request(accountComputerConnectCodePath(connectCodeId), ComputerConnectCodeStatusSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tlistAccountComputers(accessToken, options) {\n\t\treturn this.#request(HTTP_PATHS.accountComputers, ListAccountComputersResponseSchema, { headers: {\n\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t[PROVIDER_READINESS_V1_HEADER]: \"1\",\n\t\t\t[PROVIDER_READINESS_V2_HEADER]: \"2\",\n\t\t\t[PROVIDER_CLI_REASON_V2_HEADER]: \"2\"\n\t\t} }, options);\n\t}\n\tcreateAgent(accessToken, input, options) {\n\t\treturn this.#request(HTTP_PATHS.accountAgents, AgentAdminConfigSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tlistAgents(accessToken, options) {\n\t\treturn this.#request(HTTP_PATHS.accountAgents, ListAgentsResponseSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tgetAgent(accessToken, agentId, options) {\n\t\treturn this.#request(agentByIdPath(agentId), AgentDetailSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tgetAgentUsage(accessToken, agentId, windowDays, options) {\n\t\treturn this.#request(agentUsagePath(agentId, windowDays), AgentUsageDetailSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tgetAgentConfig(accessToken, agentId, options) {\n\t\treturn this.#request(agentConfigPath(agentId), AgentAdminConfigSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\ttestAgentRuntime(accessToken, agentId, input, options) {\n\t\treturn this.#request(agentRuntimeTestPath(agentId), AgentRuntimeTestResponseSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\trebindAgentComputer(accessToken, agentId, computerId) {\n\t\treturn this.#request(agentComputerRebindPath(agentId), AgentAdminConfigSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({ computerId }),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t});\n\t}\n\tupdateAgent(accessToken, agentId, input, options) {\n\t\treturn this.#request(agentByIdPath(agentId), AgentAdminConfigSchema, {\n\t\t\tmethod: \"PATCH\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tsuspendAgent(accessToken, agentId, options) {\n\t\treturn this.#request(agentSuspendPath(agentId), AgentAdminConfigSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\treactivateAgent(accessToken, agentId, options) {\n\t\treturn this.#request(agentReactivatePath(agentId), AgentAdminConfigSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\tdeleteAgent(accessToken, agentId, options) {\n\t\treturn this.#requestNoContent(agentByIdPath(agentId), {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\tgetAgentImBinding(accessToken, agentId, options) {\n\t\treturn this.#requestOptional(agentImBindingPath(agentId), ImBindingSummarySchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tgetAgentImBindingConfig(accessToken, agentId, options) {\n\t\treturn this.#requestOptional(agentImBindingConfigPath(agentId), ImBindingAdminDetailSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tcreateFeishuSetupAttempt(accessToken, agentId, intent = \"create\", options) {\n\t\treturn this.#request(agentFeishuSetupAttemptsPath(agentId), FeishuSetupAttemptSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({ intent }),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tgetFeishuSetupAttempt(accessToken, attemptId, options) {\n\t\treturn this.#request(feishuSetupAttemptPath(attemptId), FeishuSetupAttemptSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tcancelFeishuSetupAttempt(accessToken, attemptId, options) {\n\t\treturn this.#request(`${feishuSetupAttemptPath(attemptId)}/cancel`, FeishuSetupAttemptSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\tstartSlackOAuth(accessToken, agentId, input, options) {\n\t\treturn this.#request(agentSlackOAuthStartPath(agentId), StartSlackOAuthResponseSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tgetImBindingDiagnostics(accessToken, imBindingId, options) {\n\t\treturn this.#request(imBindingDiagnosticsPath(imBindingId), ImBindingDiagnosticsSchema, { headers: {\n\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t[PROVIDER_CLI_REASON_V2_HEADER]: \"2\"\n\t\t} }, options);\n\t}\n\tdisableImBinding(accessToken, imBindingId, options) {\n\t\treturn this.#requestNoContent(imBindingDisablePath(imBindingId), {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\tlistMcpServers(accessToken, options) {\n\t\treturn this.#request(mcpServersPath(), ListMCPServersResponseSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tcreateMcpServer(accessToken, input, options) {\n\t\treturn this.#request(mcpServersPath(), MCPServerSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tgetMcpServer(accessToken, mcpServerId, options) {\n\t\treturn this.#request(mcpServerPath(mcpServerId), MCPServerDetailSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tupdateMcpServer(accessToken, mcpServerId, input, options) {\n\t\treturn this.#request(mcpServerPath(mcpServerId), MCPServerSchema, {\n\t\t\tmethod: \"PATCH\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tremoveMcpServer(accessToken, mcpServerId, options) {\n\t\treturn this.#requestNoContent(mcpServerPath(mcpServerId), {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\tlistAgentMcpServers(accessToken, agentId, options) {\n\t\treturn this.#request(agentMcpServersPath(agentId), ListAgentMCPServersResponseSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tlistAvailableMcpServers(accessToken, agentId, options) {\n\t\treturn this.#request(`${agentMcpServersPath(agentId)}/available`, ListAvailableMCPServersResponseSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tattachMcpServer(accessToken, agentId, input, options) {\n\t\treturn this.#request(agentMcpServersPath(agentId), MCPAgentServerSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tupdateAgentMcpServer(accessToken, agentId, mcpServerId, input, options) {\n\t\treturn this.#request(agentMcpServerPath(agentId, mcpServerId), MCPAgentServerSchema, {\n\t\t\tmethod: \"PATCH\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tdetachMcpServer(accessToken, agentId, mcpServerId, options) {\n\t\treturn this.#requestNoContent(agentMcpServerPath(agentId, mcpServerId), {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\tsetMcpAuthorization(accessToken, agentId, mcpServerId, input, options) {\n\t\treturn this.#request(agentMcpAuthorizationPath(agentId, mcpServerId), MCPAgentServerSchema, {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\trevokeMcpAuthorization(accessToken, agentId, mcpServerId, options) {\n\t\treturn this.#request(agentMcpAuthorizationPath(agentId, mcpServerId), MCPAgentServerSchema, {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\tstartMcpOAuth(accessToken, agentId, mcpServerId, input = {}, options) {\n\t\treturn this.#request(agentMcpAuthorizationOAuthPath(agentId, mcpServerId), StartMCPOAuthResponseSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tprobeMcpServer(accessToken, agentId, mcpServerId, options) {\n\t\treturn this.#request(agentMcpProbePath(agentId, mcpServerId), MCPProbeResponseSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\tasync openImResource(machineToken, imMessageId, ordinal, scope, options) {\n\t\tconst response = await this.#fetchResponse(runtimeImResourcePath(imMessageId, ordinal, scope), { headers: { authorization: `Bearer ${machineToken}` } }, options);\n\t\tif (!response.ok) {\n\t\t\tconst body = await response.json().catch(() => void 0);\n\t\t\tthis.#throwResponseError(response.status, body, this.#requestIdFromResponse(response));\n\t\t}\n\t\treturn response;\n\t}\n\tasync listRuntimeDurableWork(machineToken, kind, options) {\n\t\tconst records = [];\n\t\tlet cursor;\n\t\tdo {\n\t\t\tconst query = new URLSearchParams({\n\t\t\t\tkind,\n\t\t\t\t...cursor ? { cursor } : {}\n\t\t\t});\n\t\t\tconst response = await this.#request(`${HTTP_PATHS.runtimeDurableWork}?${query.toString()}`, RuntimeDurableWorkListResponseSchema, { headers: { authorization: `Bearer ${machineToken}` } }, options);\n\t\t\trecords.push(...response.items);\n\t\t\tcursor = response.nextCursor;\n\t\t} while (cursor);\n\t\treturn records;\n\t}\n\twriteRuntimeDurableWork(machineToken, record, options) {\n\t\treturn this.#requestNoContent(runtimeDurableWorkPath(record.kind, record.key), {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: JSON.stringify(record),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${machineToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tcreateInternalSession(proof, input, options) {\n\t\treturn this.#request(HTTP_PATHS.runtimeInternalSessions, SessionCliCommandResponseSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t[SESSION_CLI_PROOF_HEADER]: proof\n\t\t\t}\n\t\t}, options);\n\t}\n\tsendSessionMessage(proof, input, options) {\n\t\treturn this.#request(HTTP_PATHS.runtimeSessionMessages, SessionCliCommandResponseSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t[SESSION_CLI_PROOF_HEADER]: proof\n\t\t\t}\n\t\t}, options);\n\t}\n\tlistInternalSessions(proof, input, options) {\n\t\tconst query = new URLSearchParams({\n\t\t\trecursive: String(input.recursive),\n\t\t\tlimit: String(input.limit),\n\t\t\t...input.cursor ? { cursor: input.cursor } : {},\n\t\t\t...input.since ? { since: input.since } : {}\n\t\t});\n\t\treturn this.#request(`${HTTP_PATHS.runtimeSessions}?${query.toString()}`, SessionCliListResponseSchema, { headers: { [SESSION_CLI_PROOF_HEADER]: proof } }, options);\n\t}\n\tlistAgentSkills(accessToken, agentId, options) {\n\t\treturn this.#request(agentSkillsPath(agentId), ListAgentSkillsResponseSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tgetAgentSkill(accessToken, agentId, skillId, options) {\n\t\treturn this.#request(agentSkillPath(agentId, skillId), SkillDetailSchema, { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tuploadAgentSkill(accessToken, agentId, input, options) {\n\t\treturn this.#request(agentSkillsPath(agentId), SkillSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: input.archive,\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t[SKILL_SHA256_HEADER]: input.sha256,\n\t\t\t\t[SKILL_FORMAT_HEADER]: input.format,\n\t\t\t\t...input.replace ? { [SKILL_REPLACE_HEADER]: \"true\" } : {},\n\t\t\t\t...skillUploadHeaders(input.archive.byteLength)\n\t\t\t}\n\t\t}, options);\n\t}\n\tupdateAgentSkill(accessToken, agentId, skillId, input, options) {\n\t\treturn this.#request(agentSkillPath(agentId, skillId), SkillSchema, {\n\t\t\tmethod: \"PATCH\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${accessToken}`,\n\t\t\t\t\"content-type\": \"application/json\"\n\t\t\t}\n\t\t}, options);\n\t}\n\tremoveAgentSkill(accessToken, agentId, skillId, options) {\n\t\treturn this.#requestNoContent(agentSkillPath(agentId, skillId), {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: { authorization: `Bearer ${accessToken}` }\n\t\t}, options);\n\t}\n\topenAgentSkillBundle(accessToken, agentId, skillId, options) {\n\t\treturn this.#openBinaryResponse(agentSkillBundlePath(agentId, skillId), { headers: { authorization: `Bearer ${accessToken}` } }, options);\n\t}\n\tgetComputerSkillManifest(machineToken, agentId, options) {\n\t\treturn this.#request(computerAgentSkillsPath(agentId), RuntimeSkillManifestSchema, { headers: { authorization: `Bearer ${machineToken}` } }, options);\n\t}\n\topenComputerSkillBundle(machineToken, agentId, skillId, options) {\n\t\treturn this.#openBinaryResponse(computerAgentSkillBundlePath(agentId, skillId), { headers: { authorization: `Bearer ${machineToken}` } }, options);\n\t}\n\tlistRuntimeSkills(proof, options) {\n\t\treturn this.#request(RUNTIME_SKILLS_PATH, ListAgentSkillsResponseSchema, { headers: { [SESSION_CLI_PROOF_HEADER]: proof } }, options);\n\t}\n\tpushRuntimeSkill(proof, input, options) {\n\t\treturn this.#request(RUNTIME_SKILLS_PATH, SkillSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: input.archive,\n\t\t\theaders: {\n\t\t\t\t[SESSION_CLI_PROOF_HEADER]: proof,\n\t\t\t\t[SKILL_SHA256_HEADER]: input.sha256,\n\t\t\t\t[SKILL_FORMAT_HEADER]: input.format,\n\t\t\t\t...input.replace ? { [SKILL_REPLACE_HEADER]: \"true\" } : {},\n\t\t\t\t...skillUploadHeaders(input.archive.byteLength)\n\t\t\t}\n\t\t}, options);\n\t}\n\topenRuntimeSkillBundle(proof, name, options) {\n\t\treturn this.#openBinaryResponse(runtimeSkillBundlePath(name), { headers: { [SESSION_CLI_PROOF_HEADER]: proof } }, options);\n\t}\n\tgetRuntimeAgentConfig(proof, options) {\n\t\treturn this.#request(RUNTIME_AGENT_PATH, AgentAdminConfigSchema, { headers: { [SESSION_CLI_PROOF_HEADER]: proof } }, options);\n\t}\n\tupdateRuntimeAgentConfig(proof, input, options) {\n\t\treturn this.#request(RUNTIME_AGENT_PATH, AgentAdminConfigSchema, {\n\t\t\tmethod: \"PATCH\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t[SESSION_CLI_PROOF_HEADER]: proof\n\t\t\t}\n\t\t}, options);\n\t}\n\tlistRuntimeAgentMcpServers(proof, options) {\n\t\treturn this.#request(RUNTIME_AGENT_MCP_SERVERS_PATH, ListAgentMCPServersResponseSchema, { headers: { [SESSION_CLI_PROOF_HEADER]: proof } }, options);\n\t}\n\tlistRuntimeAgentAvailableMcpServers(proof, options) {\n\t\treturn this.#request(RUNTIME_AGENT_MCP_SERVERS_AVAILABLE_PATH, ListAvailableMCPServersResponseSchema, { headers: { [SESSION_CLI_PROOF_HEADER]: proof } }, options);\n\t}\n\tattachRuntimeAgentMcpServer(proof, input, options) {\n\t\treturn this.#request(RUNTIME_AGENT_MCP_SERVERS_PATH, MCPAgentServerSchema, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t[SESSION_CLI_PROOF_HEADER]: proof\n\t\t\t}\n\t\t}, options);\n\t}\n\tupdateRuntimeAgentMcpBinding(proof, mcpServerId, input, options) {\n\t\treturn this.#request(runtimeAgentMcpServerPath(mcpServerId), MCPAgentServerSchema, {\n\t\t\tmethod: \"PATCH\",\n\t\t\tbody: JSON.stringify(input),\n\t\t\theaders: {\n\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t[SESSION_CLI_PROOF_HEADER]: proof\n\t\t\t}\n\t\t}, options);\n\t}\n\tdetachRuntimeAgentMcpServer(proof, mcpServerId, options) {\n\t\treturn this.#requestNoContent(runtimeAgentMcpServerPath(mcpServerId), {\n\t\t\tmethod: \"DELETE\",\n\t\t\theaders: { [SESSION_CLI_PROOF_HEADER]: proof }\n\t\t}, options);\n\t}\n\tasync #openBinaryResponse(path, init, options) {\n\t\tconst response = await this.#fetchResponse(path, init, options);\n\t\tif (!response.ok) {\n\t\t\tconst body = await response.json().catch(() => void 0);\n\t\t\tthis.#throwResponseError(response.status, body, this.#requestIdFromResponse(response));\n\t\t}\n\t\treturn response;\n\t}\n\tasync #request(path, schema, init, options) {\n\t\tconst response = await this.#fetchResponse(path, init, options);\n\t\tconst body = await response.json().catch(() => void 0);\n\t\tif (!response.ok) this.#throwResponseError(response.status, body, this.#requestIdFromResponse(response));\n\t\tconst parsed = schema.safeParse(body);\n\t\tif (!parsed.success) throw new OpenTagApiError(\"SERVICE_UNAVAILABLE\", \"transient\", \"The OpenTag server returned an invalid response\", response.status, void 0, {\n\t\t\trequestId: this.#requestIdFromResponse(response),\n\t\t\tphase: \"serialization\"\n\t\t});\n\t\treturn parsed.data;\n\t}\n\tasync #requestNoContent(path, init, options) {\n\t\tconst response = await this.#fetchResponse(path, init, options);\n\t\tif (!response.ok) {\n\t\t\tconst body = await response.json().catch(() => void 0);\n\t\t\tthis.#throwResponseError(response.status, body, this.#requestIdFromResponse(response));\n\t\t}\n\t\tif (response.status !== 204) throw new OpenTagApiError(\"SERVICE_UNAVAILABLE\", \"transient\", \"The OpenTag server returned an invalid response\", response.status, void 0, {\n\t\t\trequestId: this.#requestIdFromResponse(response),\n\t\t\tphase: \"serialization\"\n\t\t});\n\t}\n\tasync #requestOptional(path, schema, init, options) {\n\t\tconst response = await this.#fetchResponse(path, init, options);\n\t\tif (response.status === 204) return void 0;\n\t\tconst body = await response.json().catch(() => void 0);\n\t\tif (!response.ok) this.#throwResponseError(response.status, body, this.#requestIdFromResponse(response));\n\t\tconst parsed = schema.safeParse(body);\n\t\tif (!parsed.success) throw new OpenTagApiError(\"SERVICE_UNAVAILABLE\", \"transient\", \"The OpenTag server returned an invalid response\", response.status, void 0, {\n\t\t\trequestId: this.#requestIdFromResponse(response),\n\t\t\tphase: \"serialization\"\n\t\t});\n\t\treturn parsed.data;\n\t}\n\tasync #fetchResponse(path, init, options = {}) {\n\t\tconst prepared = prepareRequest(init, options, this.#timeoutMs);\n\t\ttry {\n\t\t\tconst response = await awaitWithAbort(this.#fetch(new URL(path, this.#baseUrl), prepared.init), prepared.signal);\n\t\t\tthis.#responseRequestIds.set(response, prepared.requestId);\n\t\t\treturn response;\n\t\t} catch (error) {\n\t\t\tif (prepared.reason() === \"caller\") throw new OpenTagApiError(\"REQUEST_CANCELLED\", \"deterministic\", \"The request was cancelled by the caller\", void 0, void 0, {\n\t\t\t\tcause: options.signal?.reason ?? error,\n\t\t\t\tphase: \"request\",\n\t\t\t\trequestId: prepared.requestId\n\t\t\t});\n\t\t\tif (prepared.reason() === \"deadline\") {\n\t\t\t\tconst cause = safeCause(error);\n\t\t\t\tthrow new OpenTagApiError(\"REQUEST_TIMEOUT\", \"transient\", \"The OpenTag server request timed out\", void 0, void 0, {\n\t\t\t\t\tcause,\n\t\t\t\t\tsafeCause: cause,\n\t\t\t\t\tphase: \"transport\",\n\t\t\t\t\trequestId: prepared.requestId\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst cause = safeCause(error);\n\t\t\tthrow new OpenTagApiError(\"SERVICE_UNAVAILABLE\", \"transient\", \"The OpenTag server is unavailable\", void 0, void 0, {\n\t\t\t\tcause,\n\t\t\t\tsafeCause: cause,\n\t\t\t\tphase: \"transport\",\n\t\t\t\trequestId: prepared.requestId\n\t\t\t});\n\t\t} finally {\n\t\t\tprepared.cleanup();\n\t\t}\n\t}\n\t#requestIdFromResponse(response) {\n\t\tconst requestId = response.headers.get(\"x-request-id\") ?? response.headers.get(\"x-request-id\") ?? this.#responseRequestIds.get(response);\n\t\tif (!requestId) throw new Error(\"OpenTag response is missing a request ID\");\n\t\treturn requestId;\n\t}\n\t#throwResponseError(status, body, requestId = \"unknown\") {\n\t\tconst parsed = ErrorEnvelopeSchema.safeParse(body);\n\t\tif (parsed.success) throw new OpenTagApiError(parsed.data.error.code, parsed.data.error.category, parsed.data.error.message, status, parsed.data.error.issues, { requestId: parsed.data.error.requestId ?? requestId });\n\t\tconst fallback = statusFallback(status);\n\t\tthrow new OpenTagApiError(fallback.code, fallback.category, fallback.message, status, void 0, { requestId });\n\t}\n};\nfunction skillUploadHeaders(bytes) {\n\treturn {\n\t\t\"content-type\": SKILL_UPLOAD_CONTENT_TYPE,\n\t\t\"content-length\": String(bytes)\n\t};\n}\nfunction normalizeServerUrl(serverUrl) {\n\tconst url = new URL(serverUrl);\n\tif (![\"http:\", \"https:\"].includes(url.protocol) || url.username || url.password) throw new Error(\"The OpenTag server URL must use HTTP(S) without embedded credentials\");\n\tif (url.pathname !== \"/\" && url.pathname !== \"\" || url.search || url.hash) throw new Error(\"The OpenTag server URL must be an origin without a path, query, or fragment\");\n\tconst isLoopback = url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\" || url.hostname === \"[::1]\";\n\tif (url.protocol === \"http:\" && !isLoopback) throw new Error(\"Plain HTTP is allowed only for loopback OpenTag servers\");\n\treturn url.origin;\n}\n//#endregion\n//#region src/storage/private-json-file.ts\nasync function readPrivateJson(home, filePath, validate) {\n\tconst root = resolve(home);\n\tconst path = isAbsolute(filePath) ? resolve(filePath) : resolve(root, filePath);\n\tassertWithin(root, path);\n\tif (!await validatePrivateDirectory(root, dirname(path))) return void 0;\n\tconst content = await readSecureFile(path);\n\treturn content === void 0 ? void 0 : validate(JSON.parse(content));\n}\nasync function writePrivateJson(home, filePath, value) {\n\tconst root = resolve(home);\n\tconst destination = isAbsolute(filePath) ? resolve(filePath) : resolve(root, filePath);\n\tassertWithin(root, destination);\n\tawait ensurePrivateDirectory(root, dirname(destination));\n\tawait writeDurableJson(destination, value);\n}\n//#endregion\n//#region src/auth/account-identity.ts\n/**\n* Which Account this OpenTag home last signed in as, kept beside `credentials.json` rather than in\n* it.\n*\n* The credentials file is read by a strict schema, and every CLI already installed reads it with\n* the schema it shipped with: a key added to that file by a newer CLI makes the file invalid for an\n* older one, so the documented rollback (`install.sh --version <previous>`) would leave every\n* Account-authenticated command refusing to run. This attribution is a diagnostic detail, not a\n* credential, so it lives in its own optional file that an older CLI never opens. The `serverUrl`\n* is recorded so an identity left behind by a sign-in to one server is never attributed to a\n* sign-in to another.\n*\n* `credentialsFingerprint` ties the identity to the credentials it was written beside. Rollback is\n* a supported sequence, and an older CLI signing in as another Account rewrites only\n* `credentials.json`, leaving this file naming the previous Account on the same server. The\n* fingerprint is a hash of the refresh token — never the token — so a reader can prove the file\n* still describes the credentials it reads, and omit the Account when it cannot. A file written\n* before the field existed fails the strict schema and is treated as absent, which is the safe\n* direction: no attribution rather than a wrong one.\n*/\nconst StoredAccountIdentitySchema = z.object({\n\tuserId: z.string().min(1),\n\tserverUrl: z.string().min(1),\n\tcredentialsFingerprint: z.string().regex(/^[0-9a-f]{64}$/, \"A credentials fingerprint is a hex SHA-256\")\n}).strict();\nconst ACCOUNT_IDENTITY_FILE_NAME = \"account-identity.json\";\nfunction accountIdentityPath(home = resolveOpenTagHome()) {\n\treturn join(resolveOpenTagHomeLayout(home).config, ACCOUNT_IDENTITY_FILE_NAME);\n}\n/** Throws on a malformed file, like the other identity readers; a caller decides what that costs. */\nfunction readAccountIdentity(home = resolveOpenTagHome()) {\n\treturn readPrivateJson(home, accountIdentityPath(home), validateAccountIdentity);\n}\nasync function writeAccountIdentityAtomically(identity, home = resolveOpenTagHome()) {\n\tawait writePrivateJson(home, accountIdentityPath(home), normalizeAccountIdentity(identity));\n}\n/**\n* The fingerprint an identity file carries for a set of credentials: a hex SHA-256 of the refresh\n* token. The refresh token rather than the access token because it is the credential that\n* outlives a refresh cycle and changes only when the credentials are rotated or replaced; and a\n* hash rather than the token so the identity file never holds a secret.\n*/\nfunction credentialsFingerprint(credentials) {\n\treturn createHash(\"sha256\").update(credentials.refreshToken, \"utf8\").digest(\"hex\");\n}\n/** Whether an identity file was written beside these credentials. */\nfunction accountIdentityMatchesCredentials(identity, credentials) {\n\treturn identity.credentialsFingerprint === credentialsFingerprint(credentials);\n}\n/**\n* Carry the identity over a refresh token rotation.\n*\n* Only an identity that provably belonged to the replaced credentials is rebound to the new ones;\n* one that did not match is left exactly as it was, so a stale file stays unprovable and keeps\n* being ignored. Throws like any other identity read or write; the caller decides that a refresh\n* must not fail over it.\n*/\nasync function rotateAccountIdentityFingerprint(input, home = resolveOpenTagHome()) {\n\tconst identity = await readAccountIdentity(home);\n\tif (!identity) return \"absent\";\n\tif (!accountIdentityMatchesCredentials(identity, input.previous)) return \"unbound\";\n\tawait writeAccountIdentityAtomically({\n\t\t...identity,\n\t\tcredentialsFingerprint: credentialsFingerprint(input.next)\n\t}, home);\n\treturn \"rebound\";\n}\n/** Forgets the Account; a home that has no identity file is left as it is. */\nasync function removeAccountIdentity(home = resolveOpenTagHome()) {\n\ttry {\n\t\tawait removeDurableFile(accountIdentityPath(home));\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t}\n}\nfunction validateAccountIdentity(value) {\n\ttry {\n\t\treturn normalizeAccountIdentity(StoredAccountIdentitySchema.parse(value));\n\t} catch (error) {\n\t\tthrow new Error(\"The OpenTag account identity file is invalid\", { cause: error });\n\t}\n}\nfunction normalizeAccountIdentity(value) {\n\tconst parsed = StoredAccountIdentitySchema.parse(value);\n\treturn {\n\t\t...parsed,\n\t\tserverUrl: normalizeServerUrl(parsed.serverUrl)\n\t};\n}\n//#endregion\n//#region src/auth/credentials.ts\nconst CREDENTIALS_FILE_NAME = \"credentials.json\";\nconst nonEmptyToken = z.string().min(1).refine((value) => value.trim().length > 0, \"Token must not be blank\");\nconst expiry = z.string().datetime({ offset: true }).refine((value) => Date.parse(value) >= Date.UTC(2e3, 0, 1), \"Token expiry is too weak\");\nconst StoredCredentialsSchema = z.object({\n\taccessToken: nonEmptyToken,\n\taccessTokenExpiresAt: expiry,\n\trefreshToken: nonEmptyToken,\n\tserverUrl: z.string().min(1)\n}).strict();\nfunction credentialsPath(home = resolveOpenTagHome()) {\n\treturn join(resolveOpenTagHomeLayout(home).config, CREDENTIALS_FILE_NAME);\n}\nfunction readCredentials(home = resolveOpenTagHome()) {\n\treturn readPrivateJson(home, credentialsPath(home), validateCredentials);\n}\nasync function writeCredentialsAtomically(credentials, home = resolveOpenTagHome()) {\n\tawait writePrivateJson(home, credentialsPath(home), normalizeCredentials(credentials));\n}\nfunction validateCredentials(value) {\n\ttry {\n\t\treturn normalizeCredentials(StoredCredentialsSchema.parse(value));\n\t} catch (error) {\n\t\tif (error instanceof Error && error.message.startsWith(\"The OpenTag server URL\")) throw error;\n\t\tthrow new Error(\"The OpenTag credentials file is invalid\", { cause: error });\n\t}\n}\nfunction normalizeCredentials(value) {\n\tconst parsed = StoredCredentialsSchema.parse(value);\n\treturn {\n\t\t...parsed,\n\t\tserverUrl: normalizeServerUrl(parsed.serverUrl)\n\t};\n}\n//#endregion\n//#region src/auth/machine-credentials.ts\nconst MACHINE_CREDENTIALS_FILE_NAME = \"computer-credentials.json\";\nfunction machineCredentialsPath(home = resolveOpenTagHome()) {\n\treturn join(resolveOpenTagHomeLayout(home).config, MACHINE_CREDENTIALS_FILE_NAME);\n}\nfunction readMachineCredentials(home = resolveOpenTagHome()) {\n\treturn readPrivateJson(home, machineCredentialsPath(home), validateMachineCredentials);\n}\n/**\n* Strict, read-only projection for diagnostics. Unlike the runtime reader, this rejects the whole\n* file when any stored Computer credential is unusable, so corruption cannot be reported as a healthy\n* partial configuration.\n*/\nfunction readMachineCredentialsStrict(home = resolveOpenTagHome()) {\n\treturn readPrivateJson(home, machineCredentialsPath(home), checkMachineCredentialsStrict);\n}\n/** Rejects rather than throwing synchronously, so a caller handling the returned promise sees the refusal. */\nasync function writeMachineCredentialsAtomically(credentials, home = resolveOpenTagHome()) {\n\tconst checked = checkMachineCredentialsToWrite(credentials);\n\tawait writePrivateJson(home, machineCredentialsPath(home), checked);\n}\n/** One canonical home binds at most one Account Computer. */\nfunction resolveBoundAccountComputer(credentials) {\n\tif (!credentials) return { status: \"disconnected\" };\n\treturn {\n\t\tstatus: \"bound\",\n\t\tcredential: credentials.computer\n\t};\n}\nasync function storeBoundAccountComputer(credential, home = resolveOpenTagHome()) {\n\tconst next = {\n\t\tversion: 3,\n\t\tcomputer: { ...credential }\n\t};\n\tawait writeMachineCredentialsAtomically(next, home);\n\treturn next;\n}\nfunction validateMachineCredentials(value) {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return void 0;\n\tconst record = value;\n\tif (Object.keys(record).length !== 2 || record.version !== 3) throw new Error(\"The OpenTag Computer credentials file uses an unsupported format; reconnect this Computer\");\n\tconst computer = readComputerEntry(record.computer);\n\treturn computer ? {\n\t\tversion: 3,\n\t\tcomputer\n\t} : void 0;\n}\nfunction checkMachineCredentialsToWrite(value) {\n\treturn checkMachineCredentialsStrict(value, \"Refusing to write\");\n}\nfunction checkMachineCredentialsStrict(value, failurePrefix = \"The stored OpenTag Computer credentials contain\") {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"The OpenTag Computer credentials file is invalid\");\n\tconst record = value;\n\tif (Object.keys(record).length !== 2 || record.version !== 3) throw new Error(\"The OpenTag Computer credentials file uses an unsupported format; reconnect this Computer\");\n\tconst computer = readComputerEntry(record.computer);\n\tif (!computer) throw new Error(`${failurePrefix} an unusable OpenTag Computer credential`);\n\treturn {\n\t\tversion: 3,\n\t\tcomputer\n\t};\n}\nfunction readComputerEntry(value) {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return void 0;\n\tconst entry = value;\n\tif (!isUuid(entry.computerId) || !isUuid(entry.installationId) || typeof entry.machineToken !== \"string\" || !entry.machineToken.startsWith(\"otmc_\") || typeof entry.serverUrl !== \"string\") return;\n\treturn {\n\t\tcomputerId: entry.computerId,\n\t\tinstallationId: entry.installationId,\n\t\tmachineToken: entry.machineToken,\n\t\tserverUrl: entry.serverUrl\n\t};\n}\nfunction isUuid(value) {\n\treturn typeof value === \"string\" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);\n}\n//#endregion\n//#region src/auth/token-provider.ts\nconst CREDENTIAL_LOCK_FILE_NAME = \".credentials.lock\";\nconst DEFAULT_LOCK_RETRY_MS = 25;\nconst DEFAULT_LOCK_TIMEOUT_MS = 3e4;\nconst STALE_LOCK_MS = 3e5;\nconst MIN_REFRESH_EXPIRY_SECONDS = 30;\nvar AccessTokenProvider = class {\n\t#home;\n\t#now;\n\t#refreshSkewMilliseconds;\n\t#api;\n\t#lockRetryMs;\n\t#lockTimeoutMs;\n\t#logger;\n\t#refreshInFlight;\n\tconstructor(options = {}) {\n\t\tthis.#home = options.home ?? resolveOpenTagHome();\n\t\tthis.#now = options.now ?? (() => /* @__PURE__ */ new Date());\n\t\tthis.#refreshSkewMilliseconds = (options.refreshSkewSeconds ?? 60) * 1e3;\n\t\tthis.#api = options.api;\n\t\tthis.#lockRetryMs = options.lockRetryMs ?? DEFAULT_LOCK_RETRY_MS;\n\t\tthis.#lockTimeoutMs = options.lockTimeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS;\n\t\tthis.#logger = options.logger ?? createLogger(\"auth\");\n\t\tif (!Number.isSafeInteger(this.#lockRetryMs) || this.#lockRetryMs < 1) throw new Error(\"lockRetryMs must be a positive safe integer\");\n\t\tif (!Number.isSafeInteger(this.#lockTimeoutMs) || this.#lockTimeoutMs < this.#lockRetryMs) throw new Error(\"lockTimeoutMs must be a safe integer greater than lockRetryMs\");\n\t}\n\tasync getAccessToken() {\n\t\treturn (await this.getAccessTokenLease()).accessToken;\n\t}\n\tasync getAccessTokenLease(forceRefresh = false) {\n\t\tconst credentials = await readCredentials(this.#home);\n\t\tif (!credentials) throw new Error(\"OpenTag is not logged in\");\n\t\tif (!forceRefresh && Date.parse(credentials.accessTokenExpiresAt) - this.#now().getTime() > this.#refreshSkewMilliseconds) return {\n\t\t\taccessToken: credentials.accessToken,\n\t\t\texpiresAt: credentials.accessTokenExpiresAt\n\t\t};\n\t\tthis.#refreshInFlight ??= this.#refreshWithLock(credentials, forceRefresh).finally(() => {\n\t\t\tthis.#refreshInFlight = void 0;\n\t\t});\n\t\treturn this.#refreshInFlight;\n\t}\n\tasync #refreshWithLock(credentials, forceRefresh) {\n\t\treturn withCredentialLock(this.#home, this.#lockRetryMs, this.#lockTimeoutMs, async () => {\n\t\t\tconst latest = await readCredentials(this.#home);\n\t\t\tif (!latest) throw new Error(\"OpenTag credentials disappeared while refreshing\");\n\t\t\tif (Date.parse(latest.accessTokenExpiresAt) - this.#now().getTime() > this.#refreshSkewMilliseconds && (!forceRefresh || latest.refreshToken !== credentials.refreshToken)) return {\n\t\t\t\taccessToken: latest.accessToken,\n\t\t\t\texpiresAt: latest.accessTokenExpiresAt\n\t\t\t};\n\t\t\tconst response = await (this.#api ?? new OpenTagApi(latest.serverUrl)).refresh(latest.refreshToken);\n\t\t\tif (response.expiresIn < MIN_REFRESH_EXPIRY_SECONDS) throw new Error(\"The OpenTag server returned an unsafe token expiry\");\n\t\t\tconst expiresAt = new Date(this.#now().getTime() + response.expiresIn * 1e3).toISOString();\n\t\t\tawait writeCredentialsAtomically({\n\t\t\t\t...latest,\n\t\t\t\taccessToken: response.accessToken,\n\t\t\t\taccessTokenExpiresAt: expiresAt,\n\t\t\t\trefreshToken: response.refreshToken\n\t\t\t}, this.#home);\n\t\t\tawait this.#rebindAccountIdentity(latest.refreshToken, response.refreshToken);\n\t\t\treturn {\n\t\t\t\taccessToken: response.accessToken,\n\t\t\t\texpiresAt\n\t\t\t};\n\t\t});\n\t}\n\t/**\n\t* Best effort, and only for an identity that provably belonged to the credentials just replaced:\n\t* the tokens are already persisted, and a diagnostic detail must not fail the refresh that\n\t* produced them. A failure here costs later reports their Account and nothing else.\n\t*/\n\tasync #rebindAccountIdentity(previousRefreshToken, nextRefreshToken) {\n\t\ttry {\n\t\t\tconst rotation = await rotateAccountIdentityFingerprint({\n\t\t\t\tprevious: { refreshToken: previousRefreshToken },\n\t\t\t\tnext: { refreshToken: nextRefreshToken }\n\t\t\t}, this.#home);\n\t\t\tif (rotation !== \"absent\") this.#logger.debug({ rotation }, \"Account identity checked against rotated credentials\");\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"account_identity_rebind_failed\",\n\t\t\t\treason: error instanceof Error ? error.message : String(error)\n\t\t\t}, \"Account identity could not be rebound to the rotated credentials\");\n\t\t}\n\t}\n};\nasync function withCredentialLock(home, retryMs, timeoutMs, operation) {\n\tconst lockPath = join(resolveOpenTagHomeLayout(home).config, CREDENTIAL_LOCK_FILE_NAME);\n\tconst handle = await acquireCredentialLock(lockPath, retryMs, timeoutMs);\n\ttry {\n\t\treturn await operation();\n\t} finally {\n\t\tawait handle?.close();\n\t\tawait rm(lockPath, { force: true });\n\t}\n}\nasync function acquireCredentialLock(lockPath, retryMs, timeoutMs) {\n\tconst startedAt = Date.now();\n\tfor (;;) {\n\t\tconst handle = await tryCreateCredentialLock(lockPath);\n\t\tif (handle) {\n\t\t\tawait handle.writeFile(`${process.pid}\\n`, \"utf8\");\n\t\t\treturn handle;\n\t\t}\n\t\tawait removeStaleCredentialLock(lockPath);\n\t\tif (Date.now() - startedAt >= timeoutMs) throw new Error(\"Timed out waiting for the OpenTag credential refresh lock\");\n\t\tawait new Promise((resolve) => setTimeout(resolve, retryMs));\n\t}\n}\nasync function tryCreateCredentialLock(lockPath) {\n\ttry {\n\t\treturn await open(lockPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 384);\n\t} catch (error) {\n\t\tif (error.code === \"EEXIST\") return void 0;\n\t\tthrow error;\n\t}\n}\nasync function removeStaleCredentialLock(lockPath) {\n\ttry {\n\t\tconst lock = await stat(lockPath);\n\t\tif (Date.now() - lock.mtimeMs > STALE_LOCK_MS) await rm(lockPath, { force: true });\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t}\n}\n//#endregion\n//#region src/cloud-runtime/sandbox-credential-bridge.ts\nconst IMAGE = /^(?:[a-zA-Z0-9][a-zA-Z0-9_.:/-]*)(?:@sha256:[a-f0-9]{64})?$/;\nconst MAX_PIPE_BYTES = 4194304;\n/**\n* Trusted Linux Runner entry for one Cloud execution. The relay and control token remain outside\n* the Agent container; only an execution-specific socket directory is mounted into the container.\n* This is a command execution boundary for the Cloud orchestrator, not a Local daemon trust mode.\n*/\nvar CloudSandboxCredentialBridge = class CloudSandboxCredentialBridge {\n\t#containerName;\n\t#public;\n\t#relay;\n\t#resources;\n\t#spawnProcess;\n\t#child;\n\t#closed = false;\n\t#closePromise;\n\t#containerExited = false;\n\t#containerStopped = false;\n\t#ran = false;\n\tconstructor(resources, spawnProcess) {\n\t\tthis.#resources = resources;\n\t\tthis.#public = resources.public;\n\t\tthis.#relay = resources.relay;\n\t\tthis.#containerName = `opentag-execution-${resources.relay.executionId}`;\n\t\tthis.#spawnProcess = spawnProcess;\n\t}\n\tget executionId() {\n\t\treturn this.#relay.executionId;\n\t}\n\tget signal() {\n\t\treturn this.#relay.signal;\n\t}\n\t/** Only this subdirectory is Sandbox-visible. Never mount the containing trusted directory. */\n\tget publicMountPath() {\n\t\treturn this.#public;\n\t}\n\tstatic async open(options) {\n\t\tif ((options.platform ?? process.platform) !== \"linux\") throw new Error(\"The Cloud credential bridge requires a Linux trusted Runner\");\n\t\tif (!options.subject.sandbox) throw new Error(\"Cloud execution requires Server-assigned Sandbox facts\");\n\t\toptions.signal?.throwIfAborted();\n\t\tconst directory = await createBridgeDirectory(options.temporaryRoot);\n\t\tconst resources = {\n\t\t\t...createBridgeSocketResources(),\n\t\t\tdirectory\n\t\t};\n\t\ttry {\n\t\t\tconst relay = await RuntimeCredentialRelay.open(options, options.subject, options.signal);\n\t\t\tresources.relay = relay;\n\t\t\toptions.signal?.throwIfAborted();\n\t\t\tresources.adapter = await RuntimeProxyLoopbackAdapter.start({\n\t\t\t\texecutionId: relay.executionId,\n\t\t\t\t...options.generateCa ? { generateCa: options.generateCa } : {},\n\t\t\t\t...options.logger ? { logger: options.logger } : {},\n\t\t\t\tlocalHandleFor: (provider) => relay.providers.some((entry) => entry.provider === provider) ? relay.localHandleFor(provider) : void 0,\n\t\t\t\tmaterialDir: join(directory, \"private\"),\n\t\t\t\topenStream: (request) => relay.openProviderStream(request),\n\t\t\t\tverifyHandle: (provider, handle) => relay.verifyLocalHandle(provider, handle)\n\t\t\t});\n\t\t\tresources.public = await publishExecutionMaterial({\n\t\t\t\tadapter: resources.adapter,\n\t\t\t\trelay\n\t\t\t}, join(directory, \"public\"), { includeEntryPrograms: true });\n\t\t\tawait listenBridgeProxySockets(resources, resources.adapter, resources.public);\n\t\t\tconst bridge = new CloudSandboxCredentialBridge(resources, options.spawnProcess ?? spawn);\n\t\t\tconst abort = () => void bridge.close();\n\t\t\trelay.signal.addEventListener(\"abort\", abort, { once: true });\n\t\t\toptions.signal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\tif (relay.signal.aborted || options.signal?.aborted) {\n\t\t\t\tawait bridge.close();\n\t\t\t\tthrow new Error(\"Cloud execution was aborted while opening\");\n\t\t\t}\n\t\t\treturn bridge;\n\t\t} catch (error) {\n\t\t\tawait disposeBridgeResources(resources);\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/** Deployment controller executes this argument vector. No token, Agent shell, host HOME, or Docker socket enters it. */\n\tasync dockerArguments(options) {\n\t\tif (this.#closed || this.signal.aborted) throw new Error(\"Cloud execution is unavailable\");\n\t\tif (!IMAGE.test(options.image)) throw new Error(\"Cloud execution image is invalid\");\n\t\tconst workspace = await assertSandboxWorkspace(options.workspace, this.#resources);\n\t\treturn [\n\t\t\t\"run\",\n\t\t\t\"-i\",\n\t\t\t\"--rm\",\n\t\t\t\"--init\",\n\t\t\t\"--name\",\n\t\t\tthis.#containerName,\n\t\t\t\"--user\",\n\t\t\t\"10000:10000\",\n\t\t\t\"--network\",\n\t\t\t\"none\",\n\t\t\t\"--cap-drop\",\n\t\t\t\"ALL\",\n\t\t\t\"--security-opt\",\n\t\t\t\"no-new-privileges\",\n\t\t\t\"--read-only\",\n\t\t\t\"--pids-limit\",\n\t\t\t\"128\",\n\t\t\t\"--memory\",\n\t\t\t\"1g\",\n\t\t\t\"--cpus\",\n\t\t\t\"2\",\n\t\t\t\"--tmpfs\",\n\t\t\t\"/tmp:rw,nosuid,nodev,size=128m,uid=10000,gid=10000,mode=1777\",\n\t\t\t\"--tmpfs\",\n\t\t\t\"/home/runner:rw,nosuid,nodev,size=64m,uid=10000,gid=10000,mode=700\",\n\t\t\t\"--mount\",\n\t\t\t`type=bind,src=${workspace},dst=/workspace`,\n\t\t\t\"--mount\",\n\t\t\t`type=bind,src=${this.#public},dst=${CLOUD_EXECUTION_MOUNT},readonly`,\n\t\t\t\"--workdir\",\n\t\t\t\"/workspace\",\n\t\t\t\"--entrypoint\",\n\t\t\t\"node\",\n\t\t\toptions.image,\n\t\t\t`${CLOUD_EXECUTION_MOUNT}/entry.mjs`,\n\t\t\t...options.command\n\t\t];\n\t}\n\t/** Exactly one command lifetime per execution; control loss kills the container and never replays it. */\n\tasync run(options) {\n\t\tif (this.#ran) throw new Error(\"A Cloud execution cannot be replayed\");\n\t\tthis.#ran = true;\n\t\ttry {\n\t\t\treturn await this.#execute(options);\n\t\t} catch (error) {\n\t\t\tawait this.close().catch(() => void 0);\n\t\t\tthrow error;\n\t\t}\n\t}\n\tasync #execute(options) {\n\t\tconst signal = options.signal ? AbortSignal.any([this.signal, options.signal]) : this.signal;\n\t\tsignal.throwIfAborted();\n\t\tconst args = await this.dockerArguments(options);\n\t\tconst piped = options.stdio === \"pipe\";\n\t\tconst child = this.#spawnProcess(\"docker\", args, {\n\t\t\tstdio: piped ? [\n\t\t\t\t\"ignore\",\n\t\t\t\t\"pipe\",\n\t\t\t\t\"pipe\"\n\t\t\t] : \"inherit\",\n\t\t\tenv: { PATH: process.env.PATH }\n\t\t});\n\t\tthis.#child = child;\n\t\tthis.#containerExited = false;\n\t\tconst stop = () => this.#stopContainer();\n\t\tsignal.addEventListener(\"abort\", stop, { once: true });\n\t\tif (signal.aborted) stop();\n\t\tconst capture = captureDockerOutput(child, stop);\n\t\ttry {\n\t\t\tconst code = await waitForDockerExit(child);\n\t\t\tthis.#containerExited = true;\n\t\t\treturn {\n\t\t\t\tcode,\n\t\t\t\t...piped ? capture.snapshot() : {}\n\t\t\t};\n\t\t} finally {\n\t\t\tsignal.removeEventListener(\"abort\", stop);\n\t\t\tawait this.close();\n\t\t}\n\t}\n\tasync close() {\n\t\tif (this.#closePromise) return this.#closePromise;\n\t\tthis.#closed = true;\n\t\tthis.#stopContainer();\n\t\tthis.#closePromise = disposeBridgeResources(this.#resources);\n\t\treturn this.#closePromise;\n\t}\n\t#stopContainer() {\n\t\tconst child = this.#child;\n\t\tif (!child || this.#containerStopped || this.#containerExited) return;\n\t\tthis.#containerStopped = true;\n\t\tthis.#spawnProcess(\"docker\", [\"kill\", this.#containerName], {\n\t\t\tstdio: \"ignore\",\n\t\t\tenv: { PATH: process.env.PATH }\n\t\t}).on(\"error\", () => child.kill(\"SIGTERM\"));\n\t}\n};\nasync function createBridgeDirectory(temporaryRoot) {\n\tconst root = await realpath(temporaryRoot ?? tmpdir());\n\tconst directory = await mkdtemp(join(root, \"ot-bridge-\"));\n\tif (/[,:\\n\\r]/.test(directory)) throw new Error(\"Unsafe bridge directory path\");\n\tawait chmod(directory, 448);\n\treturn directory;\n}\n/** A dedicated workspace must never expose the trusted bridge directory or the host HOME. */\nasync function assertSandboxWorkspace(workspace, resources) {\n\tconst resolved = await realpath(workspace);\n\tif (!(await lstat(resolved)).isDirectory()) throw new Error(\"A dedicated Sandbox workspace is required\");\n\tconst home = resolve(process.env.HOME ?? \"/\");\n\tif (resolved === \"/\" || resolved === home) throw new Error(\"A dedicated Sandbox workspace is required\");\n\tfor (const trusted of [resources.directory, resources.public]) {\n\t\tif (!trusted) continue;\n\t\tif (isSameOrWithin(resolved, trusted) || isSameOrWithin(trusted, resolved)) throw new Error(\"The Sandbox workspace must not contain trusted execution material\");\n\t}\n\tif (/[,:\\n\\r]/.test(resolved)) throw new Error(\"Unsafe container mount path\");\n\treturn resolved;\n}\nfunction isSameOrWithin(parent, child) {\n\treturn child === parent || child.startsWith(`${parent}${sep}`);\n}\nfunction captureDockerOutput(child, onOverflow) {\n\tlet stdout = \"\";\n\tlet stderr = \"\";\n\tlet bytes = 0;\n\tlet overflowed = false;\n\tconst append = (target, chunk) => {\n\t\tbytes += chunk.byteLength;\n\t\tif (bytes > MAX_PIPE_BYTES) {\n\t\t\tif (!overflowed) {\n\t\t\t\toverflowed = true;\n\t\t\t\tonOverflow();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (target === \"stdout\") stdout += chunk.toString();\n\t\telse stderr += chunk.toString();\n\t};\n\tchild.stdout?.on(\"data\", (chunk) => append(\"stdout\", chunk));\n\tchild.stderr?.on(\"data\", (chunk) => append(\"stderr\", chunk));\n\treturn { snapshot: () => ({\n\t\tstdout,\n\t\tstderr\n\t}) };\n}\nfunction waitForDockerExit(child) {\n\treturn new Promise((resolve) => {\n\t\tchild.once(\"error\", () => resolve(127));\n\t\tchild.once(\"close\", (code) => resolve(typeof code === \"number\" ? code : 1));\n\t});\n}\nasync function disposeBridgeResources(resources) {\n\tawait closeBridgeSockets(resources);\n\tawait resources.adapter?.close().catch(() => void 0);\n\tawait resources.relay?.close(\"cloud_bridge_closed\").catch(() => void 0);\n\tawait rm(resources.directory, {\n\t\trecursive: true,\n\t\tforce: true\n\t}).catch(() => void 0);\n}\n//#endregion\n//#region src/health.ts\nvar ServerHealthConfigurationError = class extends Error {\n\tname = \"ServerHealthConfigurationError\";\n};\nvar ServerHealthNetworkError = class extends Error {\n\tname = \"ServerHealthNetworkError\";\n};\nvar ServerHealthTimeoutError = class extends Error {\n\tname = \"ServerHealthTimeoutError\";\n};\nvar ServerHealthHttpError = class extends Error {\n\tstatus;\n\tname = \"ServerHealthHttpError\";\n\tconstructor(status) {\n\t\tsuper(`OpenTag server health check returned HTTP ${status}`);\n\t\tthis.status = status;\n\t}\n};\nvar ServerHealthResponseError = class extends Error {\n\tname = \"ServerHealthResponseError\";\n};\nconst SERVER_HEALTH_TIMEOUT_MS = 5e3;\nasync function checkServerHealth(serverUrl, fetchImpl = fetch, timeoutMs = SERVER_HEALTH_TIMEOUT_MS) {\n\tlet healthUrl;\n\ttry {\n\t\thealthUrl = new URL(\"/healthz\", serverUrl);\n\t} catch (error) {\n\t\tthrow new ServerHealthConfigurationError(`Invalid OpenTag server URL: ${serverUrl}`, { cause: error });\n\t}\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(() => controller.abort(), timeoutMs);\n\ttry {\n\t\tconst response = await fetchImpl(healthUrl, { signal: controller.signal });\n\t\tif (!response.ok) throw new ServerHealthHttpError(response.status);\n\t\ttry {\n\t\t\treturn ServerHealthSchema.parse(await response.json());\n\t\t} catch (error) {\n\t\t\tif (controller.signal.aborted) throw new ServerHealthTimeoutError(`OpenTag server health check timed out after ${timeoutMs}ms`, { cause: error });\n\t\t\tthrow new ServerHealthResponseError(\"OpenTag server returned an invalid health response\", { cause: error });\n\t\t}\n\t} catch (error) {\n\t\tif (error instanceof ServerHealthHttpError || error instanceof ServerHealthResponseError) throw error;\n\t\tif (error instanceof ServerHealthTimeoutError) throw error;\n\t\tif (controller.signal.aborted) throw new ServerHealthTimeoutError(`OpenTag server health check timed out after ${timeoutMs}ms`, { cause: error });\n\t\tthrow new ServerHealthNetworkError(\"Could not reach the OpenTag server\", { cause: error });\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n}\n//#endregion\n//#region src/observability/error-reporting.ts\n/** How long a CLI waits on the relay before giving up; a failing tracker must not hold a command open. */\nconst CLIENT_ERROR_REPORT_TIMEOUT_MS = 3e3;\n/** How long a crashing process waits for its last report before exiting anyway. */\nconst PROCESS_ERROR_REPORT_WAIT_MS = 2e3;\n/** How long a crashing process waits for its stderr output to drain before exiting anyway. */\nconst PROCESS_ERROR_FLUSH_WAIT_MS = 1e3;\n/** Redact and bound a thrown value into the relay's request shape. */\nfunction buildClientErrorReport(error, metadata) {\n\treturn createErrorReport(error, {\n\t\tsource: \"cli\",\n\t\t...metadata\n\t});\n}\n/**\n* The machine a CLI failure happened on, as one line.\n*\n* The same three values `doctor` prints, in the same order, so a report and the diagnostic a reader\n* is asked to run describe the machine identically. One field rather than three because the relay\n* bounds each field it accepts, and this is read rather than queried.\n*/\nfunction describePlatform(source = process) {\n\treturn `${source.platform} ${source.arch} node-${source.version}`;\n}\n/**\n* Post one failure to the server relay. Never throws and never carries a credential: the relay is\n* anonymous, and a report that cannot be delivered is simply lost.\n*/\nasync function reportClientError(options) {\n\tconst { serverUrl, error, fetchImpl = fetch, timeoutMs = CLIENT_ERROR_REPORT_TIMEOUT_MS, ...metadata } = options;\n\tlet url;\n\ttry {\n\t\turl = new URL(HTTP_PATHS.errorReports, serverUrl);\n\t} catch {\n\t\treturn { ok: false };\n\t}\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(() => controller.abort(), timeoutMs);\n\ttry {\n\t\treturn { ok: (await fetchImpl(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\tbody: JSON.stringify(buildClientErrorReport(error, metadata)),\n\t\t\tsignal: controller.signal\n\t\t})).ok };\n\t} catch {\n\t\treturn { ok: false };\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n}\nfunction writeCrashOutput(error) {\n\treturn new Promise((resolve) => {\n\t\tconst flushed = setTimeout(resolve, PROCESS_ERROR_FLUSH_WAIT_MS);\n\t\tprocess.stderr.write(`${inspect(error)}\\n`, () => {\n\t\t\tclearTimeout(flushed);\n\t\t\tresolve();\n\t\t});\n\t});\n}\nfunction describeFailure(error) {\n\tif (error instanceof Error) {\n\t\tconst code = error.code;\n\t\treturn {\n\t\t\terrorName: error.name,\n\t\t\terrorMessage: error.message,\n\t\t\t...typeof code === \"string\" ? { errorCode: code } : {}\n\t\t};\n\t}\n\treturn { errorMessage: String(error) };\n}\n/**\n* Report an uncaught exception or unhandled rejection, then end the process the way Node would have.\n*\n* Node's default for both is to print the failure and exit with code 1; installing a listener\n* suppresses that, so this does the same after a bounded wait for the report. Exit codes are\n* unchanged, only the report is added. Returns the function that removes both listeners.\n*/\nfunction installProcessErrorReporting(options) {\n\tconst target = options.target ?? process;\n\tconst exit = options.exit ?? ((code) => process.exit(code));\n\tconst print = options.print ?? writeCrashOutput;\n\tconst waitMs = options.waitMs ?? 2e3;\n\tlet terminating = false;\n\tconst handle = (origin) => (error) => {\n\t\tif (terminating) return;\n\t\tterminating = true;\n\t\ttry {\n\t\t\toptions.logger.error({\n\t\t\t\torigin,\n\t\t\t\t...describeFailure(error)\n\t\t\t}, \"Process terminated by an unhandled failure\");\n\t\t} catch {}\n\t\tconst report = Promise.resolve().then(() => options.report(error, origin)).catch(() => void 0);\n\t\tconst deadline = new Promise((resolve) => setTimeout(resolve, waitMs));\n\t\tPromise.race([report, deadline]).then(() => print(error)).catch(() => void 0).finally(() => exit(1));\n\t};\n\tconst onException = handle(\"uncaughtException\");\n\tconst onRejection = handle(\"unhandledRejection\");\n\ttarget.on(\"uncaughtException\", onException);\n\ttarget.on(\"unhandledRejection\", onRejection);\n\treturn () => {\n\t\ttarget.off(\"uncaughtException\", onException);\n\t\ttarget.off(\"unhandledRejection\", onRejection);\n\t};\n}\n//#endregion\n//#region src/agent-runtime/probe-failure.ts\n/**\n* Spawn errnos that mean \"the machine could not run the check right now\", not\n* \"the binary is broken or absent\". These map to `temporarily_unavailable` and\n* must not advance same-Provider candidate fallback.\n*/\nconst TRANSIENT_SPAWN_CODES = /* @__PURE__ */ new Set([\n\t\"ETIMEDOUT\",\n\t\"EAGAIN\",\n\t\"ENOMEM\"\n]);\n/**\n* Errnos that mean the selected file is missing or not an executable artifact.\n* Only these, together with a clean non-zero exit or a deterministic crash\n* signal, are binary-shaped. Any other errno is unknown and must propagate.\n*/\nconst ARTIFACT_ERRNOS = /* @__PURE__ */ new Set([\n\t\"ENOENT\",\n\t\"ENOTDIR\",\n\t\"EISDIR\",\n\t\"EACCES\",\n\t\"ENOEXEC\",\n\t\"ELOOP\"\n]);\n/**\n* Kill signals that mean the binary crashed deterministically — a broken or\n* incompatible native install that will fault the same way on every retry.\n* Deterministic crash signals take precedence over a generic `killed` flag.\n*/\nconst DETERMINISTIC_CRASH_SIGNALS = /* @__PURE__ */ new Set([\n\t\"SIGSEGV\",\n\t\"SIGABRT\",\n\t\"SIGILL\",\n\t\"SIGBUS\",\n\t\"SIGFPE\"\n]);\nfunction readProbeFailureEvidence(error) {\n\tif (!error || typeof error !== \"object\") return {};\n\tconst err = error;\n\tconst errno = typeof err.errno === \"string\" ? err.errno : typeof err.code === \"string\" && err.code.startsWith(\"E\") ? err.code : void 0;\n\tconst exitCode = typeof err.exitCode === \"number\" ? err.exitCode : err.exitCode === null ? null : typeof err.code === \"number\" ? err.code : void 0;\n\tconst signal = typeof err.signal === \"string\" ? err.signal : void 0;\n\treturn {\n\t\t...errno ? { errno } : {},\n\t\t...exitCode !== void 0 ? { exitCode } : {},\n\t\t...signal ? { signal } : {},\n\t\t...err.killed === true ? { killed: true } : {}\n\t};\n}\nfunction isDeterministicCrashSignal(signal) {\n\treturn signal !== void 0 && DETERMINISTIC_CRASH_SIGNALS.has(signal);\n}\nfunction isTransientProviderProbeFailure(error) {\n\tconst evidence = readProbeFailureEvidence(error);\n\tif (isDeterministicCrashSignal(evidence.signal)) return false;\n\tif (evidence.errno && TRANSIENT_SPAWN_CODES.has(evidence.errno)) return true;\n\tif (evidence.killed) return true;\n\tif (evidence.signal) return true;\n\treturn false;\n}\nfunction isBinaryShapedProviderProbeFailure(error) {\n\tconst evidence = readProbeFailureEvidence(error);\n\tif (isDeterministicCrashSignal(evidence.signal)) return true;\n\tif (isTransientProviderProbeFailure(error)) return false;\n\tif (typeof evidence.exitCode === \"number\" && evidence.exitCode !== 0) return true;\n\tif (evidence.errno && ARTIFACT_ERRNOS.has(evidence.errno)) return true;\n\treturn false;\n}\nfunction classifiedProviderProbeIssue(error, artifactMessage) {\n\tif (isTransientProviderProbeFailure(error)) return {\n\t\tcode: \"temporarily_unavailable\",\n\t\tmessage: artifactMessage\n\t};\n\tif (isBinaryShapedProviderProbeFailure(error)) return {\n\t\tcode: \"artifact_missing\",\n\t\tmessage: artifactMessage\n\t};\n}\n//#endregion\n//#region src/providers/claude-code/hosted-tool-bridge.ts\nconst MAX_REQUEST_BYTES = 1048576;\nconst MCP_PROTOCOL_VERSION = \"2025-03-26\";\nconst logger$16 = createLogger(\"provider-claude-mcp\");\n/** The loopback server carrying OpenTag's own hosted tools. */\nconst LOCAL_SERVER_NAME = \"opentag\";\nasync function startClaudeCodeHostedToolBridge(hostedTools, runId, signal, mcpGateway) {\n\tsignal.throwIfAborted();\n\tconst definitions = new Map((hostedTools?.definitions ?? []).map((definition) => [definition.name, definition]));\n\tif (hostedTools && definitions.size !== hostedTools.definitions.length) throw new Error(\"Claude Code hosted tool definitions must have unique names\");\n\tconst directory = await mkdtemp(join(tmpdir(), \"opentag-claude-mcp-\"));\n\tconst configPath = join(directory, \"mcp.json\");\n\tlet server;\n\ttry {\n\t\tconst mcpServers = {};\n\t\tif (hostedTools && definitions.size > 0) {\n\t\t\tconst token = randomBytes(32).toString(\"base64url\");\n\t\t\tserver = createServer((request, response) => {\n\t\t\t\thandleRequest(server, request, response, {\n\t\t\t\t\tdefinitions,\n\t\t\t\t\thostedTools,\n\t\t\t\t\trunId,\n\t\t\t\t\tsignal,\n\t\t\t\t\ttoken\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tlogger$16.debug({\n\t\t\t\t\t\tcode: \"request_handling_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Claude Code MCP request handling failed\");\n\t\t\t\t\t/* v8 ignore next 2 -- only a socket failure after response headers can reach the destroy branch. */\n\t\t\t\t\tif (!response.headersSent) writeJson(response, 500, jsonRpcError(null, -32603, \"Internal error\"));\n\t\t\t\t\telse response.destroy();\n\t\t\t\t});\n\t\t\t});\n\t\t\tawait listen(server);\n\t\t\tconst address = server.address();\n\t\t\t/* v8 ignore start -- a successful TCP listen always exposes an AddressInfo object. */\n\t\t\tif (!address || typeof address === \"string\") throw new Error(\"Claude Code hosted tool bridge did not bind a TCP port\");\n\t\t\t/* v8 ignore stop */\n\t\t\tmcpServers[LOCAL_SERVER_NAME] = {\n\t\t\t\ttype: \"http\",\n\t\t\t\turl: `http://127.0.0.1:${address.port}/mcp`,\n\t\t\t\theaders: { Authorization: `Bearer ${token}` }\n\t\t\t};\n\t\t}\n\t\tif (mcpGateway) mcpServers[MCP_GATEWAY_SERVER_NAME] = {\n\t\t\ttype: \"http\",\n\t\t\turl: mcpGateway.url,\n\t\t\theaders: { Authorization: `Bearer ${mcpGateway.token}` }\n\t\t};\n\t\tawait writeFile(configPath, `${JSON.stringify({ mcpServers })}\\n`, {\n\t\t\tencoding: \"utf8\",\n\t\t\tmode: 384\n\t\t});\n\t} catch (error) {\n\t\tlogger$16.debug({\n\t\t\tcode: \"bridge_start_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Claude Code hosted tool bridge startup failed\");\n\t\tawait Promise.allSettled([...server ? [closeServer(server)] : [], rm(directory, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t})]);\n\t\tthrow error;\n\t}\n\t/* v8 ignore stop */\n\tlet closePromise;\n\treturn {\n\t\tallowedTools: [...[...definitions.keys()].map((name) => `mcp__${LOCAL_SERVER_NAME}__${name}`), ...mcpGateway ? [MCP_GATEWAY_ALLOWED_TOOL_RULE] : []],\n\t\tconfigPath,\n\t\tclose() {\n\t\t\tclosePromise ??= Promise.allSettled([...server ? [closeServer(server)] : [], rm(directory, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t})]).then((results) => {\n\t\t\t\t/* v8 ignore start -- owned server/temp-directory cleanup failures are OS-level and not deterministically injectable. */\n\t\t\t\tconst failures = results.flatMap((result) => result.status === \"rejected\" ? [result.reason] : []);\n\t\t\t\tif (failures.length > 0) {\n\t\t\t\t\tlogger$16.debug({\n\t\t\t\t\t\tcode: \"bridge_cleanup_failed\",\n\t\t\t\t\t\tfailureCount: failures.length\n\t\t\t\t\t}, \"Claude Code MCP cleanup failed\");\n\t\t\t\t\tthrow new AggregateError(failures, \"Claude Code hosted tool bridge cleanup failed\");\n\t\t\t\t}\n\t\t\t\t/* v8 ignore stop */\n\t\t\t});\n\t\t\treturn closePromise;\n\t\t}\n\t};\n}\nasync function handleRequest(server, request, response, context) {\n\tresponse.setHeader(\"Connection\", \"close\");\n\tconst address = server.address();\n\t/* v8 ignore next -- this owned server remains listening for the request lifetime. */\n\tconst expectedHost = address && typeof address !== \"string\" ? `127.0.0.1:${address.port}` : \"\";\n\tif (request.method !== \"POST\" || request.url !== \"/mcp\" || request.headers.host !== expectedHost || request.headers.authorization !== `Bearer ${context.token}`) {\n\t\twriteJson(response, 404, jsonRpcError(null, -32600, \"Invalid request\"));\n\t\treturn;\n\t}\n\tlet body;\n\ttry {\n\t\tbody = JSON.parse(await readBody(request));\n\t} catch (error) {\n\t\tlogger$16.debug({\n\t\t\tcode: \"request_parse_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Claude Code MCP request body was invalid\");\n\t\twriteJson(response, 400, jsonRpcError(null, -32700, \"Parse error\"));\n\t\treturn;\n\t}\n\tconst rpc = record$2(body);\n\tif (rpc?.jsonrpc !== \"2.0\" || typeof rpc.method !== \"string\") {\n\t\twriteJson(response, 400, jsonRpcError(null, -32600, \"Invalid request\"));\n\t\treturn;\n\t}\n\tconst id = validRpcId(rpc.id) ? rpc.id : null;\n\tif (rpc.id === void 0) {\n\t\tresponse.writeHead(202).end();\n\t\treturn;\n\t}\n\tif (rpc.method === \"initialize\") {\n\t\twriteJson(response, 200, {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\tresult: {\n\t\t\t\tprotocolVersion: MCP_PROTOCOL_VERSION,\n\t\t\t\tcapabilities: { tools: {} },\n\t\t\t\tserverInfo: {\n\t\t\t\t\tname: \"OpenTag\",\n\t\t\t\t\tversion: \"1\"\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn;\n\t}\n\tif (rpc.method === \"tools/list\") {\n\t\twriteJson(response, 200, {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\tresult: { tools: [...context.definitions.values()].map((definition) => ({\n\t\t\t\tname: definition.name,\n\t\t\t\t...definition.description ? { description: definition.description } : {},\n\t\t\t\tinputSchema: definition.inputSchema\n\t\t\t})) }\n\t\t});\n\t\treturn;\n\t}\n\tif (rpc.method === \"tools/call\") {\n\t\tconst params = record$2(rpc.params);\n\t\tconst name = params?.name;\n\t\tif (typeof name !== \"string\" || !context.definitions.has(name)) {\n\t\t\twriteJson(response, 200, failedToolResult(id, \"OpenTag hosted tool is unavailable.\"));\n\t\t\treturn;\n\t\t}\n\t\tlet input;\n\t\ttry {\n\t\t\tconst candidate = params?.arguments === void 0 ? {} : params.arguments;\n\t\t\tassertJsonValue(candidate, \"MCP tool arguments\");\n\t\t\tinput = candidate;\n\t\t} catch (error) {\n\t\t\tlogger$16.debug({\n\t\t\t\tcode: \"tool_input_invalid\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Claude Code MCP tool input was invalid\");\n\t\t\twriteJson(response, 200, failedToolResult(id, error.message));\n\t\t\treturn;\n\t\t}\n\t\tconst result = await context.hostedTools.handler({\n\t\t\trunId: context.runId,\n\t\t\ttoolCallId: rpcToolCallId(id),\n\t\t\tname,\n\t\t\tinput,\n\t\t\tsignal: context.signal\n\t\t});\n\t\twriteJson(response, 200, {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\tresult: {\n\t\t\t\tcontent: result.content,\n\t\t\t\tisError: !result.success,\n\t\t\t\t...result.error ? { structuredContent: { error: result.error } } : {}\n\t\t\t}\n\t\t});\n\t\treturn;\n\t}\n\twriteJson(response, 200, jsonRpcError(id, -32601, \"Method not found\"));\n}\nfunction listen(server) {\n\treturn new Promise((resolve, reject) => {\n\t\t/* v8 ignore next -- port zero on loopback has no expected contention failure. */\n\t\tconst onError = (error) => reject(error);\n\t\tserver.once(\"error\", onError);\n\t\tserver.listen(0, \"127.0.0.1\", () => {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t});\n\t});\n}\nfunction closeServer(server) {\n\treturn new Promise((resolve, reject) => {\n\t\t/* v8 ignore next -- Node does not report a close error for this owned listening server. */\n\t\tserver.close((error) => error ? reject(error) : resolve());\n\t\tserver.closeAllConnections();\n\t});\n}\nfunction readBody(request) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst chunks = [];\n\t\tlet size = 0;\n\t\trequest.on(\"data\", (chunk) => {\n\t\t\tsize += chunk.length;\n\t\t\tif (size > MAX_REQUEST_BYTES) {\n\t\t\t\treject(/* @__PURE__ */ new Error(\"MCP request is too large\"));\n\t\t\t\trequest.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tchunks.push(chunk);\n\t\t});\n\t\trequest.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n\t\t/* v8 ignore next -- malformed/oversized bodies are handled before transport-level request failure. */\n\t\trequest.on(\"error\", reject);\n\t});\n}\nfunction writeJson(response, status, value) {\n\tconst body = JSON.stringify(value);\n\tresponse.writeHead(status, {\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"Content-Length\": Buffer.byteLength(body)\n\t});\n\tresponse.end(body);\n}\nfunction jsonRpcError(id, code, message) {\n\treturn {\n\t\tjsonrpc: \"2.0\",\n\t\tid,\n\t\terror: {\n\t\t\tcode,\n\t\t\tmessage\n\t\t}\n\t};\n}\nfunction failedToolResult(id, text) {\n\treturn {\n\t\tjsonrpc: \"2.0\",\n\t\tid,\n\t\tresult: {\n\t\t\tcontent: [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext\n\t\t\t}],\n\t\t\tisError: true\n\t\t}\n\t};\n}\nfunction rpcToolCallId(id) {\n\tif (typeof id === \"string\" && id.length > 0 && Buffer.byteLength(id, \"utf8\") <= 256) return id;\n\tif (typeof id === \"number\") return String(id);\n\treturn randomUUID();\n}\nfunction validRpcId(value) {\n\treturn value === null || typeof value === \"string\" || typeof value === \"number\" && Number.isFinite(value);\n}\nfunction record$2(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? value : void 0;\n}\n//#endregion\n//#region src/providers/claude-code/process-wire.ts\nconst CLAUDE_CODE_MAX_LINE_BYTES = 8388608;\nconst CLAUDE_CODE_MAX_STDERR_BYTES = 65536;\nvar ClaudeCodeProcessError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = \"ClaudeCodeProcessError\";\n\t}\n};\nconst defaultSpawn$1 = (command, args, options) => spawnWatchedProcess(command, args, options);\nvar ClaudeCodeProcess = class {\n\t#child;\n\t#maxLineBytes;\n\t#maxStderrBytes;\n\t#logger;\n\t#exit;\n\t#resolveExit;\n\t#buffer = Buffer.alloc(0);\n\t#stderr = Buffer.alloc(0);\n\t#listener;\n\t#resolveExecution;\n\t#rejectExecution;\n\t#execution;\n\t#failure;\n\t#closed = false;\n\t#closing = false;\n\t#spawned = false;\n\t#terminalReceived = false;\n\t#signal;\n\tconstructor(options) {\n\t\tthis.#maxLineBytes = options.maxLineBytes ?? 8388608;\n\t\tthis.#maxStderrBytes = options.maxStderrBytes ?? 65536;\n\t\tthis.#logger = options.logger ?? createLogger(\"provider-claude-code\");\n\t\tif (!Number.isSafeInteger(this.#maxLineBytes) || this.#maxLineBytes < 1024) throw new Error(\"maxLineBytes must be a safe integer of at least 1024\");\n\t\tif (!Number.isSafeInteger(this.#maxStderrBytes) || this.#maxStderrBytes < 0) throw new Error(\"maxStderrBytes must be a non-negative safe integer\");\n\t\tthis.#exit = new Promise((resolve) => {\n\t\t\tthis.#resolveExit = resolve;\n\t\t});\n\t\ttry {\n\t\t\tthis.#child = (options.spawnProcess ?? defaultSpawn$1)(options.command ?? \"claude\", options.args, {\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tenv: options.env,\n\t\t\t\tdetached: process.platform !== \"win32\"\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"spawn_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Claude Code process spawn failed\");\n\t\t\tthrow new ClaudeCodeProcessError(\"spawn\", error instanceof Error ? error.message : \"Claude Code could not be started\");\n\t\t}\n\t\tthis.#child.stdout.on(\"data\", (chunk) => this.#onStdout(chunk));\n\t\tthis.#child.stderr.on(\"data\", (chunk) => this.#onStderr(chunk));\n\t\tthis.#child.once(\"spawn\", () => {\n\t\t\tthis.#spawned = true;\n\t\t});\n\t\tthis.#child.on(\"error\", (error) => {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: this.#spawned ? \"process_error\" : \"spawn_error\",\n\t\t\t\terror: error.message\n\t\t\t}, \"Claude Code process failed\");\n\t\t\tthis.#fail(new ClaudeCodeProcessError(this.#spawned ? \"exited\" : \"spawn\", error.message));\n\t\t});\n\t\tthis.#child.on(\"exit\", () => this.#onExit());\n\t}\n\texecute(input, onMessage, signal) {\n\t\tif (this.#execution) return Promise.reject(new ClaudeCodeProcessError(\"protocol\", \"Claude Code already ran\"));\n\t\tif (this.#failure) return Promise.reject(this.#failure);\n\t\tif (this.#closed) return Promise.reject(new ClaudeCodeProcessError(\"exited\", \"Claude Code is closed\"));\n\t\tif (signal.aborted) return Promise.reject(new ClaudeCodeProcessError(\"aborted\", \"Claude Code run was aborted\"));\n\t\tthis.#listener = onMessage;\n\t\tthis.#signal = signal;\n\t\tthis.#execution = new Promise((resolve, reject) => {\n\t\t\tthis.#resolveExecution = resolve;\n\t\t\tthis.#rejectExecution = reject;\n\t\t});\n\t\tconst line = `${JSON.stringify(input)}\\n`;\n\t\tif (Buffer.byteLength(line, \"utf8\") > this.#maxLineBytes) {\n\t\t\tthis.#fail(new ClaudeCodeProcessError(\"protocol\", \"Claude Code input exceeds the JSONL line limit\"));\n\t\t\treturn this.#execution;\n\t\t}\n\t\tthis.#child.stdin.write(line, (error) => {\n\t\t\tif (error) this.#fail(new ClaudeCodeProcessError(\"write\", \"Claude Code input could not be written\"));\n\t\t});\n\t\treturn this.#execution;\n\t}\n\tasync interrupt() {\n\t\tif (this.#closed || this.#terminalReceived) return;\n\t\tthis.#closing = true;\n\t\tsignalWatchedProcess(this.#child, \"SIGINT\");\n\t}\n\tasync close(graceMs = 1e3) {\n\t\tif (this.#closed) return this.#exit;\n\t\tthis.#closing = true;\n\t\tsignalWatchedProcess(this.#child, \"SIGTERM\");\n\t\tif (await settlesWithin$1(this.#exit, graceMs)) return;\n\t\tsignalWatchedProcess(this.#child, \"SIGKILL\");\n\t\t/* v8 ignore else -- a process that survives SIGTERM in tests never exits before the SIGKILL deadline either. */\n\t\tif (!await settlesWithin$1(this.#exit, graceMs)) throw new ClaudeCodeProcessError(\"exited\", \"Claude Code process tree did not exit\");\n\t}\n\t#onStdout(chunk) {\n\t\tif (this.#failure) return;\n\t\tthis.#buffer = Buffer.concat([this.#buffer, chunk]);\n\t\twhile (true) {\n\t\t\tconst newline = this.#buffer.indexOf(10);\n\t\t\tif (newline < 0) break;\n\t\t\tif (newline + 1 > this.#maxLineBytes) {\n\t\t\t\tthis.#fail(new ClaudeCodeProcessError(\"protocol\", \"Claude Code output exceeds the JSONL line limit\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst raw = this.#buffer.subarray(0, newline).toString(\"utf8\").replace(/\\r$/, \"\");\n\t\t\tthis.#buffer = this.#buffer.subarray(newline + 1);\n\t\t\tif (raw.length === 0) continue;\n\t\t\tlet parsed;\n\t\t\ttry {\n\t\t\t\tparsed = JSON.parse(raw);\n\t\t\t} catch {\n\t\t\t\tthis.#logger.debug({ code: \"stdout_malformed_json\" }, \"Claude Code protocol output was rejected\");\n\t\t\t\tthis.#fail(new ClaudeCodeProcessError(\"protocol\", \"Claude Code emitted malformed JSONL\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!isRecord$5(parsed)) {\n\t\t\t\tthis.#fail(new ClaudeCodeProcessError(\"protocol\", \"Claude Code emitted a non-object message\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tthis.#listener?.(parsed);\n\t\t\t} catch (error) {\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tcode: \"protocol_listener_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Claude Code protocol listener failed\");\n\t\t\t\tthis.#fail(error instanceof Error ? error : new ClaudeCodeProcessError(\"protocol\", \"Claude Code message listener failed\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parsed.type === \"result\") {\n\t\t\t\tthis.#terminalReceived = true;\n\t\t\t\tthis.#closing = true;\n\t\t\t\tsignalWatchedProcess(this.#child, \"SIGTERM\");\n\t\t\t}\n\t\t}\n\t\tif (this.#buffer.byteLength > this.#maxLineBytes) this.#fail(new ClaudeCodeProcessError(\"protocol\", \"Claude Code output exceeds the JSONL line limit\"));\n\t}\n\t#onStderr(chunk) {\n\t\tif (this.#stderr.byteLength >= this.#maxStderrBytes) return;\n\t\tconst remaining = this.#maxStderrBytes - this.#stderr.byteLength;\n\t\tthis.#stderr = Buffer.concat([this.#stderr, chunk.subarray(0, remaining)]);\n\t}\n\t#onExit() {\n\t\tthis.#closed = true;\n\t\tthis.#resolveExit?.();\n\t\tthis.#resolveExit = void 0;\n\t\tif (this.#failure) return;\n\t\tif (this.#buffer.byteLength > 0) {\n\t\t\tthis.#fail(new ClaudeCodeProcessError(\"protocol\", \"Claude Code exited with a truncated JSONL line\"));\n\t\t\treturn;\n\t\t}\n\t\tif (!this.#execution) return;\n\t\tif (!this.#terminalReceived) {\n\t\t\tconst aborted = this.#signal?.aborted || this.#closing;\n\t\t\tthis.#fail(new ClaudeCodeProcessError(aborted ? \"aborted\" : \"exited\", aborted ? \"Claude Code run was aborted\" : this.#exitMessage()));\n\t\t\treturn;\n\t\t}\n\t\tthis.#resolveExecution?.({ stderr: this.#stderr.toString(\"utf8\") });\n\t\tthis.#clearExecution();\n\t}\n\t#exitMessage() {\n\t\tconst stderr = this.#stderr.toString(\"utf8\").trim();\n\t\treturn stderr ? `Claude Code exited: ${stderr}` : \"Claude Code exited before a result\";\n\t}\n\t#fail(error) {\n\t\tif (this.#failure) return;\n\t\tthis.#failure = error;\n\t\tthis.#rejectExecution?.(error);\n\t\tthis.#clearExecution();\n\t\tif (!this.#closed) {\n\t\t\tthis.#closing = true;\n\t\t\tsignalWatchedProcess(this.#child, \"SIGTERM\");\n\t\t}\n\t}\n\t#clearExecution() {\n\t\tthis.#listener = void 0;\n\t\tthis.#resolveExecution = void 0;\n\t\tthis.#rejectExecution = void 0;\n\t}\n};\nasync function settlesWithin$1(promise, milliseconds) {\n\tlet timer;\n\tconst timeout = new Promise((resolve) => {\n\t\ttimer = setTimeout(() => resolve(false), milliseconds);\n\t\ttimer.unref();\n\t});\n\tconst settled = await Promise.race([promise.then(() => true), timeout]);\n\t/* v8 ignore else -- the timer is always armed before the race settles. */\n\tif (timer) clearTimeout(timer);\n\treturn settled;\n}\nfunction isRecord$5(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n//#endregion\n//#region src/providers/claude-code/agent-runtime.ts\nconst execFileAsync$3 = promisify(execFile);\nconst CLAUDE_CODE_BINDING_SCHEMA_VERSION = 1;\nconst CLAUDE_CODE_PROVIDER_ID = \"claude-code\";\nconst logger$15 = createLogger(\"provider-claude-code-runtime\");\nconst CLAUDE_CODE_AGENT_RUNTIME_MANIFEST = Object.freeze({\n\tproviderId: CLAUDE_CODE_PROVIDER_ID,\n\tdisplayName: \"Claude Code\",\n\tcontractVersion: 2,\n\tbindingSchemaVersion: CLAUDE_CODE_BINDING_SCHEMA_VERSION\n});\nvar ClaudeCodeAgentRuntime = class extends BaseAgentRuntime {\n\t#sessionId;\n\t#configuration;\n\t#createProcess;\n\t#emptyNativeToolAllowList;\n\t#hostedTools;\n\t#startHostedToolBridge;\n\t#systemPrompt;\n\t#textBlocks = /* @__PURE__ */ new Map();\n\t#tools = /* @__PURE__ */ new Map();\n\t#toolBlocks = /* @__PURE__ */ new Map();\n\t#startedModelTurns = /* @__PURE__ */ new Set();\n\t#completedModelTurns = /* @__PURE__ */ new Set();\n\t#process;\n\t#context;\n\t#eventTail = Promise.resolve();\n\t#terminal;\n\t#providerFailure;\n\t#currentMessageId;\n\t#sessionExists;\n\t#terminalClaimed = false;\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tmanifest: CLAUDE_CODE_AGENT_RUNTIME_MANIFEST,\n\t\t\tcapabilities: {\n\t\t\t\tsteer: \"unsupported\",\n\t\t\t\tinteractions: \"unsupported\"\n\t\t\t},\n\t\t\teventSink: options.eventSink,\n\t\t\tbinding: options.binding\n\t\t});\n\t\tthis.#sessionId = parseClaudeCodeBinding(options.binding);\n\t\tthis.#configuration = options.configuration;\n\t\tthis.#createProcess = options.createProcess;\n\t\tthis.#emptyNativeToolAllowList = options.emptyNativeToolAllowList === true;\n\t\tthis.#hostedTools = options.hostedTools;\n\t\tthis.#startHostedToolBridge = options.startHostedToolBridge;\n\t\tthis.#systemPrompt = options.systemPrompt;\n\t\tthis.#sessionExists = options.resume;\n\t}\n\tasync executeRun(request, context) {\n\t\tthis.#context = context;\n\t\tthis.#terminal = void 0;\n\t\tthis.#providerFailure = void 0;\n\t\tthis.#currentMessageId = void 0;\n\t\tthis.#terminalClaimed = false;\n\t\tthis.#textBlocks.clear();\n\t\tthis.#tools.clear();\n\t\tthis.#toolBlocks.clear();\n\t\tthis.#startedModelTurns.clear();\n\t\tthis.#completedModelTurns.clear();\n\t\tlet process;\n\t\tlet hostedToolBridge;\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tconst mcpGateway = parseProviderConfiguration$1(mergeConfiguration$1(this.#configuration, request.configuration)?.provider).mcpGateway;\n\t\t\t\thostedToolBridge = await this.#startHostedToolBridge(this.#hostedTools, request.runId, context.signal, mcpGateway);\n\t\t\t\tprocess = this.#createProcess(this.#arguments(request, hostedToolBridge));\n\t\t\t} catch (error) {\n\t\t\t\tlogger$15.debug({\n\t\t\t\t\tcode: \"provider_start_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Claude Code provider startup failed\");\n\t\t\t\tthrow new AgentProviderError(\"provider_start_failed\", error instanceof Error ? error.message : \"Claude Code failed before accepting input\", { cause: error });\n\t\t\t}\n\t\t\tthis.#process = process;\n\t\t\tawait process.execute(claudeCodeInput(request), (message) => this.#enqueue(message), context.signal);\n\t\t\tawait this.#eventTail;\n\t\t\tif (this.#providerFailure) throw this.#providerFailure;\n\t\t\tif (!this.#terminal) throw protocolError$1(\"Claude Code exited without a result message\");\n\t\t\treturn claudeCodeRunResult(this.#terminal);\n\t\t} catch (error) {\n\t\t\tif (context.signal.aborted) throw error;\n\t\t\tlogger$15.debug({\n\t\t\t\tcode: \"provider_run_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Claude Code provider run failed\");\n\t\t\tthis.closeForProviderFailure();\n\t\t\tif (this.#providerFailure) throw this.#providerFailure;\n\t\t\tif (error instanceof AgentProviderError) throw error;\n\t\t\tif (error instanceof ClaudeCodeProcessError) {\n\t\t\t\tif (error.code === \"spawn\") throw new AgentProviderError(\"provider_start_failed\", error.message, { cause: error });\n\t\t\t\tif (error.code === \"protocol\") throw new AgentProviderError(\"provider_protocol_error\", error.message, { cause: error });\n\t\t\t}\n\t\t\tthrow new AgentProviderError(\"provider_error\", error instanceof Error ? error.message : \"Claude Code run failed\", { cause: error });\n\t\t} finally {\n\t\t\tawait process?.close().catch((error) => {\n\t\t\t\tlogger$15.debug({\n\t\t\t\t\tcode: \"provider_close_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Claude Code provider close failed\");\n\t\t\t});\n\t\t\tawait hostedToolBridge?.close();\n\t\t\tthis.#process = void 0;\n\t\t\tthis.#context = void 0;\n\t\t\tthis.#currentMessageId = void 0;\n\t\t\tthis.#textBlocks.clear();\n\t\t\tthis.#tools.clear();\n\t\t\tthis.#toolBlocks.clear();\n\t\t}\n\t}\n\tasync abortProvider(_request) {\n\t\tif (this.#terminalClaimed) return;\n\t\tawait this.#process?.interrupt();\n\t}\n\tasync closeProvider() {\n\t\tawait this.#process?.close();\n\t}\n\t#arguments(request, hostedToolBridge) {\n\t\tconst configuration = mergeConfiguration$1(this.#configuration, request.configuration);\n\t\tconst provider = parseProviderConfiguration$1(configuration?.provider);\n\t\treturn [\n\t\t\t\"--print\",\n\t\t\t\"--input-format\",\n\t\t\t\"stream-json\",\n\t\t\t\"--output-format\",\n\t\t\t\"stream-json\",\n\t\t\t\"--verbose\",\n\t\t\t\"--include-partial-messages\",\n\t\t\t\"--no-chrome\",\n\t\t\t\"--setting-sources\",\n\t\t\t\"project\",\n\t\t\t\"--strict-mcp-config\",\n\t\t\t\"--mcp-config\",\n\t\t\thostedToolBridge.configPath,\n\t\t\t...hostedToolBridge.allowedTools.length > 0 ? [\"--allowedTools\", ...hostedToolBridge.allowedTools] : [],\n\t\t\t...this.#sessionExists ? [\"--resume\", this.#sessionId] : [\"--session-id\", this.#sessionId],\n\t\t\t\"--permission-mode\",\n\t\t\t\"bypassPermissions\",\n\t\t\t...this.#emptyNativeToolAllowList ? [\"--tools\", \"\"] : [],\n\t\t\t...configuration?.model ? [\"--model\", configuration.model] : [],\n\t\t\t...configuration?.reasoningEffort ? [\"--effort\", configuration.reasoningEffort] : [],\n\t\t\t\"--append-system-prompt\",\n\t\t\tthis.#systemPrompt,\n\t\t\t...provider.maxBudgetUsd !== void 0 ? [\"--max-budget-usd\", String(provider.maxBudgetUsd)] : [],\n\t\t\t...provider.maxTurns !== void 0 ? [\"--max-turns\", String(provider.maxTurns)] : []\n\t\t];\n\t}\n\t#enqueue(message) {\n\t\tthis.#claimTerminalAtIngress(message);\n\t\tconst next = this.#eventTail.then(async () => {\n\t\t\tif (!this.#context || this.#providerFailure) return;\n\t\t\tawait this.#handleMessage(message);\n\t\t});\n\t\tthis.#eventTail = next.catch((error) => {\n\t\t\tlogger$15.debug({\n\t\t\t\tcode: \"event_processing_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Claude Code event processing failed\");\n\t\t\tthis.#failProvider(error instanceof Error ? error : protocolError$1(\"Claude Code event processing failed\"));\n\t\t});\n\t}\n\t#claimTerminalAtIngress(message) {\n\t\tif (message.type !== \"result\" || !this.#context) return;\n\t\ttry {\n\t\t\tparseTerminal(message, this.#sessionId);\n\t\t\tthis.#context.claimTerminal();\n\t\t\tthis.#terminalClaimed = true;\n\t\t} catch (error) {\n\t\t\tlogger$15.debug({\n\t\t\t\tcode: \"terminal_message_invalid\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Claude Code terminal message was rejected\");\n\t\t}\n\t}\n\tasync #handleMessage(message) {\n\t\tconst type = requireString$1(message.type, \"Claude Code message has no type\");\n\t\tif (type === \"stream_event\") {\n\t\t\tawait this.#handleStreamEvent(requireRecord$2(message.event, \"Claude Code stream event is invalid\"));\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"assistant\") {\n\t\t\tawait this.#handleAssistant(message);\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"user\") {\n\t\t\tawait this.#handleUser(message);\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"system\" && message.subtype === \"init\") {\n\t\t\tconst sessionId = requireString$1(message.session_id, \"Claude Code init has no session id\");\n\t\t\tif (sessionId !== this.#sessionId) throw protocolError$1(\"Claude Code initialized another session\");\n\t\t\tthis.#sessionExists = true;\n\t\t\tawait this.#emitProviderEvent({\n\t\t\t\ttype,\n\t\t\t\tsubtype: \"init\",\n\t\t\t\tsession_id: sessionId,\n\t\t\t\t...typeof message.model === \"string\" ? { model: message.model } : {},\n\t\t\t\t...typeof message.claude_code_version === \"string\" ? { claude_code_version: message.claude_code_version } : {}\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"result\") {\n\t\t\tconst terminal = parseTerminal(message, this.#sessionId);\n\t\t\tthis.#sessionExists = true;\n\t\t\tawait this.#completeOutstandingTools(terminal);\n\t\t\tif (terminal.usage) await this.#requireContext().emit({\n\t\t\t\ttype: \"usage_updated\",\n\t\t\t\tusage: terminal.usage\n\t\t\t});\n\t\t\tthis.#terminal = terminal;\n\t\t\treturn;\n\t\t}\n\t\tawait this.#emitProviderEvent(message);\n\t}\n\tasync #handleStreamEvent(event) {\n\t\tconst type = requireString$1(event.type, \"Claude Code stream event has no type\");\n\t\tif (type === \"message_start\") {\n\t\t\tconst id = requireString$1(requireRecord$2(event.message, \"Claude Code message_start has no message\").id, \"Claude Code message_start has no id\");\n\t\t\tthis.#currentMessageId = id;\n\t\t\tawait this.#startModelTurn(id);\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"content_block_start\") {\n\t\t\tconst block = requireRecord$2(event.content_block, \"Claude Code content block is invalid\");\n\t\t\tawait this.#startContentBlock(requireIndex(event.index), block);\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"content_block_delta\") {\n\t\t\tconst delta = requireRecord$2(event.delta, \"Claude Code content delta is invalid\");\n\t\t\tawait this.#updateContentBlock(requireIndex(event.index), delta);\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"content_block_stop\") {\n\t\t\tawait this.#stopContentBlock(requireIndex(event.index));\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"message_delta\") {\n\t\t\tconst usage = parseUsage$1(event.usage);\n\t\t\tif (usage) await this.#requireContext().emit({\n\t\t\t\ttype: \"usage_updated\",\n\t\t\t\tusage\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (type === \"message_stop\") {\n\t\t\tconst id = this.#requireCurrentMessageId();\n\t\t\tif (!this.#completedModelTurns.has(id)) {\n\t\t\t\tthis.#completedModelTurns.add(id);\n\t\t\t\tawait this.#requireContext().emit({\n\t\t\t\t\ttype: \"model_turn_completed\",\n\t\t\t\t\tmodelTurnId: id\n\t\t\t\t});\n\t\t\t}\n\t\t\tthis.#currentMessageId = void 0;\n\t\t\treturn;\n\t\t}\n\t\tawait this.#emitProviderEvent({\n\t\t\ttype: \"stream_event\",\n\t\t\tevent: toJsonValue$1(event)\n\t\t});\n\t}\n\tasync #handleAssistant(envelope) {\n\t\tconst message = requireRecord$2(envelope.message, \"Claude Code assistant message is invalid\");\n\t\tconst id = requireString$1(message.id, \"Claude Code assistant message has no id\");\n\t\tconst alreadyStarted = this.#startedModelTurns.has(id);\n\t\tawait this.#startModelTurn(id);\n\t\tconst content = requireArray(message.content, \"Claude Code assistant content is invalid\");\n\t\tfor (let index = 0; index < content.length; index += 1) {\n\t\t\tconst block = requireRecord$2(content[index], \"Claude Code assistant block is invalid\");\n\t\t\tconst key = blockKey(id, index);\n\t\t\tif (block.type === \"text\") {\n\t\t\t\tconst text = requireString$1(block.text, \"Claude Code text block has no text\", true);\n\t\t\t\tif (!this.#textBlocks.get(key)?.completed) await this.#emitCompleteText(key, text);\n\t\t\t} else if (block.type === \"tool_use\") {\n\t\t\t\tconst toolId = requireString$1(block.id, \"Claude Code tool use has no id\");\n\t\t\t\tif (!this.#tools.has(toolId)) {\n\t\t\t\t\tconst name = requireString$1(block.name, \"Claude Code tool use has no name\");\n\t\t\t\t\tthis.#tools.set(toolId, { name });\n\t\t\t\t\tawait this.#requireContext().emit({\n\t\t\t\t\t\ttype: \"tool_started\",\n\t\t\t\t\t\ttoolCallId: toolId,\n\t\t\t\t\t\tname,\n\t\t\t\t\t\t...block.input !== void 0 ? { input: toJsonValue$1(block.input) } : {}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!alreadyStarted && !this.#completedModelTurns.has(id)) {\n\t\t\tthis.#completedModelTurns.add(id);\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"model_turn_completed\",\n\t\t\t\tmodelTurnId: id\n\t\t\t});\n\t\t}\n\t\tif (typeof envelope.error === \"string\") await this.#requireContext().emit({\n\t\t\ttype: \"provider_warning\",\n\t\t\tcode: \"claude_code_assistant_error\",\n\t\t\tmessage: envelope.error\n\t\t});\n\t}\n\tasync #handleUser(envelope) {\n\t\tconst content = requireRecord$2(envelope.message, \"Claude Code user message is invalid\").content;\n\t\tif (!Array.isArray(content)) return;\n\t\tfor (const candidate of content) {\n\t\t\tconst block = record$1(candidate);\n\t\t\tif (block?.type !== \"tool_result\") continue;\n\t\t\tconst toolCallId = requireString$1(block.tool_use_id, \"Claude Code tool result has no tool id\");\n\t\t\tconst tool = this.#tools.get(toolCallId);\n\t\t\tif (!tool) continue;\n\t\t\tthis.#tools.delete(toolCallId);\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"tool_completed\",\n\t\t\t\ttoolCallId,\n\t\t\t\tname: tool.name,\n\t\t\t\tstatus: block.is_error === true ? \"failed\" : \"completed\",\n\t\t\t\t...block.content !== void 0 ? { output: toJsonValue$1(block.content) } : {}\n\t\t\t});\n\t\t}\n\t}\n\tasync #startContentBlock(index, block) {\n\t\tconst key = blockKey(this.#requireCurrentMessageId(), index);\n\t\tif (block.type === \"text\") {\n\t\t\tconst state = {\n\t\t\t\tid: key,\n\t\t\t\tcompleted: false,\n\t\t\t\tstarted: true,\n\t\t\t\ttext: \"\"\n\t\t\t};\n\t\t\tthis.#textBlocks.set(key, state);\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"message_started\",\n\t\t\t\tmessageId: key\n\t\t\t});\n\t\t\tconst text = typeof block.text === \"string\" ? block.text : \"\";\n\t\t\tif (text) {\n\t\t\t\tstate.text += text;\n\t\t\t\tawait this.#requireContext().emit({\n\t\t\t\t\ttype: \"message_delta\",\n\t\t\t\t\tmessageId: key,\n\t\t\t\t\tdelta: text\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (block.type === \"tool_use\") {\n\t\t\tconst toolCallId = requireString$1(block.id, \"Claude Code tool use has no id\");\n\t\t\tconst name = requireString$1(block.name, \"Claude Code tool use has no name\");\n\t\t\tthis.#tools.set(toolCallId, { name });\n\t\t\tthis.#toolBlocks.set(key, toolCallId);\n\t\t\tconst event = {\n\t\t\t\ttype: \"tool_started\",\n\t\t\t\ttoolCallId,\n\t\t\t\tname\n\t\t\t};\n\t\t\t/* v8 ignore else -- Claude Code always attaches an input payload to tool_use blocks. */\n\t\t\tif (block.input !== void 0) event.input = toJsonValue$1(block.input);\n\t\t\tawait this.#requireContext().emit(event);\n\t\t\treturn;\n\t\t}\n\t\tawait this.#emitProviderEvent({\n\t\t\ttype: \"content_block_start\",\n\t\t\tindex,\n\t\t\tblock: toJsonValue$1(block)\n\t\t});\n\t}\n\tasync #updateContentBlock(index, delta) {\n\t\tconst key = blockKey(this.#requireCurrentMessageId(), index);\n\t\tif (delta.type === \"text_delta\") {\n\t\t\tconst text = requireString$1(delta.text, \"Claude Code text delta has no text\", true);\n\t\t\tconst state = this.#textBlocks.get(key);\n\t\t\tif (!state) throw protocolError$1(\"Claude Code text delta has no matching block\");\n\t\t\tstate.text += text;\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"message_delta\",\n\t\t\t\tmessageId: state.id,\n\t\t\t\tdelta: text\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (delta.type === \"input_json_delta\") {\n\t\t\tconst partialJson = requireString$1(delta.partial_json, \"Claude Code tool delta has no JSON\", true);\n\t\t\tconst toolCallId = this.#toolBlocks.get(key);\n\t\t\tif (!toolCallId) throw protocolError$1(\"Claude Code tool delta has no matching tool\");\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"tool_updated\",\n\t\t\t\ttoolCallId,\n\t\t\t\tupdate: { partialJson }\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tawait this.#emitProviderEvent({\n\t\t\ttype: \"content_block_delta\",\n\t\t\tindex,\n\t\t\tdelta: toJsonValue$1(delta)\n\t\t});\n\t}\n\tasync #stopContentBlock(index) {\n\t\tconst key = blockKey(this.#requireCurrentMessageId(), index);\n\t\tthis.#toolBlocks.delete(key);\n\t\tconst state = this.#textBlocks.get(key);\n\t\tif (!state || state.completed) return;\n\t\tstate.completed = true;\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"message_completed\",\n\t\t\tmessageId: state.id,\n\t\t\ttext: state.text\n\t\t});\n\t}\n\tasync #emitCompleteText(key, text) {\n\t\tlet state = this.#textBlocks.get(key);\n\t\tif (!state) {\n\t\t\tstate = {\n\t\t\t\tid: key,\n\t\t\t\tcompleted: false,\n\t\t\t\tstarted: false,\n\t\t\t\ttext: \"\"\n\t\t\t};\n\t\t\tthis.#textBlocks.set(key, state);\n\t\t}\n\t\tif (!state.started) {\n\t\t\tstate.started = true;\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"message_started\",\n\t\t\t\tmessageId: key\n\t\t\t});\n\t\t}\n\t\tif (!state.text && text) {\n\t\t\tstate.text = text;\n\t\t\tawait this.#requireContext().emit({\n\t\t\t\ttype: \"message_delta\",\n\t\t\t\tmessageId: key,\n\t\t\t\tdelta: text\n\t\t\t});\n\t\t}\n\t\tstate.completed = true;\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"message_completed\",\n\t\t\tmessageId: key,\n\t\t\ttext\n\t\t});\n\t}\n\tasync #startModelTurn(id) {\n\t\tif (this.#startedModelTurns.has(id)) return;\n\t\tthis.#startedModelTurns.add(id);\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"model_turn_started\",\n\t\t\tmodelTurnId: id\n\t\t});\n\t}\n\tasync #completeOutstandingTools(terminal) {\n\t\tconst denied = new Set(terminal.permissionDenials.map((item) => item.tool_use_id).filter((value) => typeof value === \"string\"));\n\t\tfor (const [toolCallId, tool] of this.#tools) await this.#requireContext().emit({\n\t\t\ttype: \"tool_completed\",\n\t\t\ttoolCallId,\n\t\t\tname: tool.name,\n\t\t\tstatus: denied.has(toolCallId) ? \"declined\" : \"failed\"\n\t\t});\n\t\tthis.#tools.clear();\n\t}\n\tasync #emitProviderEvent(payload) {\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"provider_event\",\n\t\t\tproviderId: CLAUDE_CODE_PROVIDER_ID,\n\t\t\tschemaVersion: 1,\n\t\t\tpayload: toJsonValue$1(payload)\n\t\t});\n\t}\n\t#requireCurrentMessageId() {\n\t\tif (!this.#currentMessageId) throw protocolError$1(\"Claude Code content event has no active message\");\n\t\treturn this.#currentMessageId;\n\t}\n\t#requireContext() {\n\t\t/* v8 ignore next -- the serial envelope queue drops messages after the active Run context is cleared. */\n\t\tif (!this.#context) throw protocolError$1(\"Claude Code event arrived without an active run\");\n\t\treturn this.#context;\n\t}\n\t#failProvider(error) {\n\t\tlogger$15.debug({\n\t\t\tcode: \"provider_failure\",\n\t\t\terror: error.message\n\t\t}, \"Claude Code provider failure recorded\");\n\t\tthis.#providerFailure = error;\n\t\t/* v8 ignore next -- process teardown during a provider failure must not raise a second fault. */\n\t\tthis.#process?.close().catch((error) => {\n\t\t\tlogger$15.debug({\n\t\t\t\tcode: \"provider_close_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Claude Code provider close after failure failed\");\n\t\t});\n\t\tthis.closeForProviderFailure();\n\t}\n};\nvar ClaudeCodeAgentRuntimeFactory = class {\n\tmanifest = CLAUDE_CODE_AGENT_RUNTIME_MANIFEST;\n\t#createSessionId;\n\t#createProcess;\n\t#probeRunner;\n\t#startHostedToolBridge;\n\tconstructor(options = {}) {\n\t\tthis.#createSessionId = options.createSessionId ?? randomUUID;\n\t\tconst environment = claudeCodeAgentRuntimeEnvironment(options.process?.env);\n\t\tconst command = options.process?.command ?? \"claude\";\n\t\tconst prefix = options.process?.args ?? [];\n\t\tthis.#createProcess = options.createProcess ?? ((cwd, args, workspaceEnvironment, pathPrepend) => new ClaudeCodeProcess({\n\t\t\tcommand,\n\t\t\targs: [...prefix, ...args],\n\t\t\tcwd,\n\t\t\tenv: composeRuntimeEnvironment(environment, workspaceEnvironment, pathPrepend),\n\t\t\tmaxLineBytes: options.process?.maxLineBytes,\n\t\t\tmaxStderrBytes: options.process?.maxStderrBytes,\n\t\t\tspawnProcess: options.process?.spawnProcess\n\t\t}));\n\t\tthis.#probeRunner = options.probeRunner ?? ((signal) => probeClaudeCode(command, environment, signal));\n\t\tthis.#startHostedToolBridge = options.startHostedToolBridge ?? startClaudeCodeHostedToolBridge;\n\t}\n\tasync probe(request) {\n\t\tconst issues = [];\n\t\ttry {\n\t\t\tvalidateConfiguration$1(request.configuration);\n\t\t} catch (error) {\n\t\t\tlogger$15.debug({\n\t\t\t\tcode: \"probe_configuration_invalid\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Claude Code probe configuration was rejected\");\n\t\t\tissues.push({\n\t\t\t\tcode: \"configuration_invalid\",\n\t\t\t\tmessage: error.message\n\t\t\t});\n\t\t}\n\t\tlet version;\n\t\ttry {\n\t\t\tconst result = await runWithAbortSignal(this.#probeRunner, request.signal);\n\t\t\tversion = result.version;\n\t\t\tif (!result.streamJson) issues.push({\n\t\t\t\tcode: \"version_incompatible\",\n\t\t\t\tmessage: \"Claude Code stream-json mode is unavailable\"\n\t\t\t});\n\t\t\tif (!result.credential) issues.push({\n\t\t\t\tcode: \"credential_missing\",\n\t\t\t\tmessage: \"Claude Code credentials were not found\"\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (request.signal?.aborted) throw error;\n\t\t\tlogger$15.debug({\n\t\t\t\tcode: \"probe_execution_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Claude Code probe execution failed\");\n\t\t\tconst issue = classifiedProviderProbeIssue(error, \"Claude Code CLI could not be executed\");\n\t\t\tif (!issue) throw error;\n\t\t\tissues.push(issue);\n\t\t}\n\t\treturn {\n\t\t\tready: issues.length === 0,\n\t\t\t...version ? { version } : {},\n\t\t\tissues\n\t\t};\n\t}\n\tcreate(request) {\n\t\treturn this.#open(request, \"create\");\n\t}\n\tresume(request) {\n\t\treturn this.#open(request, \"resume\");\n\t}\n\tasync #open(request, mode) {\n\t\tvalidateFactoryRequest$1(request);\n\t\tvalidateConfiguration$1(request.configuration);\n\t\tconst binding = mode === \"resume\" && \"binding\" in request ? request.binding : claudeCodeBinding(requireUuid(this.#createSessionId(), \"generated Claude Code session id\"));\n\t\tassertBinding(binding, this.manifest);\n\t\tparseClaudeCodeBinding(binding);\n\t\ttry {\n\t\t\tawait request.eventSink({\n\t\t\t\ttype: \"binding_changed\",\n\t\t\t\tbinding\n\t\t\t});\n\t\t\treturn new ClaudeCodeAgentRuntime({\n\t\t\t\tbinding,\n\t\t\t\tconfiguration: request.configuration,\n\t\t\t\tcreateProcess: (args) => this.#createProcess(request.workspace.cwd, args, request.workspace.environment, request.workspace.pathPrepend),\n\t\t\t\temptyNativeToolAllowList: isEmptyNativeToolAllowList(request.policy),\n\t\t\t\teventSink: request.eventSink,\n\t\t\t\thostedTools: request.hostedTools,\n\t\t\t\tresume: mode === \"resume\",\n\t\t\t\tstartHostedToolBridge: this.#startHostedToolBridge,\n\t\t\t\tsystemPrompt: request.systemPrompt\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger$15.debug({\n\t\t\t\tcode: \"runtime_create_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Claude Code runtime creation failed\");\n\t\t\tthrow new AgentRuntimeError(mode === \"create\" ? \"create_failed\" : \"resume_failed\", `Claude Code ${mode} failed`, { cause: error });\n\t\t}\n\t}\n};\nfunction claudeCodeAgentRuntimeEnvironment(source = process.env) {\n\tconst exact = /* @__PURE__ */ new Set([\n\t\t\"APPDATA\",\n\t\t\"CLAUDE_CODE_OAUTH_TOKEN\",\n\t\t\"CLAUDE_CONFIG_DIR\",\n\t\t\"CLAUDE_CODE_USE_BEDROCK\",\n\t\t\"CLAUDE_CODE_USE_FOUNDRY\",\n\t\t\"CLAUDE_CODE_USE_VERTEX\",\n\t\t\"CLOUD_ML_REGION\",\n\t\t\"COMSPEC\",\n\t\t\"GCLOUD_PROJECT\",\n\t\t\"HOME\",\n\t\t\"HTTPS_PROXY\",\n\t\t\"HTTP_PROXY\",\n\t\t\"LANG\",\n\t\t\"LC_ALL\",\n\t\t\"LOCALAPPDATA\",\n\t\t\"LOGNAME\",\n\t\t\"NODE_EXTRA_CA_CERTS\",\n\t\t\"OPENTAG_PROVIDER_ENV_FILE\",\n\t\t\"OPENTAG_HOME\",\n\t\t\"OPENTAG_SESSION_PROOF_FILE\",\n\t\t\"PATH\",\n\t\t\"PATHEXT\",\n\t\t\"SHELL\",\n\t\t\"SSL_CERT_DIR\",\n\t\t\"SSL_CERT_FILE\",\n\t\t\"SystemRoot\",\n\t\t\"TEMP\",\n\t\t\"TMP\",\n\t\t\"TMPDIR\",\n\t\t\"USER\",\n\t\t\"USERPROFILE\",\n\t\t\"WINDIR\",\n\t\t\"https_proxy\",\n\t\t\"http_proxy\"\n\t]);\n\tconst prefixes = [\n\t\t\"ANTHROPIC_\",\n\t\t\"AWS_\",\n\t\t\"GOOGLE_\"\n\t];\n\tconst environment = {};\n\tfor (const [key, value] of Object.entries(source)) if (value !== void 0 && (exact.has(key) || prefixes.some((prefix) => key.startsWith(prefix)))) environment[key] = value;\n\treturn environment;\n}\nasync function probeClaudeCode(command, environment, signal) {\n\tconst execution = {\n\t\tencoding: \"utf8\",\n\t\tenv: environment,\n\t\tsignal,\n\t\ttimeout: 5e3,\n\t\twindowsHide: true\n\t};\n\tconst [versionResult, helpResult] = await Promise.all([execFileAsync$3(command, [\"--version\"], execution), execFileAsync$3(command, [\"--help\"], execution)]);\n\tconst version = versionResult.stdout.trim();\n\tif (!version) throw new Error(\"Claude Code CLI returned no version\");\n\tconst streamJson = helpResult.stdout.includes(\"stream-json\") && helpResult.stdout.includes(\"--session-id\") && helpResult.stdout.includes(\"--resume\") && helpResult.stdout.includes(\"--mcp-config\") && helpResult.stdout.includes(\"--strict-mcp-config\") && helpResult.stdout.includes(\"--allowedTools\") && helpResult.stdout.includes(\"--append-system-prompt\");\n\treturn {\n\t\tcredential: hasCredentialEnvironment(environment) || await probeClaudeCodeCredential(command, execution, signal),\n\t\tstreamJson,\n\t\tversion\n\t};\n}\nasync function probeClaudeCodeCredential(command, execution, signal) {\n\tlet output;\n\ttry {\n\t\toutput = (await execFileAsync$3(command, [\n\t\t\t\"auth\",\n\t\t\t\"status\",\n\t\t\t\"--json\"\n\t\t], execution)).stdout;\n\t} catch (error) {\n\t\tif (signal?.aborted) throw error;\n\t\tlogger$15.debug({\n\t\t\tcode: \"credential_status_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Claude Code credential status command failed\");\n\t\toutput = error.stdout;\n\t}\n\tif (!output) return false;\n\ttry {\n\t\treturn record$1(JSON.parse(output))?.loggedIn === true;\n\t} catch (error) {\n\t\tlogger$15.debug({\n\t\t\tcode: \"credential_status_invalid_json\",\n\t\t\terror: String(error)\n\t\t}, \"Claude Code credential status output was invalid\");\n\t\treturn false;\n\t}\n}\nfunction hasCredentialEnvironment(environment) {\n\tif ([\n\t\t\"ANTHROPIC_API_KEY\",\n\t\t\"ANTHROPIC_AUTH_TOKEN\",\n\t\t\"ANTHROPIC_AWS_API_KEY\",\n\t\t\"ANTHROPIC_FOUNDRY_API_KEY\",\n\t\t\"ANTHROPIC_FOUNDRY_AUTH_TOKEN\",\n\t\t\"AWS_BEARER_TOKEN_BEDROCK\",\n\t\t\"CLAUDE_CODE_OAUTH_TOKEN\",\n\t\t\"GOOGLE_APPLICATION_CREDENTIALS\"\n\t].some((key) => Boolean(environment[key]))) return true;\n\treturn [\n\t\t\"CLAUDE_CODE_USE_BEDROCK\",\n\t\t\"CLAUDE_CODE_USE_FOUNDRY\",\n\t\t\"CLAUDE_CODE_USE_VERTEX\"\n\t].some((key) => environment[key] === \"1\");\n}\nfunction isEmptyNativeToolAllowList(policy) {\n\treturn policy.tools.mode === \"allow-list\" && policy.tools.names.length === 0;\n}\nfunction validateFactoryRequest$1(request) {\n\tif (!request || typeof request !== \"object\" || typeof request.eventSink !== \"function\") throw new AgentRuntimeError(\"configuration_invalid\", \"eventSink is required\");\n\tif (!request.workspace || !isAbsolute(request.workspace.cwd)) throw new AgentRuntimeError(\"configuration_invalid\", \"workspace.cwd must be absolute\");\n\tassertSystemPrompt(request.systemPrompt);\n\tfor (const root of request.workspace.writableRoots ?? []) if (!isAbsolute(root)) throw new AgentRuntimeError(\"configuration_invalid\", \"writable roots must be absolute\");\n\tif (request.policy.approvals !== \"never\") throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code requires approvals=never because interactive control is unsupported\");\n\tif (request.policy.fileSystem !== \"unrestricted\") throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code cannot guarantee a constrained filesystem because managed settings override CLI sandbox settings\");\n\tif (request.policy.network !== \"enabled\") throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code cannot guarantee disabled network because managed settings override CLI sandbox settings\");\n\tif (isEmptyNativeToolAllowList(request.policy)) {\n\t\tif (request.hostedTools) throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code does not implement the common tool allow-list contract\");\n\t} else if (request.policy.tools.mode !== \"provider-default\") throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code does not implement the common tool allow-list contract\");\n\tif (request.hostedTools) assertHostedTools({\n\t\t...request.policy,\n\t\ttools: {\n\t\t\tmode: \"allow-list\",\n\t\t\tnames: request.hostedTools.definitions.map(({ name }) => name)\n\t\t}\n\t}, request.hostedTools);\n}\nfunction validateConfiguration$1(configuration) {\n\tif (!configuration) return;\n\tif (configuration.model !== void 0 && configuration.model.trim().length === 0) throw new AgentRuntimeError(\"configuration_invalid\", \"model must be non-empty\");\n\tif (configuration.reasoningEffort && !getRuntimeConfigurationOptions(\"claude-code\").reasoningEffortAllowedValues.includes(configuration.reasoningEffort)) throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code reasoning effort is unsupported\");\n\tparseProviderConfiguration$1(configuration.provider);\n}\nfunction parseProviderConfiguration$1(value) {\n\tif (value === void 0) return {};\n\tassertJsonValue(value, \"configuration.provider\");\n\tconst object = record$1(value);\n\tif (!object) throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code provider configuration must be an object\");\n\tconst allowed = /* @__PURE__ */ new Set([\n\t\t\"maxBudgetUsd\",\n\t\t\"maxTurns\",\n\t\t\"mcpGateway\"\n\t]);\n\tfor (const key of Object.keys(object)) if (!allowed.has(key)) throw new AgentRuntimeError(\"configuration_invalid\", `unknown Claude Code configuration field: ${key}`);\n\tconst maxBudgetUsd = object.maxBudgetUsd;\n\tif (maxBudgetUsd !== void 0 && (typeof maxBudgetUsd !== \"number\" || !Number.isFinite(maxBudgetUsd) || maxBudgetUsd <= 0)) throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code maxBudgetUsd must be positive\");\n\tconst maxTurns = object.maxTurns;\n\tif (maxTurns !== void 0 && (!Number.isSafeInteger(maxTurns) || maxTurns <= 0)) throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code maxTurns must be a positive safe integer\");\n\tconst mcpGateway = parseMcpGatewayConfiguration$1(object.mcpGateway);\n\treturn {\n\t\t...typeof maxBudgetUsd === \"number\" ? { maxBudgetUsd } : {},\n\t\t...typeof maxTurns === \"number\" ? { maxTurns } : {},\n\t\t...mcpGateway ? { mcpGateway } : {}\n\t};\n}\n/**\n* Validate the MCP gateway descriptor before it reaches a config file.\n*\n* The URL is required to be absolute http(s) here even though this Client composed it itself: this\n* function also runs over a configuration supplied by a caller, and a relative or `file:` URL would\n* otherwise be written into `mcp.json` for the CLI to interpret.\n*/\nfunction parseMcpGatewayConfiguration$1(value) {\n\tif (value === void 0) return void 0;\n\tconst object = record$1(value);\n\tif (!object) throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code mcpGateway must be an object\");\n\tconst url = object.url;\n\tconst token = object.token;\n\tif (typeof url !== \"string\" || typeof token !== \"string\" || token.length === 0) throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code mcpGateway requires a url and a token\");\n\tlet parsed;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\tthrow new AgentRuntimeError(\"configuration_invalid\", \"Claude Code mcpGateway url must be absolute\");\n\t}\n\tif (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") throw new AgentRuntimeError(\"configuration_invalid\", \"Claude Code mcpGateway url must be http or https\");\n\treturn {\n\t\turl,\n\t\ttoken\n\t};\n}\nfunction mergeConfiguration$1(base, override) {\n\tif (!base) {\n\t\tvalidateConfiguration$1(override);\n\t\treturn override;\n\t}\n\tif (!override) return base;\n\tconst merged = {\n\t\t...base,\n\t\t...override,\n\t\tprovider: {\n\t\t\t...parseProviderConfiguration$1(base.provider),\n\t\t\t...parseProviderConfiguration$1(override.provider)\n\t\t}\n\t};\n\tvalidateConfiguration$1(merged);\n\treturn merged;\n}\nfunction claudeCodeInput(request) {\n\treturn {\n\t\ttype: \"user\",\n\t\tmessage: {\n\t\t\trole: \"user\",\n\t\t\tcontent: request.input.items.map((item) => ({\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: item.text\n\t\t\t}))\n\t\t},\n\t\tparent_tool_use_id: null\n\t};\n}\nfunction claudeCodeBinding(sessionId) {\n\treturn {\n\t\tproviderId: CLAUDE_CODE_PROVIDER_ID,\n\t\tschemaVersion: CLAUDE_CODE_BINDING_SCHEMA_VERSION,\n\t\tpayload: { sessionId }\n\t};\n}\nfunction parseClaudeCodeBinding(binding) {\n\tconst payload = record$1(binding.payload);\n\tif (!payload) throw new AgentRuntimeError(\"binding_incompatible\", \"Claude Code binding payload is invalid\");\n\ttry {\n\t\treturn requireUuid(payload.sessionId, \"Claude Code binding sessionId\");\n\t} catch (error) {\n\t\tlogger$15.debug({\n\t\t\tcode: \"binding_invalid\",\n\t\t\terror: String(error)\n\t\t}, \"Claude Code binding was rejected\");\n\t\tthrow new AgentRuntimeError(\"binding_incompatible\", error.message, { cause: error });\n\t}\n}\nfunction parseTerminal(message, expectedSessionId) {\n\tconst sessionId = requireUuid(message.session_id, \"Claude Code result session id\");\n\tif (sessionId !== expectedSessionId) throw protocolError$1(\"Claude Code result belongs to another session\");\n\tconst subtype = requireString$1(message.subtype, \"Claude Code result has no subtype\");\n\tconst isError = message.is_error === true || subtype !== \"success\";\n\tconst errors = Array.isArray(message.errors) ? message.errors.map((error) => requireString$1(error, \"Claude Code result contains an invalid error\")) : [];\n\tconst permissionDenials = Array.isArray(message.permission_denials) ? message.permission_denials.map((item) => requireRecord$2(item, \"Claude Code permission denial is invalid\")) : [];\n\tconst usage = parseUsage$1(message.usage);\n\treturn {\n\t\tsessionId,\n\t\tsubtype,\n\t\tisError,\n\t\terrors,\n\t\tpermissionDenials,\n\t\t...typeof message.result === \"string\" ? { result: message.result } : {},\n\t\t...typeof message.stop_reason === \"string\" ? { stopReason: message.stop_reason } : {},\n\t\t...isNonNegativeNumber$1(message.num_turns) ? { numTurns: message.num_turns } : {},\n\t\t...isNonNegativeNumber$1(message.total_cost_usd) ? { totalCostUsd: message.total_cost_usd } : {},\n\t\t...usage ? { usage } : {}\n\t};\n}\nfunction claudeCodeRunResult(terminal) {\n\tconst output = terminal.result === void 0 ? [] : [{\n\t\ttype: \"text\",\n\t\ttext: terminal.result\n\t}];\n\tconst diagnostics = {\n\t\tproviderSessionId: terminal.sessionId,\n\t\tresultSubtype: terminal.subtype,\n\t\tpermissionDenials: toJsonValue$1(terminal.permissionDenials),\n\t\t...terminal.stopReason ? { stopReason: terminal.stopReason } : {},\n\t\t...terminal.numTurns !== void 0 ? { numTurns: terminal.numTurns } : {},\n\t\t...terminal.totalCostUsd !== void 0 ? { totalCostUsd: terminal.totalCostUsd } : {}\n\t};\n\tif (!terminal.isError) return {\n\t\tstatus: \"completed\",\n\t\toutput,\n\t\t...terminal.usage ? { usage: terminal.usage } : {},\n\t\tdiagnostics\n\t};\n\treturn {\n\t\tstatus: \"failed\",\n\t\toutput,\n\t\t...terminal.usage ? { usage: terminal.usage } : {},\n\t\terror: {\n\t\t\tcode: \"provider_error\",\n\t\t\tmessage: terminal.errors[0] ?? terminal.result ?? `Claude Code failed: ${terminal.subtype}`\n\t\t},\n\t\tdiagnostics\n\t};\n}\nfunction parseUsage$1(value) {\n\tconst source = record$1(value);\n\tif (!source) return void 0;\n\tconst usage = {};\n\tconst inputTokens = isNonNegativeNumber$1(source.input_tokens) ? source.input_tokens : void 0;\n\tconst cacheCreationInputTokens = isNonNegativeNumber$1(source.cache_creation_input_tokens) ? source.cache_creation_input_tokens : void 0;\n\tif (inputTokens !== void 0 || cacheCreationInputTokens !== void 0) {\n\t\tconst total = (inputTokens ?? 0) + (cacheCreationInputTokens ?? 0);\n\t\tif (!Number.isSafeInteger(total)) throw protocolError$1(\"Claude Code input token usage overflowed\");\n\t\tusage.inputTokens = total;\n\t}\n\tif (isNonNegativeNumber$1(source.cache_read_input_tokens)) usage.cachedInputTokens = source.cache_read_input_tokens;\n\tif (isNonNegativeNumber$1(source.output_tokens)) usage.outputTokens = source.output_tokens;\n\treturn Object.keys(usage).length > 0 ? usage : void 0;\n}\nfunction blockKey(messageId, index) {\n\treturn `${messageId}:content:${index}`;\n}\nfunction requireIndex(value) {\n\tif (!Number.isSafeInteger(value) || value < 0) throw protocolError$1(\"Claude Code content block has an invalid index\");\n\treturn value;\n}\nfunction requireUuid(value, field) {\n\tconst result = requireString$1(value, `${field} must be a UUID`);\n\tif (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(result)) throw protocolError$1(`${field} must be a UUID`);\n\treturn result;\n}\nfunction toJsonValue$1(value) {\n\tassertJsonValue(value, \"Claude Code event payload\");\n\treturn value;\n}\nfunction protocolError$1(message) {\n\treturn new AgentProviderError(\"provider_protocol_error\", message);\n}\nfunction record$1(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? value : void 0;\n}\nfunction requireRecord$2(value, message) {\n\tconst result = record$1(value);\n\tif (!result) throw protocolError$1(message);\n\treturn result;\n}\nfunction requireArray(value, message) {\n\tif (!Array.isArray(value)) throw protocolError$1(message);\n\treturn value;\n}\nfunction requireString$1(value, message, allowEmpty = false) {\n\tif (typeof value !== \"string\" || !allowEmpty && value.length === 0 || Buffer.byteLength(value, \"utf8\") > 8388608) throw protocolError$1(message);\n\treturn value;\n}\nfunction isNonNegativeNumber$1(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n//#endregion\n//#region src/providers/codex/app-server-wire.ts\nconst CODEX_APP_SERVER_MAX_LINE_BYTES = 1048576;\nconst CODEX_APP_SERVER_MAX_STDERR_BYTES = 65536;\nconst CODEX_APP_SERVER_REQUEST_TIMEOUT_MS = 6e4;\nvar CodexAppServerError = class extends Error {\n\tcode;\n\terrno;\n\texitCode;\n\tsignal;\n\tkilled;\n\tconstructor(code, message, evidence = {}) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = \"CodexAppServerError\";\n\t\tif (evidence.errno !== void 0) this.errno = evidence.errno;\n\t\tif (evidence.exitCode !== void 0) this.exitCode = evidence.exitCode;\n\t\tif (evidence.signal !== void 0) this.signal = evidence.signal;\n\t\tif (evidence.killed !== void 0) this.killed = evidence.killed;\n\t}\n};\nconst defaultSpawn = (command, args, options) => spawnWatchedProcess(command, args, options);\nvar CodexAppServerProcess = class {\n\t#child;\n\t#expectedCodexHome;\n\t#maxLineBytes;\n\t#maxStderrBytes;\n\t#requestTimeoutMs;\n\t#logger;\n\t#pending = /* @__PURE__ */ new Map();\n\t#listeners = /* @__PURE__ */ new Set();\n\t#serverRequestListeners = /* @__PURE__ */ new Set();\n\t#seenServerRequests = /* @__PURE__ */ new Set();\n\t#pendingServerRequests = /* @__PURE__ */ new Set();\n\t#respondingServerRequests = /* @__PURE__ */ new Set();\n\t#duplicateServerRequests = /* @__PURE__ */ new Set();\n\t#exit;\n\t#resolveExit;\n\t#buffer = Buffer.alloc(0);\n\t#stderr = Buffer.alloc(0);\n\t#nextId = 1;\n\t#closed = false;\n\t#closing = false;\n\t#failure;\n\t#dynamicToolHandler;\n\tconstructor(options) {\n\t\tthis.#expectedCodexHome = options.expectedCodexHome;\n\t\tthis.#maxLineBytes = options.maxLineBytes ?? 1048576;\n\t\tthis.#maxStderrBytes = options.maxStderrBytes ?? 65536;\n\t\tthis.#requestTimeoutMs = options.requestTimeoutMs ?? 6e4;\n\t\tvalidateOptions(this.#maxLineBytes, this.#maxStderrBytes, this.#requestTimeoutMs);\n\t\tthis.#logger = options.logger ?? createLogger(\"provider-codex\");\n\t\tthis.#exit = new Promise((resolve) => {\n\t\t\tthis.#resolveExit = resolve;\n\t\t});\n\t\ttry {\n\t\t\tthis.#child = (options.spawnProcess ?? defaultSpawn)(options.command ?? \"codex\", options.args ?? [\"app-server\", \"--stdio\"], {\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tenv: options.env,\n\t\t\t\tdetached: process.platform !== \"win32\"\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"spawn_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Codex App Server process spawn failed\");\n\t\t\tthrow new CodexAppServerError(\"spawn\", error instanceof Error ? error.message : \"Codex could not be started\", spawnEvidence(error));\n\t\t}\n\t\tthis.#child.stdout.on(\"data\", (chunk) => this.#onStdout(chunk));\n\t\tthis.#child.stderr.on(\"data\", (chunk) => this.#onStderr(chunk));\n\t\tthis.#child.on(\"error\", (error) => this.#fail(new CodexAppServerError(\"spawn\", error.message, spawnEvidence(error))));\n\t\tthis.#child.on(\"exit\", (exitCode, signal) => {\n\t\t\tthis.#closed = true;\n\t\t\tthis.#resolveExit?.();\n\t\t\tthis.#resolveExit = void 0;\n\t\t\tif (!this.#failure && !this.#closing) {\n\t\t\t\tconst error = this.#buffer.byteLength > 0 ? new CodexAppServerError(\"protocol\", this.#exitMessage(\"Codex exited with a truncated JSONL line\")) : new CodexAppServerError(\"exited\", this.#exitMessage(), {\n\t\t\t\t\texitCode,\n\t\t\t\t\tsignal\n\t\t\t\t});\n\t\t\t\tthis.#fail(error);\n\t\t\t}\n\t\t});\n\t}\n\tget pid() {\n\t\treturn this.#child.pid;\n\t}\n\tsubscribe(listener) {\n\t\tthis.#listeners.add(listener);\n\t\treturn () => this.#listeners.delete(listener);\n\t}\n\tsetDynamicToolHandler(handler) {\n\t\tthis.#dynamicToolHandler = handler;\n\t}\n\tsubscribeServerRequests(listener) {\n\t\tthis.#serverRequestListeners.add(listener);\n\t\treturn () => this.#serverRequestListeners.delete(listener);\n\t}\n\tasync respondServerRequest(id, result) {\n\t\tawait this.#writeServerResponse(id, {\n\t\t\tid,\n\t\t\tresult\n\t\t});\n\t}\n\tasync rejectServerRequest(id, code, message) {\n\t\tawait this.#writeServerResponse(id, {\n\t\t\tid,\n\t\t\terror: {\n\t\t\t\tcode,\n\t\t\t\tmessage\n\t\t\t}\n\t\t});\n\t}\n\tasync initialize(clientVersion, signal) {\n\t\tconst initialized = requireRecord$1(await this.request(\"initialize\", {\n\t\t\tclientInfo: {\n\t\t\t\tname: \"opentag\",\n\t\t\t\ttitle: \"OpenTag\",\n\t\t\t\tversion: clientVersion\n\t\t\t},\n\t\t\tcapabilities: { experimentalApi: true }\n\t\t}, signal), \"Codex returned an invalid initialize response\");\n\t\trequireBoundedString(initialized.userAgent, \"Codex initialize response has no user agent\");\n\t\trequireBoundedString(initialized.platformFamily, \"Codex initialize response has no platform family\");\n\t\trequireBoundedString(initialized.platformOs, \"Codex initialize response has no platform OS\");\n\t\tconst codexHome = requireBoundedString(initialized.codexHome, \"Codex initialize response has no Home\");\n\t\tif (this.#expectedCodexHome && codexHome !== this.#expectedCodexHome) throw new CodexAppServerError(\"protocol\", \"Codex initialized with an unexpected Home\");\n\t\tawait this.notify(\"initialized\", {});\n\t}\n\trequest(method, params, signal) {\n\t\tif (this.#closed || this.#failure) return Promise.reject(this.#failure ?? new CodexAppServerError(\"exited\", \"Codex App Server is closed\"));\n\t\tif (signal?.aborted) return Promise.reject(new CodexAppServerError(\"aborted\", \"Codex request was aborted\"));\n\t\tconst id = this.#nextId;\n\t\tthis.#nextId += 1;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tconst pending = this.#pending.get(id);\n\t\t\t\t/* v8 ignore else -- cleanup only runs while its own pending entry is registered. */\n\t\t\t\tif (pending) clearTimeout(pending.timer);\n\t\t\t\tthis.#pending.delete(id);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new CodexAppServerError(\"aborted\", \"Codex request was aborted\"));\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\treject(new CodexAppServerError(\"timeout\", `Codex request timed out: ${method}`));\n\t\t\t}, this.#requestTimeoutMs);\n\t\t\ttimer.unref();\n\t\t\tthis.#pending.set(id, {\n\t\t\t\ttimer,\n\t\t\t\tresolve: (value) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tthis.#write({\n\t\t\t\tid,\n\t\t\t\tmethod,\n\t\t\t\tparams\n\t\t\t}).catch((error) => {\n\t\t\t\tthis.#pending.get(id)?.reject(error);\n\t\t\t});\n\t\t});\n\t}\n\tnotify(method, params) {\n\t\treturn this.#write({\n\t\t\tmethod,\n\t\t\tparams\n\t\t});\n\t}\n\tasync interrupt(threadId, turnId) {\n\t\tawait this.request(\"turn/interrupt\", {\n\t\t\tthreadId,\n\t\t\tturnId\n\t\t}, AbortSignal.timeout(2e3));\n\t}\n\tasync close(graceMs = 1e3) {\n\t\tif (this.#closed) return;\n\t\tthis.#closing = true;\n\t\tthis.#closed = true;\n\t\tconst closingError = new CodexAppServerError(\"aborted\", \"Codex App Server is closing\");\n\t\tfor (const pending of [...this.#pending.values()]) pending.reject(closingError);\n\t\tthis.#seenServerRequests.clear();\n\t\tthis.#pendingServerRequests.clear();\n\t\tthis.#respondingServerRequests.clear();\n\t\tthis.#duplicateServerRequests.clear();\n\t\tthis.#child.stdin.end();\n\t\tsignalWatchedProcess(this.#child, \"SIGTERM\");\n\t\tif (await settlesWithin(this.#exit, graceMs)) return;\n\t\tsignalWatchedProcess(this.#child, \"SIGKILL\");\n\t\tif (!await settlesWithin(this.#exit, graceMs)) throw new CodexAppServerError(\"exited\", \"Codex App Server process tree did not exit\");\n\t}\n\tasync #write(message) {\n\t\tif (this.#closed || this.#failure || !this.#child.stdin.writable) throw this.#failure ?? new CodexAppServerError(\"write\", \"Codex App Server stdin is unavailable\");\n\t\tconst line = `${JSON.stringify(message)}\\n`;\n\t\tif (Buffer.byteLength(line, \"utf8\") > this.#maxLineBytes) throw new CodexAppServerError(\"protocol\", \"Codex request exceeds the JSONL line limit\");\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tthis.#child.stdin.write(line, (error) => {\n\t\t\t\terror ? reject(new CodexAppServerError(\"write\", \"Codex request could not be written\")) : resolve();\n\t\t\t});\n\t\t});\n\t}\n\tasync #writeServerResponse(id, message) {\n\t\tif (!this.#pendingServerRequests.has(id) || this.#respondingServerRequests.has(id)) throw new CodexAppServerError(\"protocol\", \"Codex server request is unknown or already resolved\");\n\t\tthis.#respondingServerRequests.add(id);\n\t\ttry {\n\t\t\tawait this.#write(message);\n\t\t\tthis.#pendingServerRequests.delete(id);\n\t\t} finally {\n\t\t\tthis.#respondingServerRequests.delete(id);\n\t\t}\n\t}\n\t#onStdout(chunk) {\n\t\tif (this.#failure || this.#closed) return;\n\t\tthis.#buffer = Buffer.concat([this.#buffer, chunk]);\n\t\tif (this.#buffer.byteLength > this.#maxLineBytes && !this.#buffer.includes(10)) {\n\t\t\tthis.#fail(new CodexAppServerError(\"protocol\", \"Codex emitted an oversized JSONL line\"));\n\t\t\treturn;\n\t\t}\n\t\twhile (true) {\n\t\t\tconst newline = this.#buffer.indexOf(10);\n\t\t\tif (newline < 0) break;\n\t\t\tconst line = this.#buffer.subarray(0, newline);\n\t\t\tthis.#buffer = this.#buffer.subarray(newline + 1);\n\t\t\tif (line.byteLength === 0) continue;\n\t\t\tif (line.byteLength > this.#maxLineBytes) {\n\t\t\t\tthis.#fail(new CodexAppServerError(\"protocol\", \"Codex emitted an oversized JSONL line\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet message;\n\t\t\ttry {\n\t\t\t\tmessage = JSON.parse(line.toString(\"utf8\"));\n\t\t\t} catch {\n\t\t\t\tthis.#logger.debug({ code: \"stdout_malformed_json\" }, \"Codex protocol output was rejected\");\n\t\t\t\tthis.#fail(new CodexAppServerError(\"protocol\", \"Codex emitted malformed JSONL\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!isRecord$4(message)) {\n\t\t\t\tthis.#fail(new CodexAppServerError(\"protocol\", \"Codex emitted an invalid protocol message\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.#onMessage(message);\n\t\t\tif (this.#failure || this.#closed) return;\n\t\t}\n\t\tif (this.#buffer.byteLength > this.#maxLineBytes) this.#fail(new CodexAppServerError(\"protocol\", \"Codex emitted an oversized JSONL line\"));\n\t}\n\t#onStderr(chunk) {\n\t\tif (chunk.byteLength >= this.#maxStderrBytes) {\n\t\t\tthis.#stderr = Buffer.from(chunk.subarray(chunk.byteLength - this.#maxStderrBytes));\n\t\t\treturn;\n\t\t}\n\t\tconst combined = Buffer.concat([this.#stderr, chunk]);\n\t\tthis.#stderr = combined.byteLength > this.#maxStderrBytes ? combined.subarray(combined.byteLength - this.#maxStderrBytes) : combined;\n\t}\n\t#exitMessage(prefix = \"Codex App Server exited\") {\n\t\tconst stderr = this.#stderr.toString(\"utf8\").trim();\n\t\treturn stderr ? `${prefix}: ${stderr}` : prefix;\n\t}\n\t#onMessage(message) {\n\t\tif (typeof message.id === \"number\" && !Number.isNaN(message.id) && !(\"method\" in message)) {\n\t\t\tconst pending = this.#pending.get(message.id);\n\t\t\tif (!pending) {\n\t\t\t\tthis.#fail(new CodexAppServerError(\"protocol\", \"Codex emitted an unknown or duplicate response ID\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (message.error !== void 0) {\n\t\t\t\tconst error = isRecord$4(message.error) ? message.error : void 0;\n\t\t\t\tconst detail = typeof error?.message === \"string\" ? `: ${error.message}` : \"\";\n\t\t\t\tpending.reject(new CodexAppServerError(\"protocol\", `Codex returned a request error${detail}`));\n\t\t\t} else pending.resolve(message.result);\n\t\t\treturn;\n\t\t}\n\t\tif ((typeof message.id === \"number\" || typeof message.id === \"string\") && typeof message.method === \"string\") {\n\t\t\tif (message.method === \"item/tool/call\") {\n\t\t\t\tif (!this.#claimServerRequest(message.id, true)) return;\n\t\t\t\tthis.#dispatchAutomaticServerRequest(message.id, message.method, message.params);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this.#serverRequestListeners.size > 0) {\n\t\t\t\tif (!this.#claimServerRequest(message.id, false)) return;\n\t\t\t\tconst request = {\n\t\t\t\t\tid: message.id,\n\t\t\t\t\tmethod: message.method,\n\t\t\t\t\tparams: message.params\n\t\t\t\t};\n\t\t\t\tfor (const listener of this.#serverRequestListeners) try {\n\t\t\t\t\tlistener(request);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.#logger.debug({\n\t\t\t\t\t\tcode: \"server_request_listener_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Codex server request listener failed\");\n\t\t\t\t\tthis.#pendingServerRequests.delete(message.id);\n\t\t\t\t\tthis.#fail(new CodexAppServerError(\"protocol\", \"A Codex server request listener failed\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!this.#claimServerRequest(message.id, false)) return;\n\t\t\tthis.#dispatchAutomaticServerRequest(message.id, message.method, message.params);\n\t\t\treturn;\n\t\t}\n\t\tif (typeof message.method !== \"string\" || !(\"params\" in message)) {\n\t\t\tthis.#fail(new CodexAppServerError(\"protocol\", \"Codex emitted an unknown protocol message\"));\n\t\t\treturn;\n\t\t}\n\t\tfor (const listener of this.#listeners) try {\n\t\t\tlistener(message);\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"protocol_listener_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Codex protocol listener failed\");\n\t\t\tthis.#fail(new CodexAppServerError(\"protocol\", \"A Codex protocol listener rejected a message\"));\n\t\t\treturn;\n\t\t}\n\t}\n\tasync #handleServerRequest(id, method, params) {\n\t\tif (method === \"item/commandExecution/requestApproval\" || method === \"item/fileChange/requestApproval\") {\n\t\t\tawait this.respondServerRequest(id, { decision: \"cancel\" }).catch(\n\t\t\t\t/* v8 ignore next -- best-effort responses on a wire that may already be closing. */\n\t\t\t\t(error) => {\n\t\t\t\t\tthis.#logger.debug({\n\t\t\t\t\t\tcode: \"approval_response_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Codex approval response failed\");\n\t\t\t\t}\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"item/tool/requestUserInput\") {\n\t\t\tawait this.respondServerRequest(id, { answers: {} }).catch(\n\t\t\t\t/* v8 ignore next -- best-effort responses on a wire that may already be closing. */\n\t\t\t\t(error) => {\n\t\t\t\t\tthis.#logger.debug({\n\t\t\t\t\t\tcode: \"user_input_response_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Codex user input response failed\");\n\t\t\t\t}\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"item/tool/call\") {\n\t\t\tconst handler = this.#dynamicToolHandler;\n\t\t\tif (!handler) {\n\t\t\t\tawait this.respondServerRequest(id, {\n\t\t\t\t\tcontentItems: [{\n\t\t\t\t\t\ttype: \"inputText\",\n\t\t\t\t\t\ttext: \"OpenTag tool is unavailable.\"\n\t\t\t\t\t}],\n\t\t\t\t\tsuccess: false\n\t\t\t\t}).catch(\n\t\t\t\t\t/* v8 ignore next -- best-effort responses on a wire that may already be closing. */\n\t\t\t\t\t(error) => {\n\t\t\t\t\t\tthis.#logger.debug({\n\t\t\t\t\t\t\tcode: \"tool_unavailable_response_failed\",\n\t\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t\t}, \"Codex unavailable tool response failed\");\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await handler(parseDynamicToolCall(params));\n\t\t\t\tconst text = requireBoundedString(result.text, \"OpenTag tool returned invalid output\");\n\t\t\t\tawait this.respondServerRequest(id, {\n\t\t\t\t\tcontentItems: [{\n\t\t\t\t\t\ttype: \"inputText\",\n\t\t\t\t\t\ttext\n\t\t\t\t\t}],\n\t\t\t\t\tsuccess: result.success\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tcode: \"tool_request_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Codex dynamic tool request failed\");\n\t\t\t\tawait this.respondServerRequest(id, {\n\t\t\t\t\tcontentItems: [{\n\t\t\t\t\t\ttype: \"inputText\",\n\t\t\t\t\t\ttext: \"OpenTag tool request failed.\"\n\t\t\t\t\t}],\n\t\t\t\t\tsuccess: false\n\t\t\t\t}).catch(\n\t\t\t\t\t/* v8 ignore next -- best-effort responses on a wire that may already be closing. */\n\t\t\t\t\t(responseError) => {\n\t\t\t\t\t\tthis.#logger.debug({\n\t\t\t\t\t\t\tcode: \"tool_error_response_failed\",\n\t\t\t\t\t\t\terror: String(responseError)\n\t\t\t\t\t\t}, \"Codex dynamic tool error response failed\");\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tawait this.rejectServerRequest(id, -32601, \"Unsupported unattended server request\").catch(\n\t\t\t/* v8 ignore next -- best-effort responses on a wire that may already be closing. */\n\t\t\t(error) => {\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tcode: \"unsupported_request_response_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Codex unsupported request response failed\");\n\t\t\t}\n\t\t);\n\t\tthis.#fail(new CodexAppServerError(\"protocol\", `Codex requested an unsupported method: ${method}`));\n\t}\n\t#claimServerRequest(id, deferDuplicateFailure) {\n\t\tif (!this.#seenServerRequests.has(id)) {\n\t\t\tthis.#seenServerRequests.add(id);\n\t\t\tthis.#pendingServerRequests.add(id);\n\t\t\treturn true;\n\t\t}\n\t\tif (deferDuplicateFailure && this.#pendingServerRequests.has(id)) this.#duplicateServerRequests.add(id);\n\t\telse this.#fail(new CodexAppServerError(\"protocol\", \"Codex emitted a duplicate server request ID\"));\n\t\treturn false;\n\t}\n\t#dispatchAutomaticServerRequest(id, method, params) {\n\t\tthis.#handleServerRequest(id, method, params).finally(() => {\n\t\t\tthis.#pendingServerRequests.delete(id);\n\t\t\tif (!this.#duplicateServerRequests.delete(id) || this.#failure) return;\n\t\t\tsetTimeout(() => this.#fail(new CodexAppServerError(\"protocol\", \"Codex emitted a duplicate server request ID\")), 10).unref();\n\t\t});\n\t}\n\t#fail(error) {\n\t\tif (this.#failure) return;\n\t\tthis.#failure = error;\n\t\tfor (const pending of [...this.#pending.values()]) pending.reject(error);\n\t\tthis.#seenServerRequests.clear();\n\t\tthis.#pendingServerRequests.clear();\n\t\tthis.#respondingServerRequests.clear();\n\t\tthis.#duplicateServerRequests.clear();\n\t\tfor (const listener of this.#listeners) try {\n\t\t\tlistener({\n\t\t\t\tmethod: \"opentag/processError\",\n\t\t\t\tparams: { error }\n\t\t\t});\n\t\t} catch (listenerError) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"process_error_listener_failed\",\n\t\t\t\terror: String(listenerError)\n\t\t\t}, \"Codex process error listener failed\");\n\t\t}\n\t\tif (!this.#closed) {\n\t\t\tsignalWatchedProcess(this.#child, \"SIGTERM\");\n\t\t\tsetTimeout(() => {\n\t\t\t\t/* v8 ignore else -- the SIGKILL escalation timer only matters while the child is still open. */\n\t\t\t\tif (!this.#closed) signalWatchedProcess(this.#child, \"SIGKILL\");\n\t\t\t}, 1e3).unref();\n\t\t}\n\t}\n};\nfunction parseDynamicToolCall(value) {\n\tconst params = requireRecord$1(value, \"Codex returned invalid dynamic tool parameters\");\n\tconst namespace = params.namespace;\n\tif (namespace !== null && typeof namespace !== \"string\") throw new CodexAppServerError(\"protocol\", \"Codex returned invalid dynamic tool namespace\");\n\treturn {\n\t\targuments: params.arguments,\n\t\tcallId: requireBoundedString(params.callId, \"Codex returned invalid dynamic tool call ID\"),\n\t\tnamespace,\n\t\tthreadId: requireBoundedString(params.threadId, \"Codex returned invalid dynamic tool Thread ID\"),\n\t\ttool: requireBoundedString(params.tool, \"Codex returned invalid dynamic tool name\"),\n\t\tturnId: requireBoundedString(params.turnId, \"Codex returned invalid dynamic tool Turn ID\")\n\t};\n}\nasync function settlesWithin(promise, milliseconds) {\n\tlet timer;\n\tconst timeout = new Promise((resolve) => {\n\t\ttimer = setTimeout(() => resolve(false), milliseconds);\n\t\ttimer.unref();\n\t});\n\tconst settled = await Promise.race([promise.then(() => true), timeout]);\n\t/* v8 ignore else -- the timer is always armed before the race settles. */\n\tif (timer) clearTimeout(timer);\n\treturn settled;\n}\nfunction spawnEvidence(error) {\n\tconst code = error?.code;\n\treturn typeof code === \"string\" ? { errno: code } : {};\n}\nfunction validateOptions(maxLineBytes, maxStderrBytes, requestTimeoutMs) {\n\tif (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1024) throw new Error(\"maxLineBytes must be a safe integer of at least 1024\");\n\tif (!Number.isSafeInteger(requestTimeoutMs) || requestTimeoutMs < 1) throw new Error(\"requestTimeoutMs must be a positive safe integer\");\n\tif (!Number.isSafeInteger(maxStderrBytes) || maxStderrBytes < 0) throw new Error(\"maxStderrBytes must be a non-negative safe integer\");\n}\nfunction isRecord$4(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction requireRecord$1(value, message) {\n\tif (!isRecord$4(value)) throw new CodexAppServerError(\"protocol\", message);\n\treturn value;\n}\nfunction requireBoundedString(value, message) {\n\tif (typeof value !== \"string\" || value.length === 0 || Buffer.byteLength(value, \"utf8\") > 4096) throw new CodexAppServerError(\"protocol\", message);\n\treturn value;\n}\n//#endregion\n//#region src/providers/codex/agent-runtime.ts\nconst execFileAsync$2 = promisify(execFile);\nconst CODEX_BINDING_SCHEMA_VERSION = 1;\nconst CODEX_PROVIDER_ID = \"codex\";\nconst logger$14 = createLogger(\"provider-codex-runtime\");\nconst CODEX_CAPABILITY_PROBE_INSTRUCTIONS = \"OpenTag Provider prompt-surface capability probe.\";\n/** One deadline for rebinding a thread to a run's MCP gateway; a slow gateway must not stall a turn. */\nconst CODEX_MCP_ATTACH_TIMEOUT_MS = 15e3;\n/**\n* The share of that deadline the attach itself may use. The rest is reserved for restoring the\n* thread without MCP, so a timed-out attach still leaves time to recover the turn.\n*/\nconst CODEX_MCP_ATTACH_BUDGET_SHARE = 2 / 3;\n/** Codex's own MCP startup bound, kept inside the attach deadline. */\nconst CODEX_MCP_STARTUP_TIMEOUT_SEC = 10;\nconst CODEX_AGENT_RUNTIME_APP_SERVER_ARGS = [\n\t\"app-server\",\n\t\"--stdio\",\n\t\"--disable\",\n\t\"apps\",\n\t\"--disable\",\n\t\"auth_elicitation\",\n\t\"--disable\",\n\t\"browser_use\",\n\t\"--disable\",\n\t\"browser_use_external\",\n\t\"--disable\",\n\t\"browser_use_full_cdp_access\",\n\t\"--disable\",\n\t\"computer_use\",\n\t\"--disable\",\n\t\"goals\",\n\t\"--disable\",\n\t\"hooks\",\n\t\"--disable\",\n\t\"image_generation\",\n\t\"--disable\",\n\t\"in_app_browser\",\n\t\"--disable\",\n\t\"multi_agent\",\n\t\"--disable\",\n\t\"plugins\",\n\t\"--disable\",\n\t\"remote_plugin\",\n\t\"--disable\",\n\t\"shell_snapshot\",\n\t\"--disable\",\n\t\"skill_mcp_dependency_install\",\n\t\"--disable\",\n\t\"tool_call_mcp_elicitation\",\n\t\"-c\",\n\t\"mcp_servers={}\",\n\t\"-c\",\n\t\"web_search=\\\"disabled\\\"\",\n\t\"-c\",\n\t\"tools.view_image=false\",\n\t\"-c\",\n\t\"memories.use_memories=false\",\n\t\"-c\",\n\t\"memories.generate_memories=false\",\n\t\"-c\",\n\t\"allow_login_shell=false\",\n\t\"-c\",\n\t\"shell_environment_policy.inherit=\\\"all\\\"\",\n\t\"-c\",\n\t\"shell_environment_policy.filters={ PATH = \\\"include\\\", ZDOTDIR = \\\"include\\\", LANG = \\\"include\\\", LC_ALL = \\\"include\\\", OPENTAG_HOME = \\\"include\\\", OPENTAG_PROVIDER_ENV_FILE = \\\"include\\\", OPENTAG_SESSION_PROOF_FILE = \\\"include\\\" }\"\n];\nconst TOOL_ITEM_TYPES = /* @__PURE__ */ new Set([\n\t\"collabToolCall\",\n\t\"commandExecution\",\n\t\"dynamicToolCall\",\n\t\"fileChange\",\n\t\"imageView\",\n\t\"mcpToolCall\",\n\t\"webSearch\"\n]);\nconst CODEX_AGENT_RUNTIME_MANIFEST = Object.freeze({\n\tproviderId: CODEX_PROVIDER_ID,\n\tdisplayName: \"Codex\",\n\tcontractVersion: 2,\n\tbindingSchemaVersion: CODEX_BINDING_SCHEMA_VERSION\n});\nvar CodexAgentRuntime = class extends BaseAgentRuntime {\n\t#client;\n\t#threadId;\n\t#workspace;\n\t#policy;\n\t#configuration;\n\t#hostedTools;\n\t#threadParams;\n\t#threadStartParams;\n\t/** Codex writes a thread's rollout only once a turn starts; until then it cannot be resumed. */\n\t#threadPersisted;\n\t#mcpAttachTimeoutMs;\n\t/**\n\t* Whether the loaded thread may hold MCP state other than \"none\": a gateway catalogue, or an\n\t* interrupted rebind that may have left the thread unloaded. The next run rebinds it either way.\n\t*/\n\t#mcpThreadDirty = false;\n\t/** Present only between run admission and `turn/start`, when there is no provider turn to interrupt. */\n\t#preTurnAbort;\n\t#unsubscribeNotifications;\n\t#unsubscribeRequests;\n\t#wireInteractions = /* @__PURE__ */ new Map();\n\t#completedMessages = /* @__PURE__ */ new Map();\n\t#activeMessages = /* @__PURE__ */ new Map();\n\t#activeTools = /* @__PURE__ */ new Map();\n\t#hostedToolCalls = /* @__PURE__ */ new Map();\n\t#eventTail = Promise.resolve();\n\t#buffering = false;\n\t#buffered = [];\n\t#context;\n\t#providerTurnId;\n\t#turnIdReady;\n\t#terminal;\n\t#latestUsage;\n\t#providerFailure;\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tmanifest: CODEX_AGENT_RUNTIME_MANIFEST,\n\t\t\tcapabilities: {\n\t\t\t\tsteer: \"supported\",\n\t\t\t\tinteractions: \"supported\"\n\t\t\t},\n\t\t\teventSink: options.eventSink,\n\t\t\tbinding: options.binding\n\t\t});\n\t\tthis.#client = options.client;\n\t\tthis.#threadId = options.threadId;\n\t\tthis.#workspace = options.workspace;\n\t\tthis.#policy = options.policy;\n\t\tthis.#configuration = options.configuration;\n\t\tthis.#hostedTools = options.hostedTools;\n\t\tthis.#threadParams = options.threadParams;\n\t\tthis.#threadStartParams = options.threadStartParams;\n\t\tthis.#threadPersisted = options.threadPersisted;\n\t\tthis.#mcpAttachTimeoutMs = options.mcpAttachTimeoutMs;\n\t\tthis.#client.setDynamicToolHandler?.((call) => this.#handleHostedTool(call));\n\t\tthis.#unsubscribeNotifications = this.#client.subscribe((message) => {\n\t\t\tthis.#enqueue({\n\t\t\t\ttype: \"notification\",\n\t\t\t\tmessage\n\t\t\t});\n\t\t});\n\t\tthis.#unsubscribeRequests = this.#client.subscribeServerRequests((request) => {\n\t\t\tthis.#enqueue({\n\t\t\t\ttype: \"request\",\n\t\t\t\trequest\n\t\t\t});\n\t\t});\n\t}\n\tasync executeRun(request, context) {\n\t\tthis.#context = context;\n\t\tthis.#providerTurnId = void 0;\n\t\tthis.#providerFailure = void 0;\n\t\tthis.#latestUsage = void 0;\n\t\tthis.#completedMessages.clear();\n\t\tthis.#activeMessages.clear();\n\t\tthis.#activeTools.clear();\n\t\tthis.#wireInteractions.clear();\n\t\tthis.#buffered = [];\n\t\tthis.#buffering = true;\n\t\tthis.#turnIdReady = deferred();\n\t\tthis.#terminal = deferred();\n\t\tthis.#turnIdReady.promise.catch(() => void 0);\n\t\tthis.#terminal.promise.catch(() => void 0);\n\t\tconst preTurnAbort = new AbortController();\n\t\tthis.#preTurnAbort = preTurnAbort;\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tawait this.#attachMcpGateway(request, context, AbortSignal.any([context.signal, preTurnAbort.signal]));\n\t\t\t} catch (error) {\n\t\t\t\tif (!preTurnAbort.signal.aborted) throw error;\n\t\t\t}\n\t\t\tif (preTurnAbort.signal.aborted) return {\n\t\t\t\tstatus: \"aborted\",\n\t\t\t\toutput: [],\n\t\t\t\terror: {\n\t\t\t\t\tcode: \"run_aborted\",\n\t\t\t\t\tmessage: \"Codex run was aborted before its turn started\"\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.#preTurnAbort = void 0;\n\t\t\tconst response = await this.#client.request(\"turn/start\", this.#turnStartParams(request));\n\t\t\tthis.#threadPersisted = true;\n\t\t\tconst started = parseTurnResponse(response, \"turn/start\");\n\t\t\tif (started.status !== \"inProgress\") throw protocolError(\"turn/start returned a terminal turn\");\n\t\t\tthis.#providerTurnId = started.id;\n\t\t\tthis.#turnIdReady.resolve(started.id);\n\t\t\tthis.#buffering = false;\n\t\t\tconst buffered = this.#buffered.splice(0);\n\t\t\tfor (const envelope of buffered) this.#enqueue(envelope);\n\t\t\tawait this.#eventTail;\n\t\t\tif (this.#providerFailure) throw this.#providerFailure;\n\t\t\tconst terminal = await this.#terminal.promise;\n\t\t\tawait this.#eventTail;\n\t\t\tif (this.#providerFailure) throw this.#providerFailure;\n\t\t\tawait this.#completeOpenLifecycles(terminal);\n\t\t\treturn this.#runResult(terminal);\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : /* @__PURE__ */ new Error(\"Codex run failed\");\n\t\t\tlogger$14.debug({\n\t\t\t\tcode: \"provider_run_failed\",\n\t\t\t\terror: failure.message\n\t\t\t}, \"Codex provider run failed\");\n\t\t\tthis.#turnIdReady.reject(failure);\n\t\t\tthrow failure;\n\t\t} finally {\n\t\t\tthis.#preTurnAbort = void 0;\n\t\t\tthis.#buffering = false;\n\t\t\tthis.#buffered = [];\n\t\t\tthis.#context = void 0;\n\t\t\tthis.#providerTurnId = void 0;\n\t\t\tthis.#turnIdReady = void 0;\n\t\t\tthis.#terminal = void 0;\n\t\t\tthis.#wireInteractions.clear();\n\t\t\tthis.#hostedToolCalls.clear();\n\t\t}\n\t}\n\tasync steerProvider(request) {\n\t\tconst turnId = await this.#activeTurnId();\n\t\tif (requireString(requireRecord(await this.#client.request(\"turn/steer\", {\n\t\t\tthreadId: this.#threadId,\n\t\t\tinput: codexInput(request.input.items),\n\t\t\texpectedTurnId: turnId\n\t\t}), \"turn/steer returned an invalid response\").turnId, \"turn/steer returned no turnId\") !== turnId) throw protocolError(\"turn/steer accepted another turn\");\n\t}\n\tasync respondProvider(response) {\n\t\tconst request = this.#wireInteractions.get(response.requestId);\n\t\t/* v8 ignore next -- Base and the serial Codex envelope queue fence this map with the public interaction. */\n\t\tif (!request) throw new AgentRuntimeError(\"interaction_not_found\", \"Codex interaction is no longer pending\");\n\t\tconst result = codexInteractionResult(request.method, response);\n\t\tawait this.#client.respondServerRequest(request.id, result);\n\t\tthis.#wireInteractions.delete(response.requestId);\n\t}\n\tasync abortProvider(request) {\n\t\tif (this.#preTurnAbort) {\n\t\t\tthis.#preTurnAbort.abort();\n\t\t\treturn;\n\t\t}\n\t\tconst turnId = await this.#activeTurnId();\n\t\t/* v8 ignore next 3 -- Base validates expectedRunId before entering the Provider hook. */\n\t\tif (request.expectedRunId !== this.#context?.runId) throw new AgentRuntimeError(\"run_mismatch\", \"abort no longer belongs to the active Codex turn\");\n\t\tawait this.#client.interrupt(this.#threadId, turnId);\n\t}\n\tasync closeProvider() {\n\t\tif (this.#context) {\n\t\t\tconst failure = new AgentProviderError(\"provider_error\", \"Codex runtime is closing\");\n\t\t\tthis.#providerFailure ??= failure;\n\t\t\tthis.#terminal?.reject(failure);\n\t\t\tthis.#turnIdReady?.reject(failure);\n\t\t}\n\t\tthis.#unsubscribeRequests();\n\t\tthis.#unsubscribeNotifications();\n\t\tthis.#client.setDynamicToolHandler?.(void 0);\n\t\tawait this.#client.close();\n\t}\n\t/**\n\t* Rebind the thread to this run's MCP gateway, or to none, before the turn starts.\n\t*\n\t* Codex spawns one App Server per Session, but the gateway bearer is minted per execution. Codex\n\t* applies a thread's `config` overrides only when it loads the thread, so the thread is reloaded\n\t* with the run's `mcp_servers`. The bearer travels over the App Server's stdio and is held only in\n\t* its memory: never in its argument vector, environment, or a config file, so what a model command\n\t* can reach is at most the live execution's own bearer, which the Server revokes when the\n\t* execution ends. A run without a gateway rebinds only when the thread may still hold one.\n\t*\n\t* One deadline covers the whole rebind, attach and restore alike. The attach may use only part of\n\t* it, so a timed-out attach still leaves the restore time to finish. Losing the gateway never costs\n\t* the Agent its turn: an unconfirmed attach leaves the thread with no MCP server rather than with\n\t* the run's bearer attached to a catalogue it did not confirm. Only a thread Codex cannot reload at\n\t* all within the deadline fails the run, because there is no thread left to start the turn on.\n\t*/\n\tasync #attachMcpGateway(request, context, signal) {\n\t\tconst endpoint = parseProviderConfiguration(mergeConfiguration(this.#configuration, request.configuration)?.provider).mcpGateway;\n\t\tif (!endpoint && !this.#mcpThreadDirty) return;\n\t\tconst startedAt = Date.now();\n\t\tconst wasDirty = this.#mcpThreadDirty;\n\t\tthis.#mcpThreadDirty = true;\n\t\tconst deadline = AbortSignal.any([signal, AbortSignal.timeout(this.#mcpAttachTimeoutMs)]);\n\t\tconst attachBudgetMs = Math.floor(this.#mcpAttachTimeoutMs * CODEX_MCP_ATTACH_BUDGET_SHARE);\n\t\ttry {\n\t\t\tawait this.#rebindThread(codexMcpServersConfig(endpoint), context, AbortSignal.any([deadline, AbortSignal.timeout(attachBudgetMs)]));\n\t\t\tthis.#mcpThreadDirty = endpoint !== void 0;\n\t\t\tlogger$14.info({\n\t\t\t\tattached: endpoint !== void 0,\n\t\t\t\tdurationMs: Date.now() - startedAt\n\t\t\t}, \"Codex thread rebound to the run's MCP gateway\");\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tif (signal.aborted) throw error;\n\t\t\tlogger$14.warn({\n\t\t\t\tcode: \"mcp_attach_failed\",\n\t\t\t\terror: String(error),\n\t\t\t\tdurationMs: Date.now() - startedAt\n\t\t\t}, \"Codex could not rebind the thread to the MCP gateway; continuing without MCP tools\");\n\t\t}\n\t\tif (!this.#threadPersisted) {\n\t\t\tthis.#mcpThreadDirty = wasDirty;\n\t\t\treturn;\n\t\t}\n\t\tawait this.#rebindThread(codexMcpServersConfig(void 0), context, deadline);\n\t\tthis.#mcpThreadDirty = false;\n\t}\n\tasync #rebindThread(config, context, signal) {\n\t\tif (!this.#threadPersisted) {\n\t\t\tawait this.#replaceUnpersistedThread(config, context, signal);\n\t\t\treturn;\n\t\t}\n\t\tawait this.#client.request(\"thread/unsubscribe\", { threadId: this.#threadId }, signal);\n\t\tif (requireRecord(requireRecord(await this.#client.request(\"thread/resume\", {\n\t\t\t...this.#threadParams,\n\t\t\tthreadId: this.#threadId,\n\t\t\texcludeTurns: true,\n\t\t\tconfig\n\t\t}, signal), \"thread/resume returned an invalid response\").thread, \"thread/resume returned no thread\").id !== this.#threadId) throw protocolError(\"thread/resume restored another thread\");\n\t}\n\t/**\n\t* A thread that has never started a turn has no rollout to resume and no history to lose, so it is\n\t* replaced by a new thread with the run's MCP servers and the binding moves to it. The previous\n\t* thread stays loaded until the replacement exists, so a failed attach leaves it untouched, and it\n\t* is unloaded without delaying the turn.\n\t*/\n\tasync #replaceUnpersistedThread(config, context, signal) {\n\t\tconst threadId = requireString(requireRecord(requireRecord(await this.#client.request(\"thread/start\", {\n\t\t\t...this.#threadStartParams,\n\t\t\tconfig\n\t\t}, signal), \"thread/start returned an invalid response\").thread, \"thread/start returned no thread\").id, \"thread/start returned no thread id\");\n\t\tconst previous = this.#threadId;\n\t\t/* v8 ignore next -- a runtime always has a binding once its factory has opened the thread. */\n\t\tconst payload = record(this.binding?.payload) ?? {};\n\t\tconst binding = {\n\t\t\tproviderId: CODEX_PROVIDER_ID,\n\t\t\tschemaVersion: CODEX_BINDING_SCHEMA_VERSION,\n\t\t\tpayload: {\n\t\t\t\t...payload,\n\t\t\t\tthreadId\n\t\t\t}\n\t\t};\n\t\tassertBinding(binding, this.manifest);\n\t\tawait context.updateBinding(binding);\n\t\tthis.#threadId = threadId;\n\t\tthis.#client.request(\"thread/unsubscribe\", { threadId: previous }, signal).catch((error) => {\n\t\t\tlogger$14.debug({\n\t\t\t\tcode: \"replaced_thread_unsubscribe_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Codex did not unload a replaced thread\");\n\t\t});\n\t}\n\tasync #handleHostedTool(call) {\n\t\tconst hash = JSON.stringify({\n\t\t\targuments: call.arguments,\n\t\t\tnamespace: call.namespace,\n\t\t\tthreadId: call.threadId,\n\t\t\ttool: call.tool,\n\t\t\tturnId: call.turnId\n\t\t});\n\t\tconst existing = this.#hostedToolCalls.get(call.callId);\n\t\tif (existing) return existing.hash === hash ? existing.result : {\n\t\t\tsuccess: false,\n\t\t\ttext: \"OpenTag rejected conflicting reuse of a hosted tool call ID.\"\n\t\t};\n\t\tconst result = this.#executeHostedTool(call);\n\t\tthis.#hostedToolCalls.set(call.callId, {\n\t\t\thash,\n\t\t\tresult\n\t\t});\n\t\treturn result;\n\t}\n\tasync #executeHostedTool(call) {\n\t\tconst context = this.#context;\n\t\tconst hostedTools = this.#hostedTools;\n\t\tif (!context || !hostedTools || call.namespace !== null || call.threadId !== this.#threadId) return {\n\t\t\tsuccess: false,\n\t\t\ttext: \"OpenTag tool request is not authorized for this run.\"\n\t\t};\n\t\tconst toolAllowed = this.#policy.tools.mode === \"allow-list\" ? this.#policy.tools.names.includes(call.tool) : hostedTools.definitions.some(({ name }) => name === call.tool);\n\t\tif (call.turnId !== this.#providerTurnId || !toolAllowed) return {\n\t\t\tsuccess: false,\n\t\t\ttext: \"OpenTag tool request is not authorized for this run.\"\n\t\t};\n\t\ttry {\n\t\t\tconst input = toJsonValue(call.arguments);\n\t\t\tconst request = {\n\t\t\t\trunId: context.runId,\n\t\t\t\ttoolCallId: call.callId,\n\t\t\t\tname: call.tool,\n\t\t\t\tinput,\n\t\t\t\tsignal: context.signal\n\t\t\t};\n\t\t\treturn codexHostedToolResult(await hostedTools.handler(request));\n\t\t} catch (error) {\n\t\t\tlogger$14.debug({\n\t\t\t\tcode: \"hosted_tool_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Codex hosted tool execution failed\");\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\ttext: error instanceof Error ? `OpenTag tool request failed: ${error.message}` : \"OpenTag tool request failed.\"\n\t\t\t};\n\t\t}\n\t}\n\t#enqueue(envelope) {\n\t\tthis.#claimTerminalAtIngress(envelope);\n\t\tconst next = this.#eventTail.then(async () => {\n\t\t\tif (!this.#context) return;\n\t\t\tif (this.#buffering) {\n\t\t\t\tthis.#buffered.push(envelope);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (envelope.type === \"notification\") await this.#handleNotification(envelope.message);\n\t\t\telse await this.#handleServerRequest(envelope.request);\n\t\t});\n\t\tthis.#eventTail = next.catch((error) => {\n\t\t\tlogger$14.debug({\n\t\t\t\tcode: \"event_processing_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Codex event processing failed\");\n\t\t\tthis.#failProvider(error instanceof Error ? error : protocolError(\"Codex event processing failed\"));\n\t\t});\n\t}\n\tasync #handleNotification(message) {\n\t\tconst method = message.method;\n\t\tif (method === \"opentag/processError\") {\n\t\t\tconst params = record(message.params);\n\t\t\tthrow params?.error instanceof Error ? params.error : new AgentProviderError(\"provider_error\", \"Codex process failed\");\n\t\t}\n\t\tif (typeof method !== \"string\") throw protocolError(\"Codex emitted a notification without a method\");\n\t\tconst context = this.#requireContext();\n\t\tconst params = record(message.params);\n\t\tif (method === \"warning\" || method === \"configWarning\") {\n\t\t\tconst text = requireString(params?.message ?? params?.summary, `${method} has no message`);\n\t\t\tawait context.emit({\n\t\t\t\ttype: \"provider_warning\",\n\t\t\t\tcode: method,\n\t\t\t\tmessage: text\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"serverRequest/resolved\") {\n\t\t\tconst wireId = params?.requestId;\n\t\t\tconst interactionId = this.#interactionIdForWireId(wireId);\n\t\t\tif (!interactionId) return;\n\t\t\tthis.#wireInteractions.delete(interactionId);\n\t\t\tawait context.resolveInteraction(interactionId, \"expired\");\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"thread/closed\") {\n\t\t\tif (params?.threadId !== void 0 && params.threadId !== this.#threadId) return;\n\t\t\tthrow new AgentProviderError(\"provider_error\", \"Codex thread closed during an active run\");\n\t\t}\n\t\tif (method === \"turn/started\") {\n\t\t\tconst turn = parseTurn(params?.turn, \"turn/started\");\n\t\t\tthis.#assertTurn(turn.id);\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"turn/completed\") {\n\t\t\tconst turn = this.#parseCompletedTurn(params);\n\t\t\tcontext.claimTerminal();\n\t\t\tthis.#terminal?.resolve(turn);\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"thread/tokenUsage/updated\") {\n\t\t\tif (params?.turnId !== void 0 && params.turnId !== this.#providerTurnId) return;\n\t\t\tconst usage = parseUsage(params?.tokenUsage);\n\t\t\tthis.#latestUsage = usage;\n\t\t\tawait context.emit({\n\t\t\t\ttype: \"usage_updated\",\n\t\t\t\tusage\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"item/agentMessage/delta\") {\n\t\t\tthis.#assertNotificationTurn(params);\n\t\t\tconst messageId = requireString(params?.itemId, \"agent message delta has no itemId\");\n\t\t\tconst delta = requireString(params?.delta, \"agent message delta has no text\", true);\n\t\t\tawait this.#ensureMessageStarted(messageId);\n\t\t\tthis.#activeMessages.set(messageId, `${this.#activeMessages.get(messageId)}${delta}`);\n\t\t\tawait context.emit({\n\t\t\t\ttype: \"message_delta\",\n\t\t\t\tmessageId,\n\t\t\t\tdelta\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"item/commandExecution/outputDelta\") {\n\t\t\tthis.#assertNotificationTurn(params);\n\t\t\tconst toolCallId = requireString(params?.itemId, \"command output delta has no itemId\");\n\t\t\tawait this.#ensureToolStarted(toolCallId, \"commandExecution\", {\n\t\t\t\tid: toolCallId,\n\t\t\t\ttype: \"commandExecution\"\n\t\t\t});\n\t\t\tawait context.emit({\n\t\t\t\ttype: \"tool_updated\",\n\t\t\t\ttoolCallId,\n\t\t\t\tupdate: { delta: requireString(params?.delta, \"command output delta has no text\", true) }\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"item/started\" || method === \"item/completed\") {\n\t\t\tthis.#assertNotificationTurn(params);\n\t\t\tconst item = requireRecord(params?.item, `${method} has no item`);\n\t\t\tawait this.#handleItem(method, item);\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"error\") {\n\t\t\tconst error = record(params?.error);\n\t\t\tawait context.emit({\n\t\t\t\ttype: \"provider_warning\",\n\t\t\t\tcode: \"codex_turn_error\",\n\t\t\t\tmessage: typeof error?.message === \"string\" ? error.message : \"Codex reported a turn error\"\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (method === \"turn/plan/updated\" || method === \"turn/diff/updated\" || method.startsWith(\"model/\")) await context.emit({\n\t\t\ttype: \"provider_event\",\n\t\t\tproviderId: CODEX_PROVIDER_ID,\n\t\t\tschemaVersion: 1,\n\t\t\tpayload: {\n\t\t\t\tmethod,\n\t\t\t\tparams: toJsonValue(params ?? {})\n\t\t\t}\n\t\t});\n\t}\n\tasync #handleItem(method, item) {\n\t\tconst context = this.#requireContext();\n\t\tconst id = requireString(item.id, `${method} item has no id`);\n\t\tconst type = requireString(item.type, `${method} item has no type`);\n\t\tif (type === \"agentMessage\") {\n\t\t\tif (method === \"item/started\") {\n\t\t\t\tawait this.#ensureMessageStarted(id);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst text = requireString(item.text, \"completed agent message has no text\", true);\n\t\t\tconst phase = typeof item.phase === \"string\" ? item.phase : void 0;\n\t\t\tawait this.#ensureMessageStarted(id);\n\t\t\tthis.#completedMessages.set(id, {\n\t\t\t\ttext,\n\t\t\t\t...phase ? { phase } : {}\n\t\t\t});\n\t\t\tawait context.emit({\n\t\t\t\ttype: \"message_completed\",\n\t\t\t\tmessageId: id,\n\t\t\t\ttext\n\t\t\t});\n\t\t\tthis.#activeMessages.delete(id);\n\t\t\treturn;\n\t\t}\n\t\tif (!TOOL_ITEM_TYPES.has(type)) return;\n\t\tconst name = method === \"item/completed\" ? this.#activeTools.get(id) ?? toolName(item, type) : toolName(item, type);\n\t\tif (method === \"item/started\") {\n\t\t\tawait this.#ensureToolStarted(id, name, item);\n\t\t\treturn;\n\t\t}\n\t\tawait this.#ensureToolStarted(id, name, item);\n\t\tconst status = item.status === \"declined\" ? \"declined\" : item.status === \"failed\" ? \"failed\" : \"completed\";\n\t\tawait context.emit({\n\t\t\ttype: \"tool_completed\",\n\t\t\ttoolCallId: id,\n\t\t\tname,\n\t\t\tstatus,\n\t\t\toutput: toJsonValue(item)\n\t\t});\n\t\tthis.#activeTools.delete(id);\n\t}\n\tasync #ensureMessageStarted(messageId) {\n\t\tif (this.#activeMessages.has(messageId)) return;\n\t\tif (this.#completedMessages.has(messageId)) throw protocolError(\"Codex reused a completed agent message ID\");\n\t\tthis.#activeMessages.set(messageId, \"\");\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"message_started\",\n\t\t\tmessageId\n\t\t});\n\t}\n\tasync #ensureToolStarted(toolCallId, name, input) {\n\t\tconst activeName = this.#activeTools.get(toolCallId);\n\t\tif (activeName) {\n\t\t\tif (activeName !== name) throw protocolError(\"Codex changed a tool name during its lifecycle\");\n\t\t\treturn;\n\t\t}\n\t\tthis.#activeTools.set(toolCallId, name);\n\t\tawait this.#requireContext().emit({\n\t\t\ttype: \"tool_started\",\n\t\t\ttoolCallId,\n\t\t\tname,\n\t\t\tinput: toJsonValue(input)\n\t\t});\n\t}\n\tasync #completeOpenLifecycles(turn) {\n\t\tconst context = this.#requireContext();\n\t\tconst terminalItems = new Map(turn.items.filter((item) => typeof item.id === \"string\").map((item) => [item.id, item]));\n\t\tfor (const [messageId, deltaText] of this.#activeMessages) {\n\t\t\tconst item = terminalItems.get(messageId);\n\t\t\tconst text = typeof item?.text === \"string\" ? item.text : deltaText;\n\t\t\tawait context.emit({\n\t\t\t\ttype: \"message_completed\",\n\t\t\t\tmessageId,\n\t\t\t\ttext\n\t\t\t});\n\t\t\tthis.#activeMessages.delete(messageId);\n\t\t}\n\t\tfor (const [toolCallId, name] of this.#activeTools) {\n\t\t\tconst item = terminalItems.get(toolCallId);\n\t\t\tconst status = item?.status === \"declined\" ? \"declined\" : !item || item.status === \"failed\" || turn.status !== \"completed\" ? \"failed\" : \"completed\";\n\t\t\tawait context.emit({\n\t\t\t\ttype: \"tool_completed\",\n\t\t\t\ttoolCallId,\n\t\t\t\tname,\n\t\t\t\tstatus,\n\t\t\t\t...item ? { output: toJsonValue(item) } : {}\n\t\t\t});\n\t\t\tthis.#activeTools.delete(toolCallId);\n\t\t}\n\t}\n\tasync #handleServerRequest(request) {\n\t\tconst context = this.#requireContext();\n\t\tconst params = requireRecord(request.params, `${request.method} has invalid params`);\n\t\tif (params.threadId !== void 0 && params.threadId !== this.#threadId) throw protocolError(\"Codex server request belongs to another thread\");\n\t\tif (params.turnId !== void 0 && params.turnId !== this.#providerTurnId) throw protocolError(\"Codex server request belongs to another turn\");\n\t\tconst interaction = codexInteractionRequest(request, params);\n\t\tif (!interaction) {\n\t\t\tawait this.#client.rejectServerRequest(request.id, -32601, \"Unsupported Codex server request\");\n\t\t\tthrow protocolError(`Codex requested an unsupported method: ${request.method}`);\n\t\t}\n\t\tconst requestId = interaction.requestId;\n\t\tif (this.#wireInteractions.has(requestId)) throw protocolError(\"Codex reused a pending server request ID\");\n\t\tthis.#wireInteractions.set(requestId, request);\n\t\ttry {\n\t\t\tawait context.requestInteraction(interaction);\n\t\t} catch (error) {\n\t\t\tthis.#wireInteractions.delete(requestId);\n\t\t\tawait this.#client.rejectServerRequest(request.id, -32e3, \"OpenTag could not deliver the interaction\").catch((rejectionError) => {\n\t\t\t\tlogger$14.debug({\n\t\t\t\t\tcode: \"interaction_rejection_failed\",\n\t\t\t\t\terror: String(rejectionError)\n\t\t\t\t}, \"Codex interaction rejection failed\");\n\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t}\n\t#turnStartParams(request) {\n\t\tconst configuration = mergeConfiguration(this.#configuration, request.configuration);\n\t\tconst provider = parseProviderConfiguration(configuration?.provider);\n\t\treturn {\n\t\t\tthreadId: this.#threadId,\n\t\t\tinput: codexInput(request.input.items),\n\t\t\tcwd: this.#workspace.cwd,\n\t\t\tapprovalPolicy: codexApprovalPolicy(this.#policy.approvals),\n\t\t\tsandboxPolicy: codexSandboxPolicy(this.#workspace, this.#policy),\n\t\t\t...configuration?.model ? { model: configuration.model } : {},\n\t\t\t...configuration?.reasoningEffort ? { effort: configuration.reasoningEffort } : {},\n\t\t\t...provider.personality ? { personality: provider.personality } : {},\n\t\t\t...provider.summary ? { summary: provider.summary } : {}\n\t\t};\n\t}\n\t#runResult(turn) {\n\t\tconst finalText = selectFinalText(turn.items, this.#completedMessages);\n\t\tconst output = finalText === void 0 ? [] : [{\n\t\t\ttype: \"text\",\n\t\t\ttext: finalText\n\t\t}];\n\t\tconst diagnostics = {\n\t\t\tproviderThreadId: this.#threadId,\n\t\t\tproviderTurnId: turn.id\n\t\t};\n\t\tif (turn.status === \"completed\") return {\n\t\t\tstatus: \"completed\",\n\t\t\toutput,\n\t\t\t...this.#latestUsage ? { usage: this.#latestUsage } : {},\n\t\t\tdiagnostics\n\t\t};\n\t\tif (turn.status === \"interrupted\") return {\n\t\t\tstatus: \"aborted\",\n\t\t\toutput,\n\t\t\t...this.#latestUsage ? { usage: this.#latestUsage } : {},\n\t\t\terror: {\n\t\t\t\tcode: \"run_aborted\",\n\t\t\t\tmessage: \"Codex turn was interrupted\"\n\t\t\t},\n\t\t\tdiagnostics\n\t\t};\n\t\treturn {\n\t\t\tstatus: \"failed\",\n\t\t\toutput,\n\t\t\t...this.#latestUsage ? { usage: this.#latestUsage } : {},\n\t\t\terror: {\n\t\t\t\tcode: \"provider_error\",\n\t\t\t\tmessage: turn.error ?? \"Codex turn failed\"\n\t\t\t},\n\t\t\tdiagnostics\n\t\t};\n\t}\n\tasync #activeTurnId() {\n\t\tif (this.#providerTurnId) return this.#providerTurnId;\n\t\tif (!this.#turnIdReady) throw new AgentRuntimeError(\"run_mismatch\", \"there is no active Codex turn\");\n\t\treturn this.#turnIdReady.promise;\n\t}\n\t#assertNotificationTurn(params) {\n\t\tif (params?.threadId !== void 0 && params.threadId !== this.#threadId) throw protocolError(\"Codex notification belongs to another thread\");\n\t\tif (params?.turnId !== this.#providerTurnId) throw protocolError(\"Codex notification belongs to another turn\");\n\t}\n\t#assertTurn(turnId) {\n\t\tif (turnId !== this.#providerTurnId) throw protocolError(\"Codex turn identity changed during a run\");\n\t}\n\t#requireContext() {\n\t\t/* v8 ignore next -- #enqueue drops envelopes before a Run context exists. */\n\t\tif (!this.#context) throw protocolError(\"Codex event arrived without an active run\");\n\t\treturn this.#context;\n\t}\n\t#claimTerminalAtIngress(envelope) {\n\t\tif (envelope.type !== \"notification\" || envelope.message.method !== \"turn/completed\" || this.#buffering || !this.#context) return;\n\t\ttry {\n\t\t\tthis.#parseCompletedTurn(record(envelope.message.params));\n\t\t\tthis.#context.claimTerminal();\n\t\t} catch (error) {\n\t\t\tlogger$14.debug({\n\t\t\t\tcode: \"terminal_message_invalid\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Codex terminal message was rejected\");\n\t\t}\n\t}\n\t#parseCompletedTurn(params) {\n\t\tconst turn = parseTurn(params?.turn, \"turn/completed\");\n\t\tthis.#assertTurn(turn.id);\n\t\tif (turn.status === \"inProgress\") throw protocolError(\"turn/completed carried an active turn\");\n\t\treturn turn;\n\t}\n\t#failProvider(error) {\n\t\tif (this.#providerFailure) return;\n\t\tthis.#providerFailure = error;\n\t\tthis.#terminal?.reject(error);\n\t\tthis.#turnIdReady?.reject(error);\n\t\tthis.closeForProviderFailure();\n\t}\n\t#interactionIdForWireId(wireId) {\n\t\tfor (const [interactionId, request] of this.#wireInteractions)\n /* v8 ignore else -- the map holds one in-flight interaction, so lookups match on the first entry. */\n\t\tif (request.id === wireId) return interactionId;\n\t}\n};\nvar CodexAgentRuntimeFactory = class {\n\tmanifest = CODEX_AGENT_RUNTIME_MANIFEST;\n\t#clientVersion;\n\t#createClient;\n\t#mcpAttachTimeoutMs;\n\t#probeRunner;\n\tconstructor(options) {\n\t\tthis.#clientVersion = options.clientVersion;\n\t\tconst environment = options.process?.env ?? codexAgentRuntimeEnvironment();\n\t\tconst command = options.process?.command ?? \"codex\";\n\t\tconst createDefaultClient = (cwd, workspaceEnvironment, pathPrepend, expectedCodexHome = options.process?.expectedCodexHome) => {\n\t\t\tconst shellHome = pathPrepend ? workspaceEnvironment?.OPENTAG_HOME : void 0;\n\t\t\tconst managedArgs = [...CODEX_AGENT_RUNTIME_APP_SERVER_ARGS, ...shellHome ? [\"-c\", `shell_environment_policy.set.ZDOTDIR=${JSON.stringify(shellHome)}`] : []];\n\t\t\treturn new CodexAppServerProcess({\n\t\t\t\tcommand,\n\t\t\t\targs: options.process?.args ?? managedArgs,\n\t\t\t\tcwd,\n\t\t\t\tenv: composeRuntimeEnvironment(environment, workspaceEnvironment, pathPrepend),\n\t\t\t\texpectedCodexHome,\n\t\t\t\tmaxLineBytes: options.process?.maxLineBytes,\n\t\t\t\trequestTimeoutMs: options.process?.requestTimeoutMs,\n\t\t\t\tspawnProcess: options.process?.spawnProcess\n\t\t\t});\n\t\t};\n\t\tthis.#createClient = options.createClient ?? createDefaultClient;\n\t\tthis.#mcpAttachTimeoutMs = options.mcpAttachTimeoutMs ?? CODEX_MCP_ATTACH_TIMEOUT_MS;\n\t\tconst createProbeClient = options.createClient ?? ((cwd, probeEnvironment) => createDefaultClient(cwd, probeEnvironment, void 0, probeEnvironment?.CODEX_HOME));\n\t\tthis.#probeRunner = options.probeRunner ?? (async (signal) => {\n\t\t\tconst local = await probeCodex(command, environment, signal);\n\t\t\tif (!local.credential) return {\n\t\t\t\t...local,\n\t\t\t\texperimentalTools: false\n\t\t\t};\n\t\t\tconst probeHome = await realpath(await mkdtemp(join(tmpdir(), \"opentag-codex-capability-\")));\n\t\t\tconst startClient = createProbeClient(process.cwd(), { CODEX_HOME: probeHome });\n\t\t\tlet bootstrapClient;\n\t\t\tlet resumeClient;\n\t\t\ttry {\n\t\t\t\tawait startClient.initialize(this.#clientVersion, signal);\n\t\t\t\tconst threadId = requireString(requireRecord(requireRecord(await startClient.request(\"thread/start\", {\n\t\t\t\t\tcwd: process.cwd(),\n\t\t\t\t\tdeveloperInstructions: CODEX_CAPABILITY_PROBE_INSTRUCTIONS,\n\t\t\t\t\tapprovalPolicy: \"never\",\n\t\t\t\t\tsandbox: \"read-only\",\n\t\t\t\t\tephemeral: false,\n\t\t\t\t\tdynamicTools: [{\n\t\t\t\t\t\ttype: \"function\",\n\t\t\t\t\t\tname: \"opentag_capability_probe\",\n\t\t\t\t\t\tdescription: \"Validate Codex dynamic tool protocol support.\",\n\t\t\t\t\t\tinputSchema: {\n\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t\t\tproperties: {}\n\t\t\t\t\t\t}\n\t\t\t\t\t}]\n\t\t\t\t}, signal), \"Codex capability probe start returned an invalid response\").thread, \"Codex capability probe start returned no thread\").id, \"Codex capability probe start returned no thread id\");\n\t\t\t\t/* v8 ignore next -- probe client teardown is best-effort between probe phases. */\n\t\t\t\tawait startClient.close().catch(() => void 0);\n\t\t\t\tbootstrapClient = createProbeClient(process.cwd(), { CODEX_HOME: probeHome });\n\t\t\t\tawait bootstrapClient.initialize(this.#clientVersion, signal);\n\t\t\t\tconst bootstrapThreadId = requireString(requireRecord(requireRecord(await bootstrapClient.request(\"thread/resume\", {\n\t\t\t\t\tthreadId,\n\t\t\t\t\tcwd: process.cwd(),\n\t\t\t\t\tdeveloperInstructions: CODEX_CAPABILITY_PROBE_INSTRUCTIONS,\n\t\t\t\t\tapprovalPolicy: \"never\",\n\t\t\t\t\tsandbox: \"read-only\",\n\t\t\t\t\thistory: [{\n\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{\n\t\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\t\ttext: \"OpenTag capability probe history.\"\n\t\t\t\t\t\t}]\n\t\t\t\t\t}]\n\t\t\t\t}, signal), \"Codex capability probe bootstrap returned an invalid response\").thread, \"Codex capability probe bootstrap returned no thread\").id, \"Codex capability probe bootstrap returned no thread id\");\n\t\t\t\t/* v8 ignore next -- probe client teardown is best-effort between probe phases. */\n\t\t\t\tawait bootstrapClient.close().catch(() => void 0);\n\t\t\t\tresumeClient = createProbeClient(process.cwd(), { CODEX_HOME: probeHome });\n\t\t\t\tawait resumeClient.initialize(this.#clientVersion, signal);\n\t\t\t\tif (requireString(requireRecord(requireRecord(await resumeClient.request(\"thread/resume\", {\n\t\t\t\t\tthreadId: bootstrapThreadId,\n\t\t\t\t\tcwd: process.cwd(),\n\t\t\t\t\tdeveloperInstructions: CODEX_CAPABILITY_PROBE_INSTRUCTIONS,\n\t\t\t\t\tapprovalPolicy: \"never\",\n\t\t\t\t\tsandbox: \"read-only\"\n\t\t\t\t}, signal), \"Codex capability probe exact resume returned an invalid response\").thread, \"Codex capability probe exact resume returned no thread\").id, \"Codex capability probe exact resume returned no thread id\") !== bootstrapThreadId) throw new CodexAppServerError(\"protocol\", \"Codex capability probe resumed another thread\");\n\t\t\t\treturn {\n\t\t\t\t\t...local,\n\t\t\t\t\texperimentalTools: true\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\t/* v8 ignore start -- probe teardown is best-effort; close and rm failures must not mask the probe result. */\n\t\t\t\tawait startClient.close().catch((error) => {\n\t\t\t\t\tlogger$14.debug({\n\t\t\t\t\t\tcode: \"probe_start_close_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Codex capability probe start client close failed\");\n\t\t\t\t});\n\t\t\t\tawait bootstrapClient?.close().catch((error) => {\n\t\t\t\t\tlogger$14.debug({\n\t\t\t\t\t\tcode: \"probe_bootstrap_close_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Codex capability probe bootstrap client close failed\");\n\t\t\t\t});\n\t\t\t\tawait resumeClient?.close().catch((error) => {\n\t\t\t\t\tlogger$14.debug({\n\t\t\t\t\t\tcode: \"probe_resume_close_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Codex capability probe resume client close failed\");\n\t\t\t\t});\n\t\t\t\tawait rm(probeHome, {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tforce: true\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tlogger$14.debug({\n\t\t\t\t\t\tcode: \"probe_home_cleanup_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Codex capability probe home cleanup failed\");\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\tasync probe(request) {\n\t\tconst issues = [];\n\t\ttry {\n\t\t\tvalidateConfiguration(request.configuration);\n\t\t} catch (error) {\n\t\t\tissues.push({\n\t\t\t\tcode: \"configuration_invalid\",\n\t\t\t\tmessage: error.message\n\t\t\t});\n\t\t}\n\t\tlet version;\n\t\ttry {\n\t\t\tconst result = await this.#probeRunner(request.signal);\n\t\t\tversion = result.version;\n\t\t\tif (!result.appServer) issues.push({\n\t\t\t\tcode: \"version_incompatible\",\n\t\t\t\tmessage: \"Codex App Server is unavailable\"\n\t\t\t});\n\t\t\tif (!result.credential) issues.push({\n\t\t\t\tcode: \"credential_missing\",\n\t\t\t\tmessage: \"Codex credentials were not found\"\n\t\t\t});\n\t\t\tif (result.appServer && result.credential && !result.experimentalTools) issues.push({\n\t\t\t\tcode: \"version_incompatible\",\n\t\t\t\tmessage: \"Codex experimental dynamic tools are unavailable\"\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (request.signal?.aborted) throw error;\n\t\t\tlogger$14.debug({\n\t\t\t\tcode: \"probe_execution_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Codex probe execution failed\");\n\t\t\tconst issue = probeIssue(error);\n\t\t\tif (!issue) throw error;\n\t\t\tissues.push(issue);\n\t\t}\n\t\treturn {\n\t\t\tready: issues.length === 0,\n\t\t\t...version ? { version } : {},\n\t\t\tissues\n\t\t};\n\t}\n\tcreate(request) {\n\t\treturn this.#open(request, \"create\");\n\t}\n\tresume(request) {\n\t\treturn this.#open(request, \"resume\");\n\t}\n\tasync #open(request, mode) {\n\t\tvalidateFactoryRequest(request);\n\t\tvalidateConfiguration(request.configuration);\n\t\tconst providerConfiguration = parseProviderConfiguration(request.configuration?.provider);\n\t\tconst binding = mode === \"resume\" && \"binding\" in request ? request.binding : void 0;\n\t\tif (binding) assertBinding(binding, this.manifest);\n\t\tconst parsedBinding = binding ? parseCodexBinding(binding) : void 0;\n\t\tconst expectedThreadId = parsedBinding?.threadId;\n\t\tconst requestedHostedToolsHash = request.hostedTools ? hostedToolsHash(request.hostedTools.definitions) : void 0;\n\t\tif (mode === \"resume\" && parsedBinding?.hostedToolsHash !== requestedHostedToolsHash) throw new AgentRuntimeError(\"binding_incompatible\", \"Codex binding hosted tools cannot change during exact resume\");\n\t\tconst client = this.#createClient(request.workspace.cwd, request.workspace.environment, request.workspace.pathPrepend);\n\t\ttry {\n\t\t\tif (request.hostedTools && typeof client.setDynamicToolHandler !== \"function\") throw new AgentRuntimeError(\"configuration_invalid\", \"Codex App Server transport does not support hosted dynamic tools\");\n\t\t\tawait client.initialize(this.#clientVersion);\n\t\t\tconst method = mode === \"create\" ? \"thread/start\" : \"thread/resume\";\n\t\t\tconst threadParams = {\n\t\t\t\tcwd: request.workspace.cwd,\n\t\t\t\tdeveloperInstructions: request.systemPrompt,\n\t\t\t\tapprovalPolicy: codexApprovalPolicy(request.policy.approvals),\n\t\t\t\tsandbox: codexSandboxMode(request.policy.fileSystem),\n\t\t\t\t...request.configuration?.model ? { model: request.configuration.model } : {},\n\t\t\t\t...providerConfiguration.personality ? { personality: providerConfiguration.personality } : {},\n\t\t\t\tserviceName: providerConfiguration.serviceName ?? \"OpenTag\"\n\t\t\t};\n\t\t\tconst threadStartParams = {\n\t\t\t\t...threadParams,\n\t\t\t\tephemeral: false,\n\t\t\t\t...request.hostedTools ? { dynamicTools: request.hostedTools.definitions.map(codexDynamicToolDefinition) } : {}\n\t\t\t};\n\t\t\tconst threadId = requireString(requireRecord(requireRecord(await client.request(method, method === \"thread/start\" ? threadStartParams : {\n\t\t\t\t...codexResumeParams(expectedThreadId),\n\t\t\t\t...threadParams\n\t\t\t}), `${method} returned an invalid response`).thread, `${method} returned no thread`).id, `${method} returned no thread id`);\n\t\t\tif (method === \"thread/resume\" && expectedThreadId && threadId !== expectedThreadId) throw protocolError(\"thread/resume restored another thread\");\n\t\t\tconst runtimeBinding = {\n\t\t\t\tproviderId: CODEX_PROVIDER_ID,\n\t\t\t\tschemaVersion: CODEX_BINDING_SCHEMA_VERSION,\n\t\t\t\tpayload: {\n\t\t\t\t\tthreadId,\n\t\t\t\t\t...requestedHostedToolsHash ? { hostedToolsHash: requestedHostedToolsHash } : {}\n\t\t\t\t}\n\t\t\t};\n\t\t\tassertBinding(runtimeBinding, this.manifest);\n\t\t\tawait request.eventSink({\n\t\t\t\ttype: \"binding_changed\",\n\t\t\t\tbinding: runtimeBinding\n\t\t\t});\n\t\t\treturn new CodexAgentRuntime({\n\t\t\t\tclient,\n\t\t\t\tthreadId,\n\t\t\t\teventSink: request.eventSink,\n\t\t\t\tbinding: runtimeBinding,\n\t\t\t\tworkspace: request.workspace,\n\t\t\t\tpolicy: request.policy,\n\t\t\t\tconfiguration: request.configuration,\n\t\t\t\thostedTools: request.hostedTools,\n\t\t\t\tthreadParams,\n\t\t\t\tthreadStartParams,\n\t\t\t\tthreadPersisted: method === \"thread/resume\",\n\t\t\t\tmcpAttachTimeoutMs: this.#mcpAttachTimeoutMs\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger$14.debug({\n\t\t\t\tcode: \"runtime_create_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Codex runtime creation failed\");\n\t\t\tawait client.close().catch((closeError) => {\n\t\t\t\tlogger$14.debug({\n\t\t\t\t\tcode: \"provider_close_failed\",\n\t\t\t\t\terror: String(closeError)\n\t\t\t\t}, \"Codex provider close failed\");\n\t\t\t});\n\t\t\tif (error instanceof AgentRuntimeError) throw error;\n\t\t\tthrow new AgentRuntimeError(mode === \"create\" ? \"create_failed\" : \"resume_failed\", `Codex ${mode} failed`, { cause: error });\n\t\t}\n\t}\n};\nfunction codexBindingRequiresHostedToolReplacement(binding, hostedTools) {\n\tassertBinding(binding, CODEX_AGENT_RUNTIME_MANIFEST);\n\treturn parseCodexBinding(binding).hostedToolsHash !== (hostedTools ? hostedToolsHash(hostedTools.definitions) : void 0);\n}\nfunction codexAgentRuntimeEnvironment(source = process.env) {\n\tconst keys = [\n\t\t\"CODEX_HOME\",\n\t\t\"HOME\",\n\t\t\"LANG\",\n\t\t\"LC_ALL\",\n\t\t\"LOGNAME\",\n\t\t\"OPENTAG_PROVIDER_ENV_FILE\",\n\t\t\"OPENTAG_HOME\",\n\t\t\"OPENTAG_SESSION_PROOF_FILE\",\n\t\t\"PATH\",\n\t\t\"PATHEXT\",\n\t\t\"SHELL\",\n\t\t\"SystemRoot\",\n\t\t\"TMPDIR\",\n\t\t\"USER\",\n\t\t\"WINDIR\"\n\t];\n\tconst environment = {};\n\tfor (const key of keys) if (source[key] !== void 0) environment[key] = source[key];\n\treturn environment;\n}\nfunction probeIssue(error) {\n\tif (error instanceof AgentProviderError && error.code === \"provider_protocol_error\") return {\n\t\tcode: \"version_incompatible\",\n\t\tmessage: `Codex App Server protocol is incompatible: ${error.message}`\n\t};\n\tif (error instanceof CodexAppServerError) {\n\t\tif (error.code === \"protocol\") return {\n\t\t\tcode: \"version_incompatible\",\n\t\t\tmessage: `Codex App Server protocol is incompatible: ${error.message}`\n\t\t};\n\t\tif (error.code === \"timeout\" || error.code === \"aborted\" || error.code === \"write\") return {\n\t\t\tcode: \"temporarily_unavailable\",\n\t\t\tmessage: `Codex App Server is unavailable: ${error.message}`\n\t\t};\n\t\tif (isTransientProviderProbeFailure(error)) return {\n\t\t\tcode: \"temporarily_unavailable\",\n\t\t\tmessage: `Codex App Server is unavailable: ${error.message}`\n\t\t};\n\t\tif (isBinaryShapedProviderProbeFailure(error)) return typeof error.exitCode === \"number\" && error.exitCode !== 0 && !error.signal ? {\n\t\t\tcode: \"version_incompatible\",\n\t\t\tmessage: `Codex App Server protocol is incompatible: ${error.message}`\n\t\t} : {\n\t\t\tcode: \"artifact_missing\",\n\t\t\tmessage: \"Codex CLI could not be executed\"\n\t\t};\n\t\treturn;\n\t}\n\treturn classifiedProviderProbeIssue(error, \"Codex CLI could not be executed\");\n}\nasync function probeCodex(command, environment, signal) {\n\tconst execution = {\n\t\tencoding: \"utf8\",\n\t\tenv: environment,\n\t\tsignal,\n\t\ttimeout: 5e3,\n\t\twindowsHide: true\n\t};\n\tconst version = (await execFileAsync$2(command, [\"--version\"], execution)).stdout.trim();\n\tif (!version) throw new Error(\"Codex CLI returned no version\");\n\tawait execFileAsync$2(command, [\"app-server\", \"--help\"], execution);\n\tlet credential = false;\n\ttry {\n\t\tawait execFileAsync$2(command, [\"login\", \"status\"], execution);\n\t\tcredential = true;\n\t} catch (error) {\n\t\tif (signal?.aborted) throw error;\n\t\tlogger$14.debug({\n\t\t\tcode: \"credential_status_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Codex credential status command failed\");\n\t}\n\treturn {\n\t\tappServer: true,\n\t\tcredential,\n\t\tversion\n\t};\n}\nfunction validateFactoryRequest(request) {\n\tif (!request || typeof request !== \"object\" || typeof request.eventSink !== \"function\") throw new AgentRuntimeError(\"configuration_invalid\", \"eventSink is required\");\n\tif (!request.workspace || !isAbsolute(request.workspace.cwd)) throw new AgentRuntimeError(\"configuration_invalid\", \"workspace.cwd must be absolute\");\n\tassertSystemPrompt(request.systemPrompt);\n\tfor (const root of request.workspace.writableRoots ?? []) if (!isAbsolute(root)) throw new AgentRuntimeError(\"configuration_invalid\", \"writable roots must be absolute\");\n\tassertHostedTools(request.policy, request.hostedTools);\n\tif (request.policy.fileSystem === \"read-only\" && (request.workspace.writableRoots?.length ?? 0) > 0) throw new AgentRuntimeError(\"configuration_invalid\", \"read-only policy cannot have writable roots\");\n\tif (request.policy.fileSystem === \"read-only\" && request.policy.network === \"enabled\") throw new AgentRuntimeError(\"configuration_invalid\", \"Codex cannot guarantee read-only filesystem with enabled network\");\n\tif (request.policy.fileSystem === \"unrestricted\" && request.policy.network === \"disabled\") throw new AgentRuntimeError(\"configuration_invalid\", \"Codex cannot restrict network in unrestricted filesystem mode\");\n}\nfunction validateConfiguration(configuration) {\n\tif (!configuration) return;\n\tif (configuration.model !== void 0 && configuration.model.trim().length === 0) throw new AgentRuntimeError(\"configuration_invalid\", \"model must be non-empty\");\n\tif (configuration.reasoningEffort && !getRuntimeConfigurationOptions(\"codex\").reasoningEffortAllowedValues.includes(configuration.reasoningEffort)) throw new AgentRuntimeError(\"configuration_invalid\", \"Codex reasoning effort is unsupported\");\n\tparseProviderConfiguration(configuration.provider);\n}\nfunction parseProviderConfiguration(value) {\n\tif (value === void 0) return {};\n\tassertJsonValue(value, \"configuration.provider\");\n\tconst object = record(value);\n\tif (!object) throw new AgentRuntimeError(\"configuration_invalid\", \"Codex provider configuration must be an object\");\n\tconst allowed = /* @__PURE__ */ new Set([\n\t\t\"mcpGateway\",\n\t\t\"personality\",\n\t\t\"serviceName\",\n\t\t\"summary\"\n\t]);\n\tfor (const key of Object.keys(object)) if (!allowed.has(key)) throw new AgentRuntimeError(\"configuration_invalid\", `unknown Codex configuration field: ${key}`);\n\tconst mcpGateway = parseMcpGatewayConfiguration(object.mcpGateway);\n\tconst result = mcpGateway ? { mcpGateway } : {};\n\tfor (const key of [\n\t\t\"personality\",\n\t\t\"serviceName\",\n\t\t\"summary\"\n\t]) {\n\t\tconst item = object[key];\n\t\tif (item === void 0) continue;\n\t\tif (typeof item !== \"string\" || item.trim().length === 0) throw new AgentRuntimeError(\"configuration_invalid\", `Codex configuration ${key} must be non-empty`);\n\t\tresult[key] = item;\n\t}\n\treturn result;\n}\n/**\n* Validate the MCP gateway descriptor before Codex is pointed at it.\n*\n* The URL must be absolute http(s): this also runs over caller-supplied configuration, and Codex\n* would otherwise present the execution bearer to whatever it names.\n*/\nfunction parseMcpGatewayConfiguration(value) {\n\tif (value === void 0) return void 0;\n\tconst object = record(value);\n\tif (!object) throw new AgentRuntimeError(\"configuration_invalid\", \"Codex mcpGateway must be an object\");\n\tconst { url, token } = object;\n\tif (typeof url !== \"string\" || typeof token !== \"string\" || token.length === 0) throw new AgentRuntimeError(\"configuration_invalid\", \"Codex mcpGateway requires a url and a token\");\n\tlet protocol;\n\ttry {\n\t\tprotocol = new URL(url).protocol;\n\t} catch {\n\t\tthrow new AgentRuntimeError(\"configuration_invalid\", \"Codex mcpGateway url must be absolute\");\n\t}\n\tif (protocol !== \"https:\" && protocol !== \"http:\") throw new AgentRuntimeError(\"configuration_invalid\", \"Codex mcpGateway url must be http or https\");\n\treturn {\n\t\turl,\n\t\ttoken\n\t};\n}\n/**\n* The thread `config` override naming a run's MCP servers: the gateway alone, or none.\n*\n* It replaces the whole `mcp_servers` table, so the user's own Codex servers stay excluded exactly as\n* the launch arguments exclude them. Gateway tools are pre-approved as a server, matching the Claude\n* Code allow rule; Codex otherwise rejects every MCP call under the `never` approval policy.\n*/\nfunction codexMcpServersConfig(endpoint) {\n\tif (!endpoint) return { mcp_servers: {} };\n\treturn { mcp_servers: { [MCP_GATEWAY_SERVER_NAME]: {\n\t\turl: endpoint.url,\n\t\thttp_headers: { Authorization: `Bearer ${endpoint.token}` },\n\t\tdefault_tools_approval_mode: \"approve\",\n\t\tstartup_timeout_sec: CODEX_MCP_STARTUP_TIMEOUT_SEC\n\t} } };\n}\n/**\n* Turn hydration stays on the Server: Codex otherwise returns the entire stored thread inside one\n* `thread/resume` response, and a long Session exceeds the App Server JSONL line limit, which fails\n* the resume as a protocol error.\n*/\nfunction codexResumeParams(expectedThreadId) {\n\treturn {\n\t\tthreadId: expectedThreadId,\n\t\texcludeTurns: true\n\t};\n}\nfunction parseCodexBinding(binding) {\n\tconst payload = record(binding.payload);\n\tif (!payload) throw new AgentRuntimeError(\"binding_incompatible\", \"Codex binding payload is invalid\");\n\tconst threadId = payload.threadId;\n\tif (typeof threadId !== \"string\" || threadId.length === 0 || Buffer.byteLength(threadId, \"utf8\") > 1048576) throw new AgentRuntimeError(\"binding_incompatible\", \"Codex binding has no valid threadId\");\n\tconst hostedToolsHash = payload.hostedToolsHash;\n\tif (hostedToolsHash === void 0) return { threadId };\n\tif (typeof hostedToolsHash !== \"string\" || !/^[a-f0-9]{64}$/.test(hostedToolsHash)) throw new AgentRuntimeError(\"binding_incompatible\", \"Codex binding has an invalid hostedToolsHash\");\n\treturn {\n\t\tthreadId,\n\t\thostedToolsHash\n\t};\n}\nfunction hostedToolsHash(definitions) {\n\treturn hashTuple([\n\t\t\"opentag-codex-hosted-tools\",\n\t\t1,\n\t\t[...definitions].sort((left, right) => left.name.localeCompare(right.name)).map(codexDynamicToolDefinition)\n\t]);\n}\nfunction mergeConfiguration(base, override) {\n\tif (!base) {\n\t\tvalidateConfiguration(override);\n\t\treturn override;\n\t}\n\tif (!override) return base;\n\tconst provider = {\n\t\t...parseProviderConfiguration(base.provider),\n\t\t...parseProviderConfiguration(override.provider)\n\t};\n\tconst merged = {\n\t\t...base,\n\t\t...override,\n\t\tprovider\n\t};\n\tvalidateConfiguration(merged);\n\treturn merged;\n}\nfunction codexInput(items) {\n\treturn items.map((item) => ({\n\t\ttype: \"text\",\n\t\ttext: item.text\n\t}));\n}\nfunction codexApprovalPolicy(policy) {\n\tif (policy === \"on-request\") return \"onRequest\";\n\tif (policy === \"unless-trusted\") return \"unlessTrusted\";\n\treturn \"never\";\n}\nfunction codexSandboxMode(mode) {\n\tif (mode === \"read-only\") return \"read-only\";\n\tif (mode === \"workspace-write\") return \"workspace-write\";\n\treturn \"danger-full-access\";\n}\nfunction codexSandboxPolicy(workspace, policy) {\n\tif (policy.fileSystem === \"read-only\") return { type: \"readOnly\" };\n\tif (policy.fileSystem === \"unrestricted\") return { type: \"dangerFullAccess\" };\n\treturn {\n\t\ttype: \"workspaceWrite\",\n\t\twritableRoots: [...workspace.writableRoots ?? [workspace.cwd]],\n\t\tnetworkAccess: policy.network === \"enabled\"\n\t};\n}\nfunction codexDynamicToolDefinition(definition) {\n\treturn {\n\t\ttype: \"function\",\n\t\tname: definition.name,\n\t\t...definition.description ? { description: definition.description } : {},\n\t\tinputSchema: definition.inputSchema\n\t};\n}\nfunction codexHostedToolResult(result) {\n\tif (!result || typeof result !== \"object\" || typeof result.success !== \"boolean\" || !Array.isArray(result.content)) return {\n\t\tsuccess: false,\n\t\ttext: \"OpenTag tool returned an invalid result.\"\n\t};\n\tconst text = [];\n\tfor (const item of result.content) {\n\t\tif (item?.type !== \"text\" || typeof item.text !== \"string\") return {\n\t\t\tsuccess: false,\n\t\t\ttext: \"OpenTag tool returned an invalid result.\"\n\t\t};\n\t\ttext.push(item.text);\n\t}\n\tif (result.error) {\n\t\tif (typeof result.error.code !== \"string\" || typeof result.error.message !== \"string\") return {\n\t\t\tsuccess: false,\n\t\t\ttext: \"OpenTag tool returned an invalid result.\"\n\t\t};\n\t\t/* v8 ignore else -- a failed tool result without content always synthesizes the error line. */\n\t\tif (text.length === 0) text.push(`${result.error.code}: ${result.error.message}`);\n\t}\n\treturn {\n\t\tsuccess: result.success,\n\t\ttext: text.join(\"\\n\")\n\t};\n}\nfunction codexInteractionRequest(request, params) {\n\tconst requestId = wireInteractionId(request.id);\n\tconst details = toJsonValue(params);\n\tif (request.method === \"item/commandExecution/requestApproval\" || request.method === \"item/fileChange/requestApproval\" || request.method === \"item/permissions/requestApproval\") return {\n\t\trequestId,\n\t\tkind: \"approval\",\n\t\ttitle: request.method === \"item/fileChange/requestApproval\" ? \"Approve file changes\" : \"Approve tool action\",\n\t\t...typeof params.reason === \"string\" ? { message: params.reason } : {},\n\t\tdetails\n\t};\n\tif (request.method === \"item/tool/requestUserInput\" || request.method === \"mcpServer/elicitation/request\") {\n\t\tconst message = typeof params.message === \"string\" ? params.message : void 0;\n\t\treturn {\n\t\t\trequestId,\n\t\t\tkind: \"question\",\n\t\t\ttitle: \"Codex needs input\",\n\t\t\t...message ? { message } : {},\n\t\t\tdetails\n\t\t};\n\t}\n}\nfunction codexInteractionResult(method, response) {\n\tif (response.kind === \"approval\") return codexApprovalResult(method, response);\n\treturn codexQuestionResult(method, response);\n}\nfunction codexApprovalResult(method, response) {\n\tif (method === \"item/permissions/requestApproval\") {\n\t\tif (response.decision !== \"accept\") return {\n\t\t\tpermissions: [],\n\t\t\tscope: \"turn\"\n\t\t};\n\t\tconst value = record(response.value);\n\t\treturn {\n\t\t\tpermissions: Array.isArray(value?.permissions) ? value.permissions : [],\n\t\t\tscope: response.scope === \"runtime\" ? \"session\" : \"turn\"\n\t\t};\n\t}\n\treturn { decision: response.decision === \"accept\" ? response.scope === \"runtime\" ? \"acceptForSession\" : \"accept\" : response.decision };\n}\nfunction codexQuestionResult(method, response) {\n\tif (method === \"mcpServer/elicitation/request\") return response.decision === \"answer\" ? {\n\t\taction: \"accept\",\n\t\tcontent: response.value ?? null\n\t} : {\n\t\taction: \"cancel\",\n\t\tcontent: null\n\t};\n\treturn { answers: response.decision === \"answer\" ? response.value ?? {} : {} };\n}\nfunction parseTurnResponse(value, source) {\n\treturn parseTurn(requireRecord(value, `${source} returned an invalid response`).turn, source);\n}\nfunction parseTurn(value, source) {\n\tconst turn = requireRecord(value, `${source} has no turn`);\n\tconst id = requireString(turn.id, `${source} turn has no id`);\n\tconst status = turn.status;\n\tif (status !== \"completed\" && status !== \"failed\" && status !== \"inProgress\" && status !== \"interrupted\") throw protocolError(`${source} turn has an invalid status`);\n\tconst items = Array.isArray(turn.items) ? turn.items.map((item) => requireRecord(item, `${source} has an invalid item`)) : [];\n\tconst error = record(turn.error);\n\treturn {\n\t\tid,\n\t\tstatus,\n\t\titems,\n\t\t...typeof error?.message === \"string\" ? { error: error.message } : {}\n\t};\n}\nfunction parseUsage(value) {\n\tconst tokenUsage = requireRecord(value, \"token usage is invalid\");\n\tconst source = record(tokenUsage.last) ?? record(tokenUsage.total) ?? tokenUsage;\n\tconst usage = {};\n\tif (isNonNegativeNumber(source.inputTokens)) usage.inputTokens = source.inputTokens;\n\tif (isNonNegativeNumber(source.cachedInputTokens)) usage.cachedInputTokens = source.cachedInputTokens;\n\tif (isNonNegativeNumber(source.outputTokens)) usage.outputTokens = source.outputTokens;\n\treturn usage;\n}\nfunction selectFinalText(terminalItems, completed) {\n\tconst messages = new Map(completed);\n\tfor (const item of terminalItems) {\n\t\tif (item.type !== \"agentMessage\" || typeof item.id !== \"string\" || typeof item.text !== \"string\") continue;\n\t\tmessages.set(item.id, {\n\t\t\ttext: item.text,\n\t\t\t...typeof item.phase === \"string\" ? { phase: item.phase } : {}\n\t\t});\n\t}\n\tlet fallback;\n\tfor (const message of messages.values()) {\n\t\tif (message.phase === \"final_answer\") return message.text;\n\t\tif (message.phase !== \"commentary\") fallback = message.text;\n\t}\n\treturn fallback;\n}\nfunction toolName(item, type) {\n\tif (type === \"mcpToolCall\") return `${typeof item.server === \"string\" ? item.server : \"mcp\"}/${typeof item.tool === \"string\" ? item.tool : \"tool\"}`;\n\tif (type === \"dynamicToolCall\" && typeof item.tool === \"string\") return item.tool;\n\treturn type;\n}\nfunction wireInteractionId(id) {\n\treturn `${typeof id}:${String(id)}`;\n}\nfunction toJsonValue(value) {\n\tassertJsonValue(value, \"Codex event payload\");\n\treturn value;\n}\nfunction deferred() {\n\tlet resolveValue;\n\tlet rejectValue;\n\treturn {\n\t\tpromise: new Promise((resolve, reject) => {\n\t\t\tresolveValue = resolve;\n\t\t\trejectValue = reject;\n\t\t}),\n\t\tresolve: resolveValue,\n\t\treject: rejectValue\n\t};\n}\nfunction protocolError(message) {\n\treturn new AgentProviderError(\"provider_protocol_error\", message);\n}\nfunction record(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value) ? value : void 0;\n}\nfunction requireRecord(value, message) {\n\tconst result = record(value);\n\tif (!result) throw protocolError(message);\n\treturn result;\n}\nfunction requireString(value, message, allowEmpty = false) {\n\tif (typeof value !== \"string\" || !allowEmpty && value.length === 0 || Buffer.byteLength(value, \"utf8\") > 1048576) throw protocolError(message);\n\treturn value;\n}\nfunction isNonNegativeNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n//#endregion\n//#region src/runtime/admission-controller.ts\nconst DEFAULT_LIMITS = {\n\tsession: 1,\n\tagent: 10,\n\tclient: 99\n};\nvar AdmissionReservation = class {\n\tsessionId;\n\tagentId;\n\treleaseOwner;\n\t#phase = \"provisional\";\n\tconstructor(sessionId, agentId, releaseOwner) {\n\t\tthis.sessionId = sessionId;\n\t\tthis.agentId = agentId;\n\t\tthis.releaseOwner = releaseOwner;\n\t}\n\tget phase() {\n\t\treturn this.#phase;\n\t}\n\tmarkActive() {\n\t\tthis.#transition(\"active\");\n\t}\n\tmarkReporting() {\n\t\tthis.#transition(\"reporting\");\n\t}\n\trelease() {\n\t\tif (this.#phase === \"released\") return;\n\t\tthis.#phase = \"released\";\n\t\tthis.releaseOwner(this);\n\t}\n\t#transition(next) {\n\t\tif (this.#phase === \"released\") throw new Error(\"A released admission reservation cannot transition\");\n\t\tif (next === \"active\" && this.#phase !== \"provisional\") throw new Error(\"Only a provisional reservation can become active\");\n\t\tif (next === \"reporting\" && this.#phase !== \"active\") throw new Error(\"Only an active reservation can become reporting\");\n\t\tthis.#phase = next;\n\t}\n};\nvar AdmissionController = class {\n\t#limits;\n\t#sessions = /* @__PURE__ */ new Map();\n\t#agents = /* @__PURE__ */ new Map();\n\t#releaseWaiters = /* @__PURE__ */ new Set();\n\t#paused = false;\n\tconstructor(limits = {}) {\n\t\tthis.#limits = {\n\t\t\t...DEFAULT_LIMITS,\n\t\t\t...limits\n\t\t};\n\t\tfor (const [name, limit] of Object.entries(this.#limits)) if (!Number.isSafeInteger(limit) || limit < 1) throw new Error(`${name} admission limit must be positive`);\n\t\tif (this.#limits.session !== 1) throw new Error(\"The V0 Session admission limit must be exactly one\");\n\t}\n\treserve(sessionId, agentId, options = {}) {\n\t\tif (this.#paused && !options.acceptedWork) return {\n\t\t\taccepted: false,\n\t\t\treason: \"client_busy\"\n\t\t};\n\t\tif (this.#sessions.has(sessionId)) return {\n\t\t\taccepted: false,\n\t\t\treason: \"session_busy\"\n\t\t};\n\t\tif ((this.#agents.get(agentId) ?? 0) >= this.#limits.agent) return {\n\t\t\taccepted: false,\n\t\t\treason: \"agent_busy\"\n\t\t};\n\t\tif (this.#sessions.size >= this.#limits.client) return {\n\t\t\taccepted: false,\n\t\t\treason: \"client_busy\"\n\t\t};\n\t\tconst reservation = new AdmissionReservation(sessionId, agentId, (released) => this.#release(released));\n\t\tthis.#sessions.set(sessionId, reservation);\n\t\tthis.#agents.set(agentId, (this.#agents.get(agentId) ?? 0) + 1);\n\t\treturn {\n\t\t\taccepted: true,\n\t\t\treservation\n\t\t};\n\t}\n\t/** Stop taking new work while already accepted work continues to drain. */\n\tpause() {\n\t\tthis.#paused = true;\n\t}\n\t/** Resume ordinary admission after an update attempt fails or is superseded. */\n\tresume() {\n\t\tthis.#paused = false;\n\t}\n\tget paused() {\n\t\treturn this.#paused;\n\t}\n\tget(sessionId) {\n\t\treturn this.#sessions.get(sessionId);\n\t}\n\tsnapshot() {\n\t\treturn {\n\t\t\tactiveAgents: new Map(this.#agents),\n\t\t\tclient: this.#sessions.size,\n\t\t\tsessions: this.#sessions.size\n\t\t};\n\t}\n\twaitForRelease(signal) {\n\t\tif (signal?.aborted) return Promise.reject(signal.reason);\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.#releaseWaiters.delete(onRelease);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst onRelease = () => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve();\n\t\t\t};\n\t\t\tconst onAbort = () => {\n\t\t\t\tcleanup();\n\t\t\t\treject(signal?.reason);\n\t\t\t};\n\t\t\tthis.#releaseWaiters.add(onRelease);\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t});\n\t}\n\t#release(reservation) {\n\t\tif (this.#sessions.get(reservation.sessionId) !== reservation) return;\n\t\tthis.#sessions.delete(reservation.sessionId);\n\t\tconst count = this.#agents.get(reservation.agentId) ?? 0;\n\t\tif (count <= 1) this.#agents.delete(reservation.agentId);\n\t\telse this.#agents.set(reservation.agentId, count - 1);\n\t\tfor (const waiter of [...this.#releaseWaiters]) waiter();\n\t}\n};\n//#endregion\n//#region src/runtime/protected-paths.ts\nconst MACOS_PROTECTED_HOME_SUBPATHS = [\n\t\"Desktop\",\n\t\"Documents\",\n\t\"Downloads\",\n\t\"Library/Mobile Documents\",\n\t\"Library/CloudStorage\"\n];\nconst MAX_SYMLINK_HOPS = 32;\nfunction protectedRoots(platform = process.platform, home = process.env.HOME && process.env.HOME.length > 0 ? process.env.HOME : homedir()) {\n\tif (platform !== \"darwin\") return [];\n\treturn MACOS_PROTECTED_HOME_SUBPATHS.map((subpath) => join(home, subpath));\n}\nfunction fold(value) {\n\treturn value.toLocaleLowerCase(\"en-US\");\n}\nfunction insideAny(path, roots) {\n\tconst candidate = fold(path);\n\treturn roots.some((root) => {\n\t\tconst protectedRoot = fold(root);\n\t\treturn candidate === protectedRoot || candidate.startsWith(`${protectedRoot}${sep}`);\n\t});\n}\n/** Resolve symlink hops without entering a macOS TCC-protected directory. */\nfunction resolveOutsideProtectedRoots(path, roots, readLink = readlinkSync) {\n\tlet pending = resolve(path).split(sep).filter(Boolean);\n\tlet resolved = sep;\n\tlet hops = 0;\n\twhile (pending.length > 0) {\n\t\tconst [head = \"\", ...rest] = pending;\n\t\tconst candidate = join(resolved, head);\n\t\tif (insideAny(candidate, roots)) return null;\n\t\tlet target = null;\n\t\ttry {\n\t\t\ttarget = readLink(candidate);\n\t\t} catch {}\n\t\tif (target === null) {\n\t\t\tresolved = candidate;\n\t\t\tpending = rest;\n\t\t\tcontinue;\n\t\t}\n\t\thops += 1;\n\t\tif (hops > MAX_SYMLINK_HOPS) return null;\n\t\tconst expanded = isAbsolute(target) ? target : join(resolved, target);\n\t\tpending = [...resolve(expanded).split(sep).filter(Boolean), ...rest];\n\t\tresolved = sep;\n\t}\n\treturn resolved;\n}\nfunction automaticCandidateAllowed(candidate, options = {}) {\n\tconst roots = protectedRoots(options.platform, options.home);\n\tif (roots.length === 0) return true;\n\treturn resolveOutsideProtectedRoots(candidate, roots, options.readLink) !== null;\n}\n//#endregion\n//#region src/runtime/install-locations.ts\nconst logger$13 = createLogger(\"runtime-install-locations\");\n/**\n* The `bin` dir to fall back to when a version manager's per-session `$PATH`\n* entry is gone, or nothing when the selected version cannot be established.\n*\n* The answer must never be a guess. Resolving a version the user did not select\n* silently swaps the executable and its context, which is worse than reporting\n* the provider as not found, so the decision is made across the complete state\n* rather than per root:\n*\n*   - The login shell reported exactly one manager. Only that is used.\n*     `$NVM_BIN` names the selected version outright and is authoritative,\n*     replacing any nvm enumeration. `$FNM_DIR` names only the active root, so\n*     that root — and no other — is consulted, and it answers only if it holds\n*     exactly one version. Default roots are not scanned at all: if we know\n*     which manager is active and it cannot answer, an unrelated installation\n*     is not a better answer.\n*   - The login shell reported BOTH managers. Which one was active was decided\n*     by the live `$PATH` order, which is exactly what is no longer available,\n*     so neither answers.\n*   - The login shell reported nothing. The default roots are scanned and the\n*     result is used only when there is exactly ONE safe candidate in total.\n*     Any safe root holding more than one version, or two single-version roots,\n*     is globally ambiguous.\n*\n* It is a FALLBACK, not a preference: callers search it only after the\n* login-shell dirs, so a live selection always wins.\n*\n* Every root is vetted with the injected platform/home protected roots before\n* it is listed, and every candidate before it is returned. Nothing is trusted\n* for being spelled like a version manager.\n*/\nfunction versionManagerBinDirs(home, deps = {}) {\n\tconst readDir = deps.readDir ?? ((path) => readdirSync(path));\n\tconst readLink = deps.readLink;\n\tconst env = deps.env ?? process.env;\n\tconst active = deps.active ?? {};\n\tconst protectedRootList = protectedRoots(deps.platform ?? process.platform, deps.home ?? home);\n\tconst safe = (path) => {\n\t\tif (!isAbsolute(path)) return null;\n\t\tif (protectedRootList.length === 0) return path;\n\t\treturn resolveOutsideProtectedRoots(path, protectedRootList, readLink);\n\t};\n\tconst scanRoot = (root, layout) => {\n\t\tconst vetted = safe(root);\n\t\tif (vetted === null) return { kind: \"skip\" };\n\t\tlet entries;\n\t\ttry {\n\t\t\tentries = readDir(vetted);\n\t\t} catch (error) {\n\t\t\tlogger$13.debug({\n\t\t\t\tcode: \"version_manager_scan_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Version manager directory scan failed\");\n\t\t\treturn { kind: \"skip\" };\n\t\t}\n\t\tif (entries.length === 0) return { kind: \"skip\" };\n\t\tif (entries.length !== 1 || entries[0] === void 0) return { kind: \"ambiguous\" };\n\t\tconst candidate = layout(vetted, entries[0]);\n\t\tconst vettedCandidate = safe(candidate);\n\t\tif (vettedCandidate === null) return { kind: \"skip\" };\n\t\treturn {\n\t\t\tkind: \"one\",\n\t\t\tdir: vettedCandidate\n\t\t};\n\t};\n\tconst nvmLayout = (versionsRoot, version) => join(versionsRoot, version, \"bin\");\n\tconst fnmLayout = (versionsRoot, version) => join(versionsRoot, version, \"installation\", \"bin\");\n\tif (active.nvmBin !== void 0 || active.fnmDir !== void 0) {\n\t\tif (active.nvmBin !== void 0 && active.fnmDir !== void 0) return [];\n\t\tif (active.nvmBin !== void 0) {\n\t\t\tconst vetted = safe(active.nvmBin);\n\t\t\treturn vetted === null ? [] : [vetted];\n\t\t}\n\t\tconst scanned = scanRoot(join(active.fnmDir ?? \"\", \"node-versions\"), fnmLayout);\n\t\treturn scanned.kind === \"one\" ? [scanned.dir] : [];\n\t}\n\tconst defaultRoots = [[join(home, \".nvm\", \"versions\", \"node\"), nvmLayout], ...[\n\t\tenv.FNM_DIR,\n\t\tjoin(home, \".local\", \"share\", \"fnm\"),\n\t\tjoin(home, \"Library\", \"Application Support\", \"fnm\"),\n\t\tjoin(home, \".fnm\")\n\t].filter((root) => typeof root === \"string\" && root.length > 0).map((root) => [join(root, \"node-versions\"), fnmLayout])];\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst scans = [];\n\tfor (const [root, layout] of defaultRoots) {\n\t\tif (seen.has(root)) continue;\n\t\tseen.add(root);\n\t\tscans.push(scanRoot(root, layout));\n\t}\n\tif (scans.some((scan) => scan.kind === \"ambiguous\")) return [];\n\tconst ones = scans.filter((scan) => scan.kind === \"one\");\n\tconst only = ones.length === 1 ? ones[0] : void 0;\n\treturn only ? [only.dir] : [];\n}\n//#endregion\n//#region src/runtime/login-shell-path.ts\n/**\n* Unique marker that brackets the canonical dir list in the probe output so we\n* can isolate it from any prompt / rc-file noise the interactive login shell\n* prints. Chosen to be vanishingly unlikely to appear in a real PATH entry.\n*/\nconst LOGIN_SHELL_PATH_DELIM = \"__OT_SHELL_PATH__\";\n/**\n* Brackets a second section carrying the version-manager variables the login\n* shell exported. Reading an environment variable costs no filesystem access at\n* all, which is why these can be captured here while a symlink target cannot.\n*/\nconst LOGIN_SHELL_ENV_DELIM = \"__OT_SHELL_ENV__\";\nconst LOGIN_SHELL_PROBE_TIMEOUT_MS = 4e3;\nconst LOGIN_SHELL_PROBE_KILL_SIGNAL = \"SIGKILL\";\n/** Cached successful probe or the settled skip, kept for the process. */\nlet memo;\n/** In-flight probe shared by concurrent callers so one spawn serves them all. */\nlet inFlight;\n/** Count of probe spawns that did NOT succeed, used to enforce the attempt cap. */\nlet failedAttempts = 0;\nasync function probeLoginShellPath(deps = {}) {\n\tif (memo) return memo;\n\tif (inFlight) return inFlight;\n\tconst pending = runProbe(deps);\n\tinFlight = pending;\n\ttry {\n\t\treturn await pending;\n\t} finally {\n\t\tif (inFlight === pending) inFlight = void 0;\n\t}\n}\nasync function runProbe(deps) {\n\tconst logger = deps.logger ?? createLogger(\"runtime-login-shell-path\");\n\tif ((deps.platform ?? process.platform) === \"win32\") {\n\t\tmemo = {\n\t\t\tok: false,\n\t\t\tdirs: [],\n\t\t\tenv: {}\n\t\t};\n\t\treturn memo;\n\t}\n\tconst probed = await readProbe(deps.runShell ?? (() => defaultRunShell(deps)), logger);\n\tif (probed) {\n\t\tconst result = interpretProbe(probed, deps);\n\t\tmemo = result;\n\t\treturn result;\n\t}\n\tfailedAttempts += 1;\n\tlogger.debug({\n\t\tattempt: failedAttempts,\n\t\tcode: \"probe_failed\"\n\t}, \"Login shell PATH probe failed\");\n\tif (failedAttempts >= 3) {\n\t\tmemo = {\n\t\t\tok: false,\n\t\t\tdirs: [],\n\t\t\tenv: {}\n\t\t};\n\t\treturn memo;\n\t}\n\treturn {\n\t\tok: false,\n\t\tdirs: [],\n\t\tenv: {}\n\t};\n}\nasync function readProbe(runShell, logger) {\n\tlet output;\n\ttry {\n\t\toutput = await runShell();\n\t} catch (error) {\n\t\tlogger.debug({\n\t\t\tcode: \"shell_execution_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Login shell execution failed\");\n\t\treturn null;\n\t}\n\tif (!output) {\n\t\tlogger.debug({ code: \"shell_output_empty\" }, \"Login shell returned no probe output\");\n\t\treturn null;\n\t}\n\tconst dirs = parsePathFromShellOutput(output);\n\tif (dirs === null) {\n\t\tlogger.debug({ code: \"shell_path_markers_missing\" }, \"Login shell probe markers were missing\");\n\t\treturn null;\n\t}\n\treturn {\n\t\tdirs,\n\t\tenv: parseShellEnv(output)\n\t};\n}\nfunction interpretProbe(probed, deps) {\n\tconst platform = deps.platform ?? process.platform;\n\tconst environment = deps.environment ?? {};\n\tconst roots = protectedRoots(platform, deps.home ?? (environment.HOME && environment.HOME.length > 0 ? environment.HOME : void 0) ?? (process.env.HOME && process.env.HOME.length > 0 ? process.env.HOME : homedir()));\n\tconst vet = (dir) => roots.length === 0 ? dir : resolveOutsideProtectedRoots(dir, roots, deps.readLink);\n\tconst untrusted = platform === \"darwin\" && probed.env.nvmBin !== void 0 && probed.env.fnmDir !== void 0 ? [probed.env.nvmBin, probed.env.fnmDir].map(vet).filter((dir) => dir !== null) : [];\n\tconst trusted = (dir) => !untrusted.some((root) => dir === root || dir.startsWith(`${root}${sep}`));\n\treturn {\n\t\tok: true,\n\t\tdirs: probed.dirs.map(vet).filter((dir) => dir !== null).filter(trusted),\n\t\tenv: probed.env\n\t};\n}\n/**\n* Build the probe command the login shell launches: it prints, bracketed by\n* {@link LOGIN_SHELL_PATH_DELIM}, the dirs of `$PATH` — one per line.\n*\n* The login shell is used only as a launcher: it runs a single opaque\n* `/bin/sh -c '…'` token, and ALL of the `$PATH` splitting and canonicalization\n* happens inside that nested POSIX `sh`.\n*\n* Off macOS each dir is canonicalized with `(cd \"$d\" && pwd -P)` while the\n* login shell — and any per-session fnm/nvm multishell symlink — is still\n* alive. On macOS this script performs no filesystem access at all: it only\n* prints `$PATH`, and {@link probeLoginShellPath} resolves via\n* {@link resolveOutsideProtectedRoots} so a dir that lands in a TCC-protected\n* root is dropped without being entered.\n*/\nfunction buildProbeScript(platform = process.platform) {\n\treturn `/bin/sh -c '${`printf %s ${LOGIN_SHELL_PATH_DELIM}; set -f; IFS=:; for d in $PATH; do [ -n \"$d\" ] || continue; ${platform === \"darwin\" ? \"printf \\\"%s\\\\n\\\" \\\"$d\\\"\" : \"(cd \\\"$d\\\" 2>/dev/null && pwd -P)\"}; done; printf %s ${LOGIN_SHELL_PATH_DELIM}; printf %s ${LOGIN_SHELL_ENV_DELIM}; printf \"%s\\n%s\\n\" \"$FNM_DIR\" \"$NVM_BIN\"; printf %s ${LOGIN_SHELL_ENV_DELIM}`}'`;\n}\nfunction defaultRunShell(deps = {}) {\n\tconst logger = deps.logger ?? createLogger(\"runtime-login-shell-path\");\n\tconst platform = deps.platform ?? process.platform;\n\tconst environment = deps.environment ?? process.env;\n\tconst spawnFn = deps.spawn ?? spawn;\n\tconst shell = pickShell(environment, platform);\n\treturn new Promise((resolve) => {\n\t\tlet settled = false;\n\t\tlet timer;\n\t\tconst finish = (value) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tresolve(value);\n\t\t};\n\t\tlet child;\n\t\ttry {\n\t\t\tchild = spawnFn(shell, [\"-lic\", buildProbeScript(platform)], {\n\t\t\t\tstdio: [\n\t\t\t\t\t\"ignore\",\n\t\t\t\t\t\"pipe\",\n\t\t\t\t\t\"ignore\"\n\t\t\t\t],\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv: environment\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.debug({\n\t\t\t\tcode: \"shell_spawn_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Login shell could not be spawned\");\n\t\t\tfinish(null);\n\t\t\treturn;\n\t\t}\n\t\tconst killAndSettle = () => {\n\t\t\ttry {\n\t\t\t\tchild.kill(LOGIN_SHELL_PROBE_KILL_SIGNAL);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.debug({\n\t\t\t\t\tcode: \"shell_probe_kill_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Login shell probe kill failed\");\n\t\t\t}\n\t\t\tchild.stdout?.destroy();\n\t\t\tfinish(null);\n\t\t};\n\t\ttimer = setTimeout(killAndSettle, LOGIN_SHELL_PROBE_TIMEOUT_MS);\n\t\ttimer.unref();\n\t\tlet stdout = \"\";\n\t\tchild.stdout?.setEncoding(\"utf8\");\n\t\tchild.stdout?.on(\"data\", (chunk) => {\n\t\t\tif (settled) return;\n\t\t\tstdout += chunk;\n\t\t\tif (Buffer.byteLength(stdout, \"utf8\") > 65536) killAndSettle();\n\t\t});\n\t\tchild.on(\"error\", (error) => {\n\t\t\tlogger.debug({\n\t\t\t\tcode: \"shell_process_error\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Login shell process failed\");\n\t\t\tfinish(null);\n\t\t});\n\t\tchild.on(\"close\", (status, signal) => {\n\t\t\tif (signal || status !== 0) finish(null);\n\t\t\telse finish(stdout);\n\t\t});\n\t});\n}\nfunction pickShell(environment, platform) {\n\tconst shell = environment.SHELL;\n\tif (shell && shell.length > 0) return shell;\n\treturn platform === \"darwin\" ? \"/bin/zsh\" : \"/bin/bash\";\n}\nfunction parseShellEnv(output) {\n\tconst start = output.indexOf(LOGIN_SHELL_ENV_DELIM);\n\tif (start < 0) return {};\n\tconst end = output.indexOf(LOGIN_SHELL_ENV_DELIM, start + 16);\n\tif (end < 0) return {};\n\tconst [fnmDir, nvmBin] = output.slice(start + 16, end).split(\"\\n\");\n\treturn {\n\t\t...fnmDir ? { fnmDir } : {},\n\t\t...nvmBin ? { nvmBin } : {}\n\t};\n}\nfunction parsePathFromShellOutput(output) {\n\tconst start = output.indexOf(LOGIN_SHELL_PATH_DELIM);\n\tif (start < 0) return null;\n\tconst end = output.indexOf(LOGIN_SHELL_PATH_DELIM, start + 17);\n\tif (end < 0) return null;\n\treturn output.slice(start + 17, end).split(\"\\n\").filter((dir) => dir.length > 0);\n}\n//#endregion\n//#region src/runtime/agent-runtime-installation.ts\nconst PROVIDERS = [\n\t{\n\t\tprovider: \"codex\",\n\t\tdisplayName: \"Codex CLI\",\n\t\tcommand: \"codex\"\n\t},\n\t{\n\t\tprovider: \"claude-code\",\n\t\tdisplayName: \"Claude Code CLI\",\n\t\tcommand: \"claude\"\n\t},\n\t{\n\t\tprovider: \"pi\",\n\t\tdisplayName: \"Pi CLI\",\n\t\tcommand: \"pi\"\n\t}\n];\nconst defaultInstallationLogger = createLogger(\"runtime-agent-installation\");\nvar AgentRuntimeExecutableNotFoundError = class extends Error {\n\tname = \"AgentRuntimeExecutableNotFoundError\";\n};\nvar AgentRuntimeExecutableDiscoveryError = class extends Error {\n\tname = \"AgentRuntimeExecutableDiscoveryError\";\n};\n/** Cheap, spawn-free directories mirrored from First Tree's install-only discovery. */\nfunction wellKnownAgentRuntimeBinDirs(home, platform = process.platform) {\n\treturn [\n\t\tjoin(home, \".local\", \"bin\"),\n\t\tjoin(home, \".claude\", \"local\"),\n\t\tjoin(home, \".volta\", \"bin\"),\n\t\tjoin(home, \".asdf\", \"shims\"),\n\t\tjoin(home, \".local\", \"share\", \"mise\", \"shims\"),\n\t\tjoin(home, \".npm-global\", \"bin\"),\n\t\tjoin(home, \".local\", \"share\", \"pnpm\"),\n\t\t...platform === \"darwin\" ? [join(home, \"Library\", \"pnpm\")] : [],\n\t\tjoin(home, \".bun\", \"bin\"),\n\t\t...platform === \"darwin\" ? [\"/opt/homebrew/bin\"] : [],\n\t\t\"/usr/local/bin\",\n\t\t\"/usr/bin\",\n\t\t\"/bin\"\n\t];\n}\nfunction codexDesktopAppBinDirs(home, platform = process.platform) {\n\tif (platform !== \"darwin\") return [];\n\treturn [\n\t\tjoin(\"/Applications\", \"ChatGPT.app\", \"Contents\", \"Resources\"),\n\t\tjoin(home, \"Applications\", \"ChatGPT.app\", \"Contents\", \"Resources\"),\n\t\tjoin(\"/Applications\", \"Codex.app\", \"Contents\", \"Resources\"),\n\t\tjoin(home, \"Applications\", \"Codex.app\", \"Contents\", \"Resources\")\n\t];\n}\nfunction includeLoginShellEnabled(options = {}) {\n\tconst value = options.includeLoginShell;\n\tif (typeof value === \"function\") return value();\n\treturn value !== false;\n}\n/**\n* Same-Provider candidate fallback is allowed only when the full readiness\n* result contains at least one issue and every issue is binary-shaped.\n* Credential, configuration, transient, mixed, or empty results must not\n* advance, and another Provider must never be substituted.\n*/\nfunction canAdvanceRuntimeCandidate(result) {\n\tif (result.ready || result.issues.length === 0) return false;\n\treturn result.issues.every((issue) => issue.code === \"artifact_missing\" || issue.code === \"version_incompatible\");\n}\nasync function resolveAgentRuntimeExecutable(provider, command, environment, options = {}) {\n\tfor await (const candidate of iterateAgentRuntimeExecutables(provider, command, environment, options)) return candidate;\n\tthrow new AgentRuntimeExecutableNotFoundError(`The ${provider} Agent Runtime CLI is not installed`);\n}\n/**\n* Command-only install-only discovery. Desktop-app lookup is Codex-specific, so this\n* resolver never searches ChatGPT/Codex app bundles unless the caller passes dirs.\n*/\nasync function resolveInstalledCliExecutable(command, environment, options = {}) {\n\tfor await (const candidate of iterateAgentRuntimeExecutables(\"claude-code\", command, environment, {\n\t\t...options,\n\t\tdesktopAppDirs: options.desktopAppDirs ?? (() => [])\n\t})) return {\n\t\tpath: candidate.path,\n\t\tsearchDir: candidate.searchDir,\n\t\tsource: candidate.source\n\t};\n\tthrow new AgentRuntimeExecutableNotFoundError(`The ${command} CLI is not installed`);\n}\nasync function probeInstalledCliCommand(command, environment, options = {}) {\n\tconst logger = installationLogger(options);\n\ttry {\n\t\tconst resolved = await resolveInstalledCliExecutable(command, environment, options);\n\t\treturn {\n\t\t\tstatus: \"installed\",\n\t\t\tpath: resolved.path,\n\t\t\tsource: resolved.source\n\t\t};\n\t} catch (error) {\n\t\tif (error instanceof AgentRuntimeExecutableNotFoundError) return { status: \"not-installed\" };\n\t\tlogger.debug({\n\t\t\tcode: \"cli_probe_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Agent Runtime CLI probe failed\");\n\t\treturn {\n\t\t\tstatus: \"unknown\",\n\t\t\tdetail: safeErrorDetail$1(error, \"CLI installation could not be determined\")\n\t\t};\n\t}\n}\n/**\n* Lazy installed-candidate sequence. Later, more expensive sources are only\n* evaluated when the consumer asks for the next candidate — the common case of\n* a single working hit therefore keeps today's cost. An absolute explicit\n* command remains one candidate and never gains fallback sources.\n*/\nasync function* iterateAgentRuntimeExecutables(provider, command, environment, options = {}) {\n\tconst logger = installationLogger(options);\n\tconst dependencies = {\n\t\taccess: options.access ?? access,\n\t\trealpath: options.realpath ?? realpath,\n\t\tstat: options.stat ?? stat\n\t};\n\tif (isAbsolute(command)) {\n\t\tconst outcome = await inspectExecutableCandidate(command, dependencies, logger);\n\t\tif (outcome.status !== \"installed\") {\n\t\t\tif (outcome.status === \"unknown\") throw new AgentRuntimeExecutableDiscoveryError(outcome.detail);\n\t\t\tthrow new AgentRuntimeExecutableNotFoundError(`The ${provider} Agent Runtime CLI is not installed`);\n\t\t}\n\t\tyield {\n\t\t\tprovider,\n\t\t\tpath: outcome.path,\n\t\t\tsource: \"explicit\"\n\t\t};\n\t\treturn;\n\t}\n\tconst platform = options.platform ?? process.platform;\n\tconst home = options.home ?? environment.HOME ?? homedir();\n\tconst pathDelimiter = options.pathDelimiter ?? delimiter;\n\tconst wellKnownDirs = options.wellKnownDirs ?? wellKnownAgentRuntimeBinDirs;\n\tconst desktopAppDirs = options.desktopAppDirs ?? codexDesktopAppBinDirs;\n\tconst candidateAllowed = options.candidateAllowed ?? automaticCandidateAllowed;\n\tconst extensions = platform === \"win32\" ? (environment.PATHEXT ?? \".EXE;.CMD;.BAT\").split(\";\") : [\"\"];\n\tconst seenSearchPaths = /* @__PURE__ */ new Set();\n\tconst seenResolvedPaths = /* @__PURE__ */ new Set();\n\tlet firstUnknown;\n\tlet yielded = false;\n\tconst fromDirectories = async function* (directories, source) {\n\t\tfor (const candidate of executableCandidatesFrom({\n\t\t\tcommand,\n\t\t\tdirectories,\n\t\t\textensions,\n\t\t\tsource\n\t\t})) {\n\t\t\tif (seenSearchPaths.has(candidate.path)) continue;\n\t\t\tseenSearchPaths.add(candidate.path);\n\t\t\ttry {\n\t\t\t\tif (!candidateAllowed(candidate.path, {\n\t\t\t\t\tplatform,\n\t\t\t\t\thome\n\t\t\t\t})) continue;\n\t\t\t} catch (error) {\n\t\t\t\tlogger.debug({\n\t\t\t\t\tcode: \"candidate_safety_check_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Automatic Runtime candidate safety check failed\");\n\t\t\t\tfirstUnknown ??= \"An automatic Runtime candidate could not be inspected safely\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst outcome = await inspectExecutableCandidate(candidate.path, dependencies, logger);\n\t\t\tif (outcome.status === \"installed\") {\n\t\t\t\tif (seenResolvedPaths.has(outcome.path)) continue;\n\t\t\t\tseenResolvedPaths.add(outcome.path);\n\t\t\t\tyielded = true;\n\t\t\t\tyield {\n\t\t\t\t\tprovider,\n\t\t\t\t\tpath: outcome.path,\n\t\t\t\t\tsource: candidate.source,\n\t\t\t\t\tsearchDir: dirname(candidate.path)\n\t\t\t\t};\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (outcome.status === \"unknown\") firstUnknown ??= outcome.detail;\n\t\t}\n\t};\n\tyield* fromDirectories((environment.PATH ?? \"\").split(pathDelimiter).filter(Boolean), \"caller-path\");\n\tyield* fromDirectories(wellKnownDirs(home, platform), \"well-known\");\n\tif (provider === \"codex\") yield* fromDirectories(desktopAppDirs(home, platform), \"desktop-app\");\n\tif (includeLoginShellEnabled(options) && platform !== \"win32\") {\n\t\tconst login = await resolveLoginShellLayer(home, platform, environment, options);\n\t\tif (login) {\n\t\t\tyield* fromDirectories(login.dirs, \"login-shell\");\n\t\t\tyield* fromDirectories(login.versionManagerDirs, \"version-manager\");\n\t\t}\n\t}\n\tif (!yielded && firstUnknown) throw new AgentRuntimeExecutableDiscoveryError(firstUnknown);\n}\nasync function probeAgentRuntimeCliInstallations(options = {}) {\n\tconst environment = options.environment ?? process.env;\n\tconst logger = installationLogger(options);\n\treturn Promise.all(PROVIDERS.map(async ({ provider, displayName, command }) => {\n\t\ttry {\n\t\t\tconst resolved = await resolveAgentRuntimeExecutable(provider, options.commands?.[provider] ?? command, environment, options);\n\t\t\treturn {\n\t\t\t\tprovider,\n\t\t\t\tdisplayName,\n\t\t\t\tstatus: \"installed\",\n\t\t\t\tpath: resolved.path,\n\t\t\t\tsource: resolved.source\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof AgentRuntimeExecutableNotFoundError) return {\n\t\t\t\tprovider,\n\t\t\t\tdisplayName,\n\t\t\t\tstatus: \"not-installed\"\n\t\t\t};\n\t\t\tlogger.debug({\n\t\t\t\tcode: \"installation_probe_failed\",\n\t\t\t\tprovider,\n\t\t\t\terror: String(error)\n\t\t\t}, \"Agent Runtime installation probe failed\");\n\t\t\treturn {\n\t\t\t\tprovider,\n\t\t\t\tdisplayName,\n\t\t\t\tstatus: \"unknown\",\n\t\t\t\tdetail: safeErrorDetail$1(error, \"Runtime installation could not be determined\")\n\t\t\t};\n\t\t}\n\t}));\n}\nfunction installationLogger(options) {\n\treturn options.logger ?? defaultInstallationLogger;\n}\nasync function resolveLoginShellLayer(home, platform, environment, options) {\n\tconst versionManagerOptions = {\n\t\tenv: environment,\n\t\thome,\n\t\tplatform\n\t};\n\tif (options.loginShellPathDirs) {\n\t\tconst dirs = await options.loginShellPathDirs();\n\t\tconst active = await options.loginShellEnv?.() ?? {};\n\t\treturn {\n\t\t\tdirs,\n\t\t\tversionManagerDirs: options.versionManagerDirs ? options.versionManagerDirs(home, active) : versionManagerBinDirs(home, {\n\t\t\t\t...versionManagerOptions,\n\t\t\t\tactive\n\t\t\t})\n\t\t};\n\t}\n\tconst probed = await probeLoginShellPath({\n\t\tenvironment,\n\t\thome,\n\t\tlogger: options.logger,\n\t\tplatform,\n\t\trunShell: options.runShell,\n\t\tspawn: options.loginShellSpawn\n\t});\n\tif (!probed.ok) return void 0;\n\tconst versionDirs = options.versionManagerDirs ? options.versionManagerDirs(home, probed.env) : versionManagerBinDirs(home, {\n\t\t...versionManagerOptions,\n\t\tactive: probed.env\n\t});\n\treturn {\n\t\tdirs: probed.dirs,\n\t\tversionManagerDirs: versionDirs\n\t};\n}\nasync function inspectExecutableCandidate(candidate, dependencies, logger) {\n\ttry {\n\t\tif (!(await dependencies.stat(candidate)).isFile()) return { status: \"absent\" };\n\t} catch (error) {\n\t\tlogger.debug({\n\t\t\tcode: \"candidate_stat_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Runtime candidate stat failed\");\n\t\treturn missingOrUnknown(error);\n\t}\n\ttry {\n\t\tawait dependencies.access(candidate, constants.X_OK);\n\t} catch (error) {\n\t\tif (isMissing(error) || error?.code === \"EACCES\") return { status: \"absent\" };\n\t\tlogger.debug({\n\t\t\tcode: \"candidate_access_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Runtime candidate executable permission check failed\");\n\t\treturn {\n\t\t\tstatus: \"unknown\",\n\t\t\tdetail: \"A Runtime candidate's executable permission could not be inspected\"\n\t\t};\n\t}\n\ttry {\n\t\treturn {\n\t\t\tstatus: \"installed\",\n\t\t\tpath: await dependencies.realpath(candidate)\n\t\t};\n\t} catch (error) {\n\t\tlogger.debug({\n\t\t\tcode: \"candidate_realpath_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Runtime candidate canonicalization failed\");\n\t\treturn missingOrUnknown(error);\n\t}\n}\nfunction missingOrUnknown(error) {\n\tif (isMissing(error)) return { status: \"absent\" };\n\treturn {\n\t\tstatus: \"unknown\",\n\t\tdetail: \"A Runtime candidate could not be inspected safely\"\n\t};\n}\nfunction isMissing(error) {\n\tconst code = error?.code;\n\treturn code === \"ENOENT\" || code === \"ENOTDIR\";\n}\nfunction safeErrorDetail$1(error, fallback) {\n\tif (!(error instanceof Error) || error.message.length === 0) return fallback;\n\treturn error.message.slice(0, 300);\n}\nfunction* executableCandidatesFrom(options) {\n\tfor (const directory of options.directories) {\n\t\tif (!isAbsolute(directory)) continue;\n\t\tfor (const extension of options.extensions) yield {\n\t\t\tpath: join(directory, `${options.command}${extension}`),\n\t\t\tsource: options.source\n\t\t};\n\t}\n}\n//#endregion\n//#region src/runtime/runtime-paths.ts\nfunction deriveRuntimeKey(kind, id) {\n\tconst digest = createHash(\"sha256\").update(`${kind}\\0${id}`, \"utf8\").digest(\"hex\");\n\treturn `${kind[0]}-${digest.slice(0, 40)}`;\n}\nfunction agentRuntimePaths(home, agentId) {\n\tconst layout = resolveOpenTagHomeLayout(home);\n\tconst key = deriveRuntimeKey(\"agent\", agentId);\n\tconst workspaceRoot = resolve(layout.workspaces, key);\n\treturn {\n\t\tagentsFile: resolve(workspaceRoot, \"files\", \"AGENTS.md\"),\n\t\teffectiveSnapshotsRoot: layout.runtimeEffectiveSnapshots,\n\t\tfiles: resolve(workspaceRoot, \"files\"),\n\t\tlegacyAgentsFile: resolve(workspaceRoot, \"AGENTS.md\"),\n\t\truntimeRoot: layout.runtime,\n\t\tsessionBindingsRoot: layout.runtimeSessionBindings,\n\t\tsessions: resolve(layout.runtimeSessionBindings, key),\n\t\tsnapshots: resolve(layout.runtimeEffectiveSnapshots, key),\n\t\tworkspaceRoot,\n\t\tworkspaceState: resolve(layout.runtimeWorkspaceStates, `${key}.json`),\n\t\tworkspaceStatesRoot: layout.runtimeWorkspaceStates,\n\t\tworkspaceTransitionRoot: resolve(layout.runtime, \"workspace-transitions\", key)\n\t};\n}\nfunction sessionBindingPath(home, agentId, sessionId) {\n\tconst paths = agentRuntimePaths(home, agentId);\n\treturn resolve(paths.sessions, `${deriveRuntimeKey(\"session\", sessionId)}.json`);\n}\nfunction snapshotPath(home, agentId, snapshotHash) {\n\tconst paths = agentRuntimePaths(home, agentId);\n\treturn resolve(paths.snapshots, `${deriveRuntimeKey(\"snapshot\", snapshotHash)}.json`);\n}\nfunction sessionCliProofPath(home, sessionId) {\n\tconst layout = resolveOpenTagHomeLayout(home);\n\treturn resolve(layout.runtime, \"session-cli-proofs\", `${deriveRuntimeKey(\"session\", sessionId)}.json`);\n}\nfunction sessionCliProofRoot(home) {\n\treturn resolve(resolveOpenTagHomeLayout(home).runtime, \"session-cli-proofs\");\n}\n//#endregion\n//#region src/runtime/agent-workspace.ts\nconst logger$12 = createLogger(\"runtime-agent-workspace\");\nconst LEGACY_MANAGED_PLATFORM_PREFIX = [\n\t\"# OpenTag managed instructions\",\n\t\"\",\n\t\"This file is managed by OpenTag. Session-specific instructions are injected per turn.\",\n\t\"\",\n\t\"## Platform\",\n\t\"\"\n].join(\"\\n\");\nconst LEGACY_MANAGED_AGENT_SEPARATOR = \"\\n\\n## Agent\\n\\n\";\nconst KNOWN_LEGACY_PARTIAL_MIGRATIONS = [{\n\tsourcePlatform: \"You run inside OpenTag. IM output is never sent automatically. Use an opentag_message_* tool only when you intend to write to the current IM conversation.\",\n\ttargetPlatform: \"You run inside OpenTag. IM output is never sent automatically.\"\n}];\nvar AgentWorkspaceManager = class {\n\t#bindingStore;\n\t#home;\n\tconstructor(options) {\n\t\tthis.#bindingStore = options.bindingStore;\n\t\tthis.#home = options.home;\n\t}\n\tasync prepareAgent(snapshot, _hashes) {\n\t\tconst paths = agentRuntimePaths(this.#home, snapshot.agentId);\n\t\tawait ensurePrivateDirectory(this.#home, paths.workspaceStatesRoot);\n\t\tconst state = await readDurableJson(paths.workspaceState, parseAgentWorkspaceState);\n\t\tconst workspaceExists = await realDirectoryExists(paths.workspaceRoot);\n\t\tif (!state && workspaceExists && (await readdir(paths.workspaceRoot)).length > 0) throw new RuntimeStorageError(\"conflict\", \"A non-empty Agent workspace has no valid layout state\");\n\t\tawait ensurePrivateDirectory(this.#home, paths.workspaceRoot);\n\t\tif (!state) {\n\t\t\tawait writeDurableJson(paths.workspaceState, completeState(snapshot, \"root\"));\n\t\t\treturn;\n\t\t}\n\t\tvalidateWorkspaceIdentity(state, snapshot);\n\t\tif (\"managedInstructionsHash\" in state) {\n\t\t\tawait beginLegacyTransition(state, snapshot, paths);\n\t\t\treturn;\n\t\t}\n\t\tif (state.transition === \"pending\") {\n\t\t\tawait finishLegacyTransition(state, snapshot, paths);\n\t\t\treturn;\n\t\t}\n\t}\n\tasync prepareSession(request, hashes) {\n\t\treturn this.#bindingStore.prepare(request, hashes);\n\t}\n\tverifyAgent(snapshot, hashes) {\n\t\treturn this.prepareAgent(snapshot, hashes);\n\t}\n\tasync stopSession(_sessionId, _placementGeneration) {}\n\tasync cwd(agentId) {\n\t\tconst paths = agentRuntimePaths(this.#home, agentId);\n\t\tconst state = await readDurableJson(paths.workspaceState, parseAgentWorkspaceState);\n\t\tif (state?.schemaVersion !== 3 || state.transition !== \"complete\") throw new RuntimeStorageError(\"invalid\", \"Agent workspace compatibility transition is incomplete\");\n\t\tconst cwd = state.layout === \"legacy-files\" ? paths.files : paths.workspaceRoot;\n\t\tawait assertRealDirectory(cwd);\n\t\tconst canonicalHome = await realpath(this.#home);\n\t\tconst canonicalCwd = await realpath(cwd);\n\t\tassertWithin(canonicalHome, canonicalCwd);\n\t\treturn canonicalCwd;\n\t}\n\tpaths(agentId) {\n\t\treturn agentRuntimePaths(this.#home, agentId);\n\t}\n};\nasync function beginLegacyTransition(state, snapshot, paths) {\n\tawait ensurePrivateDirectory(paths.workspaceRoot, paths.files);\n\tawait ensurePrivateDirectory(paths.runtimeRoot, paths.workspaceTransitionRoot);\n\tconst root = await readSecureFile(paths.legacyAgentsFile);\n\tconst files = await readSecureFile(paths.agentsFile);\n\tconst rootHash = root === void 0 ? void 0 : sha256(root);\n\tconst managedRootHash = state.schemaVersion === 1 ? state.managedInstructionsHash : void 0;\n\tif (rootHash !== void 0 && rootHash !== managedRootHash) throw new RuntimeStorageError(\"conflict\", \"The legacy root AGENTS.md is not proven OpenTag-managed\");\n\tconst filesHash = files === void 0 ? void 0 : sha256(files);\n\tconst managedFilesHash = state.schemaVersion === 2 ? state.managedInstructionsHash : files !== void 0 && await isKnownLegacyPartialMigration(paths.agentsFile, state.managedInstructionsHash, root, files) ? filesHash : void 0;\n\tif (filesHash !== void 0 && filesHash !== managedFilesHash) throw new RuntimeStorageError(\"conflict\", \"The files/AGENTS.md is not proven OpenTag-managed\");\n\tconst pending = {\n\t\tschemaVersion: 3,\n\t\tagentId: state.agentId,\n\t\tworkspaceId: state.workspaceId,\n\t\tprovider: state.provider,\n\t\tlayout: \"legacy-files\",\n\t\ttransition: \"pending\",\n\t\tmanagedFiles: {\n\t\t\t...managedRootHash && rootHash ? { root: rootHash } : {},\n\t\t\t...managedFilesHash ? { files: managedFilesHash } : {}\n\t\t}\n\t};\n\tawait writeDurableJson(paths.workspaceState, pending);\n\tawait finishLegacyTransition(pending, snapshot, paths);\n}\nasync function finishLegacyTransition(state, snapshot, paths) {\n\tawait ensurePrivateDirectory(paths.workspaceRoot, paths.files);\n\tawait ensurePrivateDirectory(paths.runtimeRoot, paths.workspaceTransitionRoot);\n\tawait removeProvenManagedFile(paths.legacyAgentsFile, paths.workspaceTransitionRoot, \"root\", state.managedFiles.root);\n\tawait removeProvenManagedFile(paths.agentsFile, paths.workspaceTransitionRoot, \"files\", state.managedFiles.files);\n\tawait writeDurableJson(paths.workspaceState, completeState(snapshot, \"legacy-files\"));\n}\nasync function removeProvenManagedFile(path, quarantineRoot, kind, expectedHash) {\n\tif (!expectedHash) return;\n\tconst quarantine = resolve(quarantineRoot, `${kind}-${expectedHash}.managed`);\n\tassertWithin(quarantineRoot, quarantine);\n\tlet stranded;\n\tlet strandedIsReadOnly = false;\n\ttry {\n\t\tstranded = await readSecureFile(quarantine);\n\t\tif (stranded !== void 0) strandedIsReadOnly = isReadOnlyRegularFile(await lstat(quarantine));\n\t} catch (error) {\n\t\tlogger$12.debug({\n\t\t\tcode: \"quarantine_inspection_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Agent workspace quarantine inspection failed\");\n\t\tawait restoreQuarantinedEntry(quarantine, path);\n\t\tthrow new RuntimeStorageError(\"conflict\", \"A non-file Workspace entry was isolated during cleanup\");\n\t}\n\tif (stranded !== void 0) {\n\t\tif (sha256(stranded) !== expectedHash || !strandedIsReadOnly) {\n\t\t\tawait restoreQuarantinedEntry(quarantine, path);\n\t\t\tthrow new RuntimeStorageError(\"conflict\", \"A Workspace file changed while OpenTag isolated it for cleanup\");\n\t\t}\n\t\tawait removeDurableFile(quarantine);\n\t\treturn;\n\t}\n\tconst content = await readSecureFile(path);\n\tif (content === void 0) return;\n\tif (sha256(content) !== expectedHash) throw new RuntimeStorageError(\"conflict\", \"A proven OpenTag-managed instruction file changed during transition\");\n\tconst originalIdentity = await lstat(path);\n\tif (!isReadOnlyRegularFile(originalIdentity)) throw new RuntimeStorageError(\"conflict\", \"A proven OpenTag-managed instruction file is no longer read-only\");\n\tawait assertRealDirectory(dirname(path));\n\tawait assertRealDirectory(quarantineRoot);\n\ttry {\n\t\tawait rename(path, quarantine);\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return;\n\t\tlogger$12.debug({\n\t\t\tcode: \"workspace_quarantine_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Agent workspace quarantine failed\");\n\t\tthrow error;\n\t}\n\tawait syncDurableDirectory(dirname(path));\n\tawait syncDurableDirectory(quarantineRoot);\n\tlet isolated;\n\ttry {\n\t\tconst isolatedIdentity = await lstat(quarantine);\n\t\tif (!isolatedIdentity.isFile() || isolatedIdentity.isSymbolicLink() || isolatedIdentity.dev !== originalIdentity.dev || isolatedIdentity.ino !== originalIdentity.ino || !isReadOnlyRegularFile(isolatedIdentity)) {\n\t\t\tawait restoreQuarantinedEntry(quarantine, path);\n\t\t\tthrow new RuntimeStorageError(\"conflict\", \"A Workspace entry was replaced during cleanup\");\n\t\t}\n\t\tisolated = await readSecureFile(quarantine);\n\t} catch (error) {\n\t\tif (error instanceof RuntimeStorageError && error.code === \"conflict\") throw error;\n\t\tlogger$12.debug({\n\t\t\tcode: \"quarantine_verification_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Agent workspace quarantine verification failed\");\n\t\tawait restoreQuarantinedEntry(quarantine, path);\n\t\tthrow new RuntimeStorageError(\"conflict\", \"A Workspace entry changed while cleanup verified it\");\n\t}\n\tif (isolated === void 0 || sha256(isolated) !== expectedHash) {\n\t\tawait restoreQuarantinedEntry(quarantine, path);\n\t\tthrow new RuntimeStorageError(\"conflict\", \"A proven OpenTag-managed instruction file changed during cleanup\");\n\t}\n\tawait removeDurableFile(quarantine);\n}\nfunction isReadOnlyRegularFile(identity) {\n\treturn identity.isFile() && !identity.isSymbolicLink() && (identity.mode & 146) === 0;\n}\nasync function restoreQuarantinedEntry(quarantine, path) {\n\tlet status;\n\ttry {\n\t\tstatus = await lstat(quarantine);\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return;\n\t\tlogger$12.debug({\n\t\t\tcode: \"quarantine_restore_stat_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Agent workspace quarantine restore inspection failed\");\n\t\tthrow error;\n\t}\n\ttry {\n\t\tawait lstat(path);\n\t\treturn;\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t}\n\ttry {\n\t\tif (status.isFile() && !status.isSymbolicLink()) {\n\t\t\tawait copyFile(quarantine, path, constants.COPYFILE_EXCL);\n\t\t\tawait syncRestoredRegularFile(path);\n\t\t} else if (status.isSymbolicLink()) await symlink(await readlink(quarantine), path);\n\t\telse if (status.isDirectory()) await cp(quarantine, path, {\n\t\t\trecursive: true,\n\t\t\tforce: false,\n\t\t\terrorOnExist: true,\n\t\t\tpreserveTimestamps: true\n\t\t});\n\t\telse await link(quarantine, path);\n\t} catch (error) {\n\t\tif (error.code === \"EEXIST\") return;\n\t\tlogger$12.debug({\n\t\t\tcode: \"quarantine_restore_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Agent workspace quarantine restore failed\");\n\t\tthrow error;\n\t}\n\tawait syncDurableDirectory(dirname(path));\n}\nasync function syncRestoredRegularFile(path) {\n\tconst restored = await lstat(path);\n\tif (!restored.isFile() || restored.isSymbolicLink()) return;\n\tlet handle;\n\ttry {\n\t\thandle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));\n\t\tconst opened = await handle.stat();\n\t\tif (!opened.isFile() || opened.dev !== restored.dev || opened.ino !== restored.ino) return;\n\t\tawait handle.sync();\n\t} finally {\n\t\tawait handle?.close();\n\t}\n}\nasync function isKnownLegacyPartialMigration(path, managedRootHash, provenRootContent, content) {\n\tif (!matchesKnownLegacyPartialMigration(managedRootHash, provenRootContent, content)) return false;\n\treturn isReadOnlyRegularFile(await lstat(path));\n}\nfunction matchesKnownLegacyPartialMigration(managedRootHash, provenRootContent, content) {\n\tfor (const migration of KNOWN_LEGACY_PARTIAL_MIGRATIONS) {\n\t\tconst targetPrefix = `${LEGACY_MANAGED_PLATFORM_PREFIX}\\n${migration.targetPlatform}${LEGACY_MANAGED_AGENT_SEPARATOR}`;\n\t\tif (!content.startsWith(targetPrefix)) continue;\n\t\tconst agentSuffix = content.slice(targetPrefix.length);\n\t\tif (!agentSuffix.endsWith(\"\\n\")) continue;\n\t\tconst reconstructedRoot = `${`${LEGACY_MANAGED_PLATFORM_PREFIX}\\n${migration.sourcePlatform}${LEGACY_MANAGED_AGENT_SEPARATOR}`}${agentSuffix}`;\n\t\tif (sha256(reconstructedRoot) !== managedRootHash) continue;\n\t\tif (provenRootContent !== void 0 && provenRootContent !== reconstructedRoot) continue;\n\t\treturn true;\n\t}\n\treturn false;\n}\nfunction completeState(snapshot, layout) {\n\treturn {\n\t\tschemaVersion: 3,\n\t\tagentId: snapshot.agentId,\n\t\tworkspaceId: snapshot.workspace.workspaceId,\n\t\tprovider: snapshot.provider,\n\t\tlayout,\n\t\ttransition: \"complete\"\n\t};\n}\nfunction parseAgentWorkspaceState(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) throw new RuntimeStorageError(\"invalid\", \"Agent workspace state fields are invalid\");\n\tconst state = value;\n\tif (state.schemaVersion === 1 || state.schemaVersion === 2) return parseLegacyState(state);\n\tif (state.schemaVersion !== 3) throw new RuntimeStorageError(\"invalid\", \"Agent workspace state version is invalid\");\n\tassertExactFields(state, state.transition === \"pending\" ? [\n\t\t\"agentId\",\n\t\t\"layout\",\n\t\t\"managedFiles\",\n\t\t\"provider\",\n\t\t\"schemaVersion\",\n\t\t\"transition\",\n\t\t\"workspaceId\"\n\t] : [\n\t\t\"agentId\",\n\t\t\"layout\",\n\t\t\"provider\",\n\t\t\"schemaVersion\",\n\t\t\"transition\",\n\t\t\"workspaceId\"\n\t]);\n\tvalidateIdentityFields(state);\n\tif (state.layout !== \"root\" && state.layout !== \"legacy-files\") throw new RuntimeStorageError(\"invalid\", \"Agent workspace layout is invalid\");\n\tif (state.transition === \"complete\") return state;\n\tif (state.transition !== \"pending\" || state.layout !== \"legacy-files\") throw new RuntimeStorageError(\"invalid\", \"Agent workspace transition is invalid\");\n\tconst managedFiles = state.managedFiles;\n\tif (typeof managedFiles !== \"object\" || managedFiles === null || Array.isArray(managedFiles) || Object.keys(managedFiles).some((key) => key !== \"root\" && key !== \"files\")) throw new RuntimeStorageError(\"invalid\", \"Agent workspace transition provenance is invalid\");\n\tfor (const hash of Object.values(managedFiles)) if (!RuntimeSha256Schema.safeParse(hash).success) throw new RuntimeStorageError(\"invalid\", \"Agent workspace transition hash is invalid\");\n\treturn state;\n}\nfunction parseLegacyState(state) {\n\tassertExactFields(state, [\n\t\t\"agentConfigHash\",\n\t\t\"agentId\",\n\t\t\"appliedAgentRevisionId\",\n\t\t\"appliedAgentRevisionSequence\",\n\t\t\"managedInstructionsHash\",\n\t\t\"provider\",\n\t\t\"schemaVersion\",\n\t\t\"workspaceId\"\n\t]);\n\tvalidateIdentityFields(state);\n\tif (typeof state.appliedAgentRevisionSequence !== \"number\" || !Number.isSafeInteger(state.appliedAgentRevisionSequence) || state.appliedAgentRevisionSequence < 0 || typeof state.appliedAgentRevisionId !== \"string\" || !RuntimeSha256Schema.safeParse(state.agentConfigHash).success || !RuntimeSha256Schema.safeParse(state.managedInstructionsHash).success) throw new RuntimeStorageError(\"invalid\", \"Agent workspace state values are invalid\");\n\treturn state;\n}\nfunction validateIdentityFields(state) {\n\tif (typeof state.agentId !== \"string\" || typeof state.workspaceId !== \"string\" || typeof state.provider !== \"string\" || !isAgentRuntimeProviderId(state.provider)) throw new RuntimeStorageError(\"invalid\", \"Agent workspace identity values are invalid\");\n}\nfunction assertExactFields(state, fields) {\n\tif (Object.keys(state).sort().join(\",\") !== [...fields].sort().join(\",\")) throw new RuntimeStorageError(\"invalid\", \"Agent workspace state fields are invalid\");\n}\nfunction validateWorkspaceIdentity(state, snapshot) {\n\tif (state.agentId !== snapshot.agentId || state.workspaceId !== snapshot.workspace.workspaceId || state.provider !== snapshot.provider) throw new RuntimeStorageError(\"conflict\", \"Agent workspace identity cannot be changed\");\n}\nasync function realDirectoryExists(path) {\n\ttry {\n\t\tconst status = await lstat(path);\n\t\tif (!status.isDirectory() || status.isSymbolicLink()) throw new RuntimeStorageError(\"unsafe\", \"Agent workspace must be a real directory\");\n\t\treturn true;\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") return false;\n\t\tlogger$12.debug({\n\t\t\tcode: \"workspace_directory_check_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Agent workspace directory check failed\");\n\t\tthrow error;\n\t}\n}\nfunction sha256(value) {\n\treturn createHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n}\n//#endregion\n//#region src/runtime/session-reconciler.ts\nconst noopPreparation = {\n\tprepareAgent: async () => void 0,\n\tprepareSession: async () => void 0,\n\tstopSession: async () => void 0\n};\nvar SessionReconciler = class {\n\t#installationId;\n\t#preparation;\n\t#localPolicy;\n\t#maxRememberedRequests;\n\t#agents = /* @__PURE__ */ new Map();\n\t#sessions = /* @__PURE__ */ new Map();\n\t#activities = /* @__PURE__ */ new Map();\n\t#recoveries = /* @__PURE__ */ new Map();\n\t#requests = /* @__PURE__ */ new Map();\n\t#agentTails = /* @__PURE__ */ new Map();\n\tconstructor(options) {\n\t\tthis.#installationId = options.installationId;\n\t\tthis.#preparation = options.preparation ?? noopPreparation;\n\t\tthis.#localPolicy = options.localPolicy;\n\t\tthis.#maxRememberedRequests = options.maxRememberedRequests ?? 256;\n\t\tif (!Number.isSafeInteger(this.#maxRememberedRequests) || this.#maxRememberedRequests < 1) throw new Error(\"maxRememberedRequests must be a positive safe integer\");\n\t}\n\tgetAgent(agentId) {\n\t\treturn this.#agents.get(agentId);\n\t}\n\t/**\n\t* The authoritative local record of work whose interruption could lose or duplicate an accepted\n\t* Turn: live per-Session Turn activity plus unresolved Turns recovered from durable state that\n\t* still owe the Server a completion report. Accepted-but-undrained Session messages are owned by\n\t* the Session message inbox, which registers its drains here as activity.\n\t*/\n\tprotectedWorkSnapshot() {\n\t\treturn {\n\t\t\tactivities: [...this.#activities.entries()].map(([sessionId, activity]) => ({\n\t\t\t\tsessionId,\n\t\t\t\t...activity\n\t\t\t})),\n\t\t\trecoveries: [...this.#recoveries.entries()].map(([sessionId, turn]) => ({\n\t\t\t\tsessionId,\n\t\t\t\t...turn\n\t\t\t}))\n\t\t};\n\t}\n\tgetSession(sessionId) {\n\t\treturn this.#sessions.get(sessionId);\n\t}\n\tsetActivity(sessionId, activity) {\n\t\tthis.#activities.set(sessionId, activity);\n\t\tthis.#recoveries.delete(sessionId);\n\t}\n\tclearActivity(sessionId, turnId) {\n\t\tconst current = this.#activities.get(sessionId);\n\t\tif (!current || current.turnId !== turnId) return false;\n\t\treturn this.#activities.delete(sessionId);\n\t}\n\tsetRecovery(sessionId, turn) {\n\t\tif (!this.#activities.has(sessionId)) this.#recoveries.set(sessionId, turn);\n\t}\n\tclearRecovery(sessionId, turnId) {\n\t\tconst current = this.#recoveries.get(sessionId);\n\t\tif (!current || current.turnId !== turnId) return false;\n\t\treturn this.#recoveries.delete(sessionId);\n\t}\n\tclaimRecovery(sessionId, turn) {\n\t\tif (this.#activities.has(sessionId)) return false;\n\t\tconst current = this.#recoveries.get(sessionId);\n\t\tif (current) return current.turnId === turn.turnId && current.deliveryId === turn.deliveryId;\n\t\tthis.#recoveries.set(sessionId, turn);\n\t\treturn true;\n\t}\n\treconcile(input) {\n\t\tconst request = SessionReconcileRequestSchema.parse(input);\n\t\tconst payloadHash = computeReconcilePayloadHash(request);\n\t\tconst remembered = this.#requests.get(request.requestId);\n\t\tif (remembered) {\n\t\t\tif (remembered.payloadHash === payloadHash) return remembered.result;\n\t\t\treturn Promise.resolve(this.#result(request, \"rejected\", \"request_conflict\"));\n\t\t}\n\t\tconst result = this.withAgentLock(request.agentId, () => this.#reconcileLocked(request));\n\t\tthis.#requests.set(request.requestId, {\n\t\t\tpayloadHash,\n\t\t\tresult\n\t\t});\n\t\tthis.#trimRequests();\n\t\treturn result;\n\t}\n\tcheckDelivery(input) {\n\t\tif (input.agentId !== input.runtime.agentId) return \"target_mismatch\";\n\t\tif (this.#sessions.get(input.sessionId)?.sessionKind === \"internal\") return \"target_mismatch\";\n\t\treturn this.#checkRuntimeTarget(input.sessionId, input.agentId, input.placementGeneration, input.runtime);\n\t}\n\tcheckSessionMessageDelivery(input) {\n\t\tif (input.agentId !== input.runtime.agentId) return \"target_mismatch\";\n\t\treturn this.#checkRuntimeTarget(input.targetSessionId, input.agentId, input.placementGeneration, input.runtime);\n\t}\n\t#checkRuntimeTarget(sessionId, agentId, placementGeneration, runtime) {\n\t\tconst session = this.#sessions.get(sessionId);\n\t\tif (session?.status !== \"ready\") return \"session_not_ready\";\n\t\tif (session.agentId !== agentId) return \"target_mismatch\";\n\t\tif (placementGeneration < session.placementGeneration) return \"stale_generation\";\n\t\tif (placementGeneration > session.placementGeneration) return \"session_not_ready\";\n\t\tif (this.#recoveries.has(sessionId)) return \"session_recovery_required\";\n\t\tconst agent = this.#agents.get(agentId);\n\t\tif (!agent) return \"session_not_ready\";\n\t\tconst hashes = computeRuntimeSnapshotHashes(runtime);\n\t\tif (agent.provider !== runtime.provider || agent.workspaceId !== runtime.workspace.workspaceId || session.provider !== runtime.provider || session.workspaceId !== runtime.workspace.workspaceId) return \"session_binding_conflict\";\n\t\tif (runtime.revision.agent.sequence < agent.revisionSequence || runtime.revision.session.sequence < session.revisionSequence) return \"stale_configuration\";\n\t\tif (runtime.revision.agent.sequence > agent.revisionSequence || runtime.revision.session.sequence > session.revisionSequence) return \"session_not_ready\";\n\t\tif (runtime.revision.agent.id !== agent.revisionId || runtime.revision.session.id !== session.revisionId || hashes.agentConfigHash !== agent.agentConfigHash || hashes.sessionConfigHash !== session.sessionConfigHash || hashes.effectiveSnapshotHash !== session.effectiveSnapshotHash) return \"session_binding_conflict\";\n\t\treturn this.#localPolicy?.validateDelivery ? this.#localPolicy.validateDelivery(runtime) : this.#localPolicy?.validate(runtime);\n\t}\n\tasync withAgentLock(agentId, task) {\n\t\tconst previous = this.#agentTails.get(agentId) ?? Promise.resolve();\n\t\tlet release;\n\t\tconst tail = new Promise((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.#agentTails.set(agentId, tail);\n\t\tawait previous;\n\t\ttry {\n\t\t\treturn await task();\n\t\t} finally {\n\t\t\trelease?.();\n\t\t\tif (this.#agentTails.get(agentId) === tail) this.#agentTails.delete(agentId);\n\t\t}\n\t}\n\tasync #reconcileLocked(request) {\n\t\tif (request.installationId !== this.#installationId) return this.#result(request, \"rejected\", \"target_mismatch\");\n\t\tconst existingSession = this.#sessions.get(request.sessionId);\n\t\tif (existingSession && request.placementGeneration < existingSession.placementGeneration) return this.#result(request, \"rejected\", \"stale_generation\");\n\t\tif (existingSession && existingSession.agentId !== request.agentId) return this.#result(request, \"rejected\", \"session_binding_conflict\");\n\t\tif (request.desired === \"ready\" && existingSession && existingSession.sessionKind !== (request.sessionKind ?? \"visible\")) return this.#result(request, \"rejected\", \"session_binding_conflict\");\n\t\tconst activity = this.#activities.get(request.sessionId);\n\t\tif (activity) {\n\t\t\tif (request.desired === \"stopped\" || !existingSession || request.placementGeneration !== existingSession.placementGeneration) return this.#result(request, \"busy\", \"active_turn\");\n\t\t\tconst snapshot = request.runtime;\n\t\t\tconst existingAgent = this.#agents.get(request.agentId);\n\t\t\tif (!snapshot || !existingAgent) return this.#result(request, \"busy\", \"active_turn\");\n\t\t\tconst hashes = computeRuntimeSnapshotHashes(snapshot);\n\t\t\tconst agentComparison = compareRevision(snapshot.revision.agent.sequence, snapshot.revision.agent.id, hashes.agentConfigHash, existingAgent.revisionSequence, existingAgent.revisionId, existingAgent.agentConfigHash);\n\t\t\tif (agentComparison === \"stale\") return this.#result(request, \"rejected\", \"stale_configuration\");\n\t\t\tif (agentComparison === \"conflict\") return this.#result(request, \"rejected\", \"configuration_conflict\");\n\t\t\tif (agentComparison === \"newer\") return this.#result(request, \"busy\", \"agent_configuration_busy\");\n\t\t\tconst sessionComparison = compareRevision(snapshot.revision.session.sequence, snapshot.revision.session.id, hashes.sessionConfigHash, existingSession.revisionSequence, existingSession.revisionId, existingSession.sessionConfigHash);\n\t\t\tif (sessionComparison === \"stale\") return this.#result(request, \"rejected\", \"stale_configuration\");\n\t\t\tif (sessionComparison === \"conflict\") return this.#result(request, \"rejected\", \"configuration_conflict\");\n\t\t\tif (sessionComparison === \"newer\") return this.#result(request, \"busy\", \"active_turn\");\n\t\t\tconst status = activity.phase === \"running\" ? \"running\" : \"reporting\";\n\t\t\treturn {\n\t\t\t\t...this.#result(request, status),\n\t\t\t\tturn: {\n\t\t\t\t\tturnId: activity.turnId,\n\t\t\t\t\tdeliveryId: activity.deliveryId\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tconst recovery = this.#recoveries.get(request.sessionId);\n\t\tif (recovery) return {\n\t\t\t...this.#result(request, \"recovery_required\", \"unresolved_turn\"),\n\t\t\tturn: recovery\n\t\t};\n\t\tif (request.desired === \"stopped\") {\n\t\t\tawait this.#preparation.stopSession(request.sessionId, request.placementGeneration);\n\t\t\tif (existingSession) this.#sessions.set(request.sessionId, {\n\t\t\t\t...existingSession,\n\t\t\t\tplacementGeneration: request.placementGeneration,\n\t\t\t\tstatus: \"stopped\"\n\t\t\t});\n\t\t\treturn this.#result(request, \"stopped\");\n\t\t}\n\t\tconst snapshot = request.runtime;\n\t\tif (!snapshot) return this.#result(request, \"rejected\", \"runtime_missing\");\n\t\tconst policyReason = this.#localPolicy?.validate(snapshot);\n\t\tif (policyReason) return this.#result(request, \"rejected\", policyReason);\n\t\tconst hashes = computeRuntimeSnapshotHashes(snapshot);\n\t\tconst existingAgent = this.#agents.get(request.agentId);\n\t\tif (existingAgent && (existingAgent.provider !== snapshot.provider || existingAgent.workspaceId !== snapshot.workspace.workspaceId)) return this.#result(request, \"rejected\", \"session_binding_conflict\");\n\t\tif (existingAgent) {\n\t\t\tconst comparison = compareRevision(snapshot.revision.agent.sequence, snapshot.revision.agent.id, hashes.agentConfigHash, existingAgent.revisionSequence, existingAgent.revisionId, existingAgent.agentConfigHash);\n\t\t\tif (comparison === \"stale\") return this.#result(request, \"rejected\", \"stale_configuration\");\n\t\t\tif (comparison === \"conflict\") return this.#result(request, \"rejected\", \"configuration_conflict\");\n\t\t\tif (comparison === \"newer\" && this.#agentIsActive(request.agentId)) return this.#result(request, \"busy\", \"agent_configuration_busy\");\n\t\t}\n\t\tif (existingSession && request.placementGeneration === existingSession.placementGeneration) {\n\t\t\tconst comparison = compareRevision(snapshot.revision.session.sequence, snapshot.revision.session.id, hashes.sessionConfigHash, existingSession.revisionSequence, existingSession.revisionId, existingSession.sessionConfigHash);\n\t\t\tif (comparison === \"stale\") return this.#result(request, \"rejected\", \"stale_configuration\");\n\t\t\tif (comparison === \"conflict\") return this.#result(request, \"rejected\", \"configuration_conflict\");\n\t\t}\n\t\tconst shouldPrepareAgent = !existingAgent || snapshot.revision.agent.sequence > existingAgent.revisionSequence;\n\t\tconst shouldPrepareSession = !existingSession || request.placementGeneration > existingSession.placementGeneration || snapshot.revision.session.sequence > existingSession.revisionSequence || existingSession.status === \"stopped\" || this.#preparation.requiresSessionPreparation?.(request, hashes) === true;\n\t\tif (shouldPrepareAgent) await this.#preparation.prepareAgent(snapshot, hashes);\n\t\telse await this.#preparation.verifyAgent?.(snapshot, hashes);\n\t\tconst preparedSession = shouldPrepareSession ? await this.#preparation.prepareSession(request, hashes) : void 0;\n\t\tif (shouldPrepareAgent) this.#agents.set(request.agentId, {\n\t\t\t...hashes,\n\t\t\tagentId: request.agentId,\n\t\t\tprovider: snapshot.provider,\n\t\t\trevisionId: snapshot.revision.agent.id,\n\t\t\trevisionSequence: snapshot.revision.agent.sequence,\n\t\t\tworkspaceId: snapshot.workspace.workspaceId\n\t\t});\n\t\tthis.#sessions.set(request.sessionId, {\n\t\t\t...hashes,\n\t\t\tagentId: request.agentId,\n\t\t\tplacementGeneration: request.placementGeneration,\n\t\t\tprovider: snapshot.provider,\n\t\t\trevisionId: snapshot.revision.session.id,\n\t\t\trevisionSequence: snapshot.revision.session.sequence,\n\t\t\tsessionId: request.sessionId,\n\t\t\tsessionKind: existingSession?.sessionKind ?? request.sessionKind ?? \"visible\",\n\t\t\tstatus: \"ready\",\n\t\t\tworkspaceId: snapshot.workspace.workspaceId\n\t\t});\n\t\tif (preparedSession?.unresolvedTurn) {\n\t\t\tconst recovery = {\n\t\t\t\tdeliveryId: preparedSession.unresolvedTurn.deliveryId,\n\t\t\t\tturnId: preparedSession.unresolvedTurn.turnId\n\t\t\t};\n\t\t\tthis.setRecovery(request.sessionId, recovery);\n\t\t\treturn {\n\t\t\t\t...this.#result(request, \"recovery_required\", \"unresolved_turn\"),\n\t\t\t\tturn: recovery\n\t\t\t};\n\t\t}\n\t\treturn this.#result(request, \"ready\");\n\t}\n\t#result(request, status, reason) {\n\t\treturn {\n\t\t\ttype: \"session:reconcile:result\",\n\t\t\trequestId: request.requestId,\n\t\t\tsessionId: request.sessionId,\n\t\t\tplacementGeneration: request.placementGeneration,\n\t\t\tstatus,\n\t\t\t...reason ? { reason } : {}\n\t\t};\n\t}\n\t#agentIsActive(agentId) {\n\t\tfor (const sessionId of this.#activities.keys()) if (this.#sessions.get(sessionId)?.agentId === agentId) return true;\n\t\treturn false;\n\t}\n\t#trimRequests() {\n\t\twhile (this.#requests.size > this.#maxRememberedRequests) {\n\t\t\tconst oldest = this.#requests.keys().next().value;\n\t\t\tif (oldest === void 0) break;\n\t\t\tthis.#requests.delete(oldest);\n\t\t}\n\t}\n};\nfunction compareRevision(incomingSequence, incomingId, incomingHash, currentSequence, currentId, currentHash) {\n\tif (incomingSequence < currentSequence) return \"stale\";\n\tif (incomingSequence > currentSequence) return \"newer\";\n\treturn incomingId === currentId && incomingHash === currentHash ? \"same\" : \"conflict\";\n}\n//#endregion\n//#region src/runtime/client-runtime.ts\nvar ClientRuntime = class {\n\treconciler;\n\t#connection;\n\t#options;\n\t#logger;\n\t#abort = new AbortController();\n\t#tests = /* @__PURE__ */ new Map();\n\t#unsubscribe;\n\tconstructor(connection, options = {}) {\n\t\tthis.#connection = connection;\n\t\tthis.#options = options;\n\t\tthis.#logger = options.logger ?? createLogger(\"client-runtime\");\n\t\tthis.reconciler = options.reconciler ?? new SessionReconciler({ installationId: connection.installationId });\n\t}\n\tasync run() {\n\t\tthis.#unsubscribe = this.#connection.subscribeBusinessFrames((frame) => this.#handleBusinessFrame(frame));\n\t\ttry {\n\t\t\tawait this.#connection.run();\n\t\t} finally {\n\t\t\tthis.#unsubscribe?.();\n\t\t\tthis.#unsubscribe = void 0;\n\t\t}\n\t}\n\tstop() {\n\t\tthis.#options.contextTreeSettings?.close?.();\n\t\tthis.#abort.abort();\n\t\tthis.#connection.stop();\n\t}\n\tasync #handleBusinessFrame(input) {\n\t\tconst parsed = ServerRuntimeBusinessFrameSchema.safeParse(input);\n\t\tif (!parsed.success || this.#abort.signal.aborted) return;\n\t\tconst frame = parsed.data;\n\t\tif (frame.type === \"session:reconcile\") {\n\t\t\tconst fields = {\n\t\t\t\tagentId: frame.agentId,\n\t\t\t\tplacementGeneration: frame.placementGeneration,\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tsessionId: frame.sessionId\n\t\t\t};\n\t\t\tthis.#logger.debug(fields, \"Session reconcile received\");\n\t\t\tconst reconciled = await this.reconciler.reconcile(frame);\n\t\t\tconst result = SessionReconcileResultSchema.parse(await this.#options.prepareReconcileResult?.(frame, reconciled) ?? reconciled);\n\t\t\ttry {\n\t\t\t\tawait this.#connection.send(result, {\n\t\t\t\t\tpriority: \"result\",\n\t\t\t\t\tsignal: this.#abort.signal\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthis.#logger.warn({\n\t\t\t\t\t...fields,\n\t\t\t\t\tstatus: result.status\n\t\t\t\t}, \"Session reconcile result send failed\");\n\t\t\t\tawait this.#options.onReconcileResultSendFailed?.(frame, result, error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tthis.#logger.debug({\n\t\t\t\t...fields,\n\t\t\t\treason: result.reason,\n\t\t\t\tstatus: result.status\n\t\t\t}, \"Session reconcile completed\");\n\t\t\tawait this.#options.onReconciled?.(frame, result);\n\t\t\treturn;\n\t\t}\n\t\tif (frame.type === \"im:deliver\") {\n\t\t\tconst fields = {\n\t\t\t\tagentId: frame.agentId,\n\t\t\t\tdeliveryId: frame.deliveryId,\n\t\t\t\tplacementGeneration: frame.placementGeneration,\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tsessionId: frame.sessionId\n\t\t\t};\n\t\t\tthis.#logger.debug(fields, \"IM delivery received\");\n\t\t\tconst reason = this.reconciler.checkDelivery(frame);\n\t\t\tconst decision = reason ? { result: rejectedDelivery(frame, reason) } : await this.#options.handleDelivery?.(frame) ?? { result: rejectedDelivery(frame, \"provider_unavailable\") };\n\t\t\tconst result = ImMessageDeliveryResultSchema.parse(decision.result);\n\t\t\tawait this.#connection.send(result, {\n\t\t\t\tpriority: \"result\",\n\t\t\t\tsignal: this.#abort.signal\n\t\t\t});\n\t\t\tconst resultFields = {\n\t\t\t\t...fields,\n\t\t\t\treason: \"reason\" in result ? result.reason : void 0,\n\t\t\t\tstatus: result.status\n\t\t\t};\n\t\t\tif (result.status === \"accepted\") this.#logger.debug(resultFields, \"IM delivery accepted\");\n\t\t\telse if (result.status === \"absorbed\") this.#logger.debug(resultFields, \"IM delivery absorbed\");\n\t\t\telse this.#logger.warn(resultFields, \"IM delivery rejected\");\n\t\t\tif (result.status === \"accepted\") await decision.onAcceptedSent?.();\n\t\t\treturn;\n\t\t}\n\t\tif (frame.type === \"im:steer\") {\n\t\t\tconst result = RuntimeImSteerResultSchema.parse(await this.#options.handleSteer?.(frame) ?? {\n\t\t\t\ttype: \"im:steer:result\",\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tdeliveryId: frame.deliveryId,\n\t\t\t\tsessionId: frame.sessionId,\n\t\t\t\tplacementGeneration: frame.placementGeneration,\n\t\t\t\trootDeliveryId: frame.rootDeliveryId,\n\t\t\t\texpectedTurnId: frame.expectedTurnId,\n\t\t\t\tstatus: \"deferred\",\n\t\t\t\treason: \"steer_unsupported\"\n\t\t\t});\n\t\t\tawait this.#connection.send(result, {\n\t\t\t\tpriority: \"result\",\n\t\t\t\tsignal: this.#abort.signal\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (frame.type === \"session:message:deliver\") {\n\t\t\tconst result = SessionMessageDeliveryResultSchema.parse(await this.#options.handleSessionMessageDelivery?.(frame) ?? {\n\t\t\t\ttype: \"session:message:deliver:result\",\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tmessageId: frame.messageId,\n\t\t\t\ttargetSessionId: frame.targetSessionId,\n\t\t\t\tplacementGeneration: frame.placementGeneration,\n\t\t\t\tstatus: \"rejected\",\n\t\t\t\treason: \"provider_unavailable\"\n\t\t\t});\n\t\t\tawait this.#connection.send(result, {\n\t\t\t\tpriority: \"result\",\n\t\t\t\tsignal: this.#abort.signal\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (frame.type === \"im:credential:result\") return;\n\t\tawait this.#handleResidualFrame(frame);\n\t}\n\tasync #handleResidualFrame(frame) {\n\t\tif (frame.type.startsWith(\"provider-cli:\")) return;\n\t\tif (frame.type === \"context-tree:operation\") {\n\t\t\tlet result;\n\t\t\ttry {\n\t\t\t\tresult = await this.#options.contextTreeSettings?.run(frame) ?? {\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\tcode: \"capability_missing\"\n\t\t\t\t};\n\t\t\t} catch {\n\t\t\t\tresult = {\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\tcode: \"failed\"\n\t\t\t\t};\n\t\t\t}\n\t\t\tawait this.#connection.send(ContextTreeOperationResultFrameSchema.parse({\n\t\t\t\ttype: \"context-tree:operation:result\",\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tresult\n\t\t\t}), {\n\t\t\t\tpriority: \"result\",\n\t\t\t\tsignal: this.#abort.signal\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (frame.type === \"agent-runtime:test\") {\n\t\t\tawait this.#runAgentRuntimeTest(frame);\n\t\t\treturn;\n\t\t}\n\t\tif (frame.type === \"agent-runtime:test:cancel\") {\n\t\t\tthis.#tests.get(frame.requestId)?.abort();\n\t\t\treturn;\n\t\t}\n\t\tif (frame.type === \"turn:report:result\") await this.#options.handleTurnReportResult?.(frame);\n\t}\n\tasync #runAgentRuntimeTest(frame) {\n\t\tconst controller = new AbortController();\n\t\tthis.#tests.set(frame.requestId, controller);\n\t\tconst onStop = () => controller.abort();\n\t\tthis.#abort.signal.addEventListener(\"abort\", onStop, { once: true });\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = AgentRuntimeTestResultFrameSchema.parse(await this.#options.availabilityTester?.run(frame, controller.signal) ?? {\n\t\t\t\ttype: \"agent-runtime:test:result\",\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tcode: \"capability_missing\"\n\t\t\t});\n\t\t} catch {\n\t\t\tresult = {\n\t\t\t\ttype: \"agent-runtime:test:result\",\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tcode: \"provider_failed\"\n\t\t\t};\n\t\t} finally {\n\t\t\tthis.#abort.signal.removeEventListener(\"abort\", onStop);\n\t\t\tthis.#tests.delete(frame.requestId);\n\t\t}\n\t\tawait this.#connection.send(result, {\n\t\t\tpriority: \"result\",\n\t\t\tsignal: this.#abort.signal\n\t\t});\n\t}\n};\nfunction rejectedDelivery(request, reason) {\n\tif (!reason) throw new Error(\"A rejected delivery requires a reason\");\n\treturn {\n\t\ttype: \"im:deliver:result\",\n\t\trequestId: request.requestId,\n\t\tdeliveryId: request.deliveryId,\n\t\tsessionId: request.sessionId,\n\t\tplacementGeneration: request.placementGeneration,\n\t\tstatus: \"rejected\",\n\t\treason\n\t};\n}\n//#endregion\n//#region src/providers/claude-code/runtime-policy.ts\nfunction claudeCodeRuntimePolicy(_snapshot) {\n\treturn {\n\t\tfileSystem: \"unrestricted\",\n\t\tnetwork: \"enabled\",\n\t\tapprovals: \"never\",\n\t\ttools: { mode: \"provider-default\" }\n\t};\n}\nfunction validateClaudeCodeRuntimePolicy(snapshot) {\n\tif (snapshot.execution.approvalPolicy !== \"never\" || !snapshot.execution.networkAccess) return \"configuration_unsupported\";\n}\n//#endregion\n//#region src/providers/codex/runtime-policy.ts\nfunction codexRuntimePolicy(snapshot) {\n\treturn {\n\t\tfileSystem: \"workspace-write\",\n\t\tnetwork: snapshot.execution.networkAccess ? \"enabled\" : \"disabled\",\n\t\tapprovals: \"never\",\n\t\ttools: { mode: \"provider-default\" }\n\t};\n}\nfunction validateCodexRuntimePolicy(snapshot) {\n\tif (snapshot.execution.approvalPolicy !== \"never\" || !snapshot.execution.networkAccess) return \"configuration_unsupported\";\n}\n//#endregion\n//#region src/providers/pi/runtime-policy.ts\n/**\n* Pi has no OS filesystem sandbox and no approval gate. Product policy must stay unrestricted\n* writes plus network; anything stricter is rejected instead of being silently ignored.\n*/\nfunction piRuntimePolicy(_snapshot) {\n\treturn {\n\t\tfileSystem: \"unrestricted\",\n\t\tnetwork: \"enabled\",\n\t\tapprovals: \"never\",\n\t\ttools: { mode: \"provider-default\" }\n\t};\n}\nfunction validatePiRuntimePolicy(snapshot) {\n\tif (snapshot.execution.approvalPolicy !== \"never\" || !snapshot.execution.networkAccess) return \"configuration_unsupported\";\n}\n//#endregion\n//#region src/skills/skill-archive.ts\n/**\n* Local packing and extraction for Agent Skills.\n*\n* `packSkillDirectory` turns a skill directory into the canonical `tar.gz` archive the platform\n* stores; `extractSkillArchive` is the only place a downloaded bundle becomes files. Both are\n* deliberately paranoid: a Skill an Agent authors may contain anything, and a bundle from the\n* platform must never be able to write outside the directory the caller nominated.\n*/\n/** The content-digest sidecar the Client writes next to `SKILL_MARKER_FILE` in managed directories. */\nconst SKILL_CONTENT_SIDECAR_FILE = \".opentag-skill.content\";\nvar SkillArchiveError = class extends Error {\n\tcode;\n\tconstructor(code, message, options) {\n\t\tsuper(message, options);\n\t\tthis.code = code;\n\t\tthis.name = \"SkillArchiveError\";\n\t}\n};\nconst EXCLUDED_NAMES = /* @__PURE__ */ new Set([\n\t\".git\",\n\t\"node_modules\",\n\t\".DS_Store\",\n\tSKILL_MARKER_FILE,\n\tSKILL_CONTENT_SIDECAR_FILE\n]);\nfunction fail(code, message, cause) {\n\tthrow new SkillArchiveError(code, message, cause === void 0 ? void 0 : { cause });\n}\nfunction relativePosix(root, absolute) {\n\treturn relative(root, absolute).split(/[\\\\/]/u).join(\"/\");\n}\nfunction assertSkillPathWidth(rel) {\n\tif (Buffer.byteLength(rel, \"utf8\") > SKILL_MAX_PATH_BYTES) fail(\"path_too_long\", `Skill entry path exceeds ${SKILL_MAX_PATH_BYTES} bytes: ${rel.slice(0, 120)}`);\n}\nfunction entryMode(mode, directory) {\n\tif (directory) return 493;\n\treturn (mode & 73) === 0 ? 420 : 493;\n}\n/**\n* The private mode a bundled file is installed with: `0o700` when the archive records an owner\n* execute bit, otherwise `0o600`. Group/other bits are dropped, and setuid/setgid/sticky are never\n* carried — a Skill is executable only for the owner who materialized it.\n*/\nfunction extractFileMode(headerMode) {\n\treturn typeof headerMode === \"number\" && (headerMode & 64) !== 0 ? 448 : 384;\n}\nasync function lstatEntry(abs, rel) {\n\ttry {\n\t\treturn await lstat(abs);\n\t} catch (error) {\n\t\tfail(\"io_failed\", `Cannot stat skill entry: ${rel}`, error);\n\t}\n}\nasync function visitSkillEntry(root, directory, name, files, directories, state) {\n\tconst abs = join(directory.abs, name);\n\tconst rel = relativePosix(root, abs);\n\tassertSkillPathWidth(rel);\n\tstate.entries += 1;\n\tif (state.entries > SKILL_MAX_ENTRIES) fail(\"too_many_entries\", `Skill exceeds the ${SKILL_MAX_ENTRIES} entry ceiling`);\n\tconst stats = await lstatEntry(abs, rel);\n\tif (stats.isSymbolicLink()) fail(\"symlink\", `Skill directories may not contain symlinks: ${rel}`);\n\tif (stats.isDirectory()) {\n\t\tconst child = {\n\t\t\tabs,\n\t\t\trel\n\t\t};\n\t\tdirectories.push(child);\n\t\tawait walkSkillDirectory(root, child, files, directories, state);\n\t\treturn;\n\t}\n\tif (!stats.isFile()) fail(\"unsupported_entry\", `Skill entries must be regular files or directories: ${rel}`);\n\tconst size = Number(stats.size);\n\tstate.bytes += size;\n\tif (state.bytes > SKILL_UNPACKED_MAX_BYTES) fail(\"unpacked_too_large\", `Skill exceeds the ${SKILL_UNPACKED_MAX_BYTES} byte unpacked ceiling`);\n\tfiles.push({\n\t\tabs,\n\t\trel,\n\t\tbytes: size,\n\t\tmode: Number(stats.mode)\n\t});\n}\nasync function walkSkillDirectory(root, directory, files, directories, state) {\n\tlet names;\n\ttry {\n\t\tnames = (await readdir(directory.abs)).sort();\n\t} catch (error) {\n\t\tfail(\"io_failed\", `Cannot read skill directory: ${directory.rel || \".\"}`, error);\n\t}\n\tfor (const name of names) {\n\t\tif (EXCLUDED_NAMES.has(name)) continue;\n\t\tawait visitSkillEntry(root, directory, name, files, directories, state);\n\t}\n}\nasync function validateSkillManifest(root) {\n\tlet markdown;\n\ttry {\n\t\tmarkdown = await readFile(join(root, SKILL_MANIFEST_FILE), \"utf8\");\n\t} catch (error) {\n\t\tfail(\"manifest_missing\", `Skill directory must contain a root ${SKILL_MANIFEST_FILE}`, error);\n\t}\n\tconst parsed = parseSkillManifest(markdown);\n\tif (!parsed.ok) fail(\"manifest_invalid\", parsed.reason);\n\tif (isReservedSkillName(parsed.manifest.name)) fail(\"name_reserved\", `Skill name \"${parsed.manifest.name}\" is reserved by the platform`);\n\treturn parsed.manifest.name;\n}\nfunction addTarEntry(pack, header, sourcePath) {\n\treturn new Promise((resolveEntry, rejectEntry) => {\n\t\tlet settled = false;\n\t\tconst done = (error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (error === void 0 || error === null) resolveEntry();\n\t\t\telse rejectEntry(error instanceof Error ? error : new Error(String(error)));\n\t\t};\n\t\tconst sink = pack.entry(header, (error) => done(error));\n\t\tif (sourcePath === void 0) {\n\t\t\tsink.end();\n\t\t\treturn;\n\t\t}\n\t\tpipeline(createReadStream(sourcePath), sink).then(() => done(), (error) => done(error));\n\t});\n}\nasync function packSkillDirectory(directory) {\n\tconst root = resolve(directory);\n\tlet stats;\n\ttry {\n\t\tstats = await lstat(root);\n\t} catch (error) {\n\t\tfail(\"not_a_directory\", \"Skill path is not accessible\", error);\n\t}\n\tif (stats.isSymbolicLink() || !stats.isDirectory()) fail(\"not_a_directory\", \"Skill path must be a real directory\");\n\tconst name = await validateSkillManifest(root);\n\tconst files = [];\n\tconst directories = [];\n\tawait walkSkillDirectory(root, {\n\t\tabs: root,\n\t\trel: \"\"\n\t}, files, directories, {\n\t\tbytes: 0,\n\t\tentries: 0\n\t});\n\tconst records = [...directories.map((entry) => ({\n\t\tkind: \"directory\",\n\t\trel: entry.rel,\n\t\tabs: entry.abs,\n\t\tbytes: 0,\n\t\tmode: 493\n\t})), ...files.map((entry) => ({\n\t\tkind: \"file\",\n\t\trel: entry.rel,\n\t\tabs: entry.abs,\n\t\tbytes: entry.bytes,\n\t\tmode: entryMode(entry.mode, false)\n\t}))].sort((left, right) => left.rel < right.rel ? -1 : left.rel > right.rel ? 1 : 0);\n\tconst pack$1 = pack();\n\tconst meter = new PassThrough();\n\tconst chunks = [];\n\tlet compressedBytes = 0;\n\tmeter.on(\"data\", (chunk) => {\n\t\tcompressedBytes += chunk.length;\n\t\tif (compressedBytes > SKILL_ARCHIVE_MAX_BYTES) {\n\t\t\tmeter.destroy(new SkillArchiveError(\"archive_too_large\", \"Packed skill exceeds the archive ceiling\"));\n\t\t\treturn;\n\t\t}\n\t\tchunks.push(chunk);\n\t});\n\tconst output = pipeline(pack$1, createGzip({ level: 1 }), meter);\n\toutput.catch(() => pack$1.destroy());\n\ttry {\n\t\tfor (const record of records) await addTarEntry(pack$1, {\n\t\t\tname: record.rel,\n\t\t\ttype: record.kind,\n\t\t\tmode: record.mode,\n\t\t\tmtime: /* @__PURE__ */ new Date(0),\n\t\t\t...record.kind === \"file\" ? { size: record.bytes } : {}\n\t\t}, record.kind === \"file\" ? record.abs : void 0);\n\t\tpack$1.finalize();\n\t\tawait output;\n\t} catch (error) {\n\t\tpack$1.destroy();\n\t\tawait output.catch(() => void 0);\n\t\tif (error instanceof SkillArchiveError) throw error;\n\t\tfail(\"io_failed\", \"Packing the skill directory failed\", error);\n\t}\n\tconst archive = Buffer.concat(chunks);\n\treturn {\n\t\tarchive: new Uint8Array(archive),\n\t\tname,\n\t\tsha256: createHash(\"sha256\").update(archive).digest(\"hex\"),\n\t\tfileCount: files.length\n\t};\n}\n/** Normalize an archive member name; \"\" is the root pseudo-entry; rejects escapes and ambiguity. */\nfunction normalizeMemberName$1(rawName) {\n\tif (typeof rawName !== \"string\" || rawName.length === 0 || rawName.includes(\"\\0\")) fail(\"unsafe_member\", \"Archive member name is missing or invalid\");\n\tif (rawName.startsWith(\"/\") || rawName.includes(\"\\\\\") || /^[A-Za-z]:/u.test(rawName)) fail(\"unsafe_member\", `Archive member name is absolute or ambiguous: ${rawName.slice(0, 120)}`);\n\tconst segments = [];\n\tfor (const segment of rawName.split(\"/\")) {\n\t\tif (segment === \"\" || segment === \".\") continue;\n\t\tif (segment === \"..\") fail(\"unsafe_member\", \"Archive member escapes the skill root\");\n\t\tsegments.push(segment);\n\t}\n\tconst normalized = segments.join(\"/\");\n\tif (normalized.length > 0) assertSkillPathWidth(normalized);\n\treturn normalized;\n}\nasync function assertEmptyDirectory(target) {\n\tlet entries;\n\ttry {\n\t\tentries = await readdir(target);\n\t} catch (error) {\n\t\tfail(\"io_failed\", \"Cannot read the extraction destination\", error);\n\t}\n\tif (entries.length > 0) fail(\"destination_not_empty\", \"Extraction destination must be empty\");\n}\nfunction destinationPath(root, member) {\n\tconst dest = join(root, ...member.split(\"/\"));\n\tassertWithin(root, dest);\n\treturn dest;\n}\n/** The Client's own marker and digest sidecar, which an archive must never install as content. */\nfunction isPlatformMetadataName(member) {\n\tconst base = basename(member);\n\treturn base === SKILL_MARKER_FILE || base === \".opentag-skill.content\";\n}\nasync function handleMember(root, header, stream, state) {\n\tconst name = normalizeMemberName$1(header.name);\n\tstate.entries += 1;\n\tif (state.entries > SKILL_MAX_ENTRIES) fail(\"too_many_entries\", `Archive exceeds the ${SKILL_MAX_ENTRIES} entry ceiling`);\n\tif (name === \"\") {\n\t\tif (header.type !== \"directory\") fail(\"unsafe_member\", \"The archive root must be a directory\");\n\t\tfor await (const chunk of stream);\n\t\treturn;\n\t}\n\tif (isPlatformMetadataName(name)) {\n\t\tfor await (const chunk of stream);\n\t\treturn;\n\t}\n\tconst dest = destinationPath(root, name);\n\tif (header.type === \"directory\") {\n\t\tawait mkdir(dest, {\n\t\t\trecursive: true,\n\t\t\tmode: 448\n\t\t});\n\t\tawait chmod(dest, 448);\n\t\tfor await (const chunk of stream);\n\t\treturn;\n\t}\n\tif (header.type !== \"file\") fail(\"unsafe_member\", `Archive member type is unsupported: ${name}`);\n\tconst tap = new PassThrough();\n\ttap.on(\"data\", (chunk) => {\n\t\tstate.bytes += chunk.length;\n\t\tif (state.bytes > SKILL_UNPACKED_MAX_BYTES) tap.destroy(new SkillArchiveError(\"unpacked_too_large\", \"Archive expands beyond the unpacked ceiling\"));\n\t});\n\tawait mkdir(dirname(dest), {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tconst fileMode = extractFileMode(header.mode);\n\tawait pipeline(stream, tap, createWriteStream(dest, {\n\t\tflags: \"wx\",\n\t\tmode: fileMode\n\t}));\n\tawait chmod(dest, fileMode);\n}\nasync function extractSkillArchive(stream, targetDirectory) {\n\tconst target = resolve(targetDirectory);\n\tconst parent = dirname(target);\n\ttry {\n\t\tawait ensurePrivateDirectory(parent, target);\n\t} catch (error) {\n\t\tfail(\"io_failed\", \"Extraction destination is not a private directory\", error);\n\t}\n\tawait assertEmptyDirectory(target);\n\tlet compressed = 0;\n\tconst compressedMeter = new PassThrough();\n\tcompressedMeter.on(\"data\", (chunk) => {\n\t\tcompressed += chunk.length;\n\t\tif (compressed > SKILL_ARCHIVE_MAX_BYTES) compressedMeter.destroy(new SkillArchiveError(\"archive_too_large\", \"Archive exceeds the compressed ceiling\"));\n\t});\n\tconst extractor = extract();\n\tconst state = {\n\t\tbytes: 0,\n\t\tentries: 0\n\t};\n\tlet failure;\n\textractor.on(\"entry\", (header, entryStream, next) => {\n\t\thandleMember(target, header, entryStream, state).then(() => next(), (error) => {\n\t\t\tif (error instanceof SkillArchiveError) failure = error;\n\t\t\tnext(error);\n\t\t});\n\t});\n\ttry {\n\t\tawait pipeline(stream, compressedMeter, createGunzip(), extractor);\n\t} catch (error) {\n\t\tawait rm(target, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t\tif (failure) throw failure;\n\t\tif (error instanceof SkillArchiveError) throw error;\n\t\tfail(\"archive_invalid\", \"Skill archive cannot be unpacked\", error);\n\t}\n}\n//#endregion\n//#region src/skills/skill-bundle.ts\nfunction verifySkillBundle(bytes, expected) {\n\tconst label = expected.name === void 0 ? \"Skill bundle\" : `Skill bundle ${expected.name}`;\n\tif (bytes.byteLength !== expected.archiveBytes) throw new Error(`${label} has ${bytes.byteLength} bytes, expected ${expected.archiveBytes}`);\n\tif (createHash(\"sha256\").update(bytes).digest(\"hex\") !== expected.archiveSha256) throw new Error(`${label} failed its sha256 check`);\n\treturn bytes;\n}\n//#endregion\n//#region src/skills/skill-bundle-body.ts\n/**\n* Bounded body reader for a Skill bundle response.\n*\n* `OpenTagApi.#fetchResponse` clears its request timer and abort listener as soon as response\n* headers arrive, so awaiting `response.arrayBuffer()` puts the body outside every deadline the\n* API applied. A server that sends headers and then stalls would hold runtime start indefinitely.\n* This reader races every chunk against the caller's signal, caps the body at the bundle's declared\n* length, and cancels the underlying stream on abort or overrun.\n*/\n/** `skill pull` is an interactive command, so its body deadline is far longer than a sync budget. */\nconst SKILL_PULL_BUNDLE_TIMEOUT_MS = 6e4;\nasync function readWithAbort(reader, signal) {\n\tsignal.throwIfAborted();\n\tlet onAbort;\n\tconst aborted = new Promise((_resolve, reject) => {\n\t\tonAbort = () => reject(signal.reason);\n\t});\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\ttry {\n\t\treturn await Promise.race([reader.read(), aborted]);\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\nasync function readBundleBody(response, options) {\n\tconst body = response.body;\n\tif (!body) throw new Error(\"Skill bundle response has no body\");\n\tconst reader = body.getReader();\n\tconst chunks = [];\n\tlet total = 0;\n\ttry {\n\t\tfor (;;) {\n\t\t\tconst { done, value } = await readWithAbort(reader, options.signal);\n\t\t\tif (done) break;\n\t\t\tif (!value) continue;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > options.maxBytes) throw new Error(`Skill bundle body exceeds the expected ${options.maxBytes} bytes`);\n\t\t\tchunks.push(value);\n\t\t}\n\t} catch (error) {\n\t\tawait reader.cancel().catch(() => void 0);\n\t\tthrow error;\n\t}\n\tconst bytes = new Uint8Array(total);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbytes.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn bytes;\n}\n//#endregion\n//#region src/skills/skill-install.ts\n/**\n* Staging and staging-root maintenance for Skill installs.\n*\n* A bundle is fully extracted, marked and digest-verified in a private staging directory before it\n* can replace anything, so a failed extraction never costs the Agent the Skill it already had.\n*/\n/** A staging directory older than this is a crash leftover, not a slow concurrent install. */\nconst SKILL_STAGING_STALE_MS = 6e5;\n/** Content digest of a directory, ignoring the platform marker and its sidecar. */\nasync function hashSkillDirectory(root) {\n\tconst hash = createHash(\"sha256\");\n\tawait hashSkillTree(root, \"\", hash);\n\treturn hash.digest(\"hex\");\n}\nasync function hashSkillTree(directory, prefix, hash) {\n\tconst entries = (await readdir(directory, { withFileTypes: true })).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);\n\tfor (const entry of entries) await hashSkillEntry(directory, prefix, entry, hash);\n}\nasync function hashSkillEntry(directory, prefix, entry, hash) {\n\tif (entry.name === SKILL_MARKER_FILE || entry.name === \".opentag-skill.content\") return;\n\tconst rel = prefix === \"\" ? entry.name : `${prefix}/${entry.name}`;\n\tconst absolute = join(directory, entry.name);\n\tif (entry.isDirectory()) {\n\t\thash.update(`d\\0${rel}\\0`);\n\t\tawait hashSkillTree(absolute, rel, hash);\n\t\treturn;\n\t}\n\tif (!entry.isFile()) return;\n\thash.update(`f\\0${rel}\\0`);\n\tfor await (const chunk of createReadStream(absolute)) hash.update(chunk);\n}\nasync function assertStagedBundle(staging) {\n\tif (!(await stat(join(staging, SKILL_MANIFEST_FILE))).isFile()) throw new Error(`Skill bundle is missing its root ${SKILL_MANIFEST_FILE}`);\n}\n/**\n* Extract a verified bundle into a fresh staging directory and mark it managed.\n*\n* Returns the staging path, which is fully validated: on any failure the staging directory is\n* removed and the error propagates, so the caller's current copy is still intact.\n*/\nasync function stageBundle(stagingRoot, entry, bytes) {\n\tawait ensurePrivateDirectory(dirname(stagingRoot), stagingRoot);\n\tconst staging = await mkdtemp(join(stagingRoot, \"skill-\"));\n\ttry {\n\t\tawait extractSkillArchive(Readable.from(Buffer.from(bytes)), staging);\n\t\tawait assertStagedBundle(staging);\n\t\tawait writeFile(join(staging, SKILL_MARKER_FILE), `${JSON.stringify({\n\t\t\tskillId: entry.id,\n\t\t\tarchiveSha256: entry.archiveSha256\n\t\t})}\\n`, { mode: 384 });\n\t\tawait writeFile(join(staging, SKILL_CONTENT_SIDECAR_FILE), `${await hashSkillDirectory(staging)}\\n`, { mode: 384 });\n\t\treturn staging;\n\t} catch (error) {\n\t\tawait rm(staging, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t\tthrow error;\n\t}\n}\n/** Move an unedited managed copy aside so it can be restored if the swap fails. */\nasync function moveAside(stagingRoot, source, tag) {\n\tawait ensurePrivateDirectory(dirname(stagingRoot), stagingRoot);\n\tconst aside = join(stagingRoot, `retired-${tag}`);\n\tawait rename(source, aside);\n\treturn aside;\n}\n/** A crash leaves an unmarked staging directory; anything older than `maxAgeMs` is garbage. */\nasync function sweepStaleStaging(stagingRoot, maxAgeMs = SKILL_STAGING_STALE_MS, now = () => Date.now()) {\n\tlet entries;\n\ttry {\n\t\tentries = await readdir(stagingRoot);\n\t} catch {\n\t\treturn;\n\t}\n\tfor (const entry of entries) {\n\t\tconst path = join(stagingRoot, entry);\n\t\ttry {\n\t\t\tif (now() - (await stat(path)).mtimeMs > maxAgeMs) await rm(path, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t});\n\t\t} catch {}\n\t}\n}\n//#endregion\n//#region src/skills/skill-roots.ts\n/**\n* Workspace-relative roots that sync reads and writes, and the check that keeps them real.\n*\n* A workspace can contain a symlink where a root should be — most dangerously a provider skills\n* root that points into another workspace, where a removal pass would delete that workspace's\n* Skills. Every root is validated before anything is listed, read, or removed. Absence is fine; a\n* symlink or any non-directory on the path, or a root that resolves outside the workspace, is not.\n*/\n/** The roots, relative to an Agent workspace, that hold Agent-scoped Skills. */\nfunction skillRootForProvider(cwd, provider) {\n\tif (provider === \"codex\") return join(cwd, \".agents\", \"skills\");\n\tif (provider === \"pi\") return join(cwd, \".opentag\", \"skills\");\n\treturn join(cwd, \".claude\", \"skills\");\n}\n/** Staging is outside the provider root so a crash cannot leave a discoverable half-skill. */\nfunction skillStagingRoot(cwd) {\n\treturn join(cwd, \".opentag\", \"skill-staging\");\n}\nfunction skillConflictsRoot(cwd) {\n\treturn join(cwd, \".opentag\", \"skill-conflicts\");\n}\nfunction isEscape(suffix) {\n\treturn suffix === \"..\" || suffix.startsWith(`..${sep}`) || isAbsolute(suffix);\n}\n/**\n* Walk every segment from `cwd` down to `root` and require each existing one to be a real\n* directory, then require `realpath(root)` to stay inside `realpath(cwd)`.\n*/\nasync function assertSafeSkillRoot(cwd, root) {\n\tconst resolvedCwd = resolve(cwd);\n\tconst resolvedRoot = resolve(root);\n\tconst suffix = relative(resolvedCwd, resolvedRoot);\n\tif (suffix === \"\" || isEscape(suffix)) throw new Error(`Skill root is not inside its workspace: ${resolvedRoot}`);\n\tlet current = resolvedCwd;\n\tfor (const segment of suffix.split(sep)) {\n\t\tcurrent = join(current, segment);\n\t\tlet info;\n\t\ttry {\n\t\t\tinfo = await lstat(current);\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return;\n\t\t\tthrow error;\n\t\t}\n\t\tif (info.isSymbolicLink() || !info.isDirectory()) throw new Error(`Skill root traverses a symlink or non-directory: ${current}`);\n\t}\n\tconst [realCwd, realRoot] = await Promise.all([realpath(resolvedCwd), realpath(resolvedRoot)]);\n\tconst realSuffix = relative(realCwd, realRoot);\n\tif (realSuffix !== \"\" && isEscape(realSuffix)) throw new Error(`Skill root resolves outside its workspace: ${resolvedRoot}`);\n}\n/** The first unsafe root's reason, or `undefined` when every root is safe. Never throws. */\nasync function unsafeSkillRootReason(cwd, roots) {\n\tfor (const root of roots) try {\n\t\tawait assertSafeSkillRoot(cwd, root);\n\t} catch (error) {\n\t\treturn error instanceof Error ? error.message : String(error);\n\t}\n}\n/**\n* Whether sync has ever started in this workspace.\n*\n* The staging root is the sentinel: sync creates it on every runtime start. Requiring it stops\n* adoption from marking a directory nested inside a checkout that sync never manages.\n*/\nasync function isSyncedWorkspace(workspace) {\n\ttry {\n\t\tconst info = await lstat(skillStagingRoot(workspace));\n\t\treturn info.isDirectory() && !info.isSymbolicLink();\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\n//#region src/skills/skill-sync.ts\nconst SKILL_SYNC_DEFAULT_BUDGET_MS = 15e3;\nconst MARKER_MAX_BYTES = 4096;\n/** The three Agent-workspace directories that hold provider skill materializations. */\nconst MATERIALIZATION_DOT_DIRECTORIES = /* @__PURE__ */ new Set([\n\t\".claude\",\n\t\".agents\",\n\t\".opentag\"\n]);\nfunction describeError(error) {\n\treturn error instanceof Error ? error.message : String(error);\n}\nfunction installLayout(input) {\n\treturn {\n\t\troot: skillRootForProvider(input.cwd, input.provider),\n\t\tdirectoryName: (name) => name,\n\t\tskillName: (dirName) => dirName\n\t};\n}\nasync function readMarker(path) {\n\tlet raw;\n\ttry {\n\t\tconst info = await stat(path);\n\t\tif (!info.isFile() || info.size > MARKER_MAX_BYTES) return void 0;\n\t\traw = await readFile(path, \"utf8\");\n\t} catch {\n\t\treturn;\n\t}\n\ttry {\n\t\tconst parsed = SkillInstallMarkerSchema.safeParse(JSON.parse(raw));\n\t\treturn parsed.success ? parsed.data : void 0;\n\t} catch {\n\t\treturn;\n\t}\n}\nasync function listManagedDirectories(layout) {\n\tconst managed = /* @__PURE__ */ new Map();\n\tlet names;\n\ttry {\n\t\tnames = await readdir(layout.root);\n\t} catch {\n\t\treturn managed;\n\t}\n\tfor (const dirName of names) {\n\t\tconst name = layout.skillName(dirName);\n\t\tif (name === void 0) continue;\n\t\tconst path = join(layout.root, dirName);\n\t\tconst marker = await readMarker(join(path, SKILL_MARKER_FILE));\n\t\tif (marker) managed.set(name, {\n\t\t\tname,\n\t\t\tpath,\n\t\t\tmarker\n\t\t});\n\t}\n\treturn managed;\n}\nasync function readContentDigest(directory) {\n\ttry {\n\t\treturn (await readFile(join(directory, SKILL_CONTENT_SIDECAR_FILE), \"utf8\")).trim();\n\t} catch {\n\t\treturn;\n\t}\n}\n/**\n* Mark an existing directory as platform-managed so the next sync owns it.\n*\n* `skill push` calls this when the directory it uploaded is the Skill's own materialization\n* target; without it the authored directory would shadow its platform copy forever.\n*/\nasync function markSkillDirectoryManaged(directory, input) {\n\tconst target = resolve(directory);\n\tawait writeFile(join(target, SKILL_MARKER_FILE), `${JSON.stringify({\n\t\tskillId: input.skillId,\n\t\tarchiveSha256: input.archiveSha256\n\t})}\\n`, { mode: 384 });\n\tawait writeFile(join(target, SKILL_CONTENT_SIDECAR_FILE), `${await hashSkillDirectory(target)}\\n`, { mode: 384 });\n}\n/** True when `directory` is where the platform would materialize `name`, regardless of provider. */\nfunction isSkillMaterializationTarget(directory, name) {\n\treturn resolveMaterializationWorkspace(directory, name) !== void 0;\n}\n/**\n* The Agent workspace that contains `directory` as one of its Skill materialization targets.\n*\n* Matched purely on the path shape `<workspace>/<.claude|.agents|.opentag>/skills/<name>`, walking\n* up from the directory itself, so adoption still works when the caller has `cd`-ed into the skill\n* directory. No provider or ambient cwd is needed.\n*/\nfunction resolveMaterializationWorkspace(directory, name) {\n\tconst skillDirectory = resolve(directory);\n\tif (basename(skillDirectory) !== name) return void 0;\n\tconst skillsRoot = dirname(skillDirectory);\n\tif (basename(skillsRoot) !== \"skills\") return void 0;\n\tconst dotDirectory = dirname(skillsRoot);\n\tif (!MATERIALIZATION_DOT_DIRECTORIES.has(basename(dotDirectory))) return void 0;\n\treturn dirname(dotDirectory);\n}\nasync function downloadedBundle(api, token, agentId, entry, signal) {\n\treturn verifySkillBundle(await readBundleBody(await api.openComputerSkillBundle(token, agentId, entry.id, { signal }), {\n\t\tsignal,\n\t\tmaxBytes: entry.archiveBytes\n\t}), entry);\n}\nasync function quarantineConflict(cwd, name, source, nowMs, logger) {\n\tconst stamp = new Date(nowMs).toISOString().replaceAll(/[:.]/gu, \"-\");\n\tconst target = join(skillConflictsRoot(cwd), `${name}-${stamp}`);\n\tawait mkdir(dirname(target), {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tawait rm(target, {\n\t\trecursive: true,\n\t\tforce: true\n\t});\n\tawait rename(source, target);\n\tlogger.info({\n\t\tcode: \"skill_conflict_quarantined\",\n\t\tskill: name,\n\t\ttarget\n\t}, \"Locally edited Skill was quarantined\");\n}\nvar SkillSyncManager = class {\n\t#api;\n\t#machineToken;\n\t#logger;\n\t#now;\n\t#budgetMs;\n\t#rename;\n\tconstructor(options) {\n\t\tthis.#api = options.api;\n\t\tthis.#machineToken = options.machineToken;\n\t\tthis.#logger = options.logger;\n\t\tthis.#now = options.now ?? (() => Date.now());\n\t\tthis.#budgetMs = options.budgetMs ?? 15e3;\n\t\tthis.#rename = options.rename ?? rename;\n\t}\n\tasync ensureAgent(input) {\n\t\tconst layout = installLayout(input);\n\t\tconst unsafe = await unsafeSkillRootReason(input.cwd, [\n\t\t\tlayout.root,\n\t\t\tskillStagingRoot(input.cwd),\n\t\t\tskillConflictsRoot(input.cwd)\n\t\t]);\n\t\tif (unsafe) {\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"skill_root_unsafe\",\n\t\t\t\treason: unsafe\n\t\t\t}, \"Agent Skill root is unsafe; leaving every directory untouched\");\n\t\t\treturn {\n\t\t\t\tskillPaths: [],\n\t\t\t\tstatus: \"unavailable\"\n\t\t\t};\n\t\t}\n\t\tconst signal = AbortSignal.timeout(this.#budgetMs);\n\t\tconst stagingRoot = skillStagingRoot(input.cwd);\n\t\ttry {\n\t\t\tawait ensurePrivateDirectory(dirname(stagingRoot), stagingRoot);\n\t\t\tawait sweepStaleStaging(stagingRoot, SKILL_STAGING_STALE_MS, this.#now);\n\t\t\tconst token = await this.#machineToken();\n\t\t\tconst manifest = await this.#api.getComputerSkillManifest(token, input.agentId, { signal });\n\t\t\treturn {\n\t\t\t\tskillPaths: await this.#reconcile(input, layout, manifest, token, signal),\n\t\t\t\tstatus: \"synced\"\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"skill_sync_unavailable\",\n\t\t\t\treason: describeError(error)\n\t\t\t}, \"Agent Skill sync is unavailable; continuing with the Skills already on disk\");\n\t\t\treturn {\n\t\t\t\tskillPaths: await this.#existingSkillPaths(layout),\n\t\t\t\tstatus: \"unavailable\"\n\t\t\t};\n\t\t}\n\t}\n\tasync #existingSkillPaths(layout) {\n\t\ttry {\n\t\t\treturn [...(await listManagedDirectories(layout)).values()].map((entry) => entry.path);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tasync #reconcile(input, layout, manifest, token, signal) {\n\t\tconst existing = await listManagedDirectories(layout);\n\t\tconst desired = new Set(manifest.skills.map((entry) => entry.name));\n\t\tfor (const entry of manifest.skills) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst current = existing.get(entry.name);\n\t\t\tif (current && current.marker.archiveSha256 === entry.archiveSha256) {\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tcode: \"skill_sync_skip\",\n\t\t\t\t\tskill: entry.name\n\t\t\t\t}, \"Skill is already current\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!current && await pathExists(join(layout.root, layout.directoryName(entry.name)))) {\n\t\t\t\tthis.#logger.warn({\n\t\t\t\t\tcode: \"skill_name_shadowed_locally\",\n\t\t\t\t\tskill: entry.name\n\t\t\t\t}, \"An unmanaged directory shadows this Skill name; leaving it untouched\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst bytes = await downloadedBundle(this.#api, token, input.agentId, entry, signal);\n\t\t\tconst started = this.#now();\n\t\t\tconst staged = await stageBundle(skillStagingRoot(input.cwd), entry, bytes);\n\t\t\tawait this.#swapIn(input, layout, current, entry.name, staged);\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: current ? \"skill_sync_update\" : \"skill_sync_install\",\n\t\t\t\tskill: entry.name,\n\t\t\t\tms: this.#now() - started\n\t\t\t}, \"Skill synchronized\");\n\t\t}\n\t\tfor (const [name, managed] of existing) {\n\t\t\tif (desired.has(name)) continue;\n\t\t\tawait this.#removeDeparted(input, name, managed);\n\t\t}\n\t\treturn this.#existingSkillPaths(layout);\n\t}\n\t/**\n\t* Install a validated staging directory over the current copy.\n\t*\n\t* The current copy is moved aside (never deleted) until the rename succeeds, so a failure at the\n\t* final step restores it. An edited copy is quarantined instead, which already preserves it.\n\t*/\n\tasync #swapIn(input, layout, current, name, staged) {\n\t\tawait ensurePrivateDirectory(dirname(layout.root), layout.root);\n\t\tlet aside;\n\t\tif (current) aside = (await this.#retireManaged(input, name, current, true)).aside;\n\t\tconst destination = join(layout.root, layout.directoryName(name));\n\t\ttry {\n\t\t\tawait this.#rename(staged, destination);\n\t\t} catch (error) {\n\t\t\tif (aside) await rename(aside, destination).catch(() => void 0);\n\t\t\tawait rm(staged, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t}).catch(() => void 0);\n\t\t\tthrow error;\n\t\t}\n\t\tif (aside) await rm(aside, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t}).catch(() => void 0);\n\t}\n\tasync #removeDeparted(input, name, managed) {\n\t\tconst { kind } = await this.#retireManaged(input, name, managed, false);\n\t\tthis.#logger.debug({\n\t\t\tcode: \"skill_sync_remove\",\n\t\t\tskill: name,\n\t\t\toutcome: kind\n\t\t}, kind === \"quarantined\" ? \"Skill is no longer enabled; locally edited copy quarantined\" : \"Skill is no longer enabled; removed\");\n\t}\n\t/**\n\t* Retire a managed directory, whether it is being replaced or removed.\n\t*\n\t* The edited-check lives in one place so the update and removal paths cannot drift apart: a\n\t* locally edited copy is always quarantined into `.opentag/skill-conflicts/`, never silently\n\t* destroyed. On a replacement an unedited copy is moved aside (returned as `aside`) so it can be\n\t* restored; a removal deletes it outright.\n\t*/\n\tasync #retireManaged(input, name, current, keepAside) {\n\t\tconst recorded = await readContentDigest(current.path);\n\t\tconst live = await hashSkillDirectory(current.path).catch(() => void 0);\n\t\tif (recorded !== void 0 && live !== void 0 && recorded !== live) {\n\t\t\tawait quarantineConflict(input.cwd, name, current.path, this.#now(), this.#logger);\n\t\t\treturn { kind: \"quarantined\" };\n\t\t}\n\t\tif (keepAside) return {\n\t\t\tkind: \"removed\",\n\t\t\taside: await moveAside(skillStagingRoot(input.cwd), current.path, randomUUID())\n\t\t};\n\t\tawait rm(current.path, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t\treturn { kind: \"removed\" };\n\t}\n};\nasync function pathExists(path) {\n\ttry {\n\t\tawait stat(path);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\n//#region src/runtime/agent-runtime-availability-tester.ts\nconst TEST_SYSTEM_PROMPT = \"You are running a bounded OpenTag availability test. Reply with only the requested token.\";\nconst logger$11 = createLogger(\"runtime-availability-tester\");\nfunction agentRuntimeAvailabilityPolicy(provider) {\n\tif (provider === \"claude-code\") return {\n\t\tfileSystem: \"unrestricted\",\n\t\tnetwork: \"enabled\",\n\t\tapprovals: \"never\",\n\t\ttools: {\n\t\t\tmode: \"allow-list\",\n\t\t\tnames: []\n\t\t}\n\t};\n\tif (provider === \"pi\") return {\n\t\tfileSystem: \"read-only\",\n\t\tnetwork: \"disabled\",\n\t\tapprovals: \"never\",\n\t\ttools: { mode: \"provider-default\" }\n\t};\n\treturn {\n\t\tfileSystem: \"workspace-write\",\n\t\tnetwork: \"enabled\",\n\t\tapprovals: \"never\",\n\t\ttools: { mode: \"provider-default\" }\n\t};\n}\nfunction failed$1(requestId, code) {\n\treturn {\n\t\ttype: \"agent-runtime:test:result\",\n\t\trequestId,\n\t\tstatus: \"failed\",\n\t\tcode\n\t};\n}\nfunction passed(requestId) {\n\treturn {\n\t\ttype: \"agent-runtime:test:result\",\n\t\trequestId,\n\t\tstatus: \"passed\"\n\t};\n}\nfunction isAbortError$3(error) {\n\treturn error instanceof Error && error.name === \"AbortError\" || typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ABORT_ERR\";\n}\nfunction whenAborted(signal) {\n\tif (signal.aborted) return Promise.resolve();\n\treturn new Promise((resolve) => {\n\t\tsignal.addEventListener(\"abort\", () => resolve(), { once: true });\n\t});\n}\nvar AgentRuntimeAvailabilityTester = class {\n\t#cleanupMs;\n\t#factories;\n\t#timeoutMs;\n\tconstructor(options) {\n\t\tthis.#factories = options.factories;\n\t\tthis.#timeoutMs = options.timeoutMs ?? RUNTIME_AGENT_RUNTIME_TEST_TIMEOUT_MS;\n\t\tthis.#cleanupMs = options.cleanupMs ?? RUNTIME_AGENT_RUNTIME_TEST_CLEANUP_MS;\n\t\tif (!Number.isSafeInteger(this.#timeoutMs) || this.#timeoutMs < 1) throw new Error(\"Agent Runtime availability test timeout must be a positive safe integer\");\n\t\tif (!Number.isSafeInteger(this.#cleanupMs) || this.#cleanupMs < 1) throw new Error(\"Agent Runtime availability test cleanup budget must be a positive safe integer\");\n\t}\n\tasync run(request, signal) {\n\t\tif (signal.aborted) return failed$1(request.requestId, \"cancelled\");\n\t\tconst factory = this.#factories.get(request.provider);\n\t\tif (!factory) return failed$1(request.requestId, \"provider_start_failed\");\n\t\tconst sentinel = randomBytes(16).toString(\"hex\");\n\t\tconst workspace = await mkdtemp(join(tmpdir(), \"opentag-runtime-test-\"));\n\t\tconst started = { current: false };\n\t\tlet runtime;\n\t\tlet acceptingRuntime = true;\n\t\tconst execution = new AbortController();\n\t\tconst onCancel = () => execution.abort();\n\t\tsignal.addEventListener(\"abort\", onCancel);\n\t\tlet timeoutHandle;\n\t\tconst timeoutResult = new Promise((resolve) => {\n\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\texecution.abort();\n\t\t\t\tresolve(failed$1(request.requestId, \"timeout\"));\n\t\t\t}, this.#timeoutMs);\n\t\t\ttimeoutHandle.unref();\n\t\t});\n\t\tlet resolveFastFail;\n\t\tconst fastFail = new Promise((resolve) => {\n\t\t\tresolveFastFail = resolve;\n\t\t});\n\t\ttry {\n\t\t\tconst work = this.#execute(factory, request, sentinel, workspace, execution.signal, started, (created) => {\n\t\t\t\tif (acceptingRuntime) runtime = created;\n\t\t\t\telse\n /* v8 ignore next -- closing a runtime that arrived after cancellation is best-effort. */\n\t\t\t\tcreated.close().catch((error) => {\n\t\t\t\t\tlogger$11.debug({\n\t\t\t\t\t\tcode: \"late_runtime_close_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Late availability-test runtime close failed\");\n\t\t\t\t});\n\t\t\t}, (code) => {\n\t\t\t\texecution.abort();\n\t\t\t\tresolveFastFail?.(failed$1(request.requestId, code));\n\t\t\t}).then((result) => ({\n\t\t\t\tkind: \"work\",\n\t\t\t\tresult\n\t\t\t}), (error) => ({\n\t\t\t\tkind: \"error\",\n\t\t\t\terror\n\t\t\t}));\n\t\t\tconst outcome = await Promise.race([\n\t\t\t\twork,\n\t\t\t\ttimeoutResult.then((result) => ({\n\t\t\t\t\tkind: \"timeout\",\n\t\t\t\t\tresult\n\t\t\t\t})),\n\t\t\t\tfastFail.then((result) => ({\n\t\t\t\t\tkind: \"fast\",\n\t\t\t\t\tresult\n\t\t\t\t})),\n\t\t\t\twhenAborted(signal).then(() => ({ kind: \"cancel\" }))\n\t\t\t]);\n\t\t\tif (signal.aborted || outcome.kind === \"cancel\") return failed$1(request.requestId, \"cancelled\");\n\t\t\tif (outcome.kind === \"timeout\" || outcome.kind === \"fast\") return outcome.result;\n\t\t\tif (outcome.kind === \"error\") {\n\t\t\t\tconst error = outcome.error;\n\t\t\t\tif (isAbortError$3(error)) return failed$1(request.requestId, \"timeout\");\n\t\t\t\treturn failed$1(request.requestId, classifyStartFailure(error, started.current));\n\t\t\t}\n\t\t\treturn outcome.result;\n\t\t} finally {\n\t\t\tacceptingRuntime = false;\n\t\t\t/* v8 ignore else -- the timeout handle is always armed before the probe settles. */\n\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\tsignal.removeEventListener(\"abort\", onCancel);\n\t\t\tawait budgetedCleanup(async () => {\n\t\t\t\t/* v8 ignore next -- probe runtime teardown is best-effort. */\n\t\t\t\tawait runtime?.close().catch((error) => {\n\t\t\t\t\tlogger$11.debug({\n\t\t\t\t\t\tcode: \"runtime_cleanup_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Availability-test runtime cleanup failed\");\n\t\t\t\t});\n\t\t\t\t/* v8 ignore next -- filesystem cleanup rejection is an OS-level fault; keep its debug evidence in production. */\n\t\t\t\tawait rm(workspace, {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tforce: true\n\t\t\t\t}).catch((error) => {\n\t\t\t\t\tlogger$11.debug({\n\t\t\t\t\t\tcode: \"workspace_cleanup_failed\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"Availability-test workspace cleanup failed\");\n\t\t\t\t});\n\t\t\t}, this.#cleanupMs);\n\t\t}\n\t}\n\tasync #execute(factory, request, sentinel, workspace, signal, started, onCreated, onToolOrInteraction) {\n\t\tlet toolOrInteraction = false;\n\t\tconst runtime = await factory.create({\n\t\t\teventSink: (event) => {\n\t\t\t\t/* v8 ignore else -- other event types are deliberately ignored by the probe sink. */\n\t\t\t\tif (event.type === \"tool_started\" || event.type === \"interaction_requested\") {\n\t\t\t\t\ttoolOrInteraction = true;\n\t\t\t\t\tonToolOrInteraction(\"interaction_or_tool\");\n\t\t\t\t}\n\t\t\t},\n\t\t\tsystemPrompt: TEST_SYSTEM_PROMPT,\n\t\t\tworkspace: { cwd: workspace },\n\t\t\tpolicy: agentRuntimeAvailabilityPolicy(request.provider),\n\t\t\tconfiguration: {\n\t\t\t\t...request.model ? { model: request.model } : {},\n\t\t\t\t...request.reasoningEffort ? { reasoningEffort: request.reasoningEffort } : {}\n\t\t\t}\n\t\t});\n\t\tstarted.current = true;\n\t\tonCreated(runtime);\n\t\ttry {\n\t\t\tconst run = await runtime.prompt({\n\t\t\t\trunId: randomUUID(),\n\t\t\t\tinput: { items: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: `Reply with exactly ${sentinel} and nothing else. Do not use tools and do not add punctuation.`\n\t\t\t\t}] },\n\t\t\t\tsignal\n\t\t\t});\n\t\t\tif (toolOrInteraction) return failed$1(request.requestId, \"interaction_or_tool\");\n\t\t\treturn settleRun(request.requestId, run, sentinel);\n\t\t} catch (error) {\n\t\t\tif (toolOrInteraction) return failed$1(request.requestId, \"interaction_or_tool\");\n\t\t\tlogger$11.debug({\n\t\t\t\tcode: \"availability_prompt_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Agent Runtime availability prompt failed\");\n\t\t\tthrow error;\n\t\t}\n\t}\n};\nfunction settleRun(requestId, run, sentinel) {\n\tif (run.error?.code === \"provider_start_failed\") return failed$1(requestId, \"provider_start_failed\");\n\tif (run.status !== \"completed\") return failed$1(requestId, \"provider_failed\");\n\tif (run.output.filter((item) => item.type === \"text\").map((item) => item.text).join(\"\").trim() !== sentinel) return failed$1(requestId, \"provider_failed\");\n\treturn passed(requestId);\n}\nfunction classifyStartFailure(error, started) {\n\tif (error instanceof AgentProviderError && error.code === \"provider_start_failed\" || error instanceof AgentRuntimeError && (error.code === \"create_failed\" || error.code === \"configuration_invalid\")) return \"provider_start_failed\";\n\treturn started ? \"provider_failed\" : \"provider_start_failed\";\n}\nasync function budgetedCleanup(cleanup, cleanupMs) {\n\tlet timer;\n\ttry {\n\t\tawait Promise.race([cleanup().catch((error) => {\n\t\t\tlogger$11.debug({\n\t\t\t\tcode: \"budgeted_cleanup_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Availability-test budgeted cleanup failed\");\n\t\t}), new Promise((resolve) => {\n\t\t\ttimer = setTimeout(resolve, cleanupMs);\n\t\t\ttimer.unref();\n\t\t})]);\n\t} finally {\n\t\t/* v8 ignore else -- the budget timer is always armed before the race settles. */\n\t\tif (timer) clearTimeout(timer);\n\t}\n}\n//#endregion\n//#region src/runtime/context-tree-settings.ts\nconst RecordSchema = z.object({\n\tfingerprint: z.string(),\n\tresult: ContextTreeOperationResponseSchema\n}).strict();\nconst TREE_PATH = z.object({ tree: z.object({ path: z.string().min(1) }) });\n/** Keep the hash inside the CLI's 40-character project-name limit. */\nfunction contextTreeStagingName(repository) {\n\tconst identity = repository.toLowerCase();\n\treturn `${identity.replace(/[^a-z0-9.-]+/g, \"-\").slice(0, 27)}-${createHash(\"sha256\").update(identity).digest(\"hex\").slice(0, 12)}`;\n}\nfunction fingerprint(frame) {\n\tconst input = frame.input;\n\treturn JSON.stringify([\n\t\tframe.agentId,\n\t\tinput.action,\n\t\tinput.alias,\n\t\tinput.repository?.toLowerCase() ?? null,\n\t\tinput.expectedRevision,\n\t\tinput.expectedRuntimeConfigRevision\n\t]);\n}\n/** Publication intent survives lost responses, timeouts, and Computer restarts. */\nvar ContextTreeSettings = class {\n\toptions;\n\t#active;\n\t#closed = false;\n\tconstructor(options) {\n\t\tthis.options = options;\n\t}\n\trun(frame) {\n\t\tif (this.#closed) return Promise.resolve(failed(\"computer_unavailable\"));\n\t\tconst identity = fingerprint(frame);\n\t\tif (this.#active) return this.#active.identity === identity ? this.#active.promise : Promise.resolve(failed(\"busy\"));\n\t\tconst controller = new AbortController();\n\t\tconst promise = this.#run(frame, controller).finally(() => {\n\t\t\tthis.#active = void 0;\n\t\t});\n\t\tthis.#active = {\n\t\t\tidentity,\n\t\t\tpromise,\n\t\t\tcontroller\n\t\t};\n\t\treturn promise;\n\t}\n\tclose() {\n\t\tthis.#closed = true;\n\t\tthis.#active?.controller.abort();\n\t}\n\tasync #run(frame, controller) {\n\t\tconst budget = this.options.budgetMs ?? 24e4;\n\t\tconst work = new AbortController();\n\t\tconst totalTimer = setTimeout(() => controller.abort(), budget);\n\t\tconst workTimer = setTimeout(() => work.abort(), Math.max(1, budget - Math.min(1e4, budget / 10)));\n\t\tconst signal = AbortSignal.any([controller.signal, work.signal]);\n\t\ttry {\n\t\t\treturn await this.#execute(frame, signal, controller.signal);\n\t\t} catch {\n\t\t\treturn failed(\"failed\");\n\t\t} finally {\n\t\t\tclearTimeout(totalTimer);\n\t\t\tclearTimeout(workTimer);\n\t\t}\n\t}\n\t#runner(frame, signal, managedEnvironment) {\n\t\tconst assets = resolveContextTreePackage();\n\t\tif (!assets && !this.options.run) return void 0;\n\t\tconst environment = mergeContextTreeEnvironment(this.options.environment, managedEnvironment);\n\t\tconst run = this.options.run ?? ((args, cancellation) => {\n\t\t\tif (!assets) throw new Error(\"Context Tree package missing\");\n\t\t\treturn runContextTreeCli(assets, args, {\n\t\t\t\tenv: environment,\n\t\t\t\tnetwork: true,\n\t\t\t\tsignal: cancellation\n\t\t\t});\n\t\t});\n\t\treturn (args, cancellation = signal) => {\n\t\t\tconst execute = async () => {\n\t\t\t\tcancellation.throwIfAborted();\n\t\t\t\tif (frame.requireStopped && this.options.hasAgentSessions(frame.agentId)) throw new Error(\"Agent runtime resumed\");\n\t\t\t\treturn await abortable(run(args, cancellation), cancellation);\n\t\t\t};\n\t\t\tif (args[0] === \"verify\") return execute();\n\t\t\tconst queued = this.options.exclusive(execute);\n\t\t\tqueued.catch(() => void 0);\n\t\t\treturn abortable(queued, cancellation);\n\t\t};\n\t}\n\tasync #execute(frame, signal, cleanupSignal) {\n\t\tif (frame.requireStopped && this.options.hasAgentSessions(frame.agentId)) return failed(\"busy\");\n\t\tconst input = frame.input;\n\t\tconst managedEnvironment = input.action === \"disconnect\" ? void 0 : this.options.managedEnvironment?.();\n\t\tif (this.options.managedCredentials && input.action !== \"disconnect\" && !managedEnvironment) return failed(\"authentication_required\");\n\t\tif (managedEnvironment && input.action === \"connect\" && input.repository && !managedRepositoryAllowed(managedEnvironment, input.repository)) return failed(\"permission_denied\");\n\t\tconst run = this.#runner(frame, signal, managedEnvironment);\n\t\tif (!run) return failed(\"capability_missing\");\n\t\treturn this.#executeRecorded(frame, run, cleanupSignal);\n\t}\n\tasync #executeRecorded(frame, run, cleanupSignal) {\n\t\tconst input = frame.input;\n\t\tconst directory = join(this.options.home, \"state\", \"context-tree-operations\");\n\t\tawait ensurePrivateDirectory(this.options.home, directory);\n\t\tconst recordFile = join(directory, `${input.operationId}.json`);\n\t\tconst previous = await readDurableJson(recordFile, RecordSchema.parse);\n\t\tif (previous) return previous.fingerprint === fingerprint(frame) ? previous.result : failed(\"stale_configuration\");\n\t\tconst identity = fingerprint(frame);\n\t\tif (input.action === \"disconnect\") return this.#save(recordFile, identity, {\n\t\t\tstatus: \"completed\",\n\t\t\trepository: null\n\t\t});\n\t\tif (!input.repository) return failed(\"failed\");\n\t\tconst setup = join(directory, contextTreeStagingName(input.repository));\n\t\tawait ensurePrivateDirectory(this.options.home, setup);\n\t\tconst project = [\n\t\t\t\"--project-path\",\n\t\t\tsetup,\n\t\t\t\"--json\"\n\t\t];\n\t\tconst result = await this.#runRepositoryOperation(input, directory, project, run);\n\t\treturn this.#save(recordFile, identity, await this.#cleanup(project, result, run, cleanupSignal));\n\t}\n\tasync #save(recordFile, identity, result) {\n\t\tawait writeDurableFile(recordFile, JSON.stringify({\n\t\t\tfingerprint: identity,\n\t\t\tresult\n\t\t}));\n\t\treturn result;\n\t}\n\tasync #runRepositoryOperation(input, directory, project, run) {\n\t\treturn (input.action === \"create\" ? await this.#publish(directory, input.repository, project, run) : void 0) ?? verifyRepository(input.repository, project, run);\n\t}\n\tasync #cleanup(project, result, run, signal) {\n\t\ttry {\n\t\t\treturn (await run([\n\t\t\t\t\"disconnect\",\n\t\t\t\t\"--all\",\n\t\t\t\t...project\n\t\t\t], signal)).failureCode && result.status === \"completed\" ? failed(\"failed\") : result;\n\t\t} catch {\n\t\t\treturn result.status === \"completed\" ? failed(\"failed\") : result;\n\t\t}\n\t}\n\tasync #publish(directory, repository, project, run) {\n\t\tconst publicationFile = join(directory, `publication-${createHash(\"sha256\").update(repository.toLowerCase()).digest(\"hex\")}.json`);\n\t\tconst previous = await readDurableJson(publicationFile, ContextTreeOperationResponseSchema.parse);\n\t\tif (previous?.status === \"completed\") return void 0;\n\t\tif (previous?.status === \"failed\" && previous.code === \"publication_uncertain\") return previous;\n\t\tif ((await run([\n\t\t\t\"connect\",\n\t\t\t`${contextTreeStagingName(repository)}-context-tree`,\n\t\t\t\"--as\",\n\t\t\t\"settings\",\n\t\t\t...project\n\t\t])).failureCode) {\n\t\t\tconst created = await run([\n\t\t\t\t\"create\",\n\t\t\t\t\"--as\",\n\t\t\t\t\"settings\",\n\t\t\t\t...project\n\t\t\t]);\n\t\t\tif (created.failureCode) return classify(created.failureCode);\n\t\t}\n\t\tawait writeDurableFile(publicationFile, JSON.stringify(failed(\"publication_uncertain\")));\n\t\ttry {\n\t\t\tconst published = await run([\n\t\t\t\t\"publish\",\n\t\t\t\trepository,\n\t\t\t\t\"--tree\",\n\t\t\t\t\"settings\",\n\t\t\t\t...project\n\t\t\t]);\n\t\t\tconst outcome = published.failureCode ? classify(published.failureCode, true) : {\n\t\t\t\tstatus: \"completed\",\n\t\t\t\trepository\n\t\t\t};\n\t\t\tawait writeDurableFile(publicationFile, JSON.stringify(outcome));\n\t\t\treturn outcome.status === \"failed\" ? outcome : void 0;\n\t\t} catch {\n\t\t\treturn failed(\"publication_uncertain\");\n\t\t}\n\t}\n};\nasync function verifyRepository(repository, project, run) {\n\tconst connected = await run([\n\t\t\"connect\",\n\t\trepository,\n\t\t\"--as\",\n\t\t\"settings\",\n\t\t...project\n\t]);\n\tif (connected.failureCode) return classify(connected.failureCode);\n\tconst payload = TREE_PATH.safeParse(connected.payload);\n\tif (!payload.success) return failed(\"invalid_tree\");\n\treturn (await run([\n\t\t\"verify\",\n\t\t\"--tree-path\",\n\t\tpayload.data.tree.path,\n\t\t\"--json\"\n\t])).failureCode ? failed(\"invalid_tree\") : {\n\t\tstatus: \"completed\",\n\t\trepository\n\t};\n}\nfunction abortable(promise, signal) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst abort = () => reject(/* @__PURE__ */ new Error(\"Context Tree operation cancelled\"));\n\t\tif (signal.aborted) {\n\t\t\tabort();\n\t\t\treturn;\n\t\t}\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\tpromise.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", abort));\n\t});\n}\nfunction failed(code) {\n\treturn {\n\t\tstatus: \"failed\",\n\t\tcode\n\t};\n}\nfunction classify(code, publishing = false) {\n\tif (code === \"GITHUB_AUTH\") return failed(\"authentication_required\");\n\tif (code === \"GITHUB_PERMISSION\") return failed(\"permission_denied\");\n\tif (code === \"REPOSITORY_EXISTS\") return failed(\"repository_exists\");\n\tif (code === \"PUBLISH_INCOMPLETE\" || publishing) return failed(\"publication_uncertain\");\n\tif ([\n\t\t\"INVALID_TREE\",\n\t\t\"DIRTY_TREE\",\n\t\t\"NO_CONNECTION\"\n\t].includes(code)) return failed(\"invalid_tree\");\n\treturn failed(\"failed\");\n}\n//#endregion\n//#region src/runtime/im-resource-fetcher.ts\nconst MAX_RESOURCE_BYTES = 26214400;\nvar ImResourceFetcher = class {\n\t#api;\n\t#instanceId;\n\t#machineToken;\n\t#logger;\n\tconstructor(input) {\n\t\tthis.#api = input.api;\n\t\tthis.#instanceId = input.instanceId;\n\t\tthis.#machineToken = input.machineToken;\n\t\tthis.#logger = input.logger ?? createLogger(\"runtime-im-resource-fetcher\");\n\t}\n\tasync fetchForTurn(request, workspace) {\n\t\tconst resources = request.content.resources ?? [];\n\t\tif (resources.length === 0) return void 0;\n\t\tconst lines = [\"OpenTag IM resources (managed, user-supplied content):\"];\n\t\tfor (const resource of resources) {\n\t\t\tconst resourceLabel = `${resource.imMessageId}:${resource.ordinal}`;\n\t\t\tif (resource.availability !== \"available\") {\n\t\t\t\tlines.push(`- ${resourceLabel}: unavailable (${resource.availability})`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!this.#api || !this.#machineToken) {\n\t\t\t\tlines.push(`- ${resourceLabel}: unavailable (runtime resource client is not configured)`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst filename = safeFilename(resource.filename ?? `${resource.ordinal}.${resource.kind}`);\n\t\t\tconst directory = resolve(workspace, \".opentag\", \"im-resources\", request.deliveryId);\n\t\t\tconst target = join(directory, `${resource.imMessageId}-${resource.ordinal}-${filename}`);\n\t\t\tconst temporary = join(directory, `.${resource.imMessageId}-${resource.ordinal}-${randomUUID()}.tmp`);\n\t\t\ttry {\n\t\t\t\tawait mkdir(directory, {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tmode: 448\n\t\t\t\t});\n\t\t\t\ttry {\n\t\t\t\t\tawait access(target);\n\t\t\t\t\tlines.push(`- ${resourceLabel}: ${target}`);\n\t\t\t\t\tcontinue;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.#logger.debug({\n\t\t\t\t\t\tcode: \"resource_target_missing\",\n\t\t\t\t\t\terror: String(error)\n\t\t\t\t\t}, \"IM resource target is not published\");\n\t\t\t\t}\n\t\t\t\tconst response = await this.#api.openImResource(this.#machineToken, resource.imMessageId, resource.ordinal, {\n\t\t\t\t\tsessionId: request.sessionId,\n\t\t\t\t\tinstanceId: this.#instanceId,\n\t\t\t\t\tplacementGeneration: request.placementGeneration\n\t\t\t\t});\n\t\t\t\tif (!response.body) throw new Error(\"resource body unavailable\");\n\t\t\t\tlet observed = 0;\n\t\t\t\tconst limiter = new Transform({ transform(chunk, _encoding, callback) {\n\t\t\t\t\tobserved += chunk.byteLength;\n\t\t\t\t\tcallback(observed <= MAX_RESOURCE_BYTES ? null : /* @__PURE__ */ new Error(\"resource too large\"), chunk);\n\t\t\t\t} });\n\t\t\t\tawait pipeline(Readable.fromWeb(response.body), limiter, createWriteStream(temporary, {\n\t\t\t\t\tflags: \"wx\",\n\t\t\t\t\tmode: 384\n\t\t\t\t}));\n\t\t\t\tawait rename(temporary, target);\n\t\t\t\tlines.push(`- ${resourceLabel}: ${target}`);\n\t\t\t} catch (error) {\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tcode: \"resource_download_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"IM resource download failed\");\n\t\t\t\tawait rm(temporary, { force: true }).catch((cleanupError) => {\n\t\t\t\t\tthis.#logger.debug({\n\t\t\t\t\t\tcode: \"resource_temp_cleanup_failed\",\n\t\t\t\t\t\terror: String(cleanupError)\n\t\t\t\t\t}, \"IM resource temporary file cleanup failed\");\n\t\t\t\t});\n\t\t\t\tlines.push(`- ${resourceLabel}: unavailable (download failed)`);\n\t\t\t}\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n};\nfunction safeFilename(value) {\n\treturn value.replace(/[^A-Za-z0-9._-]+/g, \"_\").replace(/^\\.+/, \"\").slice(0, 160) || \"resource.bin\";\n}\n//#endregion\n//#region src/runtime/mvp-turn-report-recovery.ts\nvar MvpTurnReportRecovery = class {\n\t#bindingStore;\n\t#logger;\n\t#maxActiveReplays;\n\t#maxPreparedBatches;\n\t#reconciler;\n\t#reportOwner;\n\t#prepared = /* @__PURE__ */ new Map();\n\t#queues = /* @__PURE__ */ new Map();\n\t#activeReplays = 0;\n\tconstructor(options) {\n\t\tthis.#bindingStore = options.bindingStore;\n\t\tthis.#logger = options.logger ?? createLogger(\"report-recovery\");\n\t\tthis.#maxActiveReplays = options.maxActiveReplays ?? 10;\n\t\tthis.#maxPreparedBatches = options.maxPreparedBatches ?? 256;\n\t\tthis.#reconciler = options.reconciler;\n\t\tthis.#reportOwner = options.reportOwner;\n\t\tif (!Number.isSafeInteger(this.#maxActiveReplays) || this.#maxActiveReplays < 1) throw new Error(\"MVP Turn Report active replay limit must be a positive safe integer\");\n\t\tif (!Number.isSafeInteger(this.#maxPreparedBatches) || this.#maxPreparedBatches < 1) throw new Error(\"MVP Turn Report prepared batch limit must be a positive safe integer\");\n\t}\n\tprepare(request, result) {\n\t\tif (result.status === \"rejected\") return Promise.resolve(result);\n\t\treturn this.#reconciler.withAgentLock(request.agentId, async () => {\n\t\t\tlet binding = await this.#bindingStore.read(request.agentId, request.sessionId);\n\t\t\tif (!binding) return result;\n\t\t\tconst unresolved = binding.unresolvedTurn;\n\t\t\tif (unresolved && !this.#reconciler.claimRecovery(request.sessionId, {\n\t\t\t\tdeliveryId: unresolved.deliveryId,\n\t\t\t\tturnId: unresolved.turnId\n\t\t\t})) return result;\n\t\t\tif (unresolved && unresolved.phase !== \"reporting\") {\n\t\t\t\tconst uncertain = unresolved.phase === \"starting\" || unresolved.phase === \"running\";\n\t\t\t\tconst report = this.#reportOwner.create({\n\t\t\t\t\tdeliveryId: unresolved.deliveryId,\n\t\t\t\t\tturnId: unresolved.turnId,\n\t\t\t\t\tsessionId: binding.sessionId,\n\t\t\t\t\tagentId: binding.agentId,\n\t\t\t\t\tplacementGeneration: binding.placementGeneration,\n\t\t\t\t\toutcome: uncertain ? \"unknown\" : \"failed\",\n\t\t\t\t\texecutionEffects: uncertain ? \"may_have_occurred\" : \"not_started\",\n\t\t\t\t\terrorReason: uncertain ? \"turn_state_unknown\" : \"provider_start_failed\",\n\t\t\t\t\ttraceSummary: {\n\t\t\t\t\t\tlastSequence: 0,\n\t\t\t\t\t\tdroppedEvents: 0\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbinding = await this.#bindingStore.updateUnresolved(request.agentId, request.sessionId, unresolved.turnId, \"reporting\", {\n\t\t\t\t\treport,\n\t\t\t\t\tresultHash: report.resultHash\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst reports = retainedReports(binding);\n\t\t\tif (reports.length === 0) return result;\n\t\t\tif (reports.length > RUNTIME_MVP_RETAINED_REPORT_LIMIT) throw new Error(\"The MVP retained Turn Report manifest exceeded its protocol limit\");\n\t\t\tif (!this.#prepared.has(request.requestId) && this.#prepared.size >= this.#maxPreparedBatches) throw new Error(\"The MVP Turn Report prepared batch limit was reached\");\n\t\t\tconst existing = this.#prepared.get(request.requestId);\n\t\t\tconst references = reports.map((report) => report.reference);\n\t\t\tthis.#prepared.set(request.requestId, {\n\t\t\t\tagentId: request.agentId,\n\t\t\t\tpendingSends: (existing?.pendingSends ?? 0) + 1,\n\t\t\t\tsessionId: request.sessionId\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\tretainedReports: references\n\t\t\t};\n\t\t});\n\t}\n\tafterReconciled(request, result) {\n\t\tconst references = result.retainedReports;\n\t\tif (!references || references.length === 0) return;\n\t\tconst batch = this.#prepared.get(request.requestId);\n\t\tif (!batch) return;\n\t\tthis.#prepared.delete(request.requestId);\n\t\tconst queue = this.#queues.get(batch.sessionId) ?? {\n\t\t\tagentId: batch.agentId,\n\t\t\tblocked: false,\n\t\t\tkeys: /* @__PURE__ */ new Set(),\n\t\t\treferences: [],\n\t\t\trestartRequested: false,\n\t\t\trunning: false\n\t\t};\n\t\tif (queue.agentId !== batch.agentId) {\n\t\t\tthis.#logger.warn({\n\t\t\t\tagentId: batch.agentId,\n\t\t\t\tsessionId: batch.sessionId\n\t\t\t}, \"Turn Report replay has a conflicting Agent owner\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.#queues.has(batch.sessionId)) this.#queues.set(batch.sessionId, queue);\n\t\tqueue.blocked = false;\n\t\tif (queue.running) queue.restartRequested = true;\n\t\tfor (const reference of references) {\n\t\t\tconst key = reportKey(reference);\n\t\t\tif (queue.keys.has(key)) continue;\n\t\t\tqueue.keys.add(key);\n\t\t\tqueue.references.push(reference);\n\t\t}\n\t\tthis.#startQueues();\n\t}\n\tcancel(request, result) {\n\t\tif (!result.retainedReports || result.retainedReports.length === 0) return;\n\t\tconst batch = this.#prepared.get(request.requestId);\n\t\tif (!batch) return;\n\t\tif (batch.pendingSends === 1) this.#prepared.delete(request.requestId);\n\t\telse batch.pendingSends -= 1;\n\t}\n\t#startQueues() {\n\t\tfor (const [sessionId, queue] of this.#queues) {\n\t\t\tif (this.#activeReplays >= this.#maxActiveReplays) return;\n\t\t\tif (queue.running || queue.blocked || queue.references.length === 0) continue;\n\t\t\tqueue.running = true;\n\t\t\tthis.#activeReplays += 1;\n\t\t\tthis.#runQueue(sessionId, queue).then((completed) => {\n\t\t\t\tconst restartRequested = queue.restartRequested;\n\t\t\t\tqueue.restartRequested = false;\n\t\t\t\tqueue.running = false;\n\t\t\t\tqueue.blocked = !completed && !restartRequested;\n\t\t\t\tthis.#activeReplays -= 1;\n\t\t\t\tif (queue.references.length === 0 && this.#queues.get(sessionId) === queue) this.#queues.delete(sessionId);\n\t\t\t\tthis.#startQueues();\n\t\t\t});\n\t\t}\n\t}\n\tasync #runQueue(sessionId, queue) {\n\t\tthis.#logger.info({\n\t\t\tagentId: queue.agentId,\n\t\t\tsessionId\n\t\t}, \"Turn Report replay started\");\n\t\ttry {\n\t\t\twhile (queue.references.length > 0) {\n\t\t\t\tconst reference = queue.references[0];\n\t\t\t\tif (!reference) break;\n\t\t\t\tconst retained = retainedReports(await this.#bindingStore.read(queue.agentId, sessionId)).find((candidate) => reportMatchesReference(candidate, reference));\n\t\t\t\tif (!retained) {\n\t\t\t\t\tqueue.references.shift();\n\t\t\t\t\tqueue.keys.delete(reportKey(reference));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst report = retained.report;\n\t\t\t\tthis.#reportOwner.rearmTerminal(report);\n\t\t\t\tlet reportTerminal;\n\t\t\t\tconst terminal = new Promise((resolve) => {\n\t\t\t\t\treportTerminal = () => resolve(\"terminal\");\n\t\t\t\t});\n\t\t\t\tconst submitted = this.#reportOwner.submit(report, () => this.#reconciler.withAgentLock(queue.agentId, async () => {\n\t\t\t\t\tawait this.#bindingStore.recordResult(queue.agentId, sessionId, report.turnId, report.resultHash);\n\t\t\t\t\tthis.#reconciler.clearRecovery(sessionId, report.turnId);\n\t\t\t\t}), { onTerminal: () => reportTerminal?.() }).then(() => \"recorded\");\n\t\t\t\tif (await Promise.race([submitted, terminal]) === \"terminal\") {\n\t\t\t\t\tthis.#logger.warn({\n\t\t\t\t\t\tagentId: queue.agentId,\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tturnId: report.turnId\n\t\t\t\t\t}, \"Turn Report replay reached a terminal Server status\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tqueue.references.shift();\n\t\t\t\tqueue.keys.delete(reportKey(reference));\n\t\t\t}\n\t\t\tthis.#logger.info({\n\t\t\t\tagentId: queue.agentId,\n\t\t\t\tsessionId\n\t\t\t}, \"Turn Report replay completed\");\n\t\t\treturn true;\n\t\t} catch {\n\t\t\tthis.#logger.warn({\n\t\t\t\tagentId: queue.agentId,\n\t\t\t\tsessionId\n\t\t\t}, \"Turn Report replay remains pending\");\n\t\t\treturn false;\n\t\t}\n\t}\n};\nfunction retainedReports(binding) {\n\tif (!binding) return [];\n\tconst reports = [];\n\tif (binding.unresolvedTurn?.phase === \"reporting\" && binding.unresolvedTurn.report) reports.push({\n\t\treport: binding.unresolvedTurn.report,\n\t\treference: reportReference(binding.unresolvedTurn.report, binding.unresolvedTurn.requestId, binding.unresolvedTurn.inputHash)\n\t});\n\tfor (const recorded of binding.recentRecordedInputs) {\n\t\tif (recorded.kind !== \"turn\") continue;\n\t\tif (recorded.report && recorded.requestId && !reports.some((candidate) => candidate.report.turnId === recorded.report?.turnId)) reports.push({\n\t\t\treport: recorded.report,\n\t\t\treference: reportReference(recorded.report, recorded.requestId, recorded.inputHash)\n\t\t});\n\t}\n\treturn reports;\n}\nfunction reportKey(report) {\n\treturn `${report.turnId}:${report.resultHash}`;\n}\nfunction reportReference(report, dispatchRequestId, inputHash) {\n\treturn {\n\t\tdispatchRequestId,\n\t\tdeliveryId: report.deliveryId,\n\t\tinputHash,\n\t\tturnId: report.turnId,\n\t\tplacementGeneration: report.placementGeneration,\n\t\tresultHash: report.resultHash\n\t};\n}\nfunction reportMatchesReference(report, reference) {\n\treturn report.reference.dispatchRequestId === reference.dispatchRequestId && report.reference.deliveryId === reference.deliveryId && report.reference.inputHash === reference.inputHash && report.reference.turnId === reference.turnId && report.reference.placementGeneration === reference.placementGeneration && report.reference.resultHash === reference.resultHash;\n}\n//#endregion\n//#region src/runtime/provider-cli/account-layout.ts\nvar ProviderCliAccountError = class extends Error {\n\tname = \"ProviderCliAccountError\";\n};\n/**\n* Resolve the operating-system account home from the account record. Injectable so\n* tests and the CLI can point at an isolated account root without touching the real\n* account home.\n*/\nfunction resolveAccountHome(account = userInfo()) {\n\tif (typeof account.homedir !== \"string\" || account.homedir.length === 0 || !isAbsolute(account.homedir)) throw new ProviderCliAccountError(\"The operating-system account record has no usable home directory\");\n\treturn resolve(account.homedir);\n}\nfunction resolveProviderCliAccountLayout(accountHome, platform = process.platform) {\n\tconst platformPath = platform === \"win32\" ? win32 : posix;\n\tif (accountHome.length === 0 || !platformPath.isAbsolute(accountHome)) throw new ProviderCliAccountError(\"The Provider CLI account home must be an absolute path\");\n\tconst home = platformPath.resolve(accountHome);\n\tconst root = platform === \"win32\" ? platformPath.join(home, \"AppData\", \"Local\", \"OpenTag\", \"provider-cli\") : join(home, \".opentag\", \"provider-cli\");\n\treturn {\n\t\taccountHome: home,\n\t\troot,\n\t\tbin: platformPath.join(root, \"bin\"),\n\t\tversions: platformPath.join(root, \"versions\"),\n\t\tstate: platformPath.join(root, \"state\"),\n\t\tstaging: platformPath.join(root, \"staging\"),\n\t\tplans: platformPath.join(root, \"plans\"),\n\t\tpublicBinDir: platformPath.join(home, \".local\", \"bin\")\n\t};\n}\nfunction providerCliStateFilePath(layout, provider) {\n\treturn join(layout.state, `${provider}.json`);\n}\nfunction providerCliLockFilePath(layout, provider) {\n\treturn join(layout.state, `${provider}.lock`);\n}\nfunction providerCliLauncherPath(layout, command) {\n\treturn join(layout.bin, command);\n}\nfunction providerCliStagingDirPath(layout, provider, operationId) {\n\treturn join(layout.staging, provider, operationId);\n}\n/**\n* The digest-addressed immutable version directory for one managed artifact:\n* `versions/<provider>/<version>/<platform>-<arch>/<archive-sha256>/`.\n*/\nfunction providerCliArtifactId(artifact, version) {\n\treturn `${version}/${artifact.platform}-${artifact.arch}/${artifact.sha256}`;\n}\nfunction providerCliVersionDirPath(layout, provider, artifactId) {\n\treturn join(layout.versions, provider, artifactId);\n}\n//#endregion\n//#region src/runtime/provider-cli/executable-format.ts\nconst MACHO_CPU_X86_64 = 16777223;\nconst MACHO_CPU_ARM64 = 16777228;\nconst ELF_MACHINE_X86_64 = 62;\nconst ELF_MACHINE_AARCH64 = 183;\nfunction machoArch(cputype) {\n\tif (cputype === MACHO_CPU_X86_64) return \"x64\";\n\tif (cputype === MACHO_CPU_ARM64) return \"arm64\";\n}\nfunction inspectMachO(header) {\n\tif (header.length < 8) return void 0;\n\tconst view = new DataView(header.buffer, header.byteOffset, header.byteLength);\n\tconst magic = view.getUint32(0, false);\n\tif (magic === 3489328638 || magic === 3472551422) {\n\t\tconst arch = machoArch(view.getUint32(4, true));\n\t\treturn arch ? {\n\t\t\tkind: \"macho\",\n\t\t\tarchs: [arch]\n\t\t} : { kind: \"unknown\" };\n\t}\n\tif (magic === 3405691582) {\n\t\tconst count = view.getUint32(4, false);\n\t\tif (count > 64 || header.length < 8 + count * 20) return { kind: \"unknown\" };\n\t\tconst archs = [];\n\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\tconst arch = machoArch(view.getUint32(8 + index * 20, false));\n\t\t\tif (arch && !archs.includes(arch)) archs.push(arch);\n\t\t}\n\t\treturn archs.length > 0 ? {\n\t\t\tkind: \"macho\",\n\t\t\tarchs\n\t\t} : { kind: \"unknown\" };\n\t}\n\tif (magic === 3405691583) {\n\t\tconst count = view.getUint32(4, false);\n\t\tif (count > 64 || header.length < 8 + count * 32) return { kind: \"unknown\" };\n\t\tconst archs = [];\n\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\tconst arch = machoArch(view.getUint32(8 + index * 32, false));\n\t\t\tif (arch && !archs.includes(arch)) archs.push(arch);\n\t\t}\n\t\treturn archs.length > 0 ? {\n\t\t\tkind: \"macho\",\n\t\t\tarchs\n\t\t} : { kind: \"unknown\" };\n\t}\n}\nfunction inspectElf(header) {\n\tif (header.length < 20) return void 0;\n\tif (header[0] !== 127 || header[1] !== 69 || header[2] !== 76 || header[3] !== 70) return void 0;\n\tconst littleEndian = header[5] !== 2;\n\tconst machine = new DataView(header.buffer, header.byteOffset, header.byteLength).getUint16(18, littleEndian);\n\tif (machine === ELF_MACHINE_X86_64) return {\n\t\tkind: \"elf\",\n\t\tarch: \"x64\"\n\t};\n\tif (machine === ELF_MACHINE_AARCH64) return {\n\t\tkind: \"elf\",\n\t\tarch: \"arm64\"\n\t};\n\treturn { kind: \"unknown\" };\n}\n/** Inspect the first bytes of a candidate executable; 64 bytes cover every header read here. */\nfunction inspectExecutableFormat(header) {\n\tif (header.length >= 2 && header[0] === 35 && header[1] === 33) return { kind: \"script\" };\n\tconst macho = inspectMachO(header);\n\tif (macho) return macho;\n\tconst elf = inspectElf(header);\n\tif (elf) return elf;\n\treturn { kind: \"unknown\" };\n}\nfunction executableFormatSupportsHost(format, platform, arch) {\n\tswitch (format.kind) {\n\t\tcase \"script\": return true;\n\t\tcase \"macho\": return platform === \"darwin\" && format.archs.includes(arch);\n\t\tcase \"elf\": return platform === \"linux\" && format.arch === arch;\n\t\tcase \"unknown\": return false;\n\t}\n}\n//#endregion\n//#region src/runtime/provider-cli/fingerprint.ts\n/** Hard bound for any selected Provider CLI executable, including external wrappers. */\nconst MAX_PROVIDER_CLI_EXECUTABLE_BYTES = 268435456;\nconst logger$10 = createLogger(\"runtime-provider-cli-fingerprint\");\nvar ProviderCliFileError = class extends Error {\n\tcode;\n\tname = \"ProviderCliFileError\";\n\tconstructor(code, path) {\n\t\tsuper(`Provider CLI executable identity failed (${code}): ${path}`);\n\t\tthis.code = code;\n\t}\n};\nasync function computeFileIdentity(path, maxBytes = MAX_PROVIDER_CLI_EXECUTABLE_BYTES) {\n\tlet canonical;\n\ttry {\n\t\tcanonical = await realpath(path);\n\t} catch (error) {\n\t\tlogger$10.debug({\n\t\t\tcode: \"file_realpath_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI file canonicalization failed\");\n\t\tthrow new ProviderCliFileError(\"missing\", path);\n\t}\n\tconst status = await stat(canonical);\n\tif (!status.isFile()) throw new ProviderCliFileError(\"not-regular-file\", canonical);\n\tif (status.size > maxBytes) throw new ProviderCliFileError(\"too-large\", canonical);\n\tconst hash = createHash(\"sha256\");\n\tlet bytesRead = 0;\n\tfor await (const chunk of createReadStream(canonical)) {\n\t\tconst bytes = chunk;\n\t\tbytesRead += bytes.byteLength;\n\t\tif (bytesRead > maxBytes) throw new ProviderCliFileError(\"too-large\", canonical);\n\t\thash.update(bytes);\n\t}\n\tif (bytesRead !== status.size) throw new ProviderCliFileError(\"changed\", canonical);\n\treturn {\n\t\tpath: canonical,\n\t\tsize: status.size,\n\t\tsha256: hash.digest(\"hex\")\n\t};\n}\n/**\n* Deterministic fingerprint over the parts that define executable identity for\n* OpenTag: canonical target, file identity, version, and the managed archive digest\n* when the target is a managed artifact.\n*/\nfunction computeTargetFingerprint(identity, version, managedDigest) {\n\tconst hash = createHash(\"sha256\");\n\tconst parts = [\n\t\tidentity.path,\n\t\tString(identity.size),\n\t\tidentity.sha256,\n\t\tversion,\n\t\tmanagedDigest ?? \"\"\n\t];\n\thash.update(JSON.stringify(parts));\n\treturn `v1:${hash.digest(\"hex\")}`;\n}\n//#endregion\n//#region src/runtime/provider-cli/probe.ts\nconst execFileAsync$1 = promisify(execFile);\nconst logger$9 = createLogger(\"runtime-provider-cli-probe\");\nconst defaultProviderCliExecFile = async (file, args, options) => {\n\tconst result = await execFileAsync$1(file, [...args], {\n\t\tencoding: \"utf8\",\n\t\tenv: options.env,\n\t\tmaxBuffer: options.maxBuffer,\n\t\ttimeout: options.timeout,\n\t\twindowsHide: options.windowsHide\n\t});\n\treturn {\n\t\tstdout: result.stdout,\n\t\tstderr: result.stderr\n\t};\n};\n/**\n* Probes run with a scrubbed environment: no provider credentials, no caller PATH\n* influence beyond the absolute target, and no provider API requests. `probeHome` is a\n* fresh private temporary directory, never the real account home, so provider config,\n* tokens, and logs cannot be read from or written to the user's normal CLI state. The\n* running Node.js directory is first on PATH so `#!/usr/bin/env node` wrappers execute\n* with the same Node runtime as OpenTag.\n*/\nfunction providerCliProbeEnvironment(probeHome, execDir = dirname(process.execPath)) {\n\treturn {\n\t\tHOME: probeHome,\n\t\tPATH: [\n\t\t\texecDir,\n\t\t\t\"/usr/bin\",\n\t\t\t\"/bin\",\n\t\t\t\"/usr/sbin\",\n\t\t\t\"/sbin\"\n\t\t].join(delimiter),\n\t\tTMPDIR: join(probeHome, \"tmp\"),\n\t\tTMP: join(probeHome, \"tmp\"),\n\t\tTEMP: join(probeHome, \"tmp\"),\n\t\tXDG_CONFIG_HOME: join(probeHome, \"config\"),\n\t\tXDG_CACHE_HOME: join(probeHome, \"cache\"),\n\t\tXDG_STATE_HOME: join(probeHome, \"state\"),\n\t\tXDG_RUNTIME_DIR: join(probeHome, \"runtime\")\n\t};\n}\n/**\n* Run the reviewed probe contract against one absolute executable: version probe,\n* version parse and compatibility check, then the required command-surface probe.\n* Raw child output never leaves this function.\n*/\nasync function probeProviderCliExecutable(target, entry, options) {\n\tlet probeHome;\n\ttry {\n\t\tprobeHome = await mkdtemp(join(tmpdir(), \"opentag-provider-cli-probe-\"));\n\t\tawait chmod(probeHome, 448);\n\t\tfor (const child of [\n\t\t\t\"tmp\",\n\t\t\t\"config\",\n\t\t\t\"cache\",\n\t\t\t\"state\",\n\t\t\t\"runtime\"\n\t\t]) await mkdir(join(probeHome, child), { mode: 448 });\n\t\tif (entry.provider === \"slack\") await mkdir(join(probeHome, \"slack\"), { mode: 448 });\n\t\tconst run = options.execFile ?? defaultProviderCliExecFile;\n\t\tconst execution = {\n\t\t\tenv: {\n\t\t\t\t...providerCliProbeEnvironment(probeHome),\n\t\t\t\t...entry.managedEnvironment\n\t\t\t},\n\t\t\tmaxBuffer: entry.probes.maxOutputBytes,\n\t\t\ttimeout: entry.probes.timeoutMs,\n\t\t\twindowsHide: true\n\t\t};\n\t\tconst prefix = options.includeManagedArguments === false ? [] : [...entry.managedArguments];\n\t\tif (entry.provider === \"slack\" && !prefix.includes(\"--config-dir\")) prefix.push(\"--config-dir\", join(probeHome, \"slack\"));\n\t\tlet versionOutput;\n\t\ttry {\n\t\t\tversionOutput = (await run(target, [...prefix, ...entry.probes.versionArgs], execution)).stdout;\n\t\t} catch (error) {\n\t\t\tlogger$9.debug({\n\t\t\t\tcode: \"version_probe_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI version probe failed\");\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tcode: \"probe_failed\"\n\t\t\t};\n\t\t}\n\t\tconst version = new RegExp(entry.probes.versionPattern).exec(versionOutput)?.[1];\n\t\tif (!version || !semver.valid(version)) return {\n\t\t\tstatus: \"failed\",\n\t\t\tcode: \"unparseable_version\"\n\t\t};\n\t\tif (!semver.satisfies(version, entry.compatibility)) return {\n\t\t\tstatus: \"failed\",\n\t\t\tcode: \"version_incompatible\"\n\t\t};\n\t\ttry {\n\t\t\tawait run(target, [...prefix, ...entry.probes.surfaceArgs], execution);\n\t\t} catch (error) {\n\t\t\tlogger$9.debug({\n\t\t\t\tcode: \"surface_probe_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI surface probe failed\");\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tcode: \"probe_failed\"\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tstatus: \"ok\",\n\t\t\tversion\n\t\t};\n\t} catch (error) {\n\t\tlogger$9.debug({\n\t\t\tcode: \"probe_setup_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI probe setup failed\");\n\t\treturn {\n\t\t\tstatus: \"failed\",\n\t\t\tcode: \"probe_failed\"\n\t\t};\n\t} finally {\n\t\tif (probeHome) await rm(probeHome, {\n\t\t\tforce: true,\n\t\t\trecursive: true\n\t\t}).catch((error) => {\n\t\t\tlogger$9.debug({\n\t\t\t\tcode: \"probe_cleanup_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI probe cleanup failed\");\n\t\t});\n\t}\n}\n//#endregion\n//#region src/runtime/provider-cli/detector.ts\nconst PATH_ENTRY_LIMIT = 256;\nconst CANDIDATE_PROBE_LIMIT = 16;\nconst EXECUTABLE_HEADER_BYTES = 64;\nconst logger$8 = createLogger(\"runtime-provider-cli-detector\");\nasync function canonicalSafeDirectory(entry, platform, accountHome) {\n\tif (entry.length === 0) return { reason: \"empty-path-entry\" };\n\tif (!isAbsolute(entry)) return { reason: \"relative-path-entry\" };\n\tconst canonical = resolveOutsideProtectedRoots(entry, protectedRoots(platform, accountHome));\n\tif (canonical === null) return { reason: \"protected-path-entry\" };\n\tconst status = await lstat(canonical).catch((error) => {\n\t\tlogger$8.debug({\n\t\t\tcode: \"path_entry_stat_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI PATH entry stat failed\");\n\t});\n\tif (!status) return { reason: \"unreadable-path-entry\" };\n\tif (!status.isDirectory() || status.isSymbolicLink()) return { reason: \"non-directory-path-entry\" };\n\tif ((status.mode & 2) !== 0) return { reason: \"world-writable-path-entry\" };\n\treturn { dir: canonical };\n}\nasync function readExecutableHeader(path) {\n\tconst handle = await open(path, constants.O_RDONLY);\n\ttry {\n\t\tconst buffer = Buffer.alloc(EXECUTABLE_HEADER_BYTES);\n\t\tconst { bytesRead } = await handle.read(buffer, 0, EXECUTABLE_HEADER_BYTES, 0);\n\t\treturn buffer.subarray(0, bytesRead);\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\n/**\n* Validate one canonical executable path: regular file, executable, not world-writable,\n* right platform/architecture, version parse and compatibility, required command\n* surface, then content identity and trust.\n*/\nasync function assessCandidatePath(canonical, options, execFile, digests, managedDigest) {\n\tconst status = await lstat(canonical).catch((error) => {\n\t\tlogger$8.debug({\n\t\t\tcode: \"candidate_stat_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI candidate stat failed\");\n\t});\n\tif (!status) return { reason: \"not-found\" };\n\tif (!status.isFile() || status.isSymbolicLink()) return { reason: \"not-regular-file\" };\n\tif ((status.mode & 73) === 0) return { reason: \"not-executable\" };\n\tif ((status.mode & 2) !== 0) return { reason: \"world-writable\" };\n\tconst header = await readExecutableHeader(canonical).catch((error) => {\n\t\tlogger$8.debug({\n\t\t\tcode: \"candidate_header_read_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI candidate header read failed\");\n\t});\n\tif (!header) return { reason: \"unreadable\" };\n\tconst format = inspectExecutableFormat(header);\n\tif (format.kind === \"unknown\") return { reason: \"unrecognized-format\" };\n\tif (!executableFormatSupportsHost(format, options.platform, options.arch)) return { reason: \"wrong-platform-architecture\" };\n\tconst identity = await computeFileIdentity(canonical).catch((error) => {\n\t\tlogger$8.debug({\n\t\t\tcode: \"candidate_identity_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI candidate identity failed\");\n\t});\n\tif (!identity) return { reason: \"not-found\" };\n\tconst probed = await probeProviderCliExecutable(canonical, options.entry, { execFile });\n\tif (probed.status === \"failed\") return { reason: probed.code === \"unparseable_version\" ? \"unparseable-version\" : probed.code === \"version_incompatible\" ? \"version-incompatible\" : \"probe-failed\" };\n\tconst trust = managedDigest !== void 0 || digests.has(identity.sha256) ? \"catalog-verified\" : \"compatible-unverified\";\n\treturn {\n\t\tversion: probed.version,\n\t\ttrust,\n\t\tfingerprint: computeTargetFingerprint(identity, probed.version, managedDigest),\n\t\tidentity\n\t};\n}\nfunction managedDigestOf(selection) {\n\tif (selection.selection.kind !== \"managed\") return void 0;\n\tconst digest = selection.selection.artifactId.split(\"/\").at(-1);\n\treturn digest && digest.length > 0 ? digest : void 0;\n}\nasync function detectProviderCliCandidates(options) {\n\tconst execFile = options.execFile ?? defaultProviderCliExecFile;\n\tconst digests = catalogExecutableDigests(options.entry);\n\tconst candidates = [];\n\tconst ignored = [];\n\tconst seenCanonical = /* @__PURE__ */ new Set();\n\tconst pathRanks = /* @__PURE__ */ new Map();\n\tlet sequence = 0;\n\tlet probedCandidateCount = 0;\n\tconst launcherPath = providerCliLauncherPath(options.layout, options.entry.command);\n\tconst launcherCanonical = await realpath(launcherPath).catch((error) => {\n\t\tlogger$8.debug({\n\t\t\tcode: \"launcher_realpath_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI launcher canonicalization failed\");\n\t});\n\tconst accountHome = await realpath(options.layout.accountHome).catch((error) => {\n\t\tlogger$8.debug({\n\t\t\tcode: \"account_home_realpath_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI account home canonicalization failed\");\n\t\treturn options.layout.accountHome;\n\t});\n\tconst layoutRoot = await realpath(options.layout.root).catch((error) => {\n\t\tlogger$8.debug({\n\t\t\tcode: \"layout_root_realpath_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI layout root canonicalization failed\");\n\t\treturn resolveProviderCliAccountLayout(accountHome, options.platform).root;\n\t});\n\tif (options.mode === \"auto\") {\n\t\tconst pathEntries = (options.env.PATH ?? \"\").split(delimiter).slice(0, PATH_ENTRY_LIMIT);\n\t\tlet rank = 0;\n\t\tfor (const rawEntry of pathEntries) {\n\t\t\tconst currentRank = rank;\n\t\t\trank += 1;\n\t\t\tif (rawEntry.length === 0) continue;\n\t\t\tconst directory = await canonicalSafeDirectory(rawEntry, options.platform, accountHome);\n\t\t\tif (\"reason\" in directory) {\n\t\t\t\tif (directory.reason !== \"unreadable-path-entry\") ignored.push({\n\t\t\t\t\tpath: rawEntry,\n\t\t\t\t\treason: directory.reason\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst candidatePath = join(directory.dir, options.entry.command);\n\t\t\tlet canonical;\n\t\t\ttry {\n\t\t\t\tawait access(candidatePath, constants.X_OK);\n\t\t\t\tcanonical = await realpath(candidatePath);\n\t\t\t} catch (error) {\n\t\t\t\tlogger$8.debug({\n\t\t\t\t\tcode: \"path_candidate_resolution_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Provider CLI PATH candidate resolution failed\");\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (seenCanonical.has(canonical)) {\n\t\t\t\tpathRanks.set(canonical, Math.min(pathRanks.get(canonical) ?? currentRank, currentRank));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tseenCanonical.add(canonical);\n\t\t\tpathRanks.set(canonical, currentRank);\n\t\t\tif (canonical === launcherCanonical || canonical.startsWith(`${layoutRoot}${sep}`)) continue;\n\t\t\tif (probedCandidateCount >= CANDIDATE_PROBE_LIMIT) {\n\t\t\t\tignored.push({\n\t\t\t\t\tpath: rawEntry,\n\t\t\t\t\treason: \"candidate-probe-limit-reached\"\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tprobedCandidateCount += 1;\n\t\t\tconst assessed = await assessCandidatePath(canonical, options, execFile, digests);\n\t\t\tif (\"reason\" in assessed) {\n\t\t\t\tignored.push({\n\t\t\t\t\tpath: canonical,\n\t\t\t\t\tsourceDir: directory.dir,\n\t\t\t\t\t...assessed\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsequence += 1;\n\t\t\tcandidates.push({\n\t\t\t\tid: `candidate-${sequence}`,\n\t\t\t\tprovider: options.provider,\n\t\t\t\tkind: \"external\",\n\t\t\t\tpath: canonical,\n\t\t\t\tsourceDir: directory.dir,\n\t\t\t\tversion: assessed.version,\n\t\t\t\ttrust: assessed.trust,\n\t\t\t\tfingerprint: assessed.fingerprint,\n\t\t\t\tpathRank: currentRank,\n\t\t\t\tincumbent: false\n\t\t\t});\n\t\t}\n\t}\n\tconst selection = options.selection;\n\tif (selection) {\n\t\tconst targetPath = selection.selection.kind === \"managed\" ? selection.selection.targetPath : selection.selection.executablePath;\n\t\tconst managedDigest = managedDigestOf(selection);\n\t\tconst incumbent = await assessCandidatePath(targetPath, options, execFile, digests, managedDigest);\n\t\tif (\"reason\" in incumbent) {\n\t\t\tconst reason = selection.selection.kind === \"external\" && (incumbent.reason === \"not-found\" || incumbent.reason === \"not-regular-file\") ? \"external-path-invalid\" : incumbent.reason;\n\t\t\tignored.push({\n\t\t\t\tpath: targetPath,\n\t\t\t\tsourceDir: \"selection\",\n\t\t\t\treason\n\t\t\t});\n\t\t} else {\n\t\t\tconst incumbentPath = incumbent.identity.path;\n\t\t\tconst merged = {\n\t\t\t\tid: \"candidate-selection\",\n\t\t\t\tprovider: options.provider,\n\t\t\t\tkind: selection.selection.kind,\n\t\t\t\tpath: incumbentPath,\n\t\t\t\tsourceDir: candidates.find((candidate) => candidate.path === incumbentPath)?.sourceDir ?? \"selection\",\n\t\t\t\tversion: incumbent.version,\n\t\t\t\ttrust: selection.selection.kind === \"managed\" ? \"catalog-verified\" : incumbent.trust,\n\t\t\t\tfingerprint: incumbent.fingerprint,\n\t\t\t\t...managedDigest ? { managedDigest } : {},\n\t\t\t\tpathRank: pathRanks.get(incumbentPath) ?? Number.MAX_SAFE_INTEGER,\n\t\t\t\tincumbent: true\n\t\t\t};\n\t\t\tif (options.mode === \"managed-only\" && merged.kind === \"external\") ignored.push({\n\t\t\t\tpath: incumbentPath,\n\t\t\t\tsourceDir: \"selection\",\n\t\t\t\treason: \"managed-only\"\n\t\t\t});\n\t\t\telse {\n\t\t\t\tconst existing = candidates.findIndex((candidate) => candidate.path === incumbentPath);\n\t\t\t\tif (existing >= 0) candidates.splice(existing, 1, merged);\n\t\t\t\telse candidates.push(merged);\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tcandidates,\n\t\tignored\n\t};\n}\n/**\n* Deterministic candidate ranking: newest compatible version first, then\n* catalog-verified trust, then the incumbent selection, then effective PATH order.\n* Also explains the winner and each loser for reporting.\n*/\nfunction rankProviderCliCandidates(candidates) {\n\tconst ordered = [...candidates].sort((left, right) => {\n\t\tconst byVersion = semver.rcompare(left.version, right.version);\n\t\tif (byVersion !== 0) return byVersion;\n\t\tconst trustRank = (trust) => trust === \"catalog-verified\" ? 0 : 1;\n\t\tconst byTrust = trustRank(left.trust) - trustRank(right.trust);\n\t\tif (byTrust !== 0) return byTrust;\n\t\tconst byIncumbent = Number(right.incumbent) - Number(left.incumbent);\n\t\tif (byIncumbent !== 0) return byIncumbent;\n\t\tconst byPath = left.pathRank - right.pathRank;\n\t\tif (byPath !== 0) return byPath;\n\t\treturn left.path.localeCompare(right.path);\n\t});\n\tconst reasons = /* @__PURE__ */ new Map();\n\tconst winner = ordered[0];\n\tif (winner) {\n\t\tconst runnerUp = ordered[1];\n\t\tlet reason = \"newest compatible version\";\n\t\tif (runnerUp && semver.compare(winner.version, runnerUp.version) === 0) {\n\t\t\tif (winner.trust !== runnerUp.trust) reason = \"catalog-verified trust\";\n\t\t\telse if (winner.incumbent && !runnerUp.incumbent) reason = \"current selection\";\n\t\t\telse reason = \"first in PATH\";\n\t\t}\n\t\treasons.set(winner.id, reason);\n\t\tfor (const loser of ordered.slice(1)) if (semver.compare(winner.version, loser.version) !== 0) reasons.set(loser.id, \"older compatible version\");\n\t\telse if (winner.trust !== loser.trust) reasons.set(loser.id, \"same version with lower trust\");\n\t\telse if (loser.incumbent !== winner.incumbent) reasons.set(loser.id, \"same version, not the current selection\");\n\t\telse reasons.set(loser.id, \"same version, later in PATH\");\n\t}\n\treturn {\n\t\tordered,\n\t\treasons\n\t};\n}\n/**\n* Reopen a winner by canonical path and recompute its fingerprint immediately before\n* persistence. A changed candidate is rejected so the caller can rank again.\n*/\nasync function verifyProviderCliCandidateFingerprint(candidate) {\n\tconst identity = await computeFileIdentity(candidate.path).catch((error) => {\n\t\tlogger$8.debug({\n\t\t\tcode: \"candidate_identity_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI candidate identity failed during fingerprint verification\");\n\t});\n\tif (!identity || identity.path !== candidate.path) return false;\n\treturn computeTargetFingerprint(identity, candidate.version, candidate.managedDigest) === candidate.fingerprint;\n}\n//#endregion\n//#region src/runtime/provider-cli/tar.ts\nvar ProviderCliArchiveError = class extends Error {\n\trejection;\n\tname = \"ProviderCliArchiveError\";\n\tconstructor(rejection, message) {\n\t\tsuper(message);\n\t\tthis.rejection = rejection;\n\t}\n};\nconst BLOCK = 512;\nfunction parseOctalField(bytes) {\n\tif (bytes.length === 0 || bytes[0] !== void 0 && (bytes[0] & 128) !== 0) return void 0;\n\tlet value = 0;\n\tlet sawDigit = false;\n\tfor (const byte of bytes) {\n\t\tif (byte === 0 || byte === 32) {\n\t\t\tif (sawDigit) break;\n\t\t\tcontinue;\n\t\t}\n\t\tif (byte < 48 || byte > 55) return void 0;\n\t\tvalue = value * 8 + (byte - 48);\n\t\tsawDigit = true;\n\t}\n\treturn sawDigit ? value : void 0;\n}\nfunction readString(bytes) {\n\tconst nul = bytes.indexOf(0);\n\tconst end = nul === -1 ? bytes.length : nul;\n\treturn new TextDecoder().decode(bytes.subarray(0, end));\n}\nfunction normalizeMemberName(raw) {\n\treturn raw.split(\"/\").filter((segment) => segment.length > 0 && segment !== \".\").join(\"/\");\n}\nfunction validateMemberName(raw) {\n\tif (raw.length === 0 || raw.startsWith(\"/\") || /^[A-Za-z]:/.test(raw) || raw.includes(\"\\\\\")) throw new ProviderCliArchiveError(\"absolute-member\", `Archive member name is absolute or ambiguous: ${raw}`);\n\tfor (const segment of raw.split(\"/\")) if (segment === \"..\") throw new ProviderCliArchiveError(\"path-traversal\", `Archive member escapes its root: ${raw}`);\n\treturn normalizeMemberName(raw);\n}\nfunction verifyChecksum(header) {\n\tconst expected = parseOctalField(header.subarray(148, 156));\n\tif (expected === void 0) return false;\n\tlet sum = 0;\n\tfor (let index = 0; index < BLOCK; index += 1) sum += index >= 148 && index < 156 ? 32 : header[index] ?? 0;\n\treturn sum === expected;\n}\n/** Parse pax extended-header records; only `path` overrides are honored. */\nfunction parsePaxPathOverride(content) {\n\tlet offset = 0;\n\tlet path;\n\twhile (offset < content.length) {\n\t\tconst space = content.indexOf(32, offset);\n\t\tif (space === -1) return void 0;\n\t\tconst lengthText = readString(content.subarray(offset, space));\n\t\tconst length = Number.parseInt(lengthText, 10);\n\t\tif (!Number.isInteger(length) || length <= 0 || offset + length > content.length) return void 0;\n\t\tconst record = readString(content.subarray(space + 1, offset + length - 1));\n\t\tconst equals = record.indexOf(\"=\");\n\t\tif (equals > 0 && record.slice(0, equals) === \"path\") path = record.slice(equals + 1);\n\t\toffset += length;\n\t}\n\treturn path;\n}\nfunction extractProviderCliExecutable(archive, options) {\n\tlet tar;\n\ttry {\n\t\ttar = gunzipSync(archive, { maxOutputLength: options.maxExtractedBytes });\n\t} catch (error) {\n\t\tif (error instanceof RangeError || error.code === \"ERR_OUT_OF_RANGE\") throw new ProviderCliArchiveError(\"decompression-limit\", \"Archive exceeds the decompressed size bound\");\n\t\tthrow new ProviderCliArchiveError(\"invalid-archive\", \"Archive is not valid gzip data\");\n\t}\n\tlet offset = 0;\n\tlet pendingName;\n\tlet found;\n\tlet sawEnd = false;\n\twhile (offset + BLOCK <= tar.length) {\n\t\tconst header = tar.subarray(offset, offset + BLOCK);\n\t\toffset += BLOCK;\n\t\tif (header.every((byte) => byte === 0)) {\n\t\t\tsawEnd = true;\n\t\t\tbreak;\n\t\t}\n\t\tif (!verifyChecksum(header)) throw new ProviderCliArchiveError(\"invalid-archive\", \"Archive member header checksum is invalid\");\n\t\tconst size = parseOctalField(header.subarray(124, 136));\n\t\tif (size === void 0) throw new ProviderCliArchiveError(\"invalid-archive\", \"Archive member size is not octal\");\n\t\tif (offset + size > tar.length) throw new ProviderCliArchiveError(\"invalid-archive\", \"Archive member content is truncated\");\n\t\tconst content = tar.subarray(offset, offset + size);\n\t\toffset += Math.ceil(size / BLOCK) * BLOCK;\n\t\tconst typeflag = header[156];\n\t\tconst rawName = readString(header.subarray(0, 100));\n\t\tconst prefix = readString(header.subarray(345, 500));\n\t\tconst memberName = pendingName ?? (prefix.length > 0 ? `${prefix}/${rawName}` : rawName);\n\t\tpendingName = void 0;\n\t\tif (typeflag === 120) {\n\t\t\tpendingName = parsePaxPathOverride(content) ?? void 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeflag === 103) continue;\n\t\tif (typeflag === 76) {\n\t\t\tpendingName = readString(content);\n\t\t\tcontinue;\n\t\t}\n\t\tconst name = validateMemberName(memberName);\n\t\tconst mode = parseOctalField(header.subarray(100, 108));\n\t\tif (mode === void 0) throw new ProviderCliArchiveError(\"invalid-archive\", `Archive member mode is not octal: ${name}`);\n\t\tif (typeflag === 53) continue;\n\t\tif (name.length === 0) throw new ProviderCliArchiveError(\"path-traversal\", \"Archive member name resolves to nothing\");\n\t\tif (typeflag !== 48 && typeflag !== 0) throw new ProviderCliArchiveError(\"unexpected-member-type\", `Archive member has an unsupported type (${String.fromCharCode(typeflag ?? 0)}): ${name}`);\n\t\tif ((mode & 3072) !== 0) throw new ProviderCliArchiveError(\"setuid-setgid\", `Archive member is setuid/setgid: ${name}`);\n\t\tif ((mode & 73) !== 0 && name !== options.expectedExecutable) throw new ProviderCliArchiveError(\"unexpected-executable\", `Archive member is an unexpected executable: ${name}`);\n\t\tif (name === options.expectedExecutable) {\n\t\t\tif (found) throw new ProviderCliArchiveError(\"unexpected-executable\", `Archive contains the expected executable more than once: ${name}`);\n\t\t\tif (size > options.maxExecutableBytes) throw new ProviderCliArchiveError(\"executable-oversized\", `Archive executable exceeds its size bound: ${name}`);\n\t\t\tfound = {\n\t\t\t\tname,\n\t\t\t\tcontent: content.slice()\n\t\t\t};\n\t\t}\n\t}\n\tif (!sawEnd) throw new ProviderCliArchiveError(\"invalid-archive\", \"Archive has no end-of-archive marker\");\n\tif (!found) throw new ProviderCliArchiveError(\"executable-missing\", `Archive does not contain ${options.expectedExecutable}`);\n\treturn found;\n}\n//#endregion\n//#region src/runtime/provider-cli/installer.ts\n/**\n* Explicit managed-install transaction.\n*\n* One operation: acquire the account/provider lock (held by the caller), download the\n* reviewed catalog artifact into a private staging directory with time and size limits,\n* verify the exact digest, safely extract only the expected executable, publish to a\n* digest-addressed immutable version directory, and run the full non-secret probe.\n* Nothing here runs an upstream installer, escalates privileges, or mutates any prior\n* selection or version directory.\n*/\nvar ProviderCliInstallError = class extends Error {\n\tcode;\n\tname = \"ProviderCliInstallError\";\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t}\n};\nconst DOWNLOAD_TIMEOUT_MS = 12e4;\nconst MAX_REDIRECT_HOPS = 8;\nconst REDIRECT_STATUSES = /* @__PURE__ */ new Set([\n\t301,\n\t302,\n\t303,\n\t307,\n\t308\n]);\nconst logger$7 = createLogger(\"runtime-provider-cli-installer\");\n/**\n* Resolve one request or redirect hop to the next URL. Every hop — the reviewed catalog\n* URL itself and every redirect target — must be HTTPS; a plaintext hop is a downgrade\n* attack on the artifact channel and fails closed as an integrity failure.\n*/\nfunction resolveProviderCliArtifactUrl(current, location) {\n\tlet next;\n\ttry {\n\t\tnext = location === void 0 ? new URL(current) : new URL(location, current);\n\t} catch (error) {\n\t\tlogger$7.debug({\n\t\t\tcode: \"artifact_url_invalid\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI artifact URL was invalid\");\n\t\tthrow new ProviderCliInstallError(\"integrity_failed\", \"Artifact URL or redirect target is not a valid URL\");\n\t}\n\tif (next.protocol !== \"https:\") throw new ProviderCliInstallError(\"integrity_failed\", \"Artifact URL and every redirect hop must use HTTPS\");\n\treturn next.toString();\n}\nasync function requestProviderCliArtifact(fetchImpl, url, signal) {\n\ttry {\n\t\treturn await fetchImpl(url, {\n\t\t\tredirect: \"manual\",\n\t\t\tsignal\n\t\t});\n\t} catch (error) {\n\t\tlogger$7.debug({\n\t\t\tcode: \"artifact_download_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI artifact download failed\");\n\t\tthrow new ProviderCliInstallError(\"install_incomplete\", `Artifact download failed: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n}\nasync function cancelProviderCliRedirectBody(response) {\n\tif (!response.body) return;\n\ttry {\n\t\tawait response.body.cancel();\n\t} catch (error) {\n\t\tlogger$7.debug({\n\t\t\tcode: \"redirect_body_cleanup_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI redirect body cleanup failed\");\n\t\tthrow new ProviderCliInstallError(\"install_incomplete\", `Artifact redirect cleanup failed: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n}\nasync function fetchProviderCliArtifactResponse(fetchImpl, url, timeoutMs) {\n\tlet current = resolveProviderCliArtifactUrl(url);\n\tconst signal = AbortSignal.timeout(timeoutMs);\n\tfor (let redirects = 0;; redirects += 1) {\n\t\tconst response = await requestProviderCliArtifact(fetchImpl, current, signal);\n\t\tif (!REDIRECT_STATUSES.has(response.status)) return response;\n\t\tconst location = response.headers.get(\"location\");\n\t\tawait cancelProviderCliRedirectBody(response);\n\t\tif (location === null) throw new ProviderCliInstallError(\"integrity_failed\", \"Artifact redirect has no Location header\");\n\t\tif (redirects >= MAX_REDIRECT_HOPS) throw new ProviderCliInstallError(\"install_incomplete\", \"Artifact download exceeded the redirect bound\");\n\t\tcurrent = resolveProviderCliArtifactUrl(current, location);\n\t}\n}\nfunction concatenateProviderCliArtifactChunks(chunks, received) {\n\tconst body = new Uint8Array(received);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbody.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn body;\n}\nasync function readProviderCliArtifactBody(response, maxBytes) {\n\tif (!response.ok) throw new ProviderCliInstallError(\"install_incomplete\", `Artifact download failed with HTTP ${response.status}`);\n\tconst length = response.headers.get(\"content-length\");\n\tif (length !== null && Number.parseInt(length, 10) > maxBytes) throw new ProviderCliInstallError(\"integrity_failed\", \"Artifact exceeds the reviewed size bound\");\n\tif (!response.body) return new Uint8Array(await response.arrayBuffer());\n\tconst reader = response.body.getReader();\n\tconst chunks = [];\n\tlet received = 0;\n\tfor (;;) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\treceived += value.byteLength;\n\t\tif (received > maxBytes) {\n\t\t\tawait reader.cancel();\n\t\t\tthrow new ProviderCliInstallError(\"integrity_failed\", \"Artifact exceeds the reviewed size bound\");\n\t\t}\n\t\tchunks.push(value);\n\t}\n\treturn concatenateProviderCliArtifactChunks(chunks, received);\n}\n/**\n* Create the bounded artifact fetcher. `fetchImpl` exists so tests can exercise the\n* full redirect and size-bound policy without network or TLS; production always uses\n* the global fetch with manual redirect handling.\n*/\nfunction createProviderCliFetcher(fetchImpl = fetch) {\n\treturn async ({ url, maxBytes, timeoutMs }) => {\n\t\treturn readProviderCliArtifactBody(await fetchProviderCliArtifactResponse(fetchImpl, url, timeoutMs), maxBytes);\n\t};\n}\nconst defaultProviderCliFetcher = createProviderCliFetcher();\nconst STAGING_DIR_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\nvar ProviderCliInstaller = class {\n\t#layout;\n\t#platform;\n\t#arch;\n\t#fetcher;\n\t#execFile;\n\tconstructor(options) {\n\t\tthis.#layout = options.layout;\n\t\tthis.#platform = options.platform;\n\t\tthis.#arch = options.arch;\n\t\tthis.#fetcher = options.fetcher ?? defaultProviderCliFetcher;\n\t\tthis.#execFile = options.execFile;\n\t}\n\t/**\n\t* Remove recognized stale staging directories from interrupted operations. Safe to\n\t* run only while holding the provider lock: any staging directory present then is a\n\t* crash leftover by definition.\n\t*/\n\tasync recoverStaging(provider) {\n\t\tconst providerStaging = join(this.#layout.staging, provider);\n\t\tconst entries = await readdir(providerStaging).catch((error) => {\n\t\t\tlogger$7.debug({\n\t\t\t\tcode: \"staging_scan_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI staging scan failed\");\n\t\t\treturn [];\n\t\t});\n\t\tfor (const entry of entries) {\n\t\t\tif (!STAGING_DIR_PATTERN.test(entry)) continue;\n\t\t\tawait rm(join(providerStaging, entry), {\n\t\t\t\tforce: true,\n\t\t\t\trecursive: true\n\t\t\t});\n\t\t}\n\t}\n\t/**\n\t* Publish the reviewed catalog artifact for this platform. Callers must hold the\n\t* account/provider lock. On any failure before publication, no version directory is\n\t* created or modified.\n\t*/\n\tasync install(entry, provider) {\n\t\tconst artifact = entry.artifacts.find((candidate) => candidate.platform === this.#platform && candidate.arch === this.#arch);\n\t\tif (!artifact) throw new ProviderCliInstallError(\"unsupported_platform\", `The reviewed catalog has no ${entry.displayName} artifact for ${this.#platform}/${this.#arch}`);\n\t\tconst artifactId = providerCliArtifactId(artifact, entry.version);\n\t\tconst versionDir = providerCliVersionDirPath(this.#layout, provider, artifactId);\n\t\tconst executablePath = join(versionDir, artifact.executablePath);\n\t\tif (await lstat(executablePath).catch((error) => {\n\t\t\tlogger$7.debug({\n\t\t\t\tcode: \"published_artifact_stat_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI published artifact stat failed\");\n\t\t})) {\n\t\t\tawait verifyPublishedExecutable(executablePath, artifact, entry, this.#execFile);\n\t\t\treturn {\n\t\t\t\tartifactId,\n\t\t\t\tversion: entry.version,\n\t\t\t\texecutablePath,\n\t\t\t\tarchiveSha256: artifact.sha256,\n\t\t\t\treused: true\n\t\t\t};\n\t\t}\n\t\tawait this.recoverStaging(provider);\n\t\tconst operationId = randomUUID();\n\t\tconst stagingDir = providerCliStagingDirPath(this.#layout, provider, operationId);\n\t\ttry {\n\t\t\tawait ensurePrivateDirectory(this.#layout.root, stagingDir);\n\t\t\tconst archive = await this.#fetcher({\n\t\t\t\turl: artifact.url,\n\t\t\t\tmaxBytes: artifact.archiveBytes,\n\t\t\t\ttimeoutMs: DOWNLOAD_TIMEOUT_MS\n\t\t\t});\n\t\t\tif (archive.byteLength !== artifact.archiveBytes) throw new ProviderCliInstallError(\"integrity_failed\", \"Artifact size disagrees with the reviewed catalog\");\n\t\t\tif (createHash(\"sha256\").update(archive).digest(\"hex\") !== artifact.sha256) throw new ProviderCliInstallError(\"integrity_failed\", \"Artifact digest disagrees with the reviewed catalog\");\n\t\t\tconst extracted = await extractSafely(archive, artifact);\n\t\t\tif (createHash(\"sha256\").update(extracted.content).digest(\"hex\") !== artifact.executableSha256 || extracted.content.byteLength !== artifact.executableBytes) throw new ProviderCliInstallError(\"integrity_failed\", \"Extracted executable disagrees with the reviewed catalog\");\n\t\t\tconst payloadDir = join(stagingDir, \"payload\");\n\t\t\tconst payloadExecutable = join(payloadDir, artifact.executablePath);\n\t\t\tawait mkdir(dirname(payloadExecutable), {\n\t\t\t\trecursive: true,\n\t\t\t\tmode: 493\n\t\t\t});\n\t\t\tawait writeStagedExecutable(payloadExecutable, extracted.content);\n\t\t\tawait syncDurableDirectory(dirname(payloadExecutable));\n\t\t\tif (dirname(payloadExecutable) !== payloadDir) await syncDurableDirectory(payloadDir);\n\t\t\tawait ensurePrivateDirectory(this.#layout.root, dirname(versionDir));\n\t\t\ttry {\n\t\t\t\tawait rename(payloadDir, versionDir);\n\t\t\t} catch (error) {\n\t\t\t\tif (error.code === \"ENOTEMPTY\" || error.code === \"EEXIST\") await verifyPublishedExecutable(executablePath, artifact, entry, this.#execFile);\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tawait makeReadOnlyTree(versionDir);\n\t\t\tawait syncDurableDirectory(dirname(versionDir));\n\t\t\tawait verifyPublishedExecutable(executablePath, artifact, entry, this.#execFile);\n\t\t\treturn {\n\t\t\t\tartifactId,\n\t\t\t\tversion: entry.version,\n\t\t\t\texecutablePath,\n\t\t\t\tarchiveSha256: artifact.sha256,\n\t\t\t\treused: false\n\t\t\t};\n\t\t} finally {\n\t\t\tawait rm(stagingDir, {\n\t\t\t\tforce: true,\n\t\t\t\trecursive: true\n\t\t\t}).catch((error) => {\n\t\t\t\tlogger$7.debug({\n\t\t\t\t\tcode: \"staging_cleanup_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Provider CLI staging cleanup failed\");\n\t\t\t});\n\t\t\tawait rmdir(dirname(stagingDir)).catch((error) => {\n\t\t\t\tlogger$7.debug({\n\t\t\t\t\tcode: \"staging_parent_cleanup_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Provider CLI staging parent cleanup failed\");\n\t\t\t});\n\t\t}\n\t}\n};\nasync function extractSafely(archive, artifact) {\n\ttry {\n\t\treturn extractProviderCliExecutable(archive, {\n\t\t\texpectedExecutable: artifact.executablePath,\n\t\t\tmaxExtractedBytes: artifact.maxExtractedBytes,\n\t\t\tmaxExecutableBytes: artifact.executableBytes\n\t\t});\n\t} catch (error) {\n\t\tlogger$7.debug({\n\t\t\tcode: \"archive_extraction_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI archive extraction failed\");\n\t\tif (error instanceof ProviderCliArchiveError) throw new ProviderCliInstallError(\"integrity_failed\", `Artifact archive is unsafe: ${error.rejection}`);\n\t\tthrow error;\n\t}\n}\nasync function hashFile(path) {\n\tconst hash = createHash(\"sha256\");\n\tfor await (const chunk of createReadStream(path)) hash.update(chunk);\n\treturn hash.digest(\"hex\");\n}\nasync function writeStagedExecutable(path, content) {\n\tconst handle = await open(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | (constants.O_NOFOLLOW ?? 0), 448);\n\ttry {\n\t\tawait handle.writeFile(content);\n\t\tawait handle.chmod(493);\n\t\tawait handle.sync();\n\t} finally {\n\t\tawait handle.close();\n\t}\n}\nasync function verifyPublishedExecutable(path, artifact, entry, execFile) {\n\tconst status = await lstat(path).catch((error) => {\n\t\tlogger$7.debug({\n\t\t\tcode: \"artifact_stat_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI published artifact stat failed during verification\");\n\t});\n\tif (!status?.isFile() || status.isSymbolicLink() || (status.mode & 73) === 0) throw new ProviderCliInstallError(\"integrity_failed\", \"The immutable version executable is missing or unsafe\");\n\tif (status.size !== artifact.executableBytes || await hashFile(path) !== artifact.executableSha256) throw new ProviderCliInstallError(\"integrity_failed\", \"An immutable version directory disagrees with the reviewed catalog digest\");\n\tconst probed = await probeProviderCliExecutable(path, entry, { ...execFile ? { execFile } : {} });\n\tif (probed.status === \"failed\") throw new ProviderCliInstallError(probed.code === \"version_incompatible\" ? \"version_incompatible\" : \"probe_failed\", `The published ${entry.displayName} artifact failed its local compatibility probe`);\n}\nasync function makeReadOnlyTree(path) {\n\tif ((await stat(path)).isDirectory()) for (const entry of await readdir(path)) await makeReadOnlyTree(join(path, entry));\n\tawait chmod(path, 365);\n}\n//#endregion\n//#region src/runtime/provider-cli/launcher.ts\n/**\n* Account-global launchers and public shims.\n*\n* The internal launcher (`provider-cli/bin/<command>`) is the authoritative OpenTag\n* Runtime entrypoint: a tiny POSIX shell script that execs the exact selected target,\n* forwarding argv, stdin, stdout, stderr, signals, and exit status without interpreting\n* provider operations. Managed targets additionally get update checks disabled; an\n* external target keeps its operator-owned behavior.\n*\n* The public shim (`<account-home>/.local/bin/<command>`) only forwards to the internal\n* launcher so a human shell can use the native command name. An unmanaged file already\n* occupying that name is never overwritten.\n*/\nconst LAUNCHER_MARKER = \"# opentag-provider-cli-launcher: v1\";\nconst SHIM_MARKER = \"# opentag-provider-cli-shim: v1\";\nconst logger$6 = createLogger(\"runtime-provider-cli-launcher\");\nfunction shellSingleQuote$1(value) {\n\treturn `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n/** Deterministic launcher content for a selection; compared byte-for-byte on inspect. */\nfunction renderProviderCliLauncher(entry, selection) {\n\tconst target = selection.kind === \"managed\" ? selection.targetPath : selection.executablePath;\n\tconst lines = [\n\t\t\"#!/bin/sh\",\n\t\t`${LAUNCHER_MARKER} provider=${entry.provider} kind=${selection.kind}`,\n\t\t\"# OpenTag-managed launcher. Regenerated by `opentag provider-cli ensure`; do not edit.\"\n\t];\n\tif (selection.kind === \"managed\") for (const [name, value] of Object.entries(entry.managedEnvironment)) lines.push(`export ${name}=${shellSingleQuote$1(value)}`);\n\tconst args = selection.kind === \"managed\" && entry.managedArguments.length > 0 ? ` ${entry.managedArguments.map(shellSingleQuote$1).join(\" \")}` : \"\";\n\tlines.push(`exec ${shellSingleQuote$1(target)}${args} \"$@\"`);\n\treturn `${lines.join(\"\\n\")}\\n`;\n}\n/** Deterministic public shim content. */\nfunction renderProviderCliShim(provider, launcherPath) {\n\treturn [\n\t\t\"#!/bin/sh\",\n\t\t`${SHIM_MARKER} provider=${provider}`,\n\t\t`exec ${shellSingleQuote$1(launcherPath)} \"$@\"`,\n\t\t\"\"\n\t].join(\"\\n\");\n}\nfunction isProviderCliLauncherContent(content, provider) {\n\treturn content.startsWith(`#!/bin/sh\\n${LAUNCHER_MARKER} provider=${provider} `);\n}\n/** Write or repair the internal launcher to match the selection. */\nasync function reconcileProviderCliLauncher(layout, entry, selection) {\n\tconst launcherPath = providerCliLauncherPath(layout, entry.command);\n\tawait ensurePrivateDirectory(layout.root, layout.bin);\n\tconst expected = renderProviderCliLauncher(entry, selection);\n\tif (await readSecureFile(launcherPath).catch((error) => {\n\t\tlogger$6.debug({\n\t\t\tcode: \"launcher_read_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI launcher read failed\");\n\t}) === expected) {\n\t\tawait chmod(launcherPath, 493);\n\t\treturn {\n\t\t\tpath: launcherPath,\n\t\t\tchanged: false\n\t\t};\n\t}\n\tawait writeDurableFile(launcherPath, expected, 493);\n\tawait chmod(launcherPath, 493);\n\treturn {\n\t\tpath: launcherPath,\n\t\tchanged: true\n\t};\n}\nasync function inspectProviderCliLauncher(layout, entry, selection) {\n\tconst launcherPath = providerCliLauncherPath(layout, entry.command);\n\tconst content = await readSecureFile(launcherPath).catch((error) => {\n\t\tlogger$6.debug({\n\t\t\tcode: \"launcher_inspection_read_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI launcher inspection read failed\");\n\t});\n\tif (content === void 0) return {\n\t\tstatus: \"missing\",\n\t\tpath: launcherPath\n\t};\n\tif (!isProviderCliLauncherContent(content, entry.provider)) return {\n\t\tstatus: \"invalid\",\n\t\tpath: launcherPath\n\t};\n\tif (selection && content !== renderProviderCliLauncher(entry, selection)) return {\n\t\tstatus: \"mismatch\",\n\t\tpath: launcherPath\n\t};\n\treturn {\n\t\tstatus: \"valid\",\n\t\tpath: launcherPath\n\t};\n}\n/**\n* Create or refresh the OpenTag-owned public shim. An unmanaged file occupying the\n* public command name is left untouched and reported as `occupied`.\n*/\nasync function reconcileProviderCliShim(layout, entry) {\n\tconst shimPath = join(layout.publicBinDir, entry.command);\n\tconst launcherPath = providerCliLauncherPath(layout, entry.command);\n\tconst expected = renderProviderCliShim(entry.provider, launcherPath);\n\tconst current = await readSecureFile(shimPath).catch((error) => {\n\t\tlogger$6.debug({\n\t\t\tcode: \"shim_read_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI shim read failed\");\n\t});\n\tif (current === expected) {\n\t\tawait chmod(shimPath, 493);\n\t\treturn {\n\t\t\tstatus: \"unchanged\",\n\t\t\tpath: shimPath\n\t\t};\n\t}\n\tif (current !== void 0 && !current.startsWith(`#!/bin/sh\\n${SHIM_MARKER} `)) return {\n\t\tstatus: \"occupied\",\n\t\tpath: shimPath\n\t};\n\tawait mkdir(layout.publicBinDir, {\n\t\trecursive: true,\n\t\tmode: 493\n\t});\n\tawait writeDurableFile(shimPath, expected, 493);\n\tawait chmod(shimPath, 493);\n\treturn {\n\t\tstatus: current === void 0 ? \"created\" : \"updated\",\n\t\tpath: shimPath\n\t};\n}\n/**\n* Resolve the bare command name against the invoking environment's PATH the way a\n* shell would (first executable match wins) and compare it with the OpenTag shim.\n* Read-only; this is detection-scope information, never daemon readiness.\n*/\nasync function inspectGlobalCommand(layout, command, env) {\n\tconst shimPath = join(layout.publicBinDir, command);\n\tconst ours = (await readSecureFile(shimPath).catch((error) => {\n\t\tlogger$6.debug({\n\t\t\tcode: \"global_shim_read_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI global shim read failed\");\n\t}))?.startsWith(`#!/bin/sh\\n${SHIM_MARKER} `) === true;\n\tconst launcherPath = providerCliLauncherPath(layout, command);\n\tlet resolvedPath;\n\tfor (const entry of (env.PATH ?? \"\").split(delimiter)) {\n\t\tif (entry.length === 0 || !isAbsolute(entry)) continue;\n\t\tconst candidate = join(entry, command);\n\t\ttry {\n\t\t\tawait access(candidate, constants.X_OK);\n\t\t\tconst status = await lstat(candidate);\n\t\t\tif (!status.isFile() && !status.isSymbolicLink()) continue;\n\t\t\tresolvedPath = await realpath(candidate);\n\t\t\tbreak;\n\t\t} catch (error) {\n\t\t\tlogger$6.debug({\n\t\t\t\tcode: \"global_command_resolution_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI global command resolution failed\");\n\t\t}\n\t}\n\tconst shimCanonical = ours ? await realpath(shimPath).catch((error) => {\n\t\tlogger$6.debug({\n\t\t\tcode: \"shim_realpath_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI shim canonicalization failed\");\n\t\treturn shimPath;\n\t}) : void 0;\n\tconst launcherCanonical = await realpath(launcherPath).catch((error) => {\n\t\tlogger$6.debug({\n\t\t\tcode: \"launcher_realpath_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI launcher canonicalization failed\");\n\t});\n\tconst active = resolvedPath !== void 0 && (resolvedPath === shimCanonical || resolvedPath === launcherCanonical);\n\tconst shadowed = resolvedPath !== void 0 && !active;\n\treturn {\n\t\tactive,\n\t\t...ours ? { path: shimPath } : {},\n\t\t...resolvedPath ? { resolvedPath } : {},\n\t\tshadowed\n\t};\n}\n//#endregion\n//#region src/runtime/provider-cli/lock.ts\n/**\n* Account/provider exclusive mutation lock.\n*\n* Implemented inside `packages/client` on top of the secure durable-file primitives;\n* it deliberately does not depend on the daemon process lease in `apps/cli`. The lock\n* is an `O_CREAT | O_EXCL` file under the account-global state directory. A stale lock\n* whose holder process is gone is broken; a live holder fails the operation as busy.\n*/\nvar ProviderCliLockBusyError = class extends Error {\n\tname = \"ProviderCliLockBusyError\";\n\tconstructor(provider) {\n\t\tsuper(`Another OpenTag process is modifying the ${provider} Provider CLI`);\n\t}\n};\nfunction defaultIsProcessAlive(pid) {\n\tif (pid === process.pid) return true;\n\ttry {\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\treturn error.code === \"EPERM\";\n\t}\n}\nconst defaultSleep$3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\nconst logger$5 = createLogger(\"runtime-provider-cli-lock\");\nfunction parseLockRecord(content) {\n\ttry {\n\t\tconst value = JSON.parse(content);\n\t\tif (typeof value !== \"object\" || value === null) return void 0;\n\t\tconst record = value;\n\t\tif (typeof record.pid !== \"number\" || !Number.isSafeInteger(record.pid) || record.pid <= 0 || typeof record.token !== \"string\" || record.token.length === 0) return;\n\t\treturn {\n\t\t\tpid: record.pid,\n\t\t\ttoken: record.token\n\t\t};\n\t} catch (error) {\n\t\tlogger$5.debug({\n\t\t\tcode: \"lock_record_invalid\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI lock record was invalid\");\n\t\treturn;\n\t}\n}\nasync function withProviderCliLock(layout, provider, run, deps = {}) {\n\tconst isAlive = deps.isProcessAlive ?? defaultIsProcessAlive;\n\tconst sleep = deps.sleep ?? defaultSleep$3;\n\tconst maxAttempts = deps.maxAttempts ?? 50;\n\tconst retryDelayMs = deps.retryDelayMs ?? 100;\n\tawait ensurePrivateDirectory(layout.root, layout.state);\n\tconst lockPath = providerCliLockFilePath(layout, provider);\n\tconst token = randomUUID();\n\tlet acquired = false;\n\tfor (let attempt = 0; attempt < maxAttempts && !acquired; attempt += 1) {\n\t\tlet handle;\n\t\ttry {\n\t\t\thandle = await open(lockPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 384);\n\t\t\tawait handle.writeFile(JSON.stringify({\n\t\t\t\tpid: process.pid,\n\t\t\t\ttoken\n\t\t\t}), \"utf8\");\n\t\t\tawait handle.sync();\n\t\t\tacquired = true;\n\t\t} catch (error) {\n\t\t\tif (error.code !== \"EEXIST\") throw error;\n\t\t\tconst existing = await readSecureFile(lockPath).catch((readError) => {\n\t\t\t\tlogger$5.debug({\n\t\t\t\t\tcode: \"lock_read_failed\",\n\t\t\t\t\terror: String(readError)\n\t\t\t\t}, \"Provider CLI lock read failed\");\n\t\t\t});\n\t\t\tconst record = existing === void 0 ? void 0 : parseLockRecord(existing);\n\t\t\tif (!record || !isAlive(record.pid)) {\n\t\t\t\tawait rm(lockPath, { force: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (attempt + 1 < maxAttempts) await sleep(retryDelayMs);\n\t\t} finally {\n\t\t\tawait handle?.close();\n\t\t}\n\t}\n\tif (!acquired) throw new ProviderCliLockBusyError(provider);\n\ttry {\n\t\treturn await run();\n\t} finally {\n\t\tconst current = await readSecureFile(lockPath).catch((error) => {\n\t\t\tlogger$5.debug({\n\t\t\t\tcode: \"lock_release_read_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI lock release read failed\");\n\t\t});\n\t\tif ((current === void 0 ? void 0 : parseLockRecord(current))?.token === token) await rm(lockPath, { force: true });\n\t}\n}\n//#endregion\n//#region src/runtime/provider-cli/selection-store.ts\nconst PROVIDER_CLI_SELECTION_SCHEMA_VERSION = 1;\nfunction isRecord$3(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction isNonEmptyString(value) {\n\treturn typeof value === \"string\" && value.length > 0;\n}\nfunction isTrust(value) {\n\treturn value === \"catalog-verified\" || value === \"compatible-unverified\";\n}\nfunction isFingerprint(value) {\n\treturn typeof value === \"string\" && /^v1:[0-9a-f]{64}$/.test(value);\n}\nfunction parseSelection(value, provider) {\n\tif (!isRecord$3(value)) throw new RuntimeStorageError(\"invalid\", \"Provider CLI selection is malformed\");\n\tif (value.kind === \"managed\") {\n\t\tif (![\n\t\t\t\"kind\",\n\t\t\t\"artifactId\",\n\t\t\t\"version\",\n\t\t\t\"targetPath\",\n\t\t\t\"fingerprint\"\n\t\t].every((key) => isNonEmptyString(value[key]))) throw new RuntimeStorageError(\"invalid\", \"Provider CLI managed selection is malformed\");\n\t\tif (!isAbsolute(value.targetPath) || !semver.valid(value.version) || !isFingerprint(value.fingerprint)) throw new RuntimeStorageError(\"invalid\", \"Provider CLI managed selection identity is malformed\");\n\t\treturn {\n\t\t\tkind: \"managed\",\n\t\t\tartifactId: value.artifactId,\n\t\t\tversion: value.version,\n\t\t\ttargetPath: value.targetPath,\n\t\t\tfingerprint: value.fingerprint\n\t\t};\n\t}\n\tif (value.kind === \"external\") {\n\t\tif (![\n\t\t\t\"kind\",\n\t\t\t\"executablePath\",\n\t\t\t\"fingerprint\",\n\t\t\t\"version\"\n\t\t].every((key) => isNonEmptyString(value[key])) || !isTrust(value.trust) || !semver.valid(value.version) || !isFingerprint(value.fingerprint)) throw new RuntimeStorageError(\"invalid\", \"Provider CLI external selection is malformed\");\n\t\tif (!isAbsolute(value.executablePath)) throw new RuntimeStorageError(\"invalid\", \"Provider CLI external path must be absolute\");\n\t\treturn {\n\t\t\tkind: \"external\",\n\t\t\texecutablePath: value.executablePath,\n\t\t\tfingerprint: value.fingerprint,\n\t\t\ttrust: value.trust,\n\t\t\tversion: value.version\n\t\t};\n\t}\n\tthrow new RuntimeStorageError(\"invalid\", `Provider CLI selection kind is unknown for ${provider}`);\n}\nfunction parseProviderCliSelectionRecord(value) {\n\tif (!isRecord$3(value) || value.schemaVersion !== 1) throw new RuntimeStorageError(\"invalid\", \"Provider CLI selection schema is unsupported\");\n\tif (value.provider !== \"feishu\" && value.provider !== \"slack\" || typeof value.generation !== \"number\" || !Number.isInteger(value.generation) || value.generation < 1 || !isNonEmptyString(value.updatedAt) || Number.isNaN(Date.parse(value.updatedAt))) throw new RuntimeStorageError(\"invalid\", \"Provider CLI selection record is malformed\");\n\treturn {\n\t\tschemaVersion: 1,\n\t\tprovider: value.provider,\n\t\tgeneration: value.generation,\n\t\tupdatedAt: value.updatedAt,\n\t\tselection: parseSelection(value.selection, value.provider)\n\t};\n}\n/** Read the current selection; missing state is `undefined`, malformed state throws. */\nasync function readProviderCliSelection(layout, provider) {\n\treturn readPrivateJson(layout.root, providerCliStateFilePath(layout, provider), (value) => {\n\t\tconst record = parseProviderCliSelectionRecord(value);\n\t\tif (record.provider !== provider) throw new RuntimeStorageError(\"invalid\", \"Provider CLI selection provider does not match its state file\");\n\t\treturn record;\n\t});\n}\n/** Atomically replace the selection record (0600, write-temp-then-rename). */\nasync function writeProviderCliSelection(layout, provider, selection, previous, now = /* @__PURE__ */ new Date()) {\n\tconst record = {\n\t\tschemaVersion: 1,\n\t\tprovider,\n\t\tgeneration: (previous?.generation ?? 0) + 1,\n\t\tupdatedAt: now.toISOString(),\n\t\tselection\n\t};\n\tawait writePrivateJson(layout.root, providerCliStateFilePath(layout, provider), record);\n\treturn record;\n}\n/** Canonical target path a selection executes, regardless of kind. */\nfunction providerCliSelectionTargetPath(selection) {\n\treturn selection.kind === \"managed\" ? selection.targetPath : selection.executablePath;\n}\n//#endregion\n//#region src/runtime/provider-cli/manager.ts\nconst SUPPORTED_PLATFORMS = /* @__PURE__ */ new Set([\"darwin\", \"linux\"]);\nconst logger$4 = createLogger(\"runtime-provider-cli-manager\");\nconst REMEDIATIONS = {\n\tnot_installed: \"Run `opentag provider-cli ensure` to select a compatible CLI or install the reviewed artifact.\",\n\tunsupported_platform: \"Provider CLI management supports macOS and Linux on arm64/x64 only.\",\n\tselection_invalid: \"The selection record is malformed; run `opentag provider-cli ensure` to repair it.\",\n\texternal_path_invalid: \"The selected executable is missing or unsafe; run `opentag provider-cli ensure` again.\",\n\tartifact_drifted: \"The selected executable changed after validation; run `opentag provider-cli ensure` to re-probe.\",\n\tlauncher_invalid: \"The account-global launcher is missing or replaced; run `opentag provider-cli ensure` to repair it.\",\n\tglobal_bin_unavailable: \"Check that the account home is writable and not on a read-only filesystem.\",\n\tversion_incompatible: \"The installed Provider CLI is outside the range this OpenTag version supports; it was left untouched.\",\n\tprobe_failed: \"The selected executable failed its bounded local probe; reinstall or select another candidate.\",\n\tintegrity_failed: \"The downloaded artifact failed digest or archive verification; retry or report the mismatch.\",\n\tinstall_incomplete: \"The install did not complete; rerun `opentag provider-cli ensure`.\",\n\toperation_in_progress: \"Another OpenTag process is modifying this Provider CLI; retry after it finishes.\",\n\tglobal_command_shadowed: \"Another command resolves first on PATH; OpenTag Runtime uses its own launcher regardless.\",\n\tglobal_path_not_configured: \"Add the OpenTag shim directory to PATH to use the command from your shell.\",\n\texternal_candidate_unverified: \"The selected executable is compatible but its digest is not in the reviewed catalog; provenance is unverified.\"\n};\nfunction diagnostic(code) {\n\treturn {\n\t\tcode,\n\t\tremediation: REMEDIATIONS[code]\n\t};\n}\nfunction warning(code) {\n\treturn {\n\t\tcode,\n\t\tremediation: REMEDIATIONS[code]\n\t};\n}\nvar ProviderCliManager = class {\n\t#deps;\n\t#layout;\n\t#platform;\n\t#arch;\n\t#env;\n\tconstructor(deps) {\n\t\tthis.#deps = deps;\n\t\tthis.#platform = deps.platform ?? process.platform;\n\t\tthis.#arch = deps.arch ?? process.arch;\n\t\tthis.#env = deps.env ?? process.env;\n\t\tthis.#layout = resolveProviderCliAccountLayout(deps.accountHome, this.#platform);\n\t}\n\tget layout() {\n\t\treturn this.#layout;\n\t}\n\t#entry(provider) {\n\t\treturn requireProviderCliCatalogEntry(provider, this.#deps.catalog);\n\t}\n\t#globalCommandWarnings(globalCommand, hasSelection) {\n\t\tconst warnings = [];\n\t\tif (globalCommand.shadowed) warnings.push(warning(\"global_command_shadowed\"));\n\t\telse if (hasSelection && !globalCommand.active) warnings.push(warning(\"global_path_not_configured\"));\n\t\treturn warnings;\n\t}\n\t/** Read-only selection validation, launcher check, fingerprint verify, and probe. */\n\tasync inspect(provider) {\n\t\tconst entry = this.#entry(provider);\n\t\tconst launcherPath = providerCliLauncherPath(this.#layout, entry.command);\n\t\tconst globalCommand = await inspectGlobalCommand(this.#layout, entry.command, this.#env);\n\t\tif (!SUPPORTED_PLATFORMS.has(this.#platform)) return {\n\t\t\tprovider,\n\t\t\tstate: \"unavailable\",\n\t\t\treadiness: \"unavailable\",\n\t\t\tlauncher: {\n\t\t\t\tpath: launcherPath,\n\t\t\t\tstatus: \"missing\"\n\t\t\t},\n\t\t\tglobalCommand,\n\t\t\twarnings: [],\n\t\t\tdiagnostic: diagnostic(\"unsupported_platform\")\n\t\t};\n\t\tlet record;\n\t\ttry {\n\t\t\trecord = await readProviderCliSelection(this.#layout, provider);\n\t\t} catch (error) {\n\t\t\tlogger$4.debug({\n\t\t\t\tcode: \"selection_inspection_failed\",\n\t\t\t\tprovider,\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI selection inspection failed\");\n\t\t\tconst launcher = await inspectProviderCliLauncher(this.#layout, entry, void 0);\n\t\t\treturn {\n\t\t\t\tprovider,\n\t\t\t\tstate: \"unavailable\",\n\t\t\t\treadiness: \"unavailable\",\n\t\t\t\tlauncher: {\n\t\t\t\t\tpath: launcher.path,\n\t\t\t\t\tstatus: launcher.status\n\t\t\t\t},\n\t\t\t\tglobalCommand,\n\t\t\t\twarnings: [],\n\t\t\t\tdiagnostic: diagnostic(\"selection_invalid\")\n\t\t\t};\n\t\t}\n\t\tif (!record) {\n\t\t\tconst launcher = await inspectProviderCliLauncher(this.#layout, entry, void 0);\n\t\t\treturn {\n\t\t\t\tprovider,\n\t\t\t\tstate: \"absent\",\n\t\t\t\treadiness: \"install\",\n\t\t\t\tlauncher: {\n\t\t\t\t\tpath: launcher.path,\n\t\t\t\t\tstatus: launcher.status\n\t\t\t\t},\n\t\t\t\tglobalCommand,\n\t\t\t\twarnings: this.#globalCommandWarnings(globalCommand, false),\n\t\t\t\tdiagnostic: diagnostic(\"not_installed\")\n\t\t\t};\n\t\t}\n\t\tconst selection = record.selection;\n\t\tconst targetPath = providerCliSelectionTargetPath(selection);\n\t\tconst summary = {\n\t\t\tkind: selection.kind,\n\t\t\tpath: targetPath,\n\t\t\tversion: selection.version,\n\t\t\ttrust: selection.kind === \"managed\" ? \"catalog-verified\" : selection.trust,\n\t\t\tgeneration: record.generation\n\t\t};\n\t\tconst warnings = this.#globalCommandWarnings(globalCommand, true);\n\t\tif (selection.kind === \"external\" && selection.trust === \"compatible-unverified\") warnings.push(warning(\"external_candidate_unverified\"));\n\t\tconst fail = async (code) => {\n\t\t\tconst launcher = await inspectProviderCliLauncher(this.#layout, entry, selection);\n\t\t\treturn {\n\t\t\t\tprovider,\n\t\t\t\tstate: \"unavailable\",\n\t\t\t\treadiness: \"unavailable\",\n\t\t\t\tselection: summary,\n\t\t\t\tlauncher: {\n\t\t\t\t\tpath: launcher.path,\n\t\t\t\t\tstatus: launcher.status\n\t\t\t\t},\n\t\t\t\tglobalCommand,\n\t\t\t\twarnings,\n\t\t\t\tdiagnostic: diagnostic(code)\n\t\t\t};\n\t\t};\n\t\tconst identity = await computeFileIdentity(targetPath).catch((error) => {\n\t\t\tlogger$4.debug({\n\t\t\t\tcode: \"selection_identity_failed\",\n\t\t\t\tprovider,\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI selection identity failed\");\n\t\t});\n\t\tif (!identity) return fail(selection.kind === \"external\" ? \"external_path_invalid\" : \"artifact_drifted\");\n\t\tconst managedDigest = selection.kind === \"managed\" ? selection.artifactId.split(\"/\").at(-1) : void 0;\n\t\tconst fingerprint = computeTargetFingerprint(identity, selection.version, managedDigest);\n\t\tif (fingerprint !== selection.fingerprint) return fail(\"artifact_drifted\");\n\t\tconst launcher = await inspectProviderCliLauncher(this.#layout, entry, selection);\n\t\tif (launcher.status !== \"valid\") return fail(\"launcher_invalid\");\n\t\tconst probed = await probeProviderCliExecutable(launcher.path, entry, {\n\t\t\t...this.#deps.execFile ? { execFile: this.#deps.execFile } : {},\n\t\t\tincludeManagedArguments: selection.kind !== \"managed\"\n\t\t});\n\t\tif (probed.status === \"failed\") return fail(probed.code === \"probe_failed\" ? \"probe_failed\" : \"version_incompatible\");\n\t\treturn {\n\t\t\tprovider,\n\t\t\tstate: \"ready\",\n\t\t\treadiness: \"ready\",\n\t\t\tselection: summary,\n\t\t\tfingerprint,\n\t\t\tlauncher: {\n\t\t\t\tpath: launcher.path,\n\t\t\t\tstatus: \"valid\"\n\t\t\t},\n\t\t\tglobalCommand,\n\t\t\twarnings\n\t\t};\n\t}\n\t/**\n\t* Select the newest compatible candidate or immediately perform the managed install\n\t* when no eligible candidate exists. `auto` never skips an eligible external\n\t* candidate in favor of a managed install within the same operation.\n\t*/\n\tasync ensure(provider, options = {}) {\n\t\tconst phases = [];\n\t\tconst session = {\n\t\t\tphases,\n\t\t\trecordPhase: (phase, status, detail) => {\n\t\t\t\tconst record = detail === void 0 ? {\n\t\t\t\t\tphase,\n\t\t\t\t\tstatus\n\t\t\t\t} : {\n\t\t\t\t\tphase,\n\t\t\t\t\tstatus,\n\t\t\t\t\tdetail\n\t\t\t\t};\n\t\t\t\tphases.push(record);\n\t\t\t\toptions.onPhase?.({\n\t\t\t\t\tprovider,\n\t\t\t\t\t...record\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\t\tconst dryRunFields = options.dryRun ? { dryRun: true } : {};\n\t\tconst failed = (code, candidates) => ({\n\t\t\tok: false,\n\t\t\tprovider,\n\t\t\taction: \"failed\",\n\t\t\tphases,\n\t\t\tcandidates,\n\t\t\treadiness: \"unavailable\",\n\t\t\tglobalCommand: { active: false },\n\t\t\twarnings: [],\n\t\t\tdiagnostic: diagnostic(code),\n\t\t\t...dryRunFields\n\t\t});\n\t\tif (!SUPPORTED_PLATFORMS.has(this.#platform)) return failed(\"unsupported_platform\", []);\n\t\tconst entry = this.#entry(provider);\n\t\tconst mode = options.mode ?? \"auto\";\n\t\tconst pathUpdate = options.pathUpdate ?? true;\n\t\tsession.recordPhase(\"detect\", \"started\");\n\t\tlet selection;\n\t\tlet detection;\n\t\ttry {\n\t\t\tselection = await readProviderCliSelection(this.#layout, provider);\n\t\t\tdetection = await this.#detect(provider, entry, selection, mode);\n\t\t} catch (error) {\n\t\t\tlogger$4.debug({\n\t\t\t\tcode: \"detection_failed\",\n\t\t\t\tprovider,\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI detection failed\");\n\t\t\tsession.recordPhase(\"detect\", \"failed\", \"selection_invalid\");\n\t\t\treturn failed(\"selection_invalid\", []);\n\t\t}\n\t\tsession.recordPhase(\"detect\", \"completed\", `${detection.candidates.length} eligible candidate(s), ${detection.ignored.length} ignored`);\n\t\tif (options.dryRun) return await this.#dryRunResult(provider, entry, selection, detection, session);\n\t\ttry {\n\t\t\treturn await withProviderCliLock(this.#layout, provider, async () => {\n\t\t\t\tconst lockedSelection = await readProviderCliSelection(this.#layout, provider);\n\t\t\t\tconst lockedDetection = await this.#detect(provider, entry, lockedSelection, mode);\n\t\t\t\treturn await this.#ensureLocked(provider, entry, lockedSelection, lockedDetection, pathUpdate, session);\n\t\t\t}, {\n\t\t\t\t...this.#deps.isProcessAlive ? { isProcessAlive: this.#deps.isProcessAlive } : {},\n\t\t\t\t...this.#deps.sleep ? { sleep: this.#deps.sleep } : {}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger$4.debug({\n\t\t\t\tcode: \"ensure_failed\",\n\t\t\t\tprovider,\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI ensure failed\");\n\t\t\tif (error instanceof ProviderCliLockBusyError) return failed(\"operation_in_progress\", []);\n\t\t\tif (error instanceof ProviderCliInstallError) return failed(error.code, []);\n\t\t\tif (error instanceof RuntimeStorageError && error.code === \"invalid\") return failed(\"selection_invalid\", []);\n\t\t\tif (isStorageOrPermissionError(error)) return failed(\"global_bin_unavailable\", []);\n\t\t\treturn failed(\"install_incomplete\", []);\n\t\t}\n\t}\n\tasync #detect(provider, entry, selection, mode) {\n\t\treturn detectProviderCliCandidates({\n\t\t\tprovider,\n\t\t\tentry,\n\t\t\tlayout: this.#layout,\n\t\t\tenv: this.#env,\n\t\t\tplatform: this.#platform,\n\t\t\tarch: this.#arch,\n\t\t\tselection,\n\t\t\tmode,\n\t\t\t...this.#deps.execFile ? { execFile: this.#deps.execFile } : {}\n\t\t});\n\t}\n\tasync #dryRunResult(provider, entry, selection, detection, session) {\n\t\tconst ranked = rankProviderCliCandidates(detection.candidates);\n\t\tconst upgradeManaged = shouldInstallManagedUpgrade(selection, entry, ranked.ordered);\n\t\tconst ordered = upgradeManaged ? ranked.ordered.filter((candidate) => !(candidate.kind === \"managed\" && candidate.incumbent)) : ranked.ordered;\n\t\tconst reranked = upgradeManaged ? rankProviderCliCandidates(ordered) : ranked;\n\t\tconst winner = reranked.ordered[0];\n\t\tconst candidates = buildCandidateReports(detection, reranked.ordered, winner, reranked.reasons, [...upgradeManaged && selection ? [{\n\t\t\tpath: providerCliSelectionTargetPath(selection.selection),\n\t\t\tsourceDir: \"selection\",\n\t\t\tversion: selection.selection.version,\n\t\t\treason: \"older-managed-version\"\n\t\t}] : []]);\n\t\tconst globalStatus = await inspectGlobalCommand(this.#layout, entry.command, this.#env);\n\t\tconst globalWarnings = this.#globalCommandWarnings(globalStatus, selection !== void 0);\n\t\tconst base = {\n\t\t\tprovider,\n\t\t\tcandidates,\n\t\t\tglobalCommand: {\n\t\t\t\tactive: globalStatus.active,\n\t\t\t\t...globalStatus.path ? { path: globalStatus.path } : {},\n\t\t\t\t...globalStatus.resolvedPath ? { resolvedPath: globalStatus.resolvedPath } : {}\n\t\t\t},\n\t\t\tdryRun: true\n\t\t};\n\t\tif (winner) {\n\t\t\tconst unchanged = isUnchangedIncumbent(selection, winner);\n\t\t\tconst action = unchanged || winner.kind === \"managed\" ? \"noop\" : \"selected-existing\";\n\t\t\tsession.recordPhase(\"select\", \"completed\", unchanged ? \"dry-run: the current selection is already the best candidate\" : `dry-run: would select ${winner.version} ${winner.kind} ${winner.path}`);\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tok: true,\n\t\t\t\taction,\n\t\t\t\tphases: session.phases,\n\t\t\t\tselected: {\n\t\t\t\t\tpath: winner.path,\n\t\t\t\t\tversion: winner.version,\n\t\t\t\t\tsource: winner.kind === \"managed\" ? \"managed\" : winner.sourceDir,\n\t\t\t\t\ttrust: winner.trust\n\t\t\t\t},\n\t\t\t\treadiness: \"ready\",\n\t\t\t\twarnings: [...globalWarnings, ...winner.trust === \"compatible-unverified\" ? [warning(\"external_candidate_unverified\")] : []]\n\t\t\t};\n\t\t}\n\t\tif (incompatibleManagedIncumbent(selection, entry, detection)) {\n\t\t\tsession.recordPhase(\"managed-install\", \"failed\", \"dry-run: blocked by an incompatible managed installation\");\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tok: false,\n\t\t\t\taction: \"failed\",\n\t\t\t\tphases: session.phases,\n\t\t\t\treadiness: \"unavailable\",\n\t\t\t\twarnings: globalWarnings,\n\t\t\t\tdiagnostic: diagnostic(\"version_incompatible\")\n\t\t\t};\n\t\t}\n\t\tif (!findCatalogArtifact(entry, this.#platform, this.#arch)) {\n\t\t\tsession.recordPhase(\"managed-install\", \"failed\", \"dry-run: no reviewed artifact for this platform\");\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tok: false,\n\t\t\t\taction: \"failed\",\n\t\t\t\tphases: session.phases,\n\t\t\t\treadiness: \"unavailable\",\n\t\t\t\twarnings: globalWarnings,\n\t\t\t\tdiagnostic: diagnostic(\"unsupported_platform\")\n\t\t\t};\n\t\t}\n\t\tsession.recordPhase(\"managed-install\", \"completed\", `dry-run: would install managed ${entry.version}`);\n\t\treturn {\n\t\t\t...base,\n\t\t\tok: true,\n\t\t\taction: \"installed-managed\",\n\t\t\tphases: session.phases,\n\t\t\treadiness: \"ready\",\n\t\t\twarnings: globalWarnings\n\t\t};\n\t}\n\tasync #ensureLocked(provider, entry, selection, detection, pathUpdate, session) {\n\t\tlet ranked = rankProviderCliCandidates(detection.candidates);\n\t\tlet winner = ranked.ordered[0];\n\t\tconst extraIgnored = [];\n\t\twhile (winner && !isUnchangedIncumbent(selection, winner)) {\n\t\t\tif (winner.kind === \"managed\") {\n\t\t\t\textraIgnored.push({\n\t\t\t\t\tpath: winner.path,\n\t\t\t\t\tsourceDir: \"selection\",\n\t\t\t\t\treason: \"artifact-drifted\"\n\t\t\t\t});\n\t\t\t\tranked = rankProviderCliCandidates(ranked.ordered.slice(1));\n\t\t\t\twinner = ranked.ordered[0];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait this.#deps.beforeWinnerReverify?.(winner);\n\t\t\tif (await verifyProviderCliCandidateFingerprint(winner)) break;\n\t\t\textraIgnored.push({\n\t\t\t\tpath: winner.path,\n\t\t\t\tsourceDir: winner.sourceDir,\n\t\t\t\treason: \"external-candidate-changed\"\n\t\t\t});\n\t\t\tranked = rankProviderCliCandidates(ranked.ordered.slice(1));\n\t\t\twinner = ranked.ordered[0];\n\t\t}\n\t\tif (shouldInstallManagedUpgrade(selection, entry, ranked.ordered)) {\n\t\t\tconst incumbent = ranked.ordered.find((candidate) => candidate.kind === \"managed\" && candidate.incumbent);\n\t\t\tif (incumbent) {\n\t\t\t\textraIgnored.push({\n\t\t\t\t\tpath: incumbent.path,\n\t\t\t\t\tsourceDir: \"selection\",\n\t\t\t\t\tversion: incumbent.version,\n\t\t\t\t\treason: \"older-managed-version\"\n\t\t\t\t});\n\t\t\t\tranked = rankProviderCliCandidates(ranked.ordered.filter((candidate) => candidate.id !== incumbent.id));\n\t\t\t\twinner = ranked.ordered[0];\n\t\t\t}\n\t\t}\n\t\tconst finalize = (partial) => ({\n\t\t\tprovider,\n\t\t\tphases: session.phases,\n\t\t\tcandidates: buildCandidateReports(detection, ranked.ordered, winner, ranked.reasons, extraIgnored),\n\t\t\t...partial\n\t\t});\n\t\tlet action;\n\t\tlet newSelection;\n\t\tif (winner && isUnchangedIncumbent(selection, winner)) action = \"noop\";\n\t\telse if (winner) {\n\t\t\tsession.recordPhase(\"select\", \"started\");\n\t\t\tnewSelection = {\n\t\t\t\tkind: \"external\",\n\t\t\t\texecutablePath: winner.path,\n\t\t\t\tfingerprint: winner.fingerprint,\n\t\t\t\ttrust: winner.trust,\n\t\t\t\tversion: winner.version\n\t\t\t};\n\t\t\taction = \"selected-existing\";\n\t\t} else {\n\t\t\tif (incompatibleManagedIncumbent(selection, entry, {\n\t\t\t\tcandidates: [],\n\t\t\t\tignored: [...detection.ignored, ...extraIgnored]\n\t\t\t})) {\n\t\t\t\tsession.recordPhase(\"managed-install\", \"failed\", \"version_incompatible\");\n\t\t\t\treturn finalize({\n\t\t\t\t\tok: false,\n\t\t\t\t\taction: \"failed\",\n\t\t\t\t\treadiness: \"unavailable\",\n\t\t\t\t\tglobalCommand: { active: false },\n\t\t\t\t\twarnings: [],\n\t\t\t\t\tdiagnostic: diagnostic(\"version_incompatible\")\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (!findCatalogArtifact(entry, this.#platform, this.#arch)) {\n\t\t\t\tsession.recordPhase(\"managed-install\", \"failed\", \"unsupported_platform\");\n\t\t\t\treturn finalize({\n\t\t\t\t\tok: false,\n\t\t\t\t\taction: \"failed\",\n\t\t\t\t\treadiness: \"unavailable\",\n\t\t\t\t\tglobalCommand: { active: false },\n\t\t\t\t\twarnings: [],\n\t\t\t\t\tdiagnostic: diagnostic(\"unsupported_platform\")\n\t\t\t\t});\n\t\t\t}\n\t\t\tsession.recordPhase(\"managed-install\", \"started\", `${entry.version} from the reviewed catalog`);\n\t\t\tconst installer = new ProviderCliInstaller({\n\t\t\t\tlayout: this.#layout,\n\t\t\t\tplatform: this.#platform,\n\t\t\t\tarch: this.#arch,\n\t\t\t\t...this.#deps.fetcher ? { fetcher: this.#deps.fetcher } : {},\n\t\t\t\t...this.#deps.execFile ? { execFile: this.#deps.execFile } : {}\n\t\t\t});\n\t\t\tlet installed;\n\t\t\ttry {\n\t\t\t\tinstalled = await installer.install(entry, provider);\n\t\t\t} catch (error) {\n\t\t\t\tlogger$4.debug({\n\t\t\t\t\tcode: \"managed_install_failed\",\n\t\t\t\t\tprovider,\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Provider CLI managed install failed\");\n\t\t\t\tconst code = error instanceof ProviderCliInstallError ? error.code : isStorageOrPermissionError(error) ? \"global_bin_unavailable\" : \"install_incomplete\";\n\t\t\t\tsession.recordPhase(\"managed-install\", \"failed\", code);\n\t\t\t\treturn finalize({\n\t\t\t\t\tok: false,\n\t\t\t\t\taction: \"failed\",\n\t\t\t\t\treadiness: \"unavailable\",\n\t\t\t\t\tglobalCommand: { active: false },\n\t\t\t\t\twarnings: [],\n\t\t\t\t\tdiagnostic: diagnostic(code)\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst identity = await computeFileIdentity(installed.executablePath);\n\t\t\tnewSelection = {\n\t\t\t\tkind: \"managed\",\n\t\t\t\tartifactId: installed.artifactId,\n\t\t\t\tversion: installed.version,\n\t\t\t\ttargetPath: identity.path,\n\t\t\t\tfingerprint: computeTargetFingerprint(identity, installed.version, installed.archiveSha256)\n\t\t\t};\n\t\t\taction = \"installed-managed\";\n\t\t}\n\t\tif (newSelection) {\n\t\t\tawait reconcileProviderCliLauncher(this.#layout, entry, newSelection);\n\t\t\tif (pathUpdate) await reconcileProviderCliShim(this.#layout, entry);\n\t\t\tconst now = this.#deps.now?.() ?? /* @__PURE__ */ new Date();\n\t\t\tawait writeProviderCliSelection(this.#layout, provider, newSelection, selection, now);\n\t\t\tif (newSelection.kind === \"external\") session.recordPhase(\"select\", \"completed\", `${newSelection.version} external ${newSelection.executablePath} (${ranked.reasons.get(winner?.id ?? \"\") ?? \"selected\"})`);\n\t\t\telse session.recordPhase(\"managed-install\", \"completed\", `${newSelection.version} ${providerCliSelectionTargetPath(newSelection)}`);\n\t\t} else {\n\t\t\tconst current = selection?.selection;\n\t\t\tif (current) {\n\t\t\t\tawait reconcileProviderCliLauncher(this.#layout, entry, current);\n\t\t\t\tif (pathUpdate) await reconcileProviderCliShim(this.#layout, entry);\n\t\t\t}\n\t\t\tsession.recordPhase(\"select\", \"completed\", \"current selection is already the best candidate\");\n\t\t}\n\t\tsession.recordPhase(\"verify\", \"started\");\n\t\tconst inspection = await this.inspect(provider);\n\t\tconst ok = inspection.state === \"ready\";\n\t\tsession.recordPhase(\"verify\", ok ? \"completed\" : \"failed\", ok ? \"ready\" : inspection.diagnostic?.code ?? \"unavailable\");\n\t\tconst selected = newSelection ? {\n\t\t\tpath: providerCliSelectionTargetPath(newSelection),\n\t\t\tversion: newSelection.version,\n\t\t\tsource: newSelection.kind === \"managed\" ? \"managed\" : winner?.sourceDir ?? \"external\",\n\t\t\ttrust: newSelection.kind === \"managed\" ? \"catalog-verified\" : newSelection.trust\n\t\t} : inspection.selection ? {\n\t\t\tpath: inspection.selection.path,\n\t\t\tversion: inspection.selection.version,\n\t\t\tsource: inspection.selection.kind,\n\t\t\ttrust: inspection.selection.trust\n\t\t} : void 0;\n\t\treturn finalize({\n\t\t\tok,\n\t\t\taction: ok ? action : \"failed\",\n\t\t\t...selected ? { selected } : {},\n\t\t\treadiness: ok ? \"ready\" : \"unavailable\",\n\t\t\tglobalCommand: {\n\t\t\t\tactive: inspection.globalCommand.active,\n\t\t\t\t...inspection.globalCommand.path ? { path: inspection.globalCommand.path } : {},\n\t\t\t\t...inspection.globalCommand.resolvedPath ? { resolvedPath: inspection.globalCommand.resolvedPath } : {}\n\t\t\t},\n\t\t\twarnings: [...inspection.warnings],\n\t\t\t...inspection.diagnostic && !ok ? { diagnostic: inspection.diagnostic } : {}\n\t\t});\n\t}\n};\nfunction isUnchangedIncumbent(selection, winner) {\n\tif (!selection || !winner.incumbent) return false;\n\tconst current = selection.selection;\n\tif (winner.kind === \"managed\" && current.kind === \"managed\") return current.targetPath === winner.path && current.fingerprint === winner.fingerprint;\n\tif (winner.kind === \"external\" && current.kind === \"external\") return current.executablePath === winner.path && current.fingerprint === winner.fingerprint && current.trust === winner.trust;\n\treturn false;\n}\n/** A managed incumbent outside the catalog range blocks silent replacement. */\nfunction incompatibleManagedIncumbent(selection, entry, detection) {\n\tif (selection?.selection.kind !== \"managed\") return false;\n\tif (detection.candidates.some((candidate) => candidate.incumbent && candidate.kind === \"managed\")) return false;\n\tconst targetPath = providerCliSelectionTargetPath(selection.selection);\n\treturn detection.ignored.find((entry) => entry.sourceDir === \"selection\" && entry.path === targetPath)?.reason === \"version-incompatible\" && semver.gte(selection.selection.version, entry.version);\n}\n/** Upgrade an OpenTag-managed incumbent only when no eligible external remains. */\nfunction shouldInstallManagedUpgrade(selection, entry, candidates) {\n\treturn selection?.selection.kind === \"managed\" && semver.lt(selection.selection.version, entry.version) && !candidates.some((candidate) => candidate.kind === \"external\");\n}\nfunction buildCandidateReports(detection, ordered, winner, reasons, extraIgnored = []) {\n\tconst reports = [];\n\tfor (const candidate of ordered) {\n\t\tconst selected = winner !== void 0 && candidate.id === winner.id;\n\t\treports.push({\n\t\t\tpath: candidate.path,\n\t\t\tversion: candidate.version,\n\t\t\ttrust: candidate.trust,\n\t\t\tdisposition: selected ? \"selected\" : \"ignored\",\n\t\t\treason: reasons.get(candidate.id) ?? (selected ? \"selected\" : \"not selected\")\n\t\t});\n\t}\n\tconst seen = new Set(ordered.map((candidate) => candidate.path));\n\tfor (const entry of [...detection.ignored, ...extraIgnored]) {\n\t\tif (seen.has(entry.path)) continue;\n\t\tseen.add(entry.path);\n\t\treports.push({\n\t\t\tpath: entry.path,\n\t\t\t...entry.version ? { version: entry.version } : {},\n\t\t\tdisposition: \"ignored\",\n\t\t\treason: entry.reason\n\t\t});\n\t}\n\treturn reports;\n}\nfunction isStorageOrPermissionError(error) {\n\tif (error instanceof RuntimeStorageError) return true;\n\tconst code = error?.code;\n\treturn code === \"EACCES\" || code === \"EPERM\" || code === \"EROFS\";\n}\n//#endregion\n//#region src/runtime/provider-cli/reconciler.ts\nconst GRANT_REPLAY_RETENTION_MS = 6e4;\nconst logger$3 = createLogger(\"runtime-provider-cli-reconciler\");\n/**\n* A foreground targeted connect is the sole first-setup installer and holds the per-provider\n* lock while it works. A daemon reconcile that loses that race waits the foreground operation\n* out instead of reporting a verdict: the delay is one lock-acquire budget, and the attempt\n* bound comfortably covers the installer's own download deadline.\n*/\nconst PROVIDER_CLI_LOCK_BUSY_RETRY_DELAY_MS = 5e3;\nconst PROVIDER_CLI_LOCK_BUSY_MAX_ATTEMPTS = 30;\nconst defaultSleep$2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\nvar ProviderCliReconciler = class {\n\t#connection;\n\t#current = /* @__PURE__ */ new Map();\n\t#grants = /* @__PURE__ */ new Map();\n\t#manager;\n\t#now;\n\t#refreshRuntimeProvider;\n\t#frameJobs = /* @__PURE__ */ new Set();\n\t#imCliPublished = /* @__PURE__ */ new Map();\n\t#inspectionJobs = /* @__PURE__ */ new Map();\n\t#logger;\n\t#providerJobs = /* @__PURE__ */ new Map();\n\t#acceptedOnce = /* @__PURE__ */ new Set();\n\t#readySelection = /* @__PURE__ */ new Map();\n\t#signal;\n\t#sleep;\n\t#unsubscribe;\n\t#validation;\n\t#waiterAbort = new AbortController();\n\t#closePromise;\n\t#closed = false;\n\tconstructor(options) {\n\t\tthis.#connection = options.connection;\n\t\tthis.#logger = options.logger ?? createLogger(\"provider-cli-reconciler\");\n\t\tthis.#manager = options.manager;\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#refreshRuntimeProvider = options.refreshRuntimeProvider;\n\t\tthis.#signal = options.signal;\n\t\tthis.#sleep = options.sleep ?? defaultSleep$2;\n\t\tthis.#validation = options.validation;\n\t\tthis.#unsubscribe = this.#connection.subscribeBusinessFrames((frame) => this.#trackFrame(frame));\n\t}\n\tclose() {\n\t\tthis.#closePromise ??= this.#performClose();\n\t\treturn this.#closePromise;\n\t}\n\t/** Re-inspect published CLIs and active requirement Providers without mutating repair state. */\n\tasync refreshPublishedImCliReadiness() {\n\t\tif (this.#closed || this.#signal?.aborted) return;\n\t\tconst providers = /* @__PURE__ */ new Set([...this.#imCliPublished.keys(), ...[...this.#current.values()].map((requirement) => requirement.provider)]);\n\t\tawait Promise.all([...providers].map((provider) => this.#refreshPassive(provider)));\n\t}\n\tasync #performClose() {\n\t\tthis.#closed = true;\n\t\tthis.#waiterAbort.abort();\n\t\tthis.#unsubscribe();\n\t\tthis.#imCliPublished.clear();\n\t\tthis.#abortAll();\n\t\tawait Promise.allSettled([...this.#frameJobs, ...this.#inspectionJobs.values()]);\n\t\tawait this.#validation.cleanupAll();\n\t}\n\t#trackFrame(frame) {\n\t\tconst job = this.#handleFrame(frame).finally(() => {\n\t\t\tthis.#frameJobs.delete(job);\n\t\t});\n\t\tthis.#frameJobs.add(job);\n\t\treturn job;\n\t}\n\t/**\n\t* Return the exact selection already accepted by daemon readiness.\n\t*\n\t* An already-accepted selection that still matches the live CLI is admitted\n\t* immediately. A never-accepted, already-healthy live CLI joins in-flight owner\n\t* work when present, otherwise confirms read-only if identity stays stable. A\n\t* provider that was accepted once and later failed or rotated is not treated as\n\t* a fresh cold start and does not start Run-triggered ensure. Caller cancellation\n\t* interrupts inspect and shared-work wait without cancelling other waiters.\n\t*/\n\tasync readySelectionForRun(provider, signal) {\n\t\ttry {\n\t\t\treturn await this.#selectReadyForRun(provider, signal);\n\t\t} catch (error) {\n\t\t\tthis.#throwIfReadinessAborted(signal);\n\t\t\tif (this.#closed || this.#waiterAbort.signal.aborted) return void 0;\n\t\t\tthrow error;\n\t\t}\n\t}\n\tasync #selectReadyForRun(provider, signal) {\n\t\tthis.#throwIfReadinessAborted(signal);\n\t\tif (this.#closed) return void 0;\n\t\tconst live = await this.#awaitReadiness(this.#inspectLiveSelection(provider), signal);\n\t\tthis.#throwIfReadinessAborted(signal);\n\t\tif (this.#closed) return void 0;\n\t\tconst accepted = this.#readySelection.get(provider);\n\t\tif (accepted && live && selectionsMatch(accepted, live)) return { ...live };\n\t\tif (!(accepted === void 0 && live !== void 0 && !this.#acceptedOnce.has(provider)) || !live) return void 0;\n\t\tconst existing = this.#providerRepairJob(provider);\n\t\tif (existing) {\n\t\t\tconst outcome = await this.#awaitReadiness(existing, signal);\n\t\t\tthis.#throwIfReadinessAborted(signal);\n\t\t\tif (this.#closed || outcome.status !== \"ready\") return void 0;\n\t\t\treturn this.#admitUnchangedInitialSelection(provider, live, signal);\n\t\t}\n\t\treturn this.#confirmInitialSelection(provider, live, signal);\n\t}\n\tasync #confirmInitialSelection(provider, live, signal) {\n\t\tconst liveAfter = await this.#awaitReadiness(this.#inspectLiveSelection(provider), signal);\n\t\tthis.#throwIfReadinessAborted(signal);\n\t\tif (this.#closed) return void 0;\n\t\tif (!liveAfter || !selectionsMatch(live, liveAfter)) return void 0;\n\t\tconst accepted = this.#readySelection.get(provider);\n\t\tif (this.#acceptedOnce.has(provider)) return accepted && selectionsMatch(accepted, liveAfter) ? { ...liveAfter } : void 0;\n\t\tthis.#readySelection.set(provider, liveAfter);\n\t\tthis.#acceptedOnce.add(provider);\n\t\treturn { ...liveAfter };\n\t}\n\tasync #admitUnchangedInitialSelection(provider, live, signal) {\n\t\tconst acceptedAfter = this.#readySelection.get(provider);\n\t\tif (!acceptedAfter || !selectionsMatch(acceptedAfter, live)) return void 0;\n\t\tconst liveAfter = await this.#awaitReadiness(this.#inspectLiveSelection(provider), signal);\n\t\tthis.#throwIfReadinessAborted(signal);\n\t\tif (this.#closed) return void 0;\n\t\tif (!liveAfter || !selectionsMatch(acceptedAfter, liveAfter) || !selectionsMatch(live, liveAfter)) return;\n\t\treturn { ...liveAfter };\n\t}\n\t#throwIfReadinessAborted(signal) {\n\t\tsignal?.throwIfAborted();\n\t\tthis.#signal?.throwIfAborted();\n\t}\n\t#readinessSignals(signal) {\n\t\treturn [\n\t\t\tthis.#signal,\n\t\t\tthis.#waiterAbort.signal,\n\t\t\tsignal\n\t\t].filter((candidate) => candidate !== void 0);\n\t}\n\tasync #awaitReadiness(work, signal) {\n\t\treturn joinSharedWork(work, this.#readinessSignals(signal));\n\t}\n\tasync #inspectLiveSelection(provider) {\n\t\tconst inspection = await this.#manager.inspect(provider).catch((error) => {\n\t\t\tlogger$3.debug({\n\t\t\t\tcode: \"ready_inspection_failed\",\n\t\t\t\tprovider,\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI readiness inspection failed\");\n\t\t});\n\t\treturn inspection ? readySelectionFromInspect(this.#manager.layout, provider, inspection) : void 0;\n\t}\n\tasync #handleFrame(frame) {\n\t\tif (this.#closed) return;\n\t\tconst cancel = ProviderCliCancelFrameSchema.safeParse(frame);\n\t\tif (cancel.success) {\n\t\t\tthis.#handleCancel(cancel.data);\n\t\t\treturn;\n\t\t}\n\t\tif (this.#signal?.aborted) return;\n\t\tconst requirement = ProviderCliRequirementFrameSchema.safeParse(frame);\n\t\tif (requirement.success) {\n\t\t\tawait this.#handleRequirement(requirement.data);\n\t\t\treturn;\n\t\t}\n\t\tconst prewarm = ProviderCliPrewarmFrameSchema.safeParse(frame);\n\t\tif (prewarm.success) {\n\t\t\tawait this.#handlePrewarm(prewarm.data);\n\t\t\treturn;\n\t\t}\n\t\tconst grant = ProviderCliValidationGrantFrameSchema.safeParse(frame);\n\t\tif (grant.success) {\n\t\t\tawait this.#handleGrant(grant.data);\n\t\t\treturn;\n\t\t}\n\t\tconst validationRun = ProviderCliValidationRunFrameSchema.safeParse(frame);\n\t\tif (validationRun.success) await this.#handleValidationRun(validationRun.data);\n\t}\n\tasync #handlePrewarm(frame) {\n\t\tif (this.#closed || this.#signal?.aborted) return;\n\t\tif (this.#connection.capabilityVersion(RUNTIME_CAPABILITY.providerCliPrewarm) === void 0) return;\n\t\tconst providerPreparation = Promise.all(frame.providers.map(async (provider) => ({\n\t\t\tprovider,\n\t\t\tstatus: await this.#prewarmProvider(provider, frame.mode ?? \"inspect\")\n\t\t})));\n\t\tif ((frame.mode ?? \"inspect\") !== \"ensure\" || frame.runtimeProvider === void 0) {\n\t\t\tawait providerPreparation;\n\t\t\treturn;\n\t\t}\n\t\tconst runtimeProvider = frame.runtimeProvider;\n\t\tconst [providers, runtime] = await Promise.all([providerPreparation, this.#refreshRuntimeProvider?.(runtimeProvider).catch(() => ({\n\t\t\tprovider: runtimeProvider,\n\t\t\tstatus: \"unavailable\"\n\t\t})) ?? Promise.resolve({\n\t\t\tprovider: runtimeProvider,\n\t\t\tstatus: \"unavailable\"\n\t\t})]);\n\t\tconst result = ProviderCliPrewarmResultFrameSchema.parse({\n\t\t\ttype: \"provider-cli:prewarm:result\",\n\t\t\trequestId: frame.requestId,\n\t\t\truntime,\n\t\t\tproviders\n\t\t});\n\t\tawait this.#connection.send(result, {\n\t\t\tpriority: \"result\",\n\t\t\tsignal: this.#signal\n\t\t});\n\t}\n\tasync #prewarmProvider(provider, mode) {\n\t\tif (mode === \"inspect\") {\n\t\t\tthis.#publishImCli(provider, \"checking\");\n\t\t\tconst status = (await this.#inspectProvider(provider))?.readiness ?? \"unavailable\";\n\t\t\tthis.#publishImCli(provider, status);\n\t\t\treturn status;\n\t\t}\n\t\tthis.#publishImCli(provider, \"checking\");\n\t\tconst outcome = await this.#reconcileProvider(provider, \"auto\");\n\t\tthis.#publishImCli(provider, outcome.status);\n\t\treturn outcome.status;\n\t}\n\tasync #refreshPassive(provider) {\n\t\tconst published = this.#imCliPublished.has(provider);\n\t\tconst targets = [...this.#current.values()].filter((requirement) => requirement.provider === provider).map((requirement) => ({\n\t\t\tintegrationId: requirement.integrationId,\n\t\t\tlastStatus: requirement.lastStatus,\n\t\t\trequestId: requirement.requestId\n\t\t}));\n\t\tconst repairAtStart = this.#providerRepairJob(provider);\n\t\tconst selectionAtStart = this.#readySelection.get(provider);\n\t\tconst inspection = await this.#inspectProvider(provider);\n\t\tif (this.#closed || this.#signal?.aborted) return;\n\t\tconst readiness = inspection?.readiness ?? \"unavailable\";\n\t\tif (published && this.#imCliPublished.has(provider)) this.#publishImCli(provider, readiness);\n\t\tif (this.#passiveOverlappedRepair(provider, targets, repairAtStart, selectionAtStart)) return;\n\t\tawait this.#publishPassiveInspection(provider, inspection, targets, repairAtStart, selectionAtStart);\n\t}\n\tasync #publishPassiveInspection(provider, inspection, targets, repairAtStart, selectionAtStart) {\n\t\tconst liveTargets = targets.flatMap((target) => {\n\t\t\tconst current = this.#current.get(target.integrationId);\n\t\t\treturn current?.requestId === target.requestId ? [current] : [];\n\t\t});\n\t\tif (liveTargets.length === 0) return;\n\t\tif (inspection?.readiness === \"ready\") {\n\t\t\tconst ready = await readySelectionFromInspect(this.#manager.layout, provider, inspection);\n\t\t\tif (this.#closed || this.#signal?.aborted) return;\n\t\t\tif (this.#passiveOverlappedRepair(provider, targets, repairAtStart, selectionAtStart)) return;\n\t\t\tconst stillLive = liveTargets.filter((target) => this.#current.get(target.integrationId)?.requestId === target.requestId);\n\t\t\tif (ready) {\n\t\t\t\tthis.#readySelection.set(provider, ready);\n\t\t\t\tthis.#acceptedOnce.add(provider);\n\t\t\t} else this.#readySelection.delete(provider);\n\t\t\tawait Promise.all(stillLive.map((requirement) => this.#publishArtifact(requirement, ready ? \"ready\" : \"unavailable\")));\n\t\t\treturn;\n\t\t}\n\t\tconst code = inspection?.diagnostic?.code;\n\t\tconst publicReason = publicProviderCliArtifactReason(code);\n\t\tconst inspectReason = providerCliArtifactFailureIsManual({\n\t\t\treason: code,\n\t\t\tstage: \"inspect\"\n\t\t}) ? publicReason : void 0;\n\t\tawait Promise.all(liveTargets.map((requirement) => {\n\t\t\tif (this.#current.get(requirement.integrationId)?.requestId !== requirement.requestId) return Promise.resolve();\n\t\t\treturn this.#publishArtifact(requirement, \"unavailable\", requirement.lastStatus === \"unavailable\" ? requirement.lastReason ?? inspectReason : inspectReason);\n\t\t}));\n\t}\n\t#providerRepairJob(provider) {\n\t\treturn this.#providerJobs.get(`${provider}:managed-only`) ?? this.#providerJobs.get(`${provider}:auto`);\n\t}\n\t#passiveOverlappedRepair(provider, targets, repairAtStart, selectionAtStart) {\n\t\tif (repairAtStart || this.#providerRepairJob(provider)) return true;\n\t\tif (this.#readySelection.get(provider) !== selectionAtStart) return true;\n\t\treturn targets.some((target) => {\n\t\t\tconst current = this.#current.get(target.integrationId);\n\t\t\treturn current?.requestId === target.requestId && current.lastStatus !== target.lastStatus;\n\t\t});\n\t}\n\t#inspectProvider(provider) {\n\t\tconst existing = this.#inspectionJobs.get(provider);\n\t\tif (existing) return existing;\n\t\tconst job = this.#manager.inspect(provider).catch(() => void 0).finally(() => {\n\t\t\tif (this.#inspectionJobs.get(provider) === job) this.#inspectionJobs.delete(provider);\n\t\t});\n\t\tthis.#inspectionJobs.set(provider, job);\n\t\treturn job;\n\t}\n\t#publishImCli(provider, status) {\n\t\tif (this.#closed || this.#signal?.aborted) return;\n\t\tthis.#imCliPublished.set(provider, status);\n\t\tthis.#connection.setImCliReadiness({\n\t\t\tprovider,\n\t\t\tstatus\n\t\t});\n\t}\n\t#handleCancel(frame) {\n\t\tconst current = this.#current.get(frame.integrationId);\n\t\tif (!current || current.requestId !== frame.requirementRequestId || current.agentId !== frame.agentId || current.provider !== frame.provider || current.credentialGeneration !== frame.credentialGeneration) return;\n\t\tthis.#abortGrants(frame.requirementRequestId);\n\t\tthis.#current.delete(frame.integrationId);\n\t}\n\tasync #handleRequirement(frame) {\n\t\tconst previous = this.#current.get(frame.integrationId);\n\t\tif (previous) {\n\t\t\tif (previous.requestId === frame.requestId) return;\n\t\t\tif (frame.credentialGeneration < previous.credentialGeneration) return;\n\t\t\tthis.#abortGrants(previous.requestId);\n\t\t}\n\t\tconst tracked = {\n\t\t\tagentId: frame.agentId,\n\t\t\tcredentialGeneration: frame.credentialGeneration,\n\t\t\texpectedIdentity: frame.expectedIdentity,\n\t\t\tintegrationId: frame.integrationId,\n\t\t\tprovider: frame.provider,\n\t\t\trequestId: frame.requestId\n\t\t};\n\t\tthis.#current.set(frame.integrationId, tracked);\n\t\tawait this.#publishArtifact(tracked, \"checking\");\n\t\tconst outcome = await this.#reconcileProvider(frame.provider);\n\t\tconst current = this.#current.get(frame.integrationId);\n\t\tif (!current || current.requestId !== tracked.requestId) return;\n\t\tawait this.#publishArtifact(current, outcome.status, outcome.reason);\n\t}\n\tasync #reconcileProvider(provider, mode = \"managed-only\") {\n\t\tconst key = `${provider}:${mode}`;\n\t\tconst existing = this.#providerJobs.get(key);\n\t\tif (existing) return existing;\n\t\tconst job = this.#runProvider(provider, mode).finally(() => {\n\t\t\tif (this.#providerJobs.get(key) === job) this.#providerJobs.delete(key);\n\t\t});\n\t\tthis.#providerJobs.set(key, job);\n\t\treturn job;\n\t}\n\tasync #runProvider(provider, mode) {\n\t\ttry {\n\t\t\tlet inspection = await this.#manager.inspect(provider);\n\t\t\tif (inspection.readiness !== \"ready\") {\n\t\t\t\tif (providerCliArtifactFailureIsManual({\n\t\t\t\t\treason: inspection.diagnostic?.code,\n\t\t\t\t\tstage: \"inspect\"\n\t\t\t\t})) {\n\t\t\t\t\tthis.#readySelection.delete(provider);\n\t\t\t\t\treturn unavailableOutcome(inspection.diagnostic?.code, \"inspect\");\n\t\t\t\t}\n\t\t\t\tconst ensured = await this.#ensureConverging(provider, mode);\n\t\t\t\tinspection = await this.#manager.inspect(provider);\n\t\t\t\tif (inspection.readiness !== \"ready\") {\n\t\t\t\t\tthis.#readySelection.delete(provider);\n\t\t\t\t\treturn unavailableOutcome(ensured.diagnostic?.code ?? inspection.diagnostic?.code, \"ensure\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (inspection.readiness === \"ready\") {\n\t\t\t\tconst ready = await readySelectionFromInspect(this.#manager.layout, provider, inspection);\n\t\t\t\tif (!ready) {\n\t\t\t\t\tthis.#readySelection.delete(provider);\n\t\t\t\t\treturn { status: \"unavailable\" };\n\t\t\t\t}\n\t\t\t\tthis.#readySelection.set(provider, ready);\n\t\t\t\tthis.#acceptedOnce.add(provider);\n\t\t\t\treturn { status: \"ready\" };\n\t\t\t}\n\t\t\tthis.#readySelection.delete(provider);\n\t\t\treturn unavailableOutcome(inspection.diagnostic?.code, \"ensure\");\n\t\t} catch (error) {\n\t\t\tlogger$3.debug({\n\t\t\t\tcode: \"provider_reconcile_failed\",\n\t\t\t\tprovider,\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI reconciliation failed\");\n\t\t\tthis.#readySelection.delete(provider);\n\t\t\treturn { status: \"unavailable\" };\n\t\t}\n\t}\n\t/**\n\t* Ensure, waiting out a foreground installer's lock instead of converting the race into a\n\t* verdict: losing the cross-process provider lock is transient, so the artifact stays in its\n\t* published \"checking\" state while the foreground operation finishes, and the outcome is then\n\t* re-read so the connection converges on a terminal status without waiting for a reconnect.\n\t*/\n\tasync #ensureConverging(provider, mode) {\n\t\tlet outcome = await this.#manager.ensure(provider, { mode });\n\t\tfor (let attempt = 0; outcome.diagnostic?.code === \"operation_in_progress\"; attempt += 1) {\n\t\t\tif (attempt >= 30 || this.#closed || this.#signal?.aborted) break;\n\t\t\tawait this.#sleepBusy();\n\t\t\tif (this.#closed || this.#signal?.aborted) break;\n\t\t\toutcome = await this.#manager.ensure(provider, { mode });\n\t\t}\n\t\treturn outcome;\n\t}\n\t/** Bounded wait between lock-busy retries; returns early when the daemon is shutting down. */\n\t#sleepBusy() {\n\t\tconst signal = this.#signal;\n\t\tconst wait = this.#sleep(PROVIDER_CLI_LOCK_BUSY_RETRY_DELAY_MS);\n\t\tif (!signal) return wait;\n\t\tif (signal.aborted) return Promise.resolve();\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tlet settled = false;\n\t\t\tconst finish = (error) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tif (error === void 0) resolve();\n\t\t\t\telse reject(error);\n\t\t\t};\n\t\t\tconst onAbort = () => finish();\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tif (signal.aborted) onAbort();\n\t\t\twait.then(() => finish(), finish);\n\t\t});\n\t}\n\tasync #handleGrant(frame) {\n\t\tthis.#pruneGrants();\n\t\tif (!this.#acceptsFence(frame)) return;\n\t\tif (Date.parse(frame.expiresAt) <= this.#now()) {\n\t\t\tthis.#rememberGrant(frame, new AbortController(), true, false);\n\t\t\tawait this.#publishValidation(frame, {\n\t\t\t\tstatus: \"retrying\",\n\t\t\t\treason: \"validation_expired\"\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst inspection = await this.#manager.inspect(frame.provider);\n\t\tconst ready = this.#readySelection.get(frame.provider);\n\t\tconst live = await readySelectionFromInspect(this.#manager.layout, frame.provider, inspection);\n\t\tif (!ready || !live || !selectionsMatch(ready, live)) {\n\t\t\tthis.#rememberGrant(frame, new AbortController(), true, false);\n\t\t\tawait this.#publishValidation(frame, {\n\t\t\t\tstatus: \"retrying\",\n\t\t\t\treason: \"artifact_changed\"\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tawait this.#runValidation(frame, live);\n\t}\n\t/**\n\t* Proxy mode: the Server issues a single-use validation run instead of raw material. The\n\t* runner opens a Server-authorized validation execution (read-only identity scope) and\n\t* never falls back to raw Cloud tokens.\n\t*/\n\tasync #handleValidationRun(frame) {\n\t\tthis.#pruneGrants();\n\t\tif (!this.#acceptsFence(frame)) return;\n\t\tif (Date.parse(frame.expiresAt) <= this.#now()) {\n\t\t\tthis.#rememberGrant(frame, new AbortController(), true, false);\n\t\t\tawait this.#publishValidation(frame, {\n\t\t\t\tstatus: \"retrying\",\n\t\t\t\treason: \"validation_expired\"\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst inspection = await this.#manager.inspect(frame.provider);\n\t\tconst ready = this.#readySelection.get(frame.provider);\n\t\tconst live = await readySelectionFromInspect(this.#manager.layout, frame.provider, inspection);\n\t\tif (!ready || !live || !selectionsMatch(ready, live)) {\n\t\t\tthis.#rememberGrant(frame, new AbortController(), true, false);\n\t\t\tawait this.#publishValidation(frame, {\n\t\t\t\tstatus: \"retrying\",\n\t\t\t\treason: \"artifact_changed\"\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tawait this.#runProxyValidation(frame, live);\n\t}\n\t#acceptsFence(frame) {\n\t\tif (this.#closed || this.#signal?.aborted) return false;\n\t\tconst current = this.#current.get(frame.integrationId);\n\t\tif (!current || current.requestId !== frame.requirementRequestId) return false;\n\t\tif (current.agentId !== frame.agentId || current.provider !== frame.provider) return false;\n\t\tif (current.credentialGeneration !== frame.credentialGeneration) return false;\n\t\tif (!expectedIdentitiesMatch(current.expectedIdentity, frame.expectedIdentity)) return false;\n\t\tconst existing = this.#grants.get(frame.requestId);\n\t\treturn !existing?.consumed && !existing?.inflight;\n\t}\n\t#rememberGrant(frame, abort, consumed, inflight) {\n\t\tthis.#grants.set(frame.requestId, {\n\t\t\tabort,\n\t\t\tconsumed,\n\t\t\texpiresAt: Date.parse(frame.expiresAt),\n\t\t\tinflight,\n\t\t\trequirementRequestId: frame.requirementRequestId\n\t\t});\n\t}\n\tasync #runValidation(frame, live) {\n\t\tconst abort = new AbortController();\n\t\tthis.#rememberGrant(frame, abort, false, true);\n\t\tconst signal = this.#signal ? AbortSignal.any([this.#signal, abort.signal]) : abort.signal;\n\t\ttry {\n\t\t\tconst request = {\n\t\t\t\texpectedFingerprint: live.fingerprint,\n\t\t\t\texpectedIdentity: frame.expectedIdentity,\n\t\t\t\texpiresAt: frame.expiresAt,\n\t\t\t\tgrant: frame.grant,\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\ttargetPath: live.path,\n\t\t\t\tversion: live.version,\n\t\t\t\t...live.managedDigest ? { managedDigest: live.managedDigest } : {}\n\t\t\t};\n\t\t\tconst result = await this.#validation.run(request, {\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tprovider: frame.provider,\n\t\t\t\tagentId: frame.agentId,\n\t\t\t\tintegrationId: frame.integrationId,\n\t\t\t\tcredentialGeneration: frame.credentialGeneration\n\t\t\t}, signal);\n\t\t\tif (!this.#finishGrant(frame, abort)) return;\n\t\t\tawait this.#publishValidation(frame, result);\n\t\t} catch (error) {\n\t\t\tlogger$3.debug({\n\t\t\t\tcode: \"validation_failed\",\n\t\t\t\tprovider: frame.provider,\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI validation failed\");\n\t\t\tif (!this.#finishGrant(frame, abort)) return;\n\t\t\tawait this.#publishValidation(frame, { status: \"needs_attention\" });\n\t\t}\n\t}\n\t/** Proxy validation run: opens the Server-authorized execution through the runner hook. */\n\tasync #runProxyValidation(frame, live) {\n\t\tconst abort = new AbortController();\n\t\tthis.#rememberGrant(frame, abort, false, true);\n\t\tconst signal = this.#signal ? AbortSignal.any([this.#signal, abort.signal]) : abort.signal;\n\t\ttry {\n\t\t\tconst request = {\n\t\t\t\texpectedFingerprint: live.fingerprint,\n\t\t\t\texpectedIdentity: frame.expectedIdentity,\n\t\t\t\texpiresAt: frame.expiresAt,\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\ttargetPath: live.path,\n\t\t\t\tversion: live.version,\n\t\t\t\t...live.managedDigest ? { managedDigest: live.managedDigest } : {},\n\t\t\t\tagentId: frame.agentId,\n\t\t\t\tvalidationRunId: frame.validationRunId\n\t\t\t};\n\t\t\tconst result = await this.#validation.run(request, {\n\t\t\t\trequestId: frame.requestId,\n\t\t\t\tprovider: frame.provider,\n\t\t\t\tagentId: frame.agentId,\n\t\t\t\tintegrationId: frame.integrationId,\n\t\t\t\tcredentialGeneration: frame.credentialGeneration\n\t\t\t}, signal);\n\t\t\tif (!this.#finishGrant(frame, abort)) return;\n\t\t\tawait this.#publishValidation(frame, result);\n\t\t} catch (error) {\n\t\t\tlogger$3.debug({\n\t\t\t\tcode: \"validation_run_failed\",\n\t\t\t\tprovider: frame.provider,\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI proxy validation failed\");\n\t\t\tif (!this.#finishGrant(frame, abort)) return;\n\t\t\tawait this.#publishValidation(frame, { status: \"needs_attention\" });\n\t\t}\n\t}\n\t#finishGrant(frame, abort) {\n\t\tif (this.#closed || this.#signal?.aborted || abort.signal.aborted) return false;\n\t\tconst state = this.#grants.get(frame.requestId);\n\t\tif (!state || this.#current.get(frame.integrationId)?.requestId !== frame.requirementRequestId) return false;\n\t\tstate.consumed = true;\n\t\tstate.inflight = false;\n\t\treturn true;\n\t}\n\t#abortGrants(requirementRequestId) {\n\t\tfor (const [grantId, state] of [...this.#grants]) {\n\t\t\tif (state.requirementRequestId !== requirementRequestId) continue;\n\t\t\tstate.abort.abort();\n\t\t\tthis.#grants.delete(grantId);\n\t\t}\n\t}\n\t#pruneGrants() {\n\t\tconst now = this.#now();\n\t\tfor (const [grantId, state] of this.#grants) if (!state.inflight && state.expiresAt + GRANT_REPLAY_RETENTION_MS <= now) this.#grants.delete(grantId);\n\t}\n\t#abortAll() {\n\t\tfor (const state of this.#grants.values()) state.abort.abort();\n\t\tthis.#grants.clear();\n\t\tthis.#current.clear();\n\t}\n\tasync #publishArtifact(frame, status, reason) {\n\t\tconst current = this.#current.get(frame.integrationId);\n\t\tif (!current || current.requestId !== frame.requestId) return;\n\t\tconst publicReason = status === \"unavailable\" ? reason : void 0;\n\t\tif (current.lastPublishOk !== false && current.lastStatus === status && current.lastReason === publicReason) return;\n\t\tconst includeReason = publicReason !== void 0 && this.#connection.capabilityVersion(RUNTIME_CAPABILITY.providerCliReconcile) === 2;\n\t\tconst payload = {\n\t\t\ttype: \"provider-cli:artifact:status\",\n\t\t\trequestId: frame.requestId,\n\t\t\tprovider: frame.provider,\n\t\t\tagentId: frame.agentId,\n\t\t\tintegrationId: frame.integrationId,\n\t\t\tcredentialGeneration: frame.credentialGeneration,\n\t\t\tstatus,\n\t\t\t...includeReason ? { reason: publicReason } : {}\n\t\t};\n\t\ttry {\n\t\t\tawait this.#connection.send(payload, { priority: \"result\" });\n\t\t\tcurrent.lastStatus = status;\n\t\t\tcurrent.lastReason = publicReason;\n\t\t\tcurrent.lastPublishOk = true;\n\t\t} catch {\n\t\t\tcurrent.lastPublishOk = false;\n\t\t}\n\t}\n\tasync #publishValidation(frame, result) {\n\t\tconst payload = {\n\t\t\ttype: \"provider-cli:validation:result\",\n\t\t\trequestId: frame.requestId,\n\t\t\tprovider: frame.provider,\n\t\t\tagentId: frame.agentId,\n\t\t\tintegrationId: frame.integrationId,\n\t\t\tcredentialGeneration: frame.credentialGeneration,\n\t\t\tstatus: result.status,\n\t\t\t...result.reason ? { reason: result.reason } : {}\n\t\t};\n\t\tif (result.status !== \"ready\") {\n\t\t\tconst fields = {\n\t\t\t\tcode: \"PROVIDER_CLI_VALIDATION_NOT_READY\",\n\t\t\t\tprovider: frame.provider,\n\t\t\t\tagentId: frame.agentId,\n\t\t\t\tintegrationId: frame.integrationId,\n\t\t\t\tcredentialGeneration: frame.credentialGeneration,\n\t\t\t\tstatus: result.status,\n\t\t\t\t...result.reason ? { reason: result.reason } : {}\n\t\t\t};\n\t\t\tconst message = \"Provider CLI validation did not confirm readiness\";\n\t\t\tif (result.status === \"retrying\") this.#logger.info(fields, message);\n\t\t\telse this.#logger.warn(fields, message);\n\t\t}\n\t\tawait this.#connection.send(payload, { priority: \"result\" });\n\t}\n};\nasync function readySelectionFromInspect(layout, provider, inspection) {\n\tif (inspection.readiness !== \"ready\" || !inspection.selection || !inspection.fingerprint) return void 0;\n\tlet record;\n\ttry {\n\t\trecord = await readProviderCliSelection(layout, provider);\n\t} catch (error) {\n\t\tlogger$3.debug({\n\t\t\tcode: \"selection_read_failed\",\n\t\t\tprovider,\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI selection read failed\");\n\t\treturn;\n\t}\n\tif (!record) return void 0;\n\tconst path = providerCliSelectionTargetPath(record.selection);\n\tif (record.generation !== inspection.selection.generation || record.selection.kind !== inspection.selection.kind || record.selection.version !== inspection.selection.version || record.selection.fingerprint !== inspection.fingerprint || path !== inspection.selection.path) return;\n\tconst managedDigest = record.selection.kind === \"managed\" ? managedArtifactDigest(record.selection.artifactId) : void 0;\n\treturn {\n\t\tfingerprint: inspection.fingerprint,\n\t\tgeneration: record.generation,\n\t\tpath,\n\t\tversion: record.selection.version,\n\t\t...managedDigest ? { managedDigest } : {}\n\t};\n}\nfunction selectionsMatch(left, right) {\n\treturn left.fingerprint === right.fingerprint && left.generation === right.generation && left.path === right.path && left.version === right.version;\n}\nfunction unavailableOutcome(code, stage) {\n\tconst publicReason = publicProviderCliArtifactReason(code);\n\tif (!publicReason) return { status: \"unavailable\" };\n\tif (stage === \"inspect\" && !providerCliArtifactFailureIsManual({\n\t\treason: code,\n\t\tstage\n\t})) return { status: \"unavailable\" };\n\treturn {\n\t\tstatus: \"unavailable\",\n\t\treason: publicReason\n\t};\n}\n/**\n* Wait for shared work without cancelling it. One waiter's abort only stops that\n* waiter; the underlying job keeps running for everyone else.\n*/\nfunction joinSharedWork(work, signals) {\n\tif (signals.length === 0) return work;\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst cleanup = () => {\n\t\t\tfor (const signal of signals) signal.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst finishOk = (value) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tresolve(value);\n\t\t};\n\t\tconst finishErr = (error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tfor (const signal of signals) {\n\t\t\t\tif (!signal.aborted) continue;\n\t\t\t\ttry {\n\t\t\t\t\tsignal.throwIfAborted();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfinishErr(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinishErr(new DOMException(\"This operation was aborted\", \"AbortError\"));\n\t\t};\n\t\tfor (const signal of signals) signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\twork.then(finishOk, finishErr);\n\t\tif (signals.some((signal) => signal.aborted)) onAbort();\n\t});\n}\nfunction expectedIdentitiesMatch(left, right) {\n\tif (left.provider !== right.provider) return false;\n\tif (left.provider === \"feishu\" && right.provider === \"feishu\") return left.appId === right.appId && left.botOpenId === right.botOpenId && left.teamBrand === right.teamBrand;\n\tif (left.provider === \"slack\" && right.provider === \"slack\") return left.teamId === right.teamId && left.botUserId === right.botUserId && left.botId === right.botId;\n\treturn false;\n}\n//#endregion\n//#region src/runtime/provider-cli/outgoing-reply-sweep.ts\nconst logger$2 = createLogger(\"runtime-provider-cli-outgoing-reply-sweep\");\nasync function sweepAbandonedOutgoingReplyRuns(options) {\n\tconst runsDir = join(options.sessionDir, \"runs\");\n\tconst listed = await listPrivateFiles(options.plansRoot, runsDir, 128);\n\tif (listed === \"missing\" || listed === \"unavailable\") return;\n\tconst activeKey = options.activeRunId ? deriveProviderCliRunKey(options.activeRunId) : void 0;\n\tconst now = (options.now ?? Date.now)();\n\tconst maxAgeMs = options.maxAgeMs ?? 6048e5;\n\tfor (const name of listed) {\n\t\tif (!isProviderCliRunKey(name) || name === activeKey) continue;\n\t\tconst runDir = join(runsDir, name);\n\t\tif (!await shouldSweepAbandonedRun(options.plansRoot, runDir, now, maxAgeMs)) continue;\n\t\tawait rm(runDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t}).catch(() => {\n\t\t\tlogger$2.debug({ code: \"outgoing_reply_sweep_failed\" }, \"Abandoned outgoing reply Run could not be removed\");\n\t\t});\n\t}\n}\nasync function shouldSweepAbandonedRun(plansRoot, runDir, now, maxAgeMs) {\n\ttry {\n\t\tawait assertPrivateAncestry(plansRoot, runDir);\n\t} catch {\n\t\treturn false;\n\t}\n\tconst inflight = await listPrivateFiles(plansRoot, join(runDir, \"inflight\"), 128);\n\tif (inflight === \"unavailable\" || inflight !== \"missing\" && inflight.length > 0) return false;\n\tconst mtime = await newestInspectableMtime(plansRoot, runDir);\n\treturn mtime !== void 0 && now - mtime >= maxAgeMs;\n}\nasync function newestInspectableMtime(plansRoot, runDir) {\n\tconst runEntries = await listPrivateFiles(plansRoot, runDir, 128);\n\tif (typeof runEntries === \"string\" || runEntries.length >= 128) return void 0;\n\tif (runEntries.some((name) => ![\n\t\t\"capture-status.json\",\n\t\t\"outgoing-replies\",\n\t\t\"inflight\"\n\t].includes(name))) return void 0;\n\tconst times = [];\n\tif (await addPrivateMtime(times, runDir, \"directory\") !== \"ok\") return void 0;\n\tif (await addPrivateMtime(times, join(runDir, \"capture-status.json\"), \"file\") === \"unsafe\") return void 0;\n\tif (await addPrivateMtime(times, join(runDir, \"inflight\"), \"directory\") === \"unsafe\") return void 0;\n\tif (!await addReceiptMtimes(times, plansRoot, runDir)) return void 0;\n\treturn Math.max(...times);\n}\nasync function addReceiptMtimes(times, plansRoot, runDir) {\n\tconst receiptsDir = join(runDir, \"outgoing-replies\");\n\tconst receipts = await listPrivateFiles(plansRoot, receiptsDir, 128);\n\tif (receipts === \"missing\") return true;\n\tif (receipts === \"unavailable\" || receipts.length >= 128) return false;\n\tif (await addPrivateMtime(times, receiptsDir, \"directory\") !== \"ok\") return false;\n\tfor (const name of receipts) if (await addPrivateMtime(times, join(receiptsDir, name), \"file\") !== \"ok\") return false;\n\treturn true;\n}\nasync function addPrivateMtime(times, path, kind) {\n\ttry {\n\t\tconst status = await lstat(path);\n\t\tif (kind === \"file\" ? !status.isFile() : !status.isDirectory()) return \"unsafe\";\n\t\tif ((status.mode & 63) !== 0 || process.getuid && status.uid !== process.getuid()) return \"unsafe\";\n\t\ttimes.push(status.mtimeMs);\n\t\treturn \"ok\";\n\t} catch (error) {\n\t\treturn error.code === \"ENOENT\" ? \"missing\" : \"unsafe\";\n\t}\n}\n//#endregion\n//#region src/runtime/provider-cli/turn-launcher.ts\nconst TURN_LAUNCHER_MARKER = \"# opentag-provider-cli-turn-launcher: v1\";\nfunction shellSingleQuote(value) {\n\treturn `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\nfunction assertProviderCliTurnRunnerInvocation(invocation) {\n\tif (invocation.length < 2) throw new ProviderCliTurnPlanError(\"invalid_identity\", \"The Provider CLI Turn runner invocation must include Node and the runner module\");\n\tconst nodePath = invocation[0];\n\tif (typeof nodePath !== \"string\" || !isAbsolute(nodePath)) throw new ProviderCliTurnPlanError(\"invalid_identity\", \"The Provider CLI Turn runner must use an absolute Node path\");\n\tfor (const argument of invocation) {\n\t\tassertIdentity(\"runnerInvocation\", argument);\n\t\tif (argument.includes(\"\t\")) throw new ProviderCliTurnPlanError(\"invalid_identity\", \"The Provider CLI Turn runner invocation is unsafe\");\n\t}\n\treturn invocation;\n}\n/**\n* Private native-name launcher. It only execs the injected daemon Node/module\n* invocation, then forwards user argv after `--` without interpreting it.\n*/\nfunction renderProviderCliTurnLauncher(spec) {\n\tassertProviderCliTurnRunnerInvocation(spec.runnerInvocation);\n\tassertIdentity(\"runId\", spec.runId);\n\tif (!isAbsolute(spec.planPath)) throw new ProviderCliTurnPlanError(\"unsafe\", \"The Provider CLI Turn plan path must be absolute\");\n\tconst argv = [\n\t\t...spec.runnerInvocation,\n\t\t\"--plan\",\n\t\tspec.planPath,\n\t\t\"--provider\",\n\t\tspec.provider,\n\t\t\"--run-id\",\n\t\tspec.runId,\n\t\t\"--\"\n\t];\n\treturn [\n\t\t\"#!/bin/sh\",\n\t\t`${TURN_LAUNCHER_MARKER} provider=${spec.provider}`,\n\t\t\"# OpenTag private Turn launcher. Published per Run; do not edit.\",\n\t\t`exec ${argv.map(shellSingleQuote).join(\" \")} \"$@\"`,\n\t\t\"\"\n\t].join(\"\\n\");\n}\nasync function writeProviderCliTurnLauncher(path, spec) {\n\tconst content = renderProviderCliTurnLauncher(spec);\n\tawait writeDurableFile(path, content, 448);\n\tawait chmod(path, 448);\n}\n//#endregion\n//#region src/runtime/provider-cli/turn-plan-manager.ts\nconst logger$1 = createLogger(\"runtime-provider-cli-turn-plan-manager\");\n/**\n* Publishes and recovers per-Run exact-target plans under the account-global plans\n* root. Plans are isolated first by canonical OpenTag Home namespace, then by\n* irreversible Session key. This manager does not touch AgentTurnRunner,\n* SessionMessageInbox, SessionRuntimeManager, or daemon readiness.\n*/\nvar ProviderCliTurnPlanManager = class {\n\t#deps;\n\t#layout;\n\t#openTagHome;\n\t#homeNamespace;\n\tconstructor(deps) {\n\t\tthis.#deps = deps;\n\t\tthis.#layout = resolveProviderCliAccountLayout(deps.accountHome, deps.platform ?? process.platform);\n\t\tif (!isAbsolute(deps.openTagHome)) throw new ProviderCliTurnPlanError(\"invalid_identity\", \"The OpenTag Home must be an absolute path\");\n\t\tthis.#openTagHome = realpathSync(deps.openTagHome);\n\t\tthis.#homeNamespace = deriveProviderCliHomeNamespace(this.#openTagHome);\n\t}\n\tget layout() {\n\t\treturn this.#layout;\n\t}\n\tget homeNamespace() {\n\t\treturn this.#homeNamespace;\n\t}\n\tsessionDir(sessionId) {\n\t\treturn providerCliPlanSessionDir(this.#layout, this.#homeNamespace, deriveProviderCliSessionKey(sessionId));\n\t}\n\t/**\n\t* Read the exact current selection, verify its canonical target and fingerprint,\n\t* and atomically publish an immutable Run plan. A different active Run for the\n\t* same Session is rejected; the same Run is idempotent even if selection later\n\t* changes.\n\t*/\n\tasync prepare(input, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tconst sessionId = assertIdentity(\"sessionId\", input.sessionId);\n\t\tconst runId = assertIdentity(\"runId\", input.runId);\n\t\tassertProviderCliTurnPlanConfigDir(input.provider, input.configDir);\n\t\tconst sessionKey = deriveProviderCliSessionKey(sessionId);\n\t\tconst sessionDir = providerCliPlanSessionDir(this.#layout, this.#homeNamespace, sessionKey);\n\t\tassertPlanWithinRoot(this.#layout.plans, sessionDir);\n\t\tawait ensurePrivateDirectory(this.#layout.root, sessionDir);\n\t\tassertCaptureOutgoingRepliesInput(input);\n\t\tassertProxyPlanInput(input);\n\t\treturn await this.#withSessionLock(sessionDir, () => this.#prepareLocked(input, sessionId, runId, sessionDir, signal));\n\t}\n\t/**\n\t* Remove the matching Run's plan. The launcher deliberately remains as a\n\t* fail-closed PATH sentinel: without its plan it exits non-zero instead of\n\t* allowing a shell to fall through to an ambient provider CLI.\n\t*/\n\tasync cleanup(input) {\n\t\tconst sessionId = assertIdentity(\"sessionId\", input.sessionId);\n\t\tconst runId = assertIdentity(\"runId\", input.runId);\n\t\tconst sessionDir = this.sessionDir(sessionId);\n\t\tassertPlanWithinRoot(this.#layout.plans, sessionDir);\n\t\ttry {\n\t\t\tif (!await validatePrivateDirectory(this.#layout.root, sessionDir)) return;\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return;\n\t\t\tlogger$1.debug({\n\t\t\t\tcode: \"session_plan_directory_validation_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI Turn session directory validation failed\");\n\t\t\tthrow mapStorageSafetyError(error);\n\t\t}\n\t\tawait this.#withSessionLock(sessionDir, async () => {\n\t\t\tconst existing = await this.#readExistingPlan(sessionDir);\n\t\t\tif (!existing) return;\n\t\t\tthis.#assertMatchingHome(existing);\n\t\t\tif (existing.sessionId !== sessionId) throw new ProviderCliTurnPlanError(\"session_mismatch\", \"Provider CLI Turn plan session does not match\");\n\t\t\tif (existing.runId !== runId) throw new ProviderCliTurnPlanError(\"run_mismatch\", \"Provider CLI Turn cleanup run does not match\");\n\t\t\tif (existing.provider !== input.provider) throw new ProviderCliTurnPlanError(\"provider_mismatch\", \"Provider CLI Turn cleanup provider does not match\");\n\t\t\tawait rm(providerCliTurnPlanPath(sessionDir), { force: true });\n\t\t});\n\t}\n\t/**\n\t* Crash recovery for this canonical OpenTag Home only. Sibling Home namespaces under\n\t* the same account-global plans root are never listed or removed.\n\t*/\n\tasync recover() {\n\t\tconst homeDir = providerCliPlanHomeDir(this.#layout, this.#homeNamespace);\n\t\tassertPlanWithinRoot(this.#layout.plans, homeDir);\n\t\tlet entries;\n\t\ttry {\n\t\t\tif (!await validatePrivateDirectory(this.#layout.root, homeDir)) return;\n\t\t\tentries = await readdir(homeDir, {\n\t\t\t\tencoding: \"utf8\",\n\t\t\t\twithFileTypes: true\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return;\n\t\t\tlogger$1.debug({\n\t\t\t\tcode: \"home_plan_directory_validation_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI Turn home directory validation failed\");\n\t\t\tthrow mapStorageSafetyError(error);\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (!isProviderCliSessionKey(entry.name) || !entry.isDirectory() || entry.isSymbolicLink()) continue;\n\t\t\tconst sessionDir = join(homeDir, entry.name);\n\t\t\tassertPlanWithinRoot(homeDir, sessionDir);\n\t\t\tawait sweepAbandonedOutgoingReplyRuns({\n\t\t\t\tplansRoot: this.#layout.plans,\n\t\t\t\tsessionDir\n\t\t\t});\n\t\t\tif (await recoverSessionOutgoingReplyEvidence({\n\t\t\t\tplansRoot: this.#layout.plans,\n\t\t\t\tsessionDir\n\t\t\t})) continue;\n\t\t\tawait rm(sessionDir, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t});\n\t\t}\n\t}\n\t#prepared(plan, sessionDir) {\n\t\treturn {\n\t\t\tplan,\n\t\t\tplanPath: providerCliTurnPlanPath(sessionDir),\n\t\t\tlauncherPath: providerCliTurnLauncherPath(sessionDir, plan.command),\n\t\t\tsessionDir,\n\t\t\thomeNamespace: this.#homeNamespace\n\t\t};\n\t}\n\tasync #readExistingPlan(sessionDir) {\n\t\treturn readProviderCliTurnPlan(providerCliTurnPlanPath(sessionDir));\n\t}\n\tasync #prepareLocked(input, sessionId, runId, sessionDir, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tconst existing = await this.#readExistingPlan(sessionDir);\n\t\tawait sweepAbandonedOutgoingReplyRuns({\n\t\t\tplansRoot: this.#layout.plans,\n\t\t\tsessionDir,\n\t\t\tactiveRunId: existing?.runId ?? runId\n\t\t});\n\t\tif (existing) return this.#reuseExistingPlan(input, sessionId, runId, sessionDir, existing);\n\t\treturn this.#publishNewPlan(input, sessionId, runId, sessionDir, signal);\n\t}\n\tasync #reuseExistingPlan(input, sessionId, runId, sessionDir, existing) {\n\t\tthis.#assertMatchingHome(existing);\n\t\tif (existing.sessionId !== sessionId) throw new ProviderCliTurnPlanError(\"session_mismatch\", \"Provider CLI Turn plan session does not match\");\n\t\tif (existing.runId !== runId || existing.provider !== input.provider || planCapturesOutgoingReplies(existing) !== requestedCaptureOutgoingReplies(input)) throw new ProviderCliTurnPlanError(\"active_run_conflict\", \"The Session already has a different active Provider CLI Turn Run\");\n\t\tawait this.#writeLauncher(sessionDir, existing);\n\t\treturn this.#prepared(existing, sessionDir);\n\t}\n\tasync #publishNewPlan(input, sessionId, runId, sessionDir, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tconst expected = await this.#deps.readySelection?.(input.provider, signal);\n\t\tsignal?.throwIfAborted();\n\t\tif (this.#deps.readySelection && !expected) throw new ProviderCliTurnPlanError(\"selection_invalid\", \"Provider CLI selection has not completed daemon readiness\");\n\t\tconst record = await this.#readSelection(input.provider);\n\t\tconst plan = await this.#planFromSelection(input, sessionId, runId, record, expected);\n\t\tsignal?.throwIfAborted();\n\t\tawait this.#writeLauncher(sessionDir, plan);\n\t\tsignal?.throwIfAborted();\n\t\tlet published;\n\t\ttry {\n\t\t\tpublished = await publishProviderCliTurnPlanExclusive(providerCliTurnPlanPath(sessionDir), plan);\n\t\t} finally {\n\t\t\tif (signal?.aborted) await this.#discardMatchingPlan(input, sessionDir);\n\t\t}\n\t\tsignal?.throwIfAborted();\n\t\tif (published === \"created\") return this.#prepared(plan, sessionDir);\n\t\tconst raced = await this.#readExistingPlan(sessionDir);\n\t\tif (!raced) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn plan publish raced\");\n\t\treturn this.#reuseExistingPlan(input, sessionId, runId, sessionDir, raced);\n\t}\n\tasync #discardMatchingPlan(input, sessionDir) {\n\t\tconst existing = await this.#readExistingPlan(sessionDir);\n\t\tif (!existing) return;\n\t\tif (existing.homeNamespace !== this.#homeNamespace || existing.sessionId !== input.sessionId || existing.runId !== input.runId || existing.provider !== input.provider) return;\n\t\tawait rm(providerCliTurnPlanPath(sessionDir), { force: true });\n\t}\n\tasync #readSelection(provider) {\n\t\tlet record;\n\t\ttry {\n\t\t\trecord = await readProviderCliSelection(this.#layout, provider);\n\t\t} catch (error) {\n\t\t\tlogger$1.debug({\n\t\t\t\tcode: \"selection_read_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI Turn selection read failed\");\n\t\t\tif (error instanceof RuntimeStorageError && error.code === \"unsafe\") throw new ProviderCliTurnPlanError(\"unsafe\", error.message);\n\t\t\tthrow new ProviderCliTurnPlanError(\"selection_invalid\", error instanceof Error ? error.message : \"Provider CLI selection is malformed\");\n\t\t}\n\t\tif (!record) throw new ProviderCliTurnPlanError(\"selection_missing\", \"Provider CLI selection is missing\");\n\t\treturn record;\n\t}\n\tasync #planFromSelection(input, sessionId, runId, record, expected) {\n\t\tconst selection = record.selection;\n\t\tconst { fingerprint, identity } = await this.#verifyPlanTarget(selection, record, expected);\n\t\tconst shared = {\n\t\t\tschemaVersion: 1,\n\t\t\tselectionVersion: selection.version,\n\t\t\tselectionGeneration: record.generation,\n\t\t\ttargetPath: identity.path,\n\t\t\tfingerprint,\n\t\t\thomeNamespace: this.#homeNamespace,\n\t\t\tsessionId,\n\t\t\trunId,\n\t\t\t...requestedCaptureOutgoingReplies(input) ? { captureOutgoingReplies: true } : {},\n\t\t\t...input.environmentManifest ? { environmentManifest: input.environmentManifest } : {}\n\t\t};\n\t\tif (input.provider === \"slack\") {\n\t\t\tconst configDir = assertProviderCliTurnPlanConfigDir(\"slack\", input.configDir);\n\t\t\tif (selection.kind === \"managed\") return {\n\t\t\t\t...shared,\n\t\t\t\tprovider: \"slack\",\n\t\t\t\tcommand: \"slack\",\n\t\t\t\tselectionKind: \"managed\",\n\t\t\t\tartifactId: selection.artifactId,\n\t\t\t\tconfigDir,\n\t\t\t\t...input.slackApiHost ? { slackApiHost: input.slackApiHost } : {}\n\t\t\t};\n\t\t\treturn {\n\t\t\t\t...shared,\n\t\t\t\tprovider: \"slack\",\n\t\t\t\tcommand: \"slack\",\n\t\t\t\tselectionKind: \"external\",\n\t\t\t\tconfigDir,\n\t\t\t\t...input.slackApiHost ? { slackApiHost: input.slackApiHost } : {}\n\t\t\t};\n\t\t}\n\t\tif (selection.kind === \"managed\") return {\n\t\t\t...shared,\n\t\t\tprovider: \"feishu\",\n\t\t\tcommand: \"lark-cli\",\n\t\t\tselectionKind: \"managed\",\n\t\t\tartifactId: selection.artifactId\n\t\t};\n\t\treturn {\n\t\t\t...shared,\n\t\t\tprovider: \"feishu\",\n\t\t\tcommand: \"lark-cli\",\n\t\t\tselectionKind: \"external\"\n\t\t};\n\t}\n\t/** Fail-closed target recheck: the executable must still match the stored selection. */\n\tasync #verifyPlanTarget(selection, record, expected) {\n\t\tconst storedPath = providerCliSelectionTargetPath(selection);\n\t\tconst identity = await computeFileIdentity(storedPath).catch((error) => {\n\t\t\tlogger$1.debug({\n\t\t\t\tcode: \"selection_target_identity_failed\",\n\t\t\t\terror: String(error)\n\t\t\t}, \"Provider CLI Turn selection target identity failed\");\n\t\t\tthrow mapPrepareTargetError(error);\n\t\t});\n\t\tif (identity.path !== storedPath) throw new ProviderCliTurnPlanError(\"artifact_drifted\", \"Provider CLI selection target path drifted\");\n\t\tconst managedDigest = selection.kind === \"managed\" ? managedArtifactDigest(selection.artifactId) : void 0;\n\t\tconst fingerprint = computeTargetFingerprint(identity, selection.version, managedDigest);\n\t\tif (fingerprint !== selection.fingerprint) throw new ProviderCliTurnPlanError(\"artifact_drifted\", \"Provider CLI selection fingerprint drifted\");\n\t\tif (expected && (expected.generation !== record.generation || expected.path !== identity.path || expected.version !== selection.version || expected.fingerprint !== fingerprint || expected.managedDigest !== managedDigest)) throw new ProviderCliTurnPlanError(\"selection_invalid\", \"Provider CLI selection no longer matches daemon readiness\");\n\t\treturn {\n\t\t\tfingerprint,\n\t\t\tidentity\n\t\t};\n\t}\n\tasync #writeLauncher(sessionDir, plan) {\n\t\tconst launcherPath = providerCliTurnLauncherPath(sessionDir, plan.command);\n\t\tassertPlanWithinRoot(sessionDir, launcherPath);\n\t\tawait writeProviderCliTurnLauncher(launcherPath, {\n\t\t\tprovider: plan.provider,\n\t\t\trunId: plan.runId,\n\t\t\tplanPath: providerCliTurnPlanPath(sessionDir),\n\t\t\trunnerInvocation: this.#deps.runnerInvocation\n\t\t});\n\t}\n\t#assertMatchingHome(plan) {\n\t\tif (plan.homeNamespace !== this.#homeNamespace) throw new ProviderCliTurnPlanError(\"home_mismatch\", \"Provider CLI Turn plan home namespace does not match\");\n\t}\n\tasync #withSessionLock(sessionDir, run) {\n\t\tconst sleep = this.#deps.sleep ?? defaultSleep$1;\n\t\tconst lockPath = join(sessionDir, \".lock\");\n\t\tconst token = randomUUID();\n\t\tconst candidatePath = join(sessionDir, `.lock-${token}.candidate`);\n\t\tawait writeDurableFile(candidatePath, JSON.stringify({\n\t\t\tpid: process.pid,\n\t\t\ttoken\n\t\t}), 384);\n\t\tlet acquired = false;\n\t\ttry {\n\t\t\tacquired = await acquireSessionLock(candidatePath, lockPath, sessionDir, sleep);\n\t\t\tif (!acquired) throw new ProviderCliTurnPlanError(\"runner_failed\", \"Another process holds the Provider CLI Turn plan lock\");\n\t\t\ttry {\n\t\t\t\treturn await run();\n\t\t\t} finally {\n\t\t\t\tawait releaseSessionLock(candidatePath, lockPath);\n\t\t\t}\n\t\t} finally {\n\t\t\tawait rm(candidatePath, { force: true }).catch((error) => {\n\t\t\t\tlogger$1.debug({\n\t\t\t\t\tcode: \"session_lock_candidate_cleanup_failed\",\n\t\t\t\t\terror: String(error)\n\t\t\t\t}, \"Provider CLI Turn session lock candidate cleanup failed\");\n\t\t\t});\n\t\t}\n\t}\n};\nasync function acquireSessionLock(candidatePath, lockPath, sessionDir, sleep) {\n\tfor (let attempt = 0; attempt < 50; attempt += 1) try {\n\t\tawait link(candidatePath, lockPath);\n\t\tawait syncDurableDirectory(sessionDir);\n\t\treturn true;\n\t} catch (error) {\n\t\tif (error.code !== \"EEXIST\") throw error;\n\t\tif (attempt + 1 < 50) await sleep(20);\n\t}\n\treturn false;\n}\nasync function releaseSessionLock(candidatePath, lockPath) {\n\ttry {\n\t\tconst [candidate, lockStatus] = await Promise.all([lstat(candidatePath), lstat(lockPath)]);\n\t\tif (candidate.dev === lockStatus.dev && candidate.ino === lockStatus.ino) await rm(lockPath, { force: true });\n\t} catch (error) {\n\t\tif (error.code !== \"ENOENT\") throw error;\n\t\tlogger$1.debug({\n\t\t\tcode: \"session_lock_release_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI Turn session lock release failed\");\n\t}\n}\nfunction mapStorageSafetyError(error) {\n\tif (error instanceof RuntimeStorageError && error.code === \"unsafe\") return new ProviderCliTurnPlanError(\"unsafe\", error.message);\n\treturn error instanceof Error ? error : /* @__PURE__ */ new Error(\"Provider CLI Turn storage validation failed\");\n}\nfunction mapPrepareTargetError(error) {\n\tif (error instanceof ProviderCliTurnPlanError) return error;\n\tif (error instanceof ProviderCliFileError) {\n\t\tif (error.code === \"too-large\") return new ProviderCliTurnPlanError(\"too_large\", error.message);\n\t\tif (error.code === \"missing\") return new ProviderCliTurnPlanError(\"target_invalid\", error.message);\n\t\tif (error.code === \"not-regular-file\") return new ProviderCliTurnPlanError(\"unsafe\", error.message);\n\t\treturn new ProviderCliTurnPlanError(\"artifact_drifted\", error.message);\n\t}\n\treturn new ProviderCliTurnPlanError(\"target_invalid\", error instanceof Error ? error.message : \"Provider CLI selection target is invalid\");\n}\nfunction assertCaptureOutgoingRepliesInput(input) {\n\tif (input.captureOutgoingReplies === void 0) return;\n\tif (typeof input.captureOutgoingReplies !== \"boolean\") throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn captureOutgoingReplies must be a boolean\");\n\tif (input.provider === \"slack\" && input.captureOutgoingReplies) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Slack Provider CLI Turn plans do not capture outgoing replies\");\n}\nfunction assertProxyPlanInput(input) {\n\tif (input.environmentManifest !== void 0) {\n\t\tif (!isAbsolute(input.environmentManifest) || resolve(input.environmentManifest) !== input.environmentManifest) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn environment manifest must be an absolute canonical path\");\n\t}\n\tif (input.slackApiHost !== void 0) {\n\t\tif (input.provider !== \"slack\") throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn Slack API host requires the Slack provider\");\n\t\tif (!/^https:\\/\\/127\\.0\\.0\\.1:\\d{1,5}$/.test(input.slackApiHost)) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn Slack API host must be a loopback HTTPS endpoint\");\n\t}\n}\nconst requestedCaptureOutgoingReplies = (input) => input.provider === \"feishu\" && input.captureOutgoingReplies === true;\nconst defaultSleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n//#endregion\n//#region src/runtime/provider-cli/turn-runner.ts\nconst logger = createLogger(\"runtime-provider-cli-turn-runner\");\nfunction parseProviderCliTurnRunnerArgv(argv) {\n\tif (argv[0] !== \"--plan\" || argv[2] !== \"--provider\" || argv[4] !== \"--run-id\" || argv[6] !== \"--\") throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn runner fence is malformed\");\n\tconst planPath = argv[1];\n\tconst provider = argv[3];\n\tconst runId = argv[5];\n\tif (planPath === void 0 || provider === void 0 || runId === void 0) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"Provider CLI Turn runner fence is incomplete\");\n\tif (provider !== \"feishu\" && provider !== \"slack\") throw new ProviderCliTurnPlanError(\"provider_mismatch\", \"Provider CLI Turn runner provider is unknown\");\n\tif (!isAbsolute(planPath)) throw new ProviderCliTurnPlanError(\"unsafe\", \"Provider CLI Turn plan path must be absolute\");\n\tif (runId.length === 0) throw new ProviderCliTurnPlanError(\"run_mismatch\", \"Provider CLI Turn runner run is missing\");\n\treturn {\n\t\tplanPath,\n\t\tprovider,\n\t\trunId,\n\t\tuserArgv: argv.slice(7)\n\t};\n}\nasync function loadProviderCliTurnPlanForRun(options) {\n\tconst location = await validateTurnPlanLocation(options.plansRoot ?? resolveProviderCliAccountLayout(resolveAccountHome()).plans, options.planPath);\n\tconst plan = await readProviderCliTurnPlan(options.planPath);\n\tif (!plan) throw new ProviderCliTurnPlanError(\"plan_missing\", \"Provider CLI Turn plan is missing\");\n\tif (plan.homeNamespace !== location.homeNamespace) throw new ProviderCliTurnPlanError(\"home_mismatch\", \"Provider CLI Turn plan is outside its Home namespace\");\n\tif (deriveProviderCliSessionKey(plan.sessionId) !== location.sessionKey) throw new ProviderCliTurnPlanError(\"session_mismatch\", \"Provider CLI Turn plan is outside its Session namespace\");\n\tif (plan.provider !== options.provider) throw new ProviderCliTurnPlanError(\"provider_mismatch\", \"Provider CLI Turn plan provider does not match the fence\");\n\tif (plan.runId !== options.runId) throw new ProviderCliTurnPlanError(\"run_mismatch\", \"Provider CLI Turn plan run does not match the fence\");\n\treturn plan;\n}\n/**\n* Execute the immutable plan: re-hash the exact target, apply the provider/run fence,\n* and spawn without a shell. The current selection record is never consulted.\n*/\nasync function executeProviderCliTurnPlan(options) {\n\tconst plan = await loadProviderCliTurnPlanForRun({\n\t\tplanPath: options.planPath,\n\t\tprovider: options.provider,\n\t\trunId: options.runId,\n\t\tplansRoot: options.plansRoot\n\t});\n\tconst identity = await computeFileIdentity(plan.targetPath).catch((error) => {\n\t\tlogger.debug({\n\t\t\tcode: \"turn_target_identity_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI Turn target identity failed\");\n\t\tthrow mapTargetError(error);\n\t});\n\tif (identity.path !== plan.targetPath) throw new ProviderCliTurnPlanError(\"artifact_drifted\", \"Provider CLI Turn target path drifted\");\n\tconst managedDigest = plan.selectionKind === \"managed\" ? managedArtifactDigest(plan.artifactId) : void 0;\n\tif (computeTargetFingerprint(identity, plan.selectionVersion, managedDigest) !== plan.fingerprint) throw new ProviderCliTurnPlanError(\"artifact_drifted\", \"Provider CLI Turn target fingerprint drifted\");\n\tconst entry = requireProviderCliCatalogEntry(plan.provider, options.catalog ?? PROVIDER_CLI_CATALOG);\n\tconst baseEnv = options.env ?? process.env;\n\tconst env = plan.selectionKind === \"managed\" ? {\n\t\t...baseEnv,\n\t\t...entry.managedEnvironment\n\t} : { ...baseEnv };\n\tif (plan.environmentManifest) await mergeEnvironmentManifest(env, plan.environmentManifest);\n\tconst args = await turnPlanArguments(plan, options.argv, entry);\n\tconst plansRoot = options.plansRoot ?? resolveProviderCliAccountLayout(resolveAccountHome()).plans;\n\tif (options.spawnTarget) return options.spawnTarget(plan.targetPath, args, { env });\n\tif (!planCapturesOutgoingReplies(plan) || !classifyLarkOutgoingMutation(options.argv)) return spawnInheritedProcess({\n\t\tfile: plan.targetPath,\n\t\targs,\n\t\tenv\n\t}).catch((error) => {\n\t\tthrow new ProviderCliTurnPlanError(\"runner_failed\", error instanceof Error ? error.message : \"Provider CLI Turn runner failed\");\n\t});\n\treturn withOutgoingReplyInflight({\n\t\tplansRoot,\n\t\tplanPath: options.planPath,\n\t\trunId: plan.runId,\n\t\tenabled: true,\n\t\trun: async () => {\n\t\t\tconst spawned = await spawnCapturedProcess({\n\t\t\t\tfile: plan.targetPath,\n\t\t\t\targs,\n\t\t\t\tenv,\n\t\t\t\tmaxBytes: PROVIDER_CLI_OUTGOING_REPLY_STDOUT_CAPTURE_MAX_BYTES,\n\t\t\t\tforward: true\n\t\t\t}).catch((error) => {\n\t\t\t\tthrow new ProviderCliTurnPlanError(\"runner_failed\", error instanceof Error ? error.message : \"Provider CLI Turn runner failed\");\n\t\t\t});\n\t\t\tawait captureFeishuOutgoingReply({\n\t\t\t\tplan,\n\t\t\t\tplanPath: options.planPath,\n\t\t\t\tplansRoot,\n\t\t\t\tuserArgv: options.argv,\n\t\t\t\tspawnArgs: args,\n\t\t\t\tenv,\n\t\t\t\tcode: spawned.code,\n\t\t\t\tstdout: spawned.stdout,\n\t\t\t\tstdoutTruncated: spawned.truncated\n\t\t\t}).catch(() => {\n\t\t\t\tlogger.debug({ code: \"outgoing_reply_capture_failed\" }, \"Outgoing reply capture failed\");\n\t\t\t\treturn markOutgoingReplyCaptureStatus({\n\t\t\t\t\tplansRoot,\n\t\t\t\t\tsessionDir: dirname(options.planPath),\n\t\t\t\t\trunId: plan.runId,\n\t\t\t\t\tstatus: \"incomplete\"\n\t\t\t\t});\n\t\t\t});\n\t\t\treturn spawned.code;\n\t\t}\n\t});\n}\nasync function runProviderCliTurnRunner(argv, options = {}) {\n\ttry {\n\t\tconst parsed = parseProviderCliTurnRunnerArgv(argv);\n\t\treturn await executeProviderCliTurnPlan({\n\t\t\tplanPath: parsed.planPath,\n\t\t\tprovider: parsed.provider,\n\t\t\trunId: parsed.runId,\n\t\t\targv: parsed.userArgv,\n\t\t\tplansRoot: options.plansRoot\n\t\t});\n\t} catch (error) {\n\t\tlogger.debug({\n\t\t\tcode: \"turn_runner_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Provider CLI Turn runner failed\");\n\t\tconst message = error instanceof Error ? error.message : \"Provider CLI Turn runner failed\";\n\t\tprocess.stderr.write(`${message}\\n`);\n\t\treturn 1;\n\t}\n}\nasync function validateTurnPlanLocation(plansRoot, planPath) {\n\tconst root = resolve(plansRoot);\n\tconst target = resolve(planPath);\n\tassertPlanWithinRoot(root, target);\n\tconst segments = relative(root, target).split(sep);\n\tconst [homeNamespace, sessionKey, fileName] = segments;\n\tif (segments.length !== 3 || homeNamespace === void 0 || sessionKey === void 0 || !isProviderCliHomeNamespace(homeNamespace ?? \"\") || !isProviderCliSessionKey(sessionKey ?? \"\") || fileName !== \"plan.json\") throw new ProviderCliTurnPlanError(\"unsafe\", \"Provider CLI Turn plan path is not a derived plan location\");\n\tconst sessionDir = dirname(target);\n\tif (!await validatePrivateDirectory(root, sessionDir)) throw new ProviderCliTurnPlanError(\"plan_missing\", \"Provider CLI Turn plan directory is missing\");\n\tfor (const directory of [\n\t\troot,\n\t\tjoin(root, homeNamespace),\n\t\tsessionDir\n\t]) {\n\t\tconst status = await lstat(directory);\n\t\tconst currentUid = typeof process.getuid === \"function\" ? process.getuid() : void 0;\n\t\tif (status.isSymbolicLink() || !status.isDirectory() || currentUid !== void 0 && status.uid !== currentUid || (status.mode & 63) !== 0) throw new ProviderCliTurnPlanError(\"unsafe\", \"Provider CLI Turn plan directories must be private and owned by the daemon account\");\n\t}\n\treturn {\n\t\thomeNamespace,\n\t\tsessionKey\n\t};\n}\nfunction resolveProviderCliTurnRunnerInvocation() {\n\treturn [process.execPath, fileURLToPath(import.meta.url)];\n}\nfunction isProviderCliTurnRunnerMain(metaUrl, argv1 = process.argv[1]) {\n\tif (!argv1) return false;\n\ttry {\n\t\treturn metaUrl === pathToFileURL(resolve(argv1)).href;\n\t} catch {\n\t\treturn false;\n\t}\n}\nasync function turnPlanArguments(plan, argv, entry) {\n\tif (plan.provider === \"slack\") {\n\t\tassertSlackTurnArgv(argv);\n\t\tawait assertPrivateSlackConfigDirectory(plan.configDir);\n\t\treturn [\n\t\t\t\"--skip-update\",\n\t\t\t\"--config-dir\",\n\t\t\tplan.configDir,\n\t\t\t...plan.slackApiHost ? [\"--apihost\", plan.slackApiHost] : [],\n\t\t\t...argv\n\t\t];\n\t}\n\treturn plan.selectionKind === \"managed\" ? [...entry.managedArguments, ...argv] : [...argv];\n}\nconst PROXY_ENVIRONMENT_MANIFEST_MAX_BYTES = 16384;\n/** Merge the daemon-published execution manifest; fail closed when it is missing/invalid. */\nasync function mergeEnvironmentManifest(env, manifestPath) {\n\tconst content = await readSecureFile(manifestPath).catch((error) => {\n\t\tif (error.code === \"ENOENT\" || error === void 0) return void 0;\n\t\tthrow error;\n\t});\n\tif (content === void 0) throw new ProviderCliTurnPlanError(\"plan_missing\", \"The execution environment manifest is missing\");\n\tif (Buffer.byteLength(content, \"utf8\") > PROXY_ENVIRONMENT_MANIFEST_MAX_BYTES) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"The execution environment manifest is too large\");\n\tlet manifest;\n\ttry {\n\t\tmanifest = parseProxyEnvironmentManifest(JSON.parse(content));\n\t} catch (error) {\n\t\tif (error instanceof ProviderCliTurnPlanError) throw error;\n\t\tthrow new ProviderCliTurnPlanError(\"plan_invalid\", \"The execution environment manifest is invalid\");\n\t}\n\tfor (const [key, value] of Object.entries(manifest.environment)) if (value === null) delete env[key];\n\telse env[key] = value;\n\tObject.assign(env, providerRoutingEnvironment(env));\n\treturn manifest;\n}\nfunction parseProxyEnvironmentManifest(value) {\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"The execution environment manifest is malformed\");\n\tconst record = value;\n\tif (record.schemaVersion !== 1 || typeof record.executionId !== \"string\" || record.executionId.length === 0) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"The execution environment manifest identity is malformed\");\n\tconst environment = record.environment;\n\tif (typeof environment !== \"object\" || environment === null || Array.isArray(environment)) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"The execution environment manifest entries are malformed\");\n\tconst entries = {};\n\tfor (const [key, entryValue] of Object.entries(environment)) {\n\t\tif (/[\\0=]/.test(key)) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"The execution environment manifest key is unsafe\");\n\t\tif (entryValue !== null && (typeof entryValue !== \"string\" || entryValue.includes(\"\\0\"))) throw new ProviderCliTurnPlanError(\"plan_invalid\", \"The execution environment manifest value is unsafe\");\n\t\tentries[key] = entryValue;\n\t}\n\treturn {\n\t\texecutionId: record.executionId,\n\t\tenvironment: entries\n\t};\n}\nconst RESERVED_SLACK_TURN_FLAGS = [\n\t\"--token\",\n\t\"--app\",\n\t\"--team\",\n\t\"--workspace\",\n\t\"--config-dir\",\n\t\"--skip-update\",\n\t\"--apihost\"\n];\nfunction assertSlackTurnArgv(argv) {\n\tfor (const argument of argv) if (RESERVED_SLACK_TURN_FLAGS.some((flag) => argument === flag || argument.startsWith(`${flag}=`)) || argument.startsWith(\"-w\")) throw new ProviderCliTurnPlanError(\"unsafe\", \"Slack Provider CLI Turn argv must not override OpenTag-managed authority flags\");\n}\nasync function assertPrivateSlackConfigDirectory(configDir) {\n\tconst frozen = assertProviderCliSlackConfigDir(configDir);\n\tlet status;\n\ttry {\n\t\tstatus = await lstat(frozen);\n\t} catch (error) {\n\t\tif (error.code === \"ENOENT\") throw new ProviderCliTurnPlanError(\"unsafe\", \"Slack config directory is missing\");\n\t\tlogger.debug({\n\t\t\tcode: \"slack_config_stat_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Slack config directory inspection failed\");\n\t\tthrow error;\n\t}\n\tconst currentUid = typeof process.getuid === \"function\" ? process.getuid() : void 0;\n\tif (status.isSymbolicLink() || !status.isDirectory() || currentUid !== void 0 && status.uid !== currentUid || (status.mode & 511) !== 448) throw new ProviderCliTurnPlanError(\"unsafe\", \"Slack config directory must be a real private daemon-owned directory\");\n\tlet canonical;\n\ttry {\n\t\tcanonical = await realpath(frozen);\n\t} catch (error) {\n\t\tlogger.debug({\n\t\t\tcode: \"slack_config_realpath_failed\",\n\t\t\terror: String(error)\n\t\t}, \"Slack config directory canonicalization failed\");\n\t\tthrow new ProviderCliTurnPlanError(\"unsafe\", \"Slack config directory cannot be canonicalized\");\n\t}\n\tif (canonical !== frozen) throw new ProviderCliTurnPlanError(\"unsafe\", \"Slack config directory must not traverse a symlink\");\n}\nfunction mapTargetError(error) {\n\tif (error instanceof ProviderCliTurnPlanError) return error;\n\tif (error instanceof ProviderCliFileError) {\n\t\tif (error.code === \"too-large\") return new ProviderCliTurnPlanError(\"too_large\", error.message);\n\t\tif (error.code === \"not-regular-file\") return new ProviderCliTurnPlanError(\"unsafe\", error.message);\n\t\treturn new ProviderCliTurnPlanError(\"artifact_drifted\", error.message);\n\t}\n\treturn new ProviderCliTurnPlanError(\"artifact_drifted\", error instanceof Error ? error.message : \"Provider CLI Turn target could not be verified\");\n}\nif (isProviderCliTurnRunnerMain(import.meta.url)) runProviderCliTurnRunner(process.argv.slice(2)).then(async (code) => {\n\tprocess.exitCode = code;\n\tawait flushStdout();\n}, async () => {\n\tprocess.exitCode = 1;\n\tawait flushStdout();\n});\n//#endregion\n//#region src/runtime/provider-cli/validation-classify.ts\nconst defaultValidationLogger$1 = createLogger(\"provider-cli-validation\");\nfunction extractBoundedJson(text, maxBytes = RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES, logger = defaultValidationLogger$1) {\n\tif (Buffer.byteLength(text) > maxBytes) {\n\t\tlogDiagnostic(logger, \"json_output_oversize\");\n\t\treturn;\n\t}\n\tconst trimmed = text.trim();\n\tif (!trimmed) {\n\t\tlogDiagnostic(logger, \"json_output_empty\");\n\t\treturn;\n\t}\n\tconst start = trimmed.indexOf(\"{\");\n\tconst end = trimmed.lastIndexOf(\"}\");\n\tif (start < 0 || end < start) {\n\t\tlogDiagnostic(logger, \"json_object_bounds_missing\");\n\t\treturn;\n\t}\n\tconst slice = trimmed.slice(start, end + 1);\n\tif (Buffer.byteLength(slice) > maxBytes) {\n\t\tlogDiagnostic(logger, \"json_output_oversize\");\n\t\treturn;\n\t}\n\ttry {\n\t\treturn JSON.parse(slice);\n\t} catch {\n\t\tlogDiagnostic(logger, \"json_output_malformed\");\n\t\treturn;\n\t}\n}\nfunction classifySlackAuthTest(payload, expected, logger = defaultValidationLogger$1) {\n\tif (!isRecord$2(payload)) {\n\t\tlogDiagnostic(logger, \"slack_payload_not_record\");\n\t\treturn { status: \"needs_attention\" };\n\t}\n\tif (typeof payload.ok !== \"boolean\") {\n\t\tlogDiagnostic(logger, \"slack_ok_field_missing\");\n\t\treturn { status: \"needs_attention\" };\n\t}\n\tconst error = typeof payload.error === \"string\" ? payload.error : void 0;\n\tconst failure = classifyProviderFailure([error], payload.missing_scopes, error === \"missing_scope\");\n\tif (failure) return failure;\n\tif (payload.ok !== true) {\n\t\tlogDiagnostic(logger, \"slack_ok_not_true\");\n\t\treturn { status: \"needs_attention\" };\n\t}\n\tconst identity = slackIdentity(payload);\n\tif (!identity) {\n\t\tlogDiagnostic(logger, \"slack_identity_unparseable\");\n\t\treturn { status: \"needs_attention\" };\n\t}\n\tif (identity.teamId !== expected.teamId || identity.userId !== expected.botUserId || identity.botId !== expected.botId) return {\n\t\tstatus: \"needs_attention\",\n\t\treason: \"identity_mismatch\"\n\t};\n\treturn { status: \"ready\" };\n}\nfunction classifyLarkAuthStatus(payload, expected, logger = defaultValidationLogger$1) {\n\tif (!isRecord$2(payload)) {\n\t\tlogDiagnostic(logger, \"lark_payload_not_record\");\n\t\treturn { status: \"needs_attention\" };\n\t}\n\tconst failure = classifyLarkFailure(payload, logger);\n\tif (failure) return failure;\n\tconst rawSuccess = payload.code === 0;\n\tconst normalizedSuccess = payload.ok === true;\n\tif (!rawSuccess && !normalizedSuccess) {\n\t\tlogDiagnostic(logger, \"lark_success_field_invalid\");\n\t\treturn { status: \"needs_attention\" };\n\t}\n\tif (normalizedSuccess && payload.identity !== \"bot\") {\n\t\tif (typeof payload.identity === \"string\") return {\n\t\t\tstatus: \"needs_attention\",\n\t\t\treason: \"identity_mismatch\"\n\t\t};\n\t\tlogDiagnostic(logger, \"lark_identity_field_invalid\");\n\t\treturn { status: \"needs_attention\" };\n\t}\n\tconst container = normalizedSuccess && isRecord$2(payload.data) ? payload.data : payload;\n\tif (!isRecord$2(container.bot) || typeof container.bot.open_id !== \"string\" || container.bot.open_id.length === 0) {\n\t\tlogDiagnostic(logger, \"lark_bot_identity_unparseable\");\n\t\treturn { status: \"needs_attention\" };\n\t}\n\tif (container.bot.open_id !== expected.botOpenId) return {\n\t\tstatus: \"needs_attention\",\n\t\treason: \"identity_mismatch\"\n\t};\n\treturn { status: \"ready\" };\n}\nfunction classifyLarkFailure(payload, logger) {\n\tconst error = isRecord$2(payload.error) ? payload.error : void 0;\n\tconst type = normalizedField(error?.type);\n\tconst subtype = normalizedField(error?.subtype);\n\tconst code = error?.code ?? payload.code;\n\tif (hasMissingScopes(error?.missing_scopes ?? payload.missing_scopes) || type === \"authorization\" || isScopeFailure(subtype)) return {\n\t\tstatus: \"needs_attention\",\n\t\treason: \"scope_missing\"\n\t};\n\tif (isRateLimitFailure(type, subtype, code)) return {\n\t\tstatus: \"retrying\",\n\t\treason: \"rate_limited\"\n\t};\n\tif (type === \"authentication\") return {\n\t\tstatus: \"needs_attention\",\n\t\treason: \"credential_rejected\"\n\t};\n\tif (type === \"validation\" && isCliCompatibilityFailure(subtype)) return {\n\t\tstatus: \"needs_attention\",\n\t\treason: \"upgrade_required\"\n\t};\n\tif (isProviderFailure(type, subtype, code, error?.retryable)) return {\n\t\tstatus: \"retrying\",\n\t\treason: \"provider_unreachable\"\n\t};\n\treturn classifyProviderFailure([error ? void 0 : stringifyUnknown(payload.error, logger), stringifyUnknown(payload.code, logger)], payload.missing_scopes);\n}\nfunction classifyProviderFailure(errors, missingScopes, explicitMissingScope = false) {\n\tif (explicitMissingScope || hasMissingScopes(missingScopes)) return {\n\t\tstatus: \"needs_attention\",\n\t\treason: \"scope_missing\"\n\t};\n\tif (errors.some(isRateLimited)) return {\n\t\tstatus: \"retrying\",\n\t\treason: \"rate_limited\"\n\t};\n\tif (errors.some(isProviderUnreachable)) return {\n\t\tstatus: \"retrying\",\n\t\treason: \"provider_unreachable\"\n\t};\n\tif (errors.some(isCredentialRejected)) return {\n\t\tstatus: \"needs_attention\",\n\t\treason: \"credential_rejected\"\n\t};\n}\nfunction slackIdentity(payload) {\n\tif (typeof payload.team_id !== \"string\") return void 0;\n\tif (typeof payload.user_id !== \"string\") return void 0;\n\tif (typeof payload.bot_id !== \"string\") return void 0;\n\treturn {\n\t\tbotId: payload.bot_id,\n\t\tteamId: payload.team_id,\n\t\tuserId: payload.user_id\n\t};\n}\nfunction classifySpawnFailure(error) {\n\tif (isAbortError$2(error)) throw error;\n\tconst code = errorCode(error);\n\tif (code === \"ETIMEDOUT\" || code === \"TIMEOUT\") return {\n\t\tstatus: \"retrying\",\n\t\treason: \"provider_unreachable\"\n\t};\n\tif (code === \"ENETUNREACH\" || code === \"EAI_AGAIN\" || code === \"ENOTFOUND\" || code === \"ECONNRESET\") return {\n\t\tstatus: \"retrying\",\n\t\treason: \"provider_unreachable\"\n\t};\n\tconst status = httpStatus(error);\n\tif (status === 429) return {\n\t\tstatus: \"retrying\",\n\t\treason: \"rate_limited\"\n\t};\n\tif (status !== void 0 && status >= 500) return {\n\t\tstatus: \"retrying\",\n\t\treason: \"provider_unreachable\"\n\t};\n\treturn { status: \"needs_attention\" };\n}\nfunction isRecord$2(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction hasMissingScopes(value) {\n\tif (Array.isArray(value)) return value.length > 0;\n\treturn typeof value === \"string\" ? value.length > 0 : false;\n}\nfunction normalizedField(value) {\n\treturn typeof value === \"string\" && value.length > 0 ? value.toLowerCase() : void 0;\n}\nfunction isScopeFailure(subtype) {\n\treturn subtype === \"missing_scope\" || subtype === \"app_scope_not_applied\" || subtype === \"token_scope_insufficient\" || subtype === \"permission_denied\";\n}\nfunction isRateLimitFailure(type, subtype, code) {\n\treturn type === \"rate_limit\" || type === \"rate_limited\" || subtype === \"rate_limit\" || subtype === \"rate_limited\" || String(code) === \"429\";\n}\nfunction isProviderFailure(type, subtype, code, retryable) {\n\tif (retryable === true) return true;\n\tif (type === \"network\" || type === \"transport\") return true;\n\tif (subtype === \"timeout\" || subtype === \"dns\" || subtype === \"tls\" || subtype === \"server_error\" || subtype === \"service_unavailable\") return true;\n\tconst status = Number(code);\n\treturn Number.isInteger(status) && status >= 500 && status < 600;\n}\nfunction isCliCompatibilityFailure(subtype) {\n\treturn subtype === \"invalid_argument\" || subtype === \"command_unavailable\" || subtype === \"unsupported_command\" || subtype === \"unsupported_flag\";\n}\nfunction isRateLimited(error) {\n\treturn error === \"ratelimited\" || error === \"rate_limited\" || error === \"429\";\n}\nfunction isProviderUnreachable(error) {\n\tif (!error) return false;\n\tif (error === \"internal_error\" || error === \"fatal_error\" || error === \"provider_unreachable\" || error === \"service_unavailable\" || error === \"5xx\") return true;\n\tconst status = Number(error);\n\treturn Number.isInteger(status) && status >= 500 && status < 600;\n}\nfunction isCredentialRejected(error) {\n\treturn error === \"invalid_auth\" || error === \"token_revoked\" || error === \"account_inactive\" || error === \"not_authed\" || error === \"token_expired\" || error === \"invalid_token\";\n}\nfunction stringifyUnknown(value, logger) {\n\tif (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\tif (value === null || typeof value !== \"object\") return void 0;\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\tlogDiagnostic(logger, \"error_value_not_serializable\");\n\t\treturn;\n\t}\n}\nfunction errorCode(error) {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && typeof error.code === \"string\" ? error.code : void 0;\n}\nfunction httpStatus(error) {\n\tif (typeof error !== \"object\" || error === null || !(\"status\" in error)) return void 0;\n\treturn typeof error.status === \"number\" ? error.status : void 0;\n}\nfunction isAbortError$2(error) {\n\treturn typeof error === \"object\" && error !== null && \"name\" in error && error.name === \"AbortError\";\n}\nfunction logDiagnostic(logger, code) {\n\tlogger.debug({ code }, \"Provider CLI validation output rejected\");\n}\n//#endregion\n//#region src/runtime/provider-cli/validation-runner.ts\nconst execFileAsync = promisify(execFile);\nconst defaultValidationLogger = createLogger(\"provider-cli-validation\");\nconst PRIVATE_DIRS = [\n\t\"home\",\n\t\"config\",\n\t\"tmp\",\n\t\"cache\",\n\t\"state\",\n\t\"runtime\"\n];\nfunction deriveProviderCliValidationRequestKey(requestId) {\n\treturn createHash(\"sha256\").update(requestId).digest(\"hex\").slice(0, 32);\n}\nvar FeishuTokenExchangeError = class extends Error {\n\tkind;\n\tconstructor(kind) {\n\t\tsuper(\"Feishu tenant token exchange failed\");\n\t\tthis.kind = kind;\n\t\tthis.name = \"FeishuTokenExchangeError\";\n\t}\n};\nvar ProviderCliValidationRunner = class {\n\t#exchangeFeishuToken;\n\t#execFile;\n\t#home;\n\t#logger;\n\t#now;\n\t#openProxyValidation;\n\t#proxyCredentialMode;\n\t#root;\n\t#verifyTarget;\n\t#busy = false;\n\t#startupCleanup;\n\tconstructor(options) {\n\t\tthis.#exchangeFeishuToken = options.exchangeFeishuToken ?? ((grant, signal) => exchangeFeishuTenantToken(grant, signal, options.fetch ?? fetch));\n\t\tthis.#execFile = options.execFile ?? defaultExecFile;\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#openProxyValidation = options.openProxyValidation;\n\t\tthis.#proxyCredentialMode = options.proxyCredentialMode ?? false;\n\t\tthis.#verifyTarget = options.verifyTarget ?? verifyTargetFingerprint;\n\t\tconst layout = resolveOpenTagHomeLayout(options.home);\n\t\tthis.#home = layout.home;\n\t\tthis.#logger = options.logger ?? createLogger(\"provider-cli-validation\");\n\t\tthis.#root = join(layout.runtime, \"provider-cli-validation\");\n\t\tthis.#startupCleanup = this.cleanupAll();\n\t}\n\tasync run(request, fence, signal) {\n\t\tawait this.#startupCleanup;\n\t\tsignal?.throwIfAborted();\n\t\tif (this.#proxyCredentialMode) return this.#runProxyValidation(request, fence, signal);\n\t\tif (Date.parse(request.expiresAt) <= this.#now()) return {\n\t\t\t...fence,\n\t\t\tstatus: \"retrying\",\n\t\t\treason: \"validation_expired\"\n\t\t};\n\t\tif (this.#busy) return {\n\t\t\t...fence,\n\t\t\tstatus: \"retrying\",\n\t\t\treason: \"validation_busy\"\n\t\t};\n\t\tthis.#busy = true;\n\t\tconst requestKey = deriveProviderCliValidationRequestKey(request.requestId);\n\t\tconst workDir = join(this.#root, requestKey);\n\t\ttry {\n\t\t\tawait this.#prepareWorkDirectory(workDir);\n\t\t\tif (!await this.#verifyTarget(request)) return {\n\t\t\t\t...fence,\n\t\t\t\tstatus: \"retrying\",\n\t\t\t\treason: \"artifact_changed\"\n\t\t\t};\n\t\t\tif (Date.parse(request.expiresAt) <= this.#now()) return {\n\t\t\t\t...fence,\n\t\t\t\tstatus: \"retrying\",\n\t\t\t\treason: \"validation_expired\"\n\t\t\t};\n\t\t\tconst env = scrubbedEnvironment(workDir, findProviderCliCatalogEntry(fence.provider)?.managedEnvironment ?? {});\n\t\t\tif (!request.grant) return {\n\t\t\t\t...fence,\n\t\t\t\tstatus: \"needs_attention\"\n\t\t\t};\n\t\t\treturn validationResult(fence, await this.#classifyRequest(request, env, workDir, signal));\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"validation_run_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Provider CLI validation run failed\");\n\t\t\treturn validationFailureResult(fence, error, signal);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait rm(workDir, {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tforce: true\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tthis.#busy = false;\n\t\t\t}\n\t\t}\n\t}\n\tasync #prepareWorkDirectory(workDir) {\n\t\tawait rm(workDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t\tawait ensurePrivateDirectory(this.#home, workDir);\n\t\tawait chmod(workDir, 448);\n\t\tawait Promise.all(PRIVATE_DIRS.map((child) => mkdir(join(workDir, child), { mode: 448 })));\n\t}\n\t/**\n\t* Proxy readiness: open a Server-issued validation execution with read-only identity\n\t* scope, run the same native identity probe with the execution-local environment, and\n\t* always release the execution before reporting. Missing validation authority is an\n\t* explicit `needs_attention`; raw grant material is never used.\n\t*/\n\tasync #runProxyValidation(request, fence, signal) {\n\t\tconst open = this.#openProxyValidation;\n\t\tif (!open) return {\n\t\t\t...fence,\n\t\t\tstatus: \"needs_attention\"\n\t\t};\n\t\tif (!request.validationRunId) return {\n\t\t\t...fence,\n\t\t\tstatus: \"needs_attention\"\n\t\t};\n\t\tif (Date.parse(request.expiresAt) <= this.#now()) return {\n\t\t\t...fence,\n\t\t\tstatus: \"retrying\",\n\t\t\treason: \"validation_expired\"\n\t\t};\n\t\tif (this.#busy) return {\n\t\t\t...fence,\n\t\t\tstatus: \"retrying\",\n\t\t\treason: \"validation_busy\"\n\t\t};\n\t\tthis.#busy = true;\n\t\tconst requestKey = deriveProviderCliValidationRequestKey(request.requestId);\n\t\tconst workDir = join(this.#root, requestKey);\n\t\tlet session;\n\t\ttry {\n\t\t\tawait this.#prepareWorkDirectory(workDir);\n\t\t\tif (!await this.#verifyTarget(request)) return {\n\t\t\t\t...fence,\n\t\t\t\tstatus: \"retrying\",\n\t\t\t\treason: \"artifact_changed\"\n\t\t\t};\n\t\t\tsession = await open(request, signal);\n\t\t\tif (!session) return {\n\t\t\t\t...fence,\n\t\t\t\tstatus: \"needs_attention\"\n\t\t\t};\n\t\t\tconst combinedSignal = combineSignals(signal, session.signal);\n\t\t\tcombinedSignal?.throwIfAborted();\n\t\t\tconst env = scrubbedEnvironment(workDir, findProviderCliCatalogEntry(fence.provider)?.managedEnvironment ?? {});\n\t\t\tfor (const [key, value] of Object.entries(session.environment)) if (value === void 0) delete env[key];\n\t\t\telse env[key] = value;\n\t\t\treturn validationResult(fence, await this.#classifyProxyRequest(fence.provider, request, env, workDir, session.arguments ?? [], combinedSignal));\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"validation_run_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Provider CLI proxy validation run failed\");\n\t\t\treturn validationFailureResult(fence, error, signal);\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait session?.cleanup().catch((error) => {\n\t\t\t\t\tthis.#logger.debug({\n\t\t\t\t\t\tcode: \"validation_session_cleanup_failed\",\n\t\t\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t\t\t}, \"Proxy validation session cleanup failed\");\n\t\t\t\t});\n\t\t\t\tawait rm(workDir, {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tforce: true\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tthis.#busy = false;\n\t\t\t}\n\t\t}\n\t}\n\t/** Read-only identity probes only; the Server enforces the validation purpose scope. */\n\tasync #classifyProxyRequest(provider, request, env, workDir, extraArguments, signal) {\n\t\tif (provider === \"slack\") return this.#runProcess(request.targetPath, [\n\t\t\t\"--skip-update\",\n\t\t\t\"--config-dir\",\n\t\t\tjoin(workDir, \"config\"),\n\t\t\t...extraArguments,\n\t\t\t\"api\",\n\t\t\t\"auth.test\"\n\t\t], env, workDir, (payload) => classifySlackAuthTest(payload, request.expectedIdentity, this.#logger), signal);\n\t\tif (provider === \"feishu\" && request.expectedIdentity.provider === \"feishu\") return this.#runProcess(request.targetPath, [\n\t\t\t\"api\",\n\t\t\t\"GET\",\n\t\t\t\"/open-apis/bot/v3/info\",\n\t\t\t\"--as\",\n\t\t\t\"bot\",\n\t\t\t\"--format\",\n\t\t\t\"ndjson\",\n\t\t\t...extraArguments\n\t\t], env, workDir, (payload) => classifyLarkAuthStatus(payload, request.expectedIdentity, this.#logger), signal);\n\t\treturn { status: \"needs_attention\" };\n\t}\n\tasync #classifyRequest(request, env, workDir, signal) {\n\t\tif (request.grant.provider === \"slack\") {\n\t\t\tenv.SLACK_BOT_TOKEN = request.grant.botAccessToken;\n\t\t\treturn this.#runProcess(request.targetPath, [\n\t\t\t\t\"--skip-update\",\n\t\t\t\t\"--config-dir\",\n\t\t\t\tjoin(workDir, \"config\"),\n\t\t\t\t\"api\",\n\t\t\t\t\"auth.test\"\n\t\t\t], env, workDir, (payload) => classifySlackAuthTest(payload, request.expectedIdentity, this.#logger), signal);\n\t\t}\n\t\treturn this.#classifyFeishuRequest(request, env, workDir, signal);\n\t}\n\tasync #classifyFeishuRequest(request, env, workDir, signal) {\n\t\tif (request.grant.provider !== \"feishu\") return { status: \"needs_attention\" };\n\t\tif (request.expectedIdentity.provider !== \"feishu\") return {\n\t\t\tstatus: \"needs_attention\",\n\t\t\treason: \"identity_mismatch\"\n\t\t};\n\t\tconst expectedIdentity = request.expectedIdentity;\n\t\tif (request.grant.appId !== expectedIdentity.appId || request.grant.teamBrand !== expectedIdentity.teamBrand) return {\n\t\t\tstatus: \"needs_attention\",\n\t\t\treason: \"identity_mismatch\"\n\t\t};\n\t\tconst tenantAccessToken = await this.#exchangeFeishuToken(request.grant, signal);\n\t\tif (Date.parse(request.expiresAt) <= this.#now()) return {\n\t\t\tstatus: \"retrying\",\n\t\t\treason: \"validation_expired\"\n\t\t};\n\t\tenv.LARKSUITE_CLI_APP_ID = request.grant.appId;\n\t\tenv.LARKSUITE_CLI_CONFIG_DIR = join(workDir, \"config\");\n\t\tenv.LARKSUITE_CLI_BRAND = request.grant.teamBrand;\n\t\tenv.LARKSUITE_CLI_TENANT_ACCESS_TOKEN = tenantAccessToken;\n\t\tdelete env.LARKSUITE_CLI_APP_SECRET;\n\t\tdelete env.LARKSUITE_CLI_USER_ACCESS_TOKEN;\n\t\treturn this.#runProcess(request.targetPath, [\n\t\t\t\"api\",\n\t\t\t\"GET\",\n\t\t\t\"/open-apis/bot/v3/info\",\n\t\t\t\"--as\",\n\t\t\t\"bot\",\n\t\t\t\"--format\",\n\t\t\t\"ndjson\"\n\t\t], env, workDir, (payload) => classifyLarkAuthStatus(payload, expectedIdentity, this.#logger), signal);\n\t}\n\tasync cleanupAll() {\n\t\tlet names = [];\n\t\ttry {\n\t\t\tnames = await readdir(this.#root);\n\t\t} catch (error) {\n\t\t\tif (error.code === \"ENOENT\") return;\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"validation_cleanup_scan_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Provider CLI validation cleanup scan failed\");\n\t\t\tthrow error;\n\t\t}\n\t\tif ((await Promise.allSettled(names.map((name) => rm(join(this.#root, name), {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t})))).some((result) => result.status === \"rejected\")) throw new Error(\"Provider CLI validation cleanup failed\");\n\t}\n\tasync #runProcess(targetPath, args, env, cwd, classify, signal) {\n\t\tif (!isAbsolute(targetPath)) return { status: \"needs_attention\" };\n\t\tsignal?.throwIfAborted();\n\t\ttry {\n\t\t\treturn classifyProcessOutput(await this.#execFile(targetPath, args, {\n\t\t\t\tcwd,\n\t\t\t\tenv,\n\t\t\t\tmaxBuffer: RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES,\n\t\t\t\ttimeout: RUNTIME_PROVIDER_CLI_VALIDATION_TIMEOUT_MS,\n\t\t\t\twindowsHide: true,\n\t\t\t\t...signal ? { signal } : {}\n\t\t\t}), classify, this.#logger);\n\t\t} catch (error) {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"validation_process_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Provider CLI validation process failed\");\n\t\t\treturn classifyProcessFailure(error, signal, classify, this.#logger);\n\t\t}\n\t}\n};\nfunction combineSignals(first, second) {\n\tif (first && second) return AbortSignal.any([first, second]);\n\treturn first ?? second;\n}\nfunction validationResult(fence, classification) {\n\tif (classification.status === \"ready\") return {\n\t\t...fence,\n\t\tstatus: \"ready\"\n\t};\n\treturn {\n\t\t...fence,\n\t\tstatus: classification.status,\n\t\t...classification.reason ? { reason: classification.reason } : {}\n\t};\n}\nfunction validationFailureResult(fence, error, signal) {\n\tif (isAbortError$1(error) || signal?.aborted) throw abortError$1();\n\tif (!(error instanceof FeishuTokenExchangeError)) return validationResult(fence, classifySpawnFailure(error));\n\tif (error.kind === \"aborted\") throw abortError$1();\n\tif (error.kind === \"rate_limited\") return {\n\t\t...fence,\n\t\tstatus: \"retrying\",\n\t\treason: \"rate_limited\"\n\t};\n\tif (error.kind === \"provider_unreachable\") return {\n\t\t...fence,\n\t\tstatus: \"retrying\",\n\t\treason: \"provider_unreachable\"\n\t};\n\tif (error.kind === \"credential_rejected\") return {\n\t\t...fence,\n\t\tstatus: \"needs_attention\",\n\t\treason: \"credential_rejected\"\n\t};\n\treturn {\n\t\t...fence,\n\t\tstatus: \"needs_attention\"\n\t};\n}\nfunction classifyProcessOutput(output, classify, logger) {\n\tif (combinedBytes(output.stdout, output.stderr) > RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES) return { status: \"needs_attention\" };\n\tconst payload = extractBoundedJson(output.stdout, RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES, logger) ?? extractBoundedJson(output.stderr, RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES, logger);\n\treturn payload === void 0 ? { status: \"needs_attention\" } : classify(payload);\n}\nfunction classifyProcessFailure(error, signal, classify, logger) {\n\tif (isAbortError$1(error) || signal?.aborted) throw abortError$1();\n\tconst output = processOutput(error);\n\tif (output && combinedBytes(output.stdout, output.stderr) > RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES) return { status: \"needs_attention\" };\n\tconst payload = extractBoundedJson(output?.stdout ?? \"\", RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES, logger) ?? extractBoundedJson(output?.stderr ?? \"\", RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES, logger);\n\tif (payload !== void 0) return classify(payload);\n\tif (isTimeout(error)) return {\n\t\tstatus: \"retrying\",\n\t\treason: \"provider_unreachable\"\n\t};\n\tthrow error;\n}\nasync function verifyTargetFingerprint(request) {\n\tif (!isAbsolute(request.targetPath)) return false;\n\ttry {\n\t\treturn computeTargetFingerprint(await computeFileIdentity(request.targetPath), request.version, request.managedDigest) === request.expectedFingerprint;\n\t} catch (error) {\n\t\tdefaultValidationLogger.debug({\n\t\t\tcode: \"validation_target_verification_failed\",\n\t\t\terror: runtimeProxyErrorReason(error)\n\t\t}, \"Provider CLI validation target verification failed\");\n\t\treturn false;\n\t}\n}\nfunction scrubbedEnvironment(workDir, managedEnvironment) {\n\tconst env = {\n\t\t...providerCliProbeEnvironment(join(workDir, \"home\")),\n\t\t...managedEnvironment,\n\t\tXDG_CONFIG_HOME: join(workDir, \"config\"),\n\t\tXDG_CACHE_HOME: join(workDir, \"cache\"),\n\t\tXDG_STATE_HOME: join(workDir, \"state\"),\n\t\tXDG_RUNTIME_DIR: join(workDir, \"runtime\"),\n\t\tTMPDIR: join(workDir, \"tmp\"),\n\t\tTMP: join(workDir, \"tmp\"),\n\t\tTEMP: join(workDir, \"tmp\")\n\t};\n\tfor (const key of [\n\t\t\"SLACK_BOT_TOKEN\",\n\t\t\"SLACK_USER_TOKEN\",\n\t\t\"SLACK_APP_TOKEN\",\n\t\t\"SLACK_CONFIG_DIR\",\n\t\t\"LARKSUITE_CLI_APP_ID\",\n\t\t\"LARKSUITE_CLI_APP_SECRET\",\n\t\t\"LARKSUITE_CLI_TENANT_ACCESS_TOKEN\",\n\t\t\"LARKSUITE_CLI_USER_ACCESS_TOKEN\",\n\t\t\"LARKSUITE_CLI_CONFIG_DIR\"\n\t]) delete env[key];\n\treturn env;\n}\nfunction combinedBytes(stdout, stderr) {\n\treturn Buffer.byteLength(stdout) + Buffer.byteLength(stderr);\n}\nfunction processOutput(error) {\n\tif (typeof error !== \"object\" || error === null) return void 0;\n\treturn {\n\t\tstdout: \"stdout\" in error && typeof error.stdout === \"string\" ? error.stdout : \"\",\n\t\tstderr: \"stderr\" in error && typeof error.stderr === \"string\" ? error.stderr : \"\"\n\t};\n}\nfunction isTimeout(error) {\n\treturn typeof error === \"object\" && error !== null && \"killed\" in error && error.killed === true;\n}\nfunction isAbortError$1(error) {\n\treturn typeof error === \"object\" && error !== null && \"name\" in error && error.name === \"AbortError\" || error instanceof Error && error.message === \"The operation was aborted\";\n}\nfunction abortError$1() {\n\tconst error = /* @__PURE__ */ new Error(\"The operation was aborted\");\n\terror.name = \"AbortError\";\n\treturn error;\n}\nasync function defaultExecFile(file, args, options) {\n\tconst result = await execFileAsync(file, [...args], {\n\t\tcwd: options.cwd,\n\t\tencoding: \"utf8\",\n\t\tenv: options.env,\n\t\tmaxBuffer: options.maxBuffer,\n\t\ttimeout: options.timeout,\n\t\twindowsHide: options.windowsHide,\n\t\t...options.signal ? { signal: options.signal } : {}\n\t});\n\treturn {\n\t\tstdout: result.stdout,\n\t\tstderr: result.stderr\n\t};\n}\nasync function exchangeFeishuTenantToken(grant, signal, fetchImpl = fetch, timeoutMs = RUNTIME_PROVIDER_CLI_VALIDATION_TIMEOUT_MS) {\n\tif (signal?.aborted) throw new FeishuTokenExchangeError(\"aborted\");\n\tconst timeout = AbortSignal.timeout(timeoutMs);\n\tconst combined = signal ? AbortSignal.any([signal, timeout]) : timeout;\n\tconst origin = grant.teamBrand === \"lark\" ? \"https://open.larksuite.com\" : \"https://open.feishu.cn\";\n\tlet response;\n\ttry {\n\t\tresponse = await fetchImpl(`${origin}/open-apis/auth/v3/tenant_access_token/internal`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({\n\t\t\t\tapp_id: grant.appId,\n\t\t\t\tapp_secret: grant.appSecret\n\t\t\t}),\n\t\t\tsignal: combined\n\t\t});\n\t} catch (error) {\n\t\tdefaultValidationLogger.debug({\n\t\t\tcode: \"feishu_token_exchange_request_failed\",\n\t\t\terror: runtimeProxyErrorReason(error)\n\t\t}, \"Feishu tenant token exchange request failed\");\n\t\tif (combined.aborted && signal?.aborted) throw new FeishuTokenExchangeError(\"aborted\");\n\t\tthrow new FeishuTokenExchangeError(\"provider_unreachable\");\n\t}\n\tif (response.status === 429) throw new FeishuTokenExchangeError(\"rate_limited\");\n\tif (response.status >= 500) throw new FeishuTokenExchangeError(\"provider_unreachable\");\n\tconst buffer = await readBoundedResponseBody(response, RUNTIME_PROVIDER_CLI_VALIDATION_MAX_OUTPUT_BYTES);\n\tlet body;\n\ttry {\n\t\tbody = JSON.parse(new TextDecoder().decode(buffer));\n\t} catch (error) {\n\t\tdefaultValidationLogger.debug({\n\t\t\tcode: \"feishu_token_exchange_invalid_json\",\n\t\t\terror: runtimeProxyErrorReason(error)\n\t\t}, \"Feishu tenant token exchange response was invalid\");\n\t\tthrow new FeishuTokenExchangeError(response.status >= 500 ? \"provider_unreachable\" : \"invalid\");\n\t}\n\tif (!response.ok) throw new FeishuTokenExchangeError(\"credential_rejected\");\n\tif (!isRecord$1(body) || body.code !== 0 || typeof body.tenant_access_token !== \"string\") throw new FeishuTokenExchangeError(\"credential_rejected\");\n\treturn body.tenant_access_token;\n}\nasync function readBoundedResponseBody(response, maxBytes) {\n\tif (!response.body) return /* @__PURE__ */ new Uint8Array();\n\tconst reader = response.body.getReader();\n\tconst chunks = [];\n\tlet total = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) throw new FeishuTokenExchangeError(\"invalid\");\n\t\t\tchunks.push(value);\n\t\t}\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\tconst body = new Uint8Array(total);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tbody.set(chunk, offset);\n\t\toffset += chunk.byteLength;\n\t}\n\treturn body;\n}\nfunction isRecord$1(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n//#endregion\n//#region src/runtime/runtime-credential-environment-manager.ts\n/**\n* Runtime credential environment lifecycle with explicit proxy mode. Proxy mode opens\n* a trusted execution through the control connection, holds short-lived capabilities\n* only inside the trusted Relay, and materializes execution-local handles, CA, CLI\n* config, and shims for the Sandbox. Legacy mode delegates to the existing IM\n* credential environment manager unchanged.\n*/\nvar RuntimeCredentialEnvironmentManager = class {\n\t#legacy;\n\t#logger;\n\t#mode;\n\t#options;\n\t#platform;\n\t#proxyExecutions = /* @__PURE__ */ new Map();\n\t#store;\n\t#startupCleanup;\n\t#closed = false;\n\tconstructor(options) {\n\t\tthis.#options = options;\n\t\tthis.#mode = options.mode ?? \"legacy\";\n\t\tthis.#platform = options.platform ?? process.platform;\n\t\tthis.#logger = options.logger ?? createLogger(\"runtime-credential-environment\");\n\t\tif (this.#mode === \"legacy\") this.#legacy = (options.legacy ?? ((legacyOptions) => new ImCredentialEnvironmentManager(legacyOptions)))({\n\t\t\tconnection: options.connection,\n\t\t\thome: options.home,\n\t\t\tlogger: options.logger,\n\t\t\t...options.platform ? { platform: options.platform } : {}\n\t\t});\n\t\tif (this.#mode === \"proxy\") {\n\t\t\tif (!options.serverUrl) throw new ImCredentialEnvironmentError(\"proxy_configuration_missing\");\n\t\t\tif (this.#platform === \"win32\") throw new ImCredentialEnvironmentError(\"proxy_platform_unsupported\");\n\t\t\tthis.#store = new RuntimeProxyMaterialStore({ home: options.home });\n\t\t\tthis.#startupCleanup = this.#store.cleanupStale().then(() => void 0, () => new ImCredentialEnvironmentError(\"stale_cleanup_failed\"));\n\t\t}\n\t}\n\tget mode() {\n\t\treturn this.#mode;\n\t}\n\tpathForSession(sessionId) {\n\t\tif (this.#mode === \"proxy\") return this.#requireStore().environmentFilePath(sessionId);\n\t\treturn this.#requireLegacy().pathForSession(sessionId);\n\t}\n\tactiveSlackConfigDirForSession(sessionId) {\n\t\tif (this.#mode === \"proxy\") return this.#proxyExecutions.get(sessionId)?.slackConfigDir;\n\t\treturn this.#requireLegacy().activeSlackConfigDirForSession(sessionId);\n\t}\n\t/** Proxy shim directory prepended to the Session PATH in proxy mode. */\n\tshimDirForSession(sessionId) {\n\t\tif (this.#mode !== \"proxy\") return void 0;\n\t\treturn this.#requireStore().shimDir(sessionId);\n\t}\n\t/**\n\t* Current execution CLI env map (defined values) for the Agent runtime: execution-scoped\n\t* handles and routing inputs only, never the standard proxy/CA variables. Provider CLI\n\t* children derive those from the same execution through `providerRoutingEnvironment`.\n\t*/\n\tenvironmentForSession(sessionId) {\n\t\tconst active = this.#proxyExecutions.get(sessionId);\n\t\tif (!active) return void 0;\n\t\treturn Object.fromEntries(Object.entries(active.environment).flatMap(([key, value]) => value === void 0 ? [] : [[key, value]]));\n\t}\n\t/**\n\t* Raw execution environment for trusted host-side CLI children (for example Context Tree Git).\n\t* The standard proxy/CA variables are derived here because these consumers are allowed to use\n\t* the credential proxy; the Agent runtime environment intentionally never receives them. Unlike\n\t* `environmentForSession`, `undefined` entries are preserved so a caller can unset inherited\n\t* ambient credentials (for example a daemon-level `GITHUB_TOKEN`). Legacy mode returns\n\t* `undefined`; the returned map is valid only for the current execution.\n\t*/\n\texecutionEnvironmentForSession(sessionId) {\n\t\tconst environment = this.#proxyExecutions.get(sessionId)?.environment;\n\t\tif (!environment) return void 0;\n\t\treturn {\n\t\t\t...environment,\n\t\t\t...providerRoutingEnvironment(environment)\n\t\t};\n\t}\n\t/** Current execution id for a Session, when a proxy execution is active. */\n\texecutionIdForSession(sessionId) {\n\t\treturn this.#proxyExecutions.get(sessionId)?.executionId;\n\t}\n\t/** Trusted web tools launch facts for the Session's live execution, when authorized and started. */\n\twebToolsForSession(sessionId) {\n\t\treturn this.#proxyExecutions.get(sessionId)?.web;\n\t}\n\tasync prepare(request, signal) {\n\t\tif (this.#mode === \"legacy\") {\n\t\t\tconst prepared = await this.#requireLegacy().prepare(request, signal);\n\t\t\treturn {\n\t\t\t\t...prepared,\n\t\t\t\tproviders: [prepared.provider]\n\t\t\t};\n\t\t}\n\t\treturn this.#prepareProxy(request, signal);\n\t}\n\t/**\n\t* Open a Server-authorized validation execution through the same Relay/data path as a\n\t* business Run. Raw grant material is never accepted; the local adapter only receives\n\t* execution-local handles and the loopback CA. Release with `cleanup()` before reporting.\n\t*/\n\tasync prepareValidationSession(request, signal) {\n\t\tif (this.#mode !== \"proxy\") throw new ImCredentialEnvironmentError(\"proxy_negotiation_unavailable\");\n\t\tconst sessionId = `validation:${request.validationRunId}`;\n\t\tconst prepared = await this.#prepareProxy({\n\t\t\tagentId: request.agentId,\n\t\t\tplacementGeneration: request.placementGeneration,\n\t\t\tsessionId,\n\t\t\trun: {\n\t\t\t\trunId: request.validationRunId,\n\t\t\t\tsource: {\n\t\t\t\t\tkind: \"validation\",\n\t\t\t\t\tvalidationRunId: request.validationRunId\n\t\t\t\t}\n\t\t\t}\n\t\t}, signal);\n\t\tconst executionId = prepared.executionId;\n\t\tif (!executionId) throw new ImCredentialEnvironmentError(\"proxy_unavailable\");\n\t\tconst active = this.#proxyExecutions.get(sessionId);\n\t\tconst environment = {\n\t\t\t...this.environmentForSession(sessionId) ?? {},\n\t\t\t...providerRoutingEnvironment(active?.environment ?? {})\n\t\t};\n\t\treturn {\n\t\t\targuments: active?.slackApiHost !== void 0 ? [\"--apihost\", active.slackApiHost] : [],\n\t\t\tenvironment,\n\t\t\texecutionId,\n\t\t\tsignal: prepared.signal ?? new AbortController().signal,\n\t\t\t...active?.slackApiHost ? { slackApiHost: active.slackApiHost } : {},\n\t\t\tcleanup: async () => {\n\t\t\t\tawait this.cleanup(sessionId, executionId).catch(() => void 0);\n\t\t\t}\n\t\t};\n\t}\n\tasync cleanup(sessionId, executionId) {\n\t\tif (this.#mode === \"legacy\") return this.#requireLegacy().cleanup(sessionId);\n\t\tconst active = this.#proxyExecutions.get(sessionId);\n\t\tif (executionId !== void 0 && active && active.executionId !== executionId) return;\n\t\tconst targetExecutionId = executionId ?? active?.executionId;\n\t\tif (active) {\n\t\t\tthis.#proxyExecutions.delete(sessionId);\n\t\t\tawait this.#closeActive(active);\n\t\t}\n\t\tconst store = this.#requireStore();\n\t\tif (targetExecutionId !== void 0) {\n\t\t\tawait store.cleanupExecution(sessionId, targetExecutionId);\n\t\t\treturn;\n\t\t}\n\t\tawait store.cleanupSession(sessionId);\n\t}\n\tasync close() {\n\t\tif (this.#closed) return;\n\t\tthis.#closed = true;\n\t\tif (this.#mode === \"legacy\") return this.#requireLegacy().close();\n\t\tconst startupFailure = await this.#startupCleanup;\n\t\tconst sessions = [...this.#proxyExecutions.keys()];\n\t\tawait Promise.all(sessions.map((sessionId) => this.cleanup(sessionId)));\n\t\tif (startupFailure) throw startupFailure;\n\t}\n\tasync #prepareProxy(request, signal) {\n\t\tif (this.#closed) throw new ImCredentialEnvironmentError(\"client_shutdown\");\n\t\tconst startupFailure = await this.#startupCleanup;\n\t\tif (startupFailure) throw startupFailure;\n\t\tthis.#assertProxyNegotiation();\n\t\tif (!request.run) throw new ImCredentialEnvironmentError(\"execution_source_required\");\n\t\tthis.#requireStore();\n\t\tconst relay = await this.#openProxyRelay(request, request.run, signal);\n\t\ttry {\n\t\t\treturn await this.#materializeProxyExecution(request.sessionId, relay, signal);\n\t\t} catch (error) {\n\t\t\tawait relay.close(\"materialization_failed\").catch(() => void 0);\n\t\t\tthrow toEnvironmentError(error);\n\t\t}\n\t}\n\t/** Explicit negotiation gate: unsupported Cloud/proxy can never fall back to raw material. */\n\t#assertProxyNegotiation() {\n\t\tconst connection = this.#options.connection;\n\t\tif (connection.capabilityVersion(RUNTIME_CREDENTIAL_CAPABILITY) !== 1 || connection.capabilityVersion(RUNTIME_PROVIDER_PROXY_CAPABILITY) !== 1) throw new ImCredentialEnvironmentError(\"proxy_negotiation_unavailable\");\n\t}\n\t/**\n\t* Platform service opt-in, one entry per service whose own capability the Server negotiated.\n\t*\n\t* Web additionally requires a deployment opt-in, because it spends a Router tenant key. MCP needs\n\t* none: binding a Server in the web UI is the opt-in, and the Server still refuses the grant when\n\t* the Agent has nothing mounted.\n\t*/\n\t#requestedProxyServices() {\n\t\tconst services = [];\n\t\tif (this.#options.webTools && this.#options.connection.capabilityVersion(RUNTIME_WEB_TOOLS_CAPABILITY) === 1) services.push(\"web\");\n\t\tif (this.#options.connection.capabilityVersion(RUNTIME_MCP_GATEWAY_CAPABILITY) === 1) services.push(\"mcp\");\n\t\treturn services.length > 0 ? services : void 0;\n\t}\n\t/**\n\t* Fetch this execution's MCP gateway bearer, if the Server granted the service.\n\t*\n\t* Soft-fails for the same reason the web gateway does: losing MCP tools must never cost the Agent\n\t* its turn. The URL is composed against the pinned Server origin, never taken from the Server.\n\t*/\n\tasync #prepareMcpGateway(relay) {\n\t\tconst serverUrl = this.#options.serverUrl;\n\t\tif (!serverUrl) return void 0;\n\t\ttry {\n\t\t\tconst granted = await relay.acquireMcpGatewayToken();\n\t\t\tif (!granted) return void 0;\n\t\t\treturn {\n\t\t\t\turl: new URL(MCP_GATEWAY_PATH$1, serverUrl).toString(),\n\t\t\t\ttoken: granted.token\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"mcp_gateway_unavailable\",\n\t\t\t\treason: runtimeProxyErrorReason(error)\n\t\t\t}, \"The MCP gateway could not be prepared for this execution\");\n\t\t\treturn;\n\t\t}\n\t}\n\tasync #openProxyRelay(request, run, signal) {\n\t\tconst sandbox = this.#options.sandboxForSession?.(request.sessionId);\n\t\tconst requestedServices = this.#requestedProxyServices();\n\t\ttry {\n\t\t\treturn await RuntimeCredentialRelay.open({\n\t\t\t\tconnection: this.#options.connection,\n\t\t\t\t...this.#options.dataConnectionFactory ? { dataConnectionFactory: this.#options.dataConnectionFactory } : {},\n\t\t\t\tlogger: this.#logger,\n\t\t\t\t...this.#options.now ? { now: this.#options.now } : {},\n\t\t\t\t...this.#options.openBudgetMs ? { openBudgetMs: this.#options.openBudgetMs } : {},\n\t\t\t\t...this.#options.scheduler ? { scheduler: this.#options.scheduler } : {},\n\t\t\t\tserverUrl: this.#options.serverUrl ?? \"\"\n\t\t\t}, {\n\t\t\t\tagentId: request.agentId,\n\t\t\t\tplacementGeneration: request.placementGeneration,\n\t\t\t\trunId: run.runId,\n\t\t\t\tsessionId: request.sessionId,\n\t\t\t\tsource: run.source,\n\t\t\t\t...sandbox ? { sandbox } : {},\n\t\t\t\t...requestedServices ? { services: [...requestedServices] } : {}\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthrow toEnvironmentError(error);\n\t\t}\n\t}\n\tasync #materializeProxyExecution(sessionId, relay, signal) {\n\t\tconst store = this.#requireStore();\n\t\tawait this.#closeReplacedProxyExecution(sessionId, store);\n\t\tsignal?.throwIfAborted();\n\t\tconst layout = store.executionLayout(sessionId, relay.executionId);\n\t\tconst handles = collectProxyHandles(relay);\n\t\tconst adapter = await this.#startProxyAdapter(relay, layout);\n\t\ttry {\n\t\t\tconst active = await this.#activateProxyExecution(sessionId, relay, store, layout, handles, adapter);\n\t\t\treturn this.#preparedProxyResult(sessionId, relay, store, active);\n\t\t} catch (error) {\n\t\t\tawait adapter.close().catch(() => void 0);\n\t\t\tawait store.cleanupExecution(sessionId, relay.executionId).catch(() => void 0);\n\t\t\tthrow error;\n\t\t}\n\t}\n\t/** One active execution per Session: close the replaced execution and its material first. */\n\tasync #closeReplacedProxyExecution(sessionId, store) {\n\t\tconst previous = this.#proxyExecutions.get(sessionId);\n\t\tif (!previous) return;\n\t\tthis.#proxyExecutions.delete(sessionId);\n\t\tawait this.#closeActive(previous);\n\t\tawait store.cleanupExecution(sessionId, previous.executionId);\n\t}\n\tasync #startProxyAdapter(relay, layout) {\n\t\treturn RuntimeProxyLoopbackAdapter.start({\n\t\t\texecutionId: relay.executionId,\n\t\t\t...this.#options.generateCa ? { generateCa: this.#options.generateCa } : {},\n\t\t\tlocalHandleFor: (provider) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn relay.localHandleFor(provider);\n\t\t\t\t} catch {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t},\n\t\t\tlogger: this.#logger,\n\t\t\tmaterialDir: layout.executionDir,\n\t\t\topenStream: (request) => relay.openProviderStream(request),\n\t\t\tverifyHandle: (provider, handle) => relay.verifyLocalHandle(provider, handle)\n\t\t});\n\t}\n\tasync #activateProxyExecution(sessionId, relay, store, layout, handles, adapter) {\n\t\tconst environment = buildRuntimeProxyEnvironment({\n\t\t\tadapterCaCertPath: adapter.caCertPath,\n\t\t\tcliMetadata: (provider) => relay.cliMetadataFor(provider),\n\t\t\tconnectProxyUrl: adapter.connectProxyUrl,\n\t\t\thandles,\n\t\t\tlayout,\n\t\t\tslackApiHost: adapter.slackApiHost\n\t\t});\n\t\tawait store.publish({\n\t\t\tadapterCaCertPath: adapter.caCertPath,\n\t\t\tenvironment,\n\t\t\texecutionId: relay.executionId,\n\t\t\thandles,\n\t\t\tplatform: this.#platform,\n\t\t\tsessionId\n\t\t});\n\t\tconst providers = relay.providers.map((provider) => provider.provider);\n\t\tconst imProvider = providers.includes(\"feishu\") ? \"feishu\" : providers.includes(\"slack\") ? \"slack\" : void 0;\n\t\tconst outboxContext = imProvider ? runtimeProxyOutboxContext(relay.cliMetadataFor(imProvider)) : void 0;\n\t\tconst webGateway = await this.#startWebGateway(relay);\n\t\tconst mcp = await this.#prepareMcpGateway(relay);\n\t\tconst web = webGateway ? {\n\t\t\textensionPath: this.#options.webTools?.extensionPath ?? \"\",\n\t\t\tsocketPath: webGateway.gateway.socketPath\n\t\t} : void 0;\n\t\tconst active = {\n\t\t\tadapter,\n\t\t\tenvironment,\n\t\t\texecutionId: relay.executionId,\n\t\t\t...outboxContext ? { outboxContext } : {},\n\t\t\t...imProvider ? { provider: imProvider } : {},\n\t\t\tproviders,\n\t\t\trelay,\n\t\t\tslackApiHost: adapter.slackApiHost,\n\t\t\t...imProvider === \"slack\" ? { slackConfigDir: layout.slackConfigDir } : {},\n\t\t\t...web ? { web } : {},\n\t\t\t...mcp ? { mcp } : {},\n\t\t\t...webGateway ? {\n\t\t\t\twebGateway: webGateway.gateway,\n\t\t\t\twebSocketDirectory: webGateway.socketDirectory\n\t\t\t} : {}\n\t\t};\n\t\tthis.#proxyExecutions.set(sessionId, active);\n\t\trelay.signal.addEventListener(\"abort\", () => {\n\t\t\tif (this.#proxyExecutions.get(sessionId) === active) this.#proxyExecutions.delete(sessionId);\n\t\t\tadapter.close().catch(() => void 0);\n\t\t\tthis.#closeWebGateway(active).catch(() => void 0);\n\t\t\tstore.cleanupExecution(sessionId, active.executionId).catch(() => void 0);\n\t\t}, { once: true });\n\t\treturn active;\n\t}\n\t#preparedProxyResult(sessionId, relay, store, active) {\n\t\treturn {\n\t\t\texecutionId: relay.executionId,\n\t\t\tenvironmentManifest: store.manifestPath(sessionId),\n\t\t\t...active.outboxContext ? { outboxContext: active.outboxContext } : {},\n\t\t\tpath: store.environmentFilePath(sessionId),\n\t\t\t...active.provider ? { provider: active.provider } : {},\n\t\t\tproviders: active.providers,\n\t\t\tsignal: relay.signal,\n\t\t\tslackApiHost: active.slackApiHost,\n\t\t\t...active.slackConfigDir ? { slackConfigDir: active.slackConfigDir } : {},\n\t\t\t...active.web ? { web: active.web } : {},\n\t\t\t...active.mcp ? { mcp: active.mcp } : {}\n\t\t};\n\t}\n\t/**\n\t* Start the per-execution web gateway when the Server granted web scopes to this execution.\n\t* Every execution owns a fresh, short, private socket directory (mkdtemp under the OS temp\n\t* root, never a long Session storage path), so a stale descriptor from an earlier execution\n\t* can never reach a successor and a late close can never unlink a successor socket. A start\n\t* failure keeps the execution usable without web tools (the tools simply never register).\n\t*/\n\tasync #startWebGateway(relay) {\n\t\tconst options = this.#options.webTools;\n\t\tif (!options) return void 0;\n\t\tconst webGrant = relay.services.find((service) => service.service === \"web\");\n\t\tif (!webGrant || webGrant.scopes.length === 0) return void 0;\n\t\tconst client = new WebToolsServerClient({\n\t\t\tserverUrl: this.#options.serverUrl ?? \"\",\n\t\t\tbearerToken: options.bearerToken,\n\t\t\t...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}\n\t\t});\n\t\tlet socketDirectory;\n\t\ttry {\n\t\t\tconst allocated = await allocateWebGatewaySocket();\n\t\t\tsocketDirectory = allocated.directory;\n\t\t\treturn {\n\t\t\t\tgateway: await WebToolsGatewayServer.start({\n\t\t\t\t\tsocketPath: allocated.socketPath,\n\t\t\t\t\tdispatch: createExecutionWebDispatch({\n\t\t\t\t\t\tclient,\n\t\t\t\t\t\texecutionId: relay.executionId\n\t\t\t\t\t})\n\t\t\t\t}),\n\t\t\t\tsocketDirectory\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (socketDirectory) await rm(socketDirectory, {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true\n\t\t\t}).catch(() => void 0);\n\t\t\tthis.#logger.warn({\n\t\t\t\tcode: \"web_gateway_start_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"The web tools gateway could not start\");\n\t\t\treturn;\n\t\t}\n\t}\n\t/** Close one execution's gateway and remove only that execution's private socket directory. */\n\tasync #closeWebGateway(active) {\n\t\tawait active.webGateway?.close().catch(() => void 0);\n\t\tif (active.webSocketDirectory) await rm(active.webSocketDirectory, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t}).catch(() => void 0);\n\t}\n\tasync #closeActive(active) {\n\t\tawait this.#closeWebGateway(active);\n\t\tawait active.adapter.close().catch(() => void 0);\n\t\tawait active.relay.close(\"cleanup\").catch((error) => {\n\t\t\tthis.#logger.debug({\n\t\t\t\tcode: \"proxy_execution_close_failed\",\n\t\t\t\terror: runtimeProxyErrorReason(error)\n\t\t\t}, \"Proxy execution close failed\");\n\t\t});\n\t}\n\t#requireLegacy() {\n\t\tif (!this.#legacy) throw new ImCredentialEnvironmentError(\"proxy_configuration_missing\");\n\t\treturn this.#legacy;\n\t}\n\t#requireStore() {\n\t\tif (!this.#store) throw new ImCredentialEnvironmentError(\"proxy_configuration_missing\");\n\t\treturn this.#store;\n\t}\n};\nfunction collectProxyHandles(relay) {\n\tconst handles = /* @__PURE__ */ new Map();\n\tfor (const provider of relay.providers) handles.set(provider.provider, relay.localHandleFor(provider.provider));\n\treturn handles;\n}\nfunction toEnvironmentError(error) {\n\tif (error instanceof ImCredentialEnvironmentError) return error;\n\tif (error instanceof RuntimeCredentialRelayError) {\n\t\tconst code = error.code === \"execution_rejected\" || error.code === \"acquire_failed\" || error.code === \"ticket_failed\" ? \"execution_rejected\" : error.code === \"execution_not_ready\" || error.code === \"execution_timeout\" ? \"execution_not_ready\" : error.code === \"aborted\" ? \"aborted\" : \"proxy_unavailable\";\n\t\treturn new ImCredentialEnvironmentError(code);\n\t}\n\treturn new ImCredentialEnvironmentError(\"proxy_unavailable\");\n}\n//#endregion\n//#region src/runtime/server-runtime-durability-store.ts\n/** Runtime durability adapter backed by the authenticated Computer's Server rows. */\nvar ServerRuntimeDurabilityStore = class {\n\t#api;\n\t#machineToken;\n\t#now;\n\tconstructor(options) {\n\t\tthis.#api = options.api;\n\t\tthis.#machineToken = options.machineToken;\n\t\tthis.#now = options.now ?? Date.now;\n\t\tif (!this.#machineToken) throw new Error(\"A machine token is required for Server Runtime durability\");\n\t}\n\tasync list(kind) {\n\t\tconst parsedKind = RuntimeDurableWorkKindSchema.parse(kind);\n\t\treturn (await this.#api.listRuntimeDurableWork(this.#machineToken, parsedKind)).map((record) => RuntimeDurableWorkRecordSchema.parse(record));\n\t}\n\tasync write(record) {\n\t\tconst parsed = RuntimeDurableWorkRecordSchema.parse(record);\n\t\tthis.#now();\n\t\tawait this.#api.writeRuntimeDurableWork(this.#machineToken, parsed);\n\t}\n};\n//#endregion\n//#region src/runtime/session-binding-store.ts\nconst SESSION_BINDING_SCHEMA_VERSION = 3;\nconst SESSION_RECORDED_INPUT_LIMIT = 64;\nvar SessionBindingConflictError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = \"SessionBindingConflictError\";\n\t}\n};\nvar SessionBindingStore = class {\n\t#home;\n\t#providerArtifactIdentity;\n\t#recordedInputLimit;\n\t#tails = /* @__PURE__ */ new Map();\n\tconstructor(options) {\n\t\tthis.#home = options.home;\n\t\tthis.#providerArtifactIdentity = options.providerArtifactIdentity;\n\t\tthis.#recordedInputLimit = options.recordedInputLimit ?? 64;\n\t\tif (!Number.isSafeInteger(this.#recordedInputLimit) || this.#recordedInputLimit < 1) throw new Error(\"recordedInputLimit must be a positive safe integer\");\n\t}\n\tread(agentId, sessionId) {\n\t\treturn this.#readBinding(sessionBindingPath(this.#home, agentId, sessionId));\n\t}\n\tprepare(request, hashes) {\n\t\treturn this.#withSessionLock(request.sessionId, async () => {\n\t\t\tconst runtime = request.runtime;\n\t\t\tif (!runtime) throw new SessionBindingConflictError(\"conflict\", \"A ready binding requires a runtime snapshot\");\n\t\t\tconst paths = agentRuntimePaths(this.#home, request.agentId);\n\t\t\tawait ensurePrivateDirectory(this.#home, paths.sessions);\n\t\t\tawait ensurePrivateDirectory(this.#home, paths.snapshots);\n\t\t\tconst bindingPath = sessionBindingPath(this.#home, request.agentId, request.sessionId);\n\t\t\tconst current = await this.#readBinding(bindingPath);\n\t\t\tif (current) this.#validateIdentity(current, request);\n\t\t\tif (current?.unresolvedTurn) {\n\t\t\t\tif (current.placementGeneration !== request.placementGeneration || current.lastEffectiveSnapshotHash !== hashes.effectiveSnapshotHash) throw new SessionBindingConflictError(\"recovery_required\", \"An unresolved turn fences binding changes\");\n\t\t\t\treturn {\n\t\t\t\t\tbinding: current,\n\t\t\t\t\tunresolvedTurn: current.unresolvedTurn\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (current && request.placementGeneration < current.placementGeneration) throw new SessionBindingConflictError(\"stale\", \"The placement generation is stale\");\n\t\t\tif (current && request.placementGeneration === current.placementGeneration && runtime.revision.session.sequence < current.appliedSessionRevisionSequence) throw new SessionBindingConflictError(\"stale\", \"The Session runtime revision is stale\");\n\t\t\tif (current && request.placementGeneration === current.placementGeneration && runtime.revision.session.sequence === current.appliedSessionRevisionSequence && (runtime.revision.session.id !== current.appliedSessionRevisionId || hashes.sessionConfigHash !== current.sessionConfigHash)) throw new SessionBindingConflictError(\"conflict\", \"The Session runtime revision conflicts with the binding\");\n\t\t\tconst snapshot = EffectiveRuntimeSnapshotSchema.parse(runtime);\n\t\t\tconst storedSnapshot = snapshotPath(this.#home, request.agentId, hashes.effectiveSnapshotHash);\n\t\t\tconst existingSnapshot = await readDurableJson(storedSnapshot, EffectiveRuntimeSnapshotSchema.parse);\n\t\t\tif (existingSnapshot) {\n\t\t\t\tif (computeRuntimeSnapshotHashes(existingSnapshot).effectiveSnapshotHash !== hashes.effectiveSnapshotHash) throw new SessionBindingConflictError(\"conflict\", \"The stored runtime snapshot hash conflicts\");\n\t\t\t} else await writeDurableJson(storedSnapshot, snapshot);\n\t\t\tconst binding = {\n\t\t\t\tschemaVersion: 3,\n\t\t\t\tsessionId: request.sessionId,\n\t\t\t\tagentId: request.agentId,\n\t\t\t\tworkspaceId: runtime.workspace.workspaceId,\n\t\t\t\tplacementGeneration: request.placementGeneration,\n\t\t\t\tprovider: runtime.provider,\n\t\t\t\tproviderHomeIdentity: this.#artifactIdentity(runtime.provider),\n\t\t\t\t...current && current.lastEffectiveSnapshotHash === hashes.effectiveSnapshotHash && current.runtimeBinding ? { runtimeBinding: current.runtimeBinding } : {},\n\t\t\t\tappliedSessionRevisionSequence: runtime.revision.session.sequence,\n\t\t\t\tappliedSessionRevisionId: runtime.revision.session.id,\n\t\t\t\tsessionConfigHash: hashes.sessionConfigHash,\n\t\t\t\tlastEffectiveSnapshotHash: hashes.effectiveSnapshotHash,\n\t\t\t\trecentRecordedInputs: current?.recentRecordedInputs ?? []\n\t\t\t};\n\t\t\tawait this.#writeBinding(bindingPath, binding);\n\t\t\treturn { binding };\n\t\t});\n\t}\n\trecordAccepted(request, inputHash, turnId) {\n\t\treturn this.#withSessionLock(request.sessionId, async () => {\n\t\t\tRuntimeSha256Schema.parse(inputHash);\n\t\t\tconst path = sessionBindingPath(this.#home, request.agentId, request.sessionId);\n\t\t\tconst binding = await this.#requireBinding(request.agentId, request.sessionId);\n\t\t\tthis.#validateDeliveryBinding(binding, request);\n\t\t\tconst recorded = binding.recentRecordedInputs.find((entry) => entry.deliveryId === request.deliveryId);\n\t\t\tif (recorded) {\n\t\t\t\tif (recorded.kind === \"steer\") {\n\t\t\t\t\tif (recorded.inputHash !== computeRuntimeImMessageSemanticHash(request)) throw new SessionBindingConflictError(\"conflict\", \"The delivery ID is recorded with different input\");\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"absorbed\",\n\t\t\t\t\t\tbinding,\n\t\t\t\t\t\trecorded\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (recorded.inputHash !== inputHash) throw new SessionBindingConflictError(\"conflict\", \"The delivery ID is recorded with different input\");\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"recorded\",\n\t\t\t\t\tbinding,\n\t\t\t\t\trecorded\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (binding.unresolvedTurn) {\n\t\t\t\tif (binding.unresolvedTurn.deliveryId !== request.deliveryId || binding.unresolvedTurn.inputHash !== inputHash || binding.unresolvedTurn.turnId !== turnId) throw new SessionBindingConflictError(\"recovery_required\", \"Another unresolved turn owns the Session\");\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"existing\",\n\t\t\t\t\tbinding,\n\t\t\t\t\tunresolvedTurn: binding.unresolvedTurn\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst unresolvedTurn = {\n\t\t\t\trequestId: request.requestId,\n\t\t\t\tdeliveryId: request.deliveryId,\n\t\t\t\tinputHash,\n\t\t\t\tturnId,\n\t\t\t\tphase: \"accepted\"\n\t\t\t};\n\t\t\tconst updated = {\n\t\t\t\t...binding,\n\t\t\t\tunresolvedTurn\n\t\t\t};\n\t\t\tawait this.#writeBinding(path, updated);\n\t\t\treturn {\n\t\t\t\tstatus: \"committed\",\n\t\t\t\tbinding: updated,\n\t\t\t\tunresolvedTurn\n\t\t\t};\n\t\t});\n\t}\n\tgetSteerReceipt(request, inputHash) {\n\t\treturn this.#withSessionLock(request.sessionId, async () => {\n\t\t\tRuntimeSha256Schema.parse(inputHash);\n\t\t\tconst binding = await this.#requireBinding(request.agentId, request.sessionId);\n\t\t\tthis.#validateSteerBinding(binding, request);\n\t\t\tconst recorded = binding.recentRecordedInputs.find((entry) => entry.deliveryId === request.deliveryId);\n\t\t\tif (!recorded) return void 0;\n\t\t\tif (recorded.kind !== \"steer\" || recorded.inputHash !== inputHash || recorded.rootDeliveryId !== request.rootDeliveryId || recorded.turnId !== request.expectedTurnId) throw new SessionBindingConflictError(\"conflict\", \"The steer delivery ID is recorded with different input\");\n\t\t\treturn recorded;\n\t\t});\n\t}\n\tgetAbsorbedReceipt(request) {\n\t\treturn this.#withSessionLock(request.sessionId, async () => {\n\t\t\tconst binding = await this.#requireBinding(request.agentId, request.sessionId);\n\t\t\tthis.#validateDeliveryBinding(binding, request);\n\t\t\tconst recorded = binding.recentRecordedInputs.find((entry) => entry.deliveryId === request.deliveryId);\n\t\t\tif (!recorded) return void 0;\n\t\t\tif (recorded.kind !== \"steer\" || recorded.inputHash !== computeRuntimeImMessageSemanticHash(request)) throw new SessionBindingConflictError(\"conflict\", \"The delivery ID is recorded with different input\");\n\t\t\treturn recorded;\n\t\t});\n\t}\n\trecordSteer(request, inputHash) {\n\t\treturn this.#withSessionLock(request.sessionId, async () => {\n\t\t\tRuntimeSha256Schema.parse(inputHash);\n\t\t\tconst path = sessionBindingPath(this.#home, request.agentId, request.sessionId);\n\t\t\tconst binding = await this.#requireBinding(request.agentId, request.sessionId);\n\t\t\tthis.#validateSteerBinding(binding, request);\n\t\t\tconst existing = binding.recentRecordedInputs.find((entry) => entry.deliveryId === request.deliveryId);\n\t\t\tif (existing) {\n\t\t\t\tif (existing.kind === \"steer\" && existing.inputHash === inputHash && existing.rootDeliveryId === request.rootDeliveryId && existing.turnId === request.expectedTurnId) return existing;\n\t\t\t\tthrow new SessionBindingConflictError(\"conflict\", \"The steer delivery ID is recorded with different input\");\n\t\t\t}\n\t\t\tconst unresolved = binding.unresolvedTurn;\n\t\t\tif (!unresolved || unresolved.deliveryId !== request.rootDeliveryId || unresolved.turnId !== request.expectedTurnId) throw new SessionBindingConflictError(\"conflict\", \"The steer target does not match the unresolved Turn\");\n\t\t\tconst recorded = {\n\t\t\t\tkind: \"steer\",\n\t\t\t\tdeliveryId: request.deliveryId,\n\t\t\t\tinputHash,\n\t\t\t\trequestId: request.requestId,\n\t\t\t\trootDeliveryId: request.rootDeliveryId,\n\t\t\t\tturnId: request.expectedTurnId\n\t\t\t};\n\t\t\tconst recentRecordedInputs = [...binding.recentRecordedInputs.filter((entry) => entry.deliveryId !== recorded.deliveryId), recorded].slice(-this.#recordedInputLimit);\n\t\t\tawait this.#writeBinding(path, {\n\t\t\t\t...binding,\n\t\t\t\trecentRecordedInputs\n\t\t\t});\n\t\t\treturn recorded;\n\t\t});\n\t}\n\tupdateUnresolved(agentId, sessionId, turnId, phase, fields = {}) {\n\t\treturn this.#withSessionLock(sessionId, async () => {\n\t\t\tconst path = sessionBindingPath(this.#home, agentId, sessionId);\n\t\t\tconst binding = await this.#requireBinding(agentId, sessionId);\n\t\t\tconst unresolved = binding.unresolvedTurn;\n\t\t\tif (!unresolved || unresolved.turnId !== turnId) throw new SessionBindingConflictError(\"conflict\", \"The unresolved turn does not match\");\n\t\t\tif (phaseOrder(phase) < phaseOrder(unresolved.phase)) throw new SessionBindingConflictError(\"conflict\", \"The unresolved turn phase cannot move backwards\");\n\t\t\tconst report = fields.report ? TurnReportRequestSchema.parse(fields.report) : void 0;\n\t\t\tif (report) this.#validateReport(binding, unresolved, report);\n\t\t\tif (report && fields.resultHash !== void 0 && fields.resultHash !== report.resultHash) throw new SessionBindingConflictError(\"conflict\", \"The Turn Report result hash does not match the update\");\n\t\t\tif (unresolved.report && report && unresolved.report.requestId !== report.requestId) throw new SessionBindingConflictError(\"conflict\", \"The immutable Turn Report cannot be replaced\");\n\t\t\tif (unresolved.report && fields.resultHash && unresolved.report.resultHash !== fields.resultHash) throw new SessionBindingConflictError(\"conflict\", \"The Turn Report result hash cannot be replaced\");\n\t\t\tconst updated = {\n\t\t\t\t...binding,\n\t\t\t\tunresolvedTurn: {\n\t\t\t\t\t...unresolved,\n\t\t\t\t\tphase,\n\t\t\t\t\t...fields.providerTurnId ? { providerTurnId: fields.providerTurnId } : {},\n\t\t\t\t\t...report ? { report } : {},\n\t\t\t\t\t...fields.resultHash ? { resultHash: fields.resultHash } : {}\n\t\t\t\t}\n\t\t\t};\n\t\t\tawait this.#writeBinding(path, updated);\n\t\t\treturn updated;\n\t\t});\n\t}\n\tsaveRuntimeBinding(agentId, sessionId, effectiveSnapshotHash, runtimeBinding) {\n\t\treturn this.#withSessionLock(sessionId, async () => {\n\t\t\tRuntimeSha256Schema.parse(effectiveSnapshotHash);\n\t\t\tvalidateRuntimeBinding(runtimeBinding);\n\t\t\tconst path = sessionBindingPath(this.#home, agentId, sessionId);\n\t\t\tconst binding = await this.#requireBinding(agentId, sessionId);\n\t\t\tif (binding.lastEffectiveSnapshotHash !== effectiveSnapshotHash || binding.provider !== runtimeBinding.providerId) throw new SessionBindingConflictError(\"conflict\", \"The Agent Runtime binding does not match the Session\");\n\t\t\tconst updated = {\n\t\t\t\t...binding,\n\t\t\t\truntimeBinding\n\t\t\t};\n\t\t\tawait this.#writeBinding(path, updated);\n\t\t\treturn updated;\n\t\t});\n\t}\n\trecordResult(agentId, sessionId, turnId, resultHash) {\n\t\treturn this.#withSessionLock(sessionId, async () => {\n\t\t\tRuntimeSha256Schema.parse(resultHash);\n\t\t\tconst path = sessionBindingPath(this.#home, agentId, sessionId);\n\t\t\tconst binding = await this.#requireBinding(agentId, sessionId);\n\t\t\tconst alreadyRecorded = binding.recentRecordedInputs.find((entry) => entry.kind === \"turn\" && entry.turnId === turnId);\n\t\t\tif (alreadyRecorded) {\n\t\t\t\tif (alreadyRecorded.resultHash === resultHash) return binding;\n\t\t\t\tthrow new SessionBindingConflictError(\"conflict\", \"The recorded result hash cannot be replaced\");\n\t\t\t}\n\t\t\tconst unresolved = binding.unresolvedTurn;\n\t\t\tif (!unresolved) throw new SessionBindingConflictError(\"conflict\", \"The recorded result does not match the Session binding\");\n\t\t\tif (unresolved.turnId !== turnId || unresolved.resultHash !== resultHash) throw new SessionBindingConflictError(\"conflict\", \"The recorded result does not match the unresolved turn\");\n\t\t\tconst recorded = {\n\t\t\t\tkind: \"turn\",\n\t\t\t\tdeliveryId: unresolved.deliveryId,\n\t\t\t\tinputHash: unresolved.inputHash,\n\t\t\t\trequestId: unresolved.requestId,\n\t\t\t\t...unresolved.report ? { report: unresolved.report } : {},\n\t\t\t\tresultHash,\n\t\t\t\tturnId\n\t\t\t};\n\t\t\tconst recentRecordedInputs = [...binding.recentRecordedInputs.filter((entry) => entry.deliveryId !== recorded.deliveryId), recorded].slice(-this.#recordedInputLimit);\n\t\t\tconst updated = {\n\t\t\t\t...binding,\n\t\t\t\trecentRecordedInputs\n\t\t\t};\n\t\t\tdelete updated.unresolvedTurn;\n\t\t\tawait this.#writeBinding(path, updated);\n\t\t\treturn updated;\n\t\t});\n\t}\n\tasync #requireBinding(agentId, sessionId) {\n\t\tconst binding = await this.read(agentId, sessionId);\n\t\tif (!binding) throw new SessionBindingConflictError(\"conflict\", \"The Session binding does not exist\");\n\t\treturn binding;\n\t}\n\tasync #readBinding(path) {\n\t\tif (!await validatePrivateDirectory(this.#home, dirname(path))) return void 0;\n\t\treturn readDurableJson(path, parseLocalSessionBinding);\n\t}\n\tasync #writeBinding(path, binding) {\n\t\tif (!await validatePrivateDirectory(this.#home, dirname(path))) throw new RuntimeStorageError(\"unsafe\", \"The Session binding directory does not exist\");\n\t\tawait writeDurableJson(path, binding);\n\t}\n\t#validateIdentity(binding, request) {\n\t\tif (binding.sessionId !== request.sessionId || binding.agentId !== request.agentId || request.runtime && binding.provider !== request.runtime.provider || binding.providerHomeIdentity !== this.#artifactIdentity(binding.provider) || request.runtime && binding.workspaceId !== request.runtime.workspace.workspaceId) throw new SessionBindingConflictError(\"conflict\", \"The Session binding identity cannot be changed\");\n\t}\n\t#validateDeliveryBinding(binding, request) {\n\t\tconst hashes = computeRuntimeSnapshotHashes(request.runtime);\n\t\tif (binding.agentId !== request.agentId || binding.workspaceId !== request.runtime.workspace.workspaceId || binding.placementGeneration !== request.placementGeneration || binding.lastEffectiveSnapshotHash !== hashes.effectiveSnapshotHash || binding.providerHomeIdentity !== this.#artifactIdentity(binding.provider)) throw new SessionBindingConflictError(\"conflict\", \"The delivery does not match the Session binding\");\n\t}\n\t#validateSteerBinding(binding, request) {\n\t\tif (binding.agentId !== request.agentId || binding.sessionId !== request.sessionId || binding.placementGeneration !== request.placementGeneration || binding.providerHomeIdentity !== this.#artifactIdentity(binding.provider)) throw new SessionBindingConflictError(\"conflict\", \"The steer delivery does not match the Session binding\");\n\t}\n\t#artifactIdentity(providerId) {\n\t\tconst identity = this.#providerArtifactIdentity(providerId);\n\t\tif (identity === void 0) throw new SessionBindingConflictError(\"conflict\", `Provider artifact identity is unavailable: ${providerId}`);\n\t\treturn RuntimeSha256Schema.parse(identity);\n\t}\n\t#validateReport(binding, unresolved, report) {\n\t\tif (report.requestId.length === 0 || report.deliveryId !== unresolved.deliveryId || report.turnId !== unresolved.turnId || report.sessionId !== binding.sessionId || report.agentId !== binding.agentId || report.placementGeneration !== binding.placementGeneration || unresolved.resultHash !== void 0 && unresolved.resultHash !== report.resultHash) throw new SessionBindingConflictError(\"conflict\", \"The Turn Report does not match the unresolved custody\");\n\t}\n\tasync #withSessionLock(sessionId, task) {\n\t\tconst previous = this.#tails.get(sessionId) ?? Promise.resolve();\n\t\tlet release;\n\t\tconst tail = new Promise((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.#tails.set(sessionId, tail);\n\t\tawait previous;\n\t\ttry {\n\t\t\treturn await task();\n\t\t} finally {\n\t\t\trelease?.();\n\t\t\tif (this.#tails.get(sessionId) === tail) this.#tails.delete(sessionId);\n\t\t}\n\t}\n};\nfunction parseLocalSessionBinding(value) {\n\tif (!isRecord(value) || value.schemaVersion !== 1 && value.schemaVersion !== 2 && value.schemaVersion !== 3) throw new RuntimeStorageError(\"invalid\", \"Unsupported Session binding schema\");\n\tconst isLegacy = value.schemaVersion === 1;\n\tconst hasInputKinds = value.schemaVersion === 3;\n\tconst required = [\n\t\t\"schemaVersion\",\n\t\t\"sessionId\",\n\t\t\"agentId\",\n\t\t\"workspaceId\",\n\t\t\"placementGeneration\",\n\t\t\"provider\",\n\t\t\"providerHomeIdentity\",\n\t\t\"appliedSessionRevisionSequence\",\n\t\t\"appliedSessionRevisionId\",\n\t\t\"sessionConfigHash\",\n\t\t\"lastEffectiveSnapshotHash\",\n\t\t\"recentRecordedInputs\"\n\t];\n\tconst optional = isLegacy ? [\"providerThreadId\", \"unresolvedTurn\"] : [\"runtimeBinding\", \"unresolvedTurn\"];\n\tif (!hasOnlyKeys(value, [...required, ...optional]) || required.some((key) => !(key in value))) throw new RuntimeStorageError(\"invalid\", \"Session binding fields are invalid\");\n\tif (!isString(value.sessionId) || !isString(value.agentId) || !isString(value.workspaceId) || !isSequence(value.placementGeneration) || !isAgentRuntimeProviderId(value.provider) || isLegacy && value.provider !== \"codex\" || !RuntimeSha256Schema.safeParse(value.providerHomeIdentity).success || !isSequence(value.appliedSessionRevisionSequence) || !isString(value.appliedSessionRevisionId) || !RuntimeSha256Schema.safeParse(value.sessionConfigHash).success || !RuntimeSha256Schema.safeParse(value.lastEffectiveSnapshotHash).success || isLegacy && value.providerThreadId !== void 0 && !isString(value.providerThreadId) || !Array.isArray(value.recentRecordedInputs)) throw new RuntimeStorageError(\"invalid\", \"Session binding values are invalid\");\n\tconst recentRecordedInputs = value.recentRecordedInputs.map((entry) => parseRecordedInput(entry, value.sessionId, value.agentId, value.placementGeneration, hasInputKinds));\n\tif (recentRecordedInputs.length > 64) throw new RuntimeStorageError(\"invalid\", \"Session binding has too many recorded inputs\");\n\tconst unresolvedTurn = value.unresolvedTurn === void 0 ? void 0 : parseUnresolvedTurn(value.unresolvedTurn, value.sessionId, value.agentId, value.placementGeneration);\n\tlet runtimeBinding;\n\tif (isLegacy && value.providerThreadId) runtimeBinding = {\n\t\tproviderId: \"codex\",\n\t\tschemaVersion: 1,\n\t\tpayload: { threadId: value.providerThreadId }\n\t};\n\telse if (!isLegacy && value.runtimeBinding !== void 0) {\n\t\truntimeBinding = validateRuntimeBinding(value.runtimeBinding);\n\t\tif (runtimeBinding.providerId !== value.provider) throw new RuntimeStorageError(\"invalid\", \"Agent Runtime binding provider does not match the Session\");\n\t}\n\treturn {\n\t\tschemaVersion: 3,\n\t\tsessionId: value.sessionId,\n\t\tagentId: value.agentId,\n\t\tworkspaceId: value.workspaceId,\n\t\tplacementGeneration: value.placementGeneration,\n\t\tprovider: value.provider,\n\t\tproviderHomeIdentity: value.providerHomeIdentity,\n\t\t...runtimeBinding ? { runtimeBinding } : {},\n\t\tappliedSessionRevisionSequence: value.appliedSessionRevisionSequence,\n\t\tappliedSessionRevisionId: value.appliedSessionRevisionId,\n\t\tsessionConfigHash: value.sessionConfigHash,\n\t\tlastEffectiveSnapshotHash: value.lastEffectiveSnapshotHash,\n\t\trecentRecordedInputs,\n\t\t...unresolvedTurn ? { unresolvedTurn } : {}\n\t};\n}\nfunction validateRuntimeBinding(value) {\n\tif (!isRecord(value) || !hasOnlyKeys(value, [\n\t\t\"providerId\",\n\t\t\"schemaVersion\",\n\t\t\"payload\"\n\t]) || !isAgentRuntimeProviderId(value.providerId) || !Number.isSafeInteger(value.schemaVersion) || value.schemaVersion < 1 || !(\"payload\" in value)) throw new RuntimeStorageError(\"invalid\", \"Agent Runtime binding is invalid\");\n\ttry {\n\t\tassertJsonValue(value.payload, \"runtimeBinding.payload\", \"binding_incompatible\");\n\t} catch {\n\t\tthrow new RuntimeStorageError(\"invalid\", \"Agent Runtime binding payload is invalid\");\n\t}\n\tif (Buffer.byteLength(JSON.stringify(value), \"utf8\") > 65536) throw new RuntimeStorageError(\"invalid\", \"Agent Runtime binding exceeds the size limit\");\n\treturn value;\n}\nfunction parseRecordedInput(value, sessionId, agentId, placementGeneration, hasInputKinds) {\n\tif (hasInputKinds && isRecord(value) && value.kind === \"steer\") {\n\t\tif (!hasOnlyKeys(value, [\n\t\t\t\"kind\",\n\t\t\t\"deliveryId\",\n\t\t\t\"inputHash\",\n\t\t\t\"requestId\",\n\t\t\t\"rootDeliveryId\",\n\t\t\t\"turnId\"\n\t\t]) || !isString(value.deliveryId) || !RuntimeSha256Schema.safeParse(value.inputHash).success || !RuntimeRequestIdSchema.safeParse(value.requestId).success || !isString(value.rootDeliveryId) || !isString(value.turnId)) throw new RuntimeStorageError(\"invalid\", \"Recorded steer input is invalid\");\n\t\treturn {\n\t\t\tkind: \"steer\",\n\t\t\tdeliveryId: value.deliveryId,\n\t\t\tinputHash: value.inputHash,\n\t\t\trequestId: value.requestId,\n\t\t\trootDeliveryId: value.rootDeliveryId,\n\t\t\tturnId: value.turnId\n\t\t};\n\t}\n\tif (!isRecord(value) || !hasOnlyKeys(value, [\n\t\t\"kind\",\n\t\t\"deliveryId\",\n\t\t\"inputHash\",\n\t\t\"requestId\",\n\t\t\"turnId\",\n\t\t\"resultHash\",\n\t\t\"report\"\n\t]) || (hasInputKinds ? value.kind !== \"turn\" : value.kind !== void 0) || !isString(value.deliveryId) || !RuntimeSha256Schema.safeParse(value.inputHash).success || !isString(value.turnId) || !RuntimeSha256Schema.safeParse(value.resultHash).success || value.requestId !== void 0 && !RuntimeRequestIdSchema.safeParse(value.requestId).success) throw new RuntimeStorageError(\"invalid\", \"Recorded input is invalid\");\n\tconst report = value.report === void 0 ? void 0 : TurnReportRequestSchema.parse(value.report);\n\tif (report && (report.deliveryId !== value.deliveryId || report.turnId !== value.turnId || report.sessionId !== sessionId || report.agentId !== agentId || report.placementGeneration !== placementGeneration || report.resultHash !== value.resultHash)) throw new RuntimeStorageError(\"invalid\", \"Recorded Turn Report identity is invalid\");\n\treturn {\n\t\tkind: \"turn\",\n\t\tdeliveryId: value.deliveryId,\n\t\tinputHash: value.inputHash,\n\t\t...value.requestId ? { requestId: value.requestId } : {},\n\t\t...report ? { report } : {},\n\t\tresultHash: value.resultHash,\n\t\tturnId: value.turnId\n\t};\n}\nfunction parseUnresolvedTurn(value, sessionId, agentId, placementGeneration) {\n\tif (!isRecord(value) || !hasOnlyKeys(value, [\n\t\t\"requestId\",\n\t\t\"deliveryId\",\n\t\t\"inputHash\",\n\t\t\"turnId\",\n\t\t\"phase\",\n\t\t\"providerTurnId\",\n\t\t\"report\",\n\t\t\"resultHash\"\n\t]) || !isString(value.requestId) || !isString(value.deliveryId) || !RuntimeSha256Schema.safeParse(value.inputHash).success || !isString(value.turnId) || !isPhase(value.phase) || value.providerTurnId !== void 0 && !isString(value.providerTurnId) || value.resultHash !== void 0 && !RuntimeSha256Schema.safeParse(value.resultHash).success) throw new RuntimeStorageError(\"invalid\", \"Unresolved turn is invalid\");\n\tconst report = value.report === void 0 ? void 0 : TurnReportRequestSchema.parse(value.report);\n\tif (report && (report.deliveryId !== value.deliveryId || report.turnId !== value.turnId || report.sessionId !== sessionId || report.agentId !== agentId || report.placementGeneration !== placementGeneration || report.resultHash !== value.resultHash)) throw new RuntimeStorageError(\"invalid\", \"Unresolved Turn Report identity is invalid\");\n\treturn {\n\t\trequestId: value.requestId,\n\t\tdeliveryId: value.deliveryId,\n\t\tinputHash: value.inputHash,\n\t\tturnId: value.turnId,\n\t\tphase: value.phase,\n\t\t...value.providerTurnId ? { providerTurnId: value.providerTurnId } : {},\n\t\t...report ? { report } : {},\n\t\t...value.resultHash ? { resultHash: value.resultHash } : {}\n\t};\n}\nfunction phaseOrder(phase) {\n\treturn [\n\t\t\"accepted\",\n\t\t\"starting\",\n\t\t\"running\",\n\t\t\"reporting\"\n\t].indexOf(phase);\n}\nfunction isPhase(value) {\n\treturn value === \"accepted\" || value === \"starting\" || value === \"running\" || value === \"reporting\";\n}\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction isString(value) {\n\treturn typeof value === \"string\" && value.length > 0 && value.length <= 4096;\n}\nfunction isSequence(value) {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\nfunction hasOnlyKeys(value, allowed) {\n\tconst accepted = new Set(allowed);\n\treturn Object.keys(value).every((key) => accepted.has(key));\n}\n//#endregion\n//#region src/runtime/session-cli-proof-manager.ts\nvar SessionCliProofManager = class {\n\t#home;\n\tconstructor(home) {\n\t\tthis.#home = home;\n\t}\n\tpathForSession(sessionId) {\n\t\treturn sessionCliProofPath(this.#home, sessionId);\n\t}\n\tasync materialize(sessionId, proof) {\n\t\tconst parsed = parseStoredSessionCliProof(proof);\n\t\tawait ensurePrivateDirectory(this.#home, sessionCliProofRoot(this.#home));\n\t\tconst path = this.pathForSession(sessionId);\n\t\tconst current = await readDurableJson(path, parseStoredSessionCliProof);\n\t\tif (current?.proofId !== parsed.proofId || current.token !== parsed.token) await writeDurableJson(path, parsed);\n\t\treturn path;\n\t}\n\tasync cleanup(sessionId) {\n\t\ttry {\n\t\t\tawait removeDurableFile(this.pathForSession(sessionId));\n\t\t} catch (error) {\n\t\t\tif (error.code !== \"ENOENT\") throw error;\n\t\t}\n\t}\n};\nasync function readSessionCliProofFile(path) {\n\tconst proof = await readDurableJson(path, parseStoredSessionCliProof);\n\tif (!proof) throw new Error(\"The OpenTag-managed Session proof file is missing\");\n\treturn proof;\n}\nfunction parseStoredSessionCliProof(value) {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"Invalid Session CLI proof file\");\n\tconst record = value;\n\tif (Object.keys(record).length !== 2 || typeof record.proofId !== \"string\" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.proofId) || typeof record.token !== \"string\" || record.token.length < 32 || record.token.length > 4096) throw new Error(\"Invalid Session CLI proof file\");\n\treturn {\n\t\tproofId: record.proofId,\n\t\ttoken: record.token\n\t};\n}\n//#endregion\n//#region src/runtime/turn-custody-owner.ts\nvar TurnCustodyOwner = class {\n\tadmission;\n\t#bindingStore;\n\t#reconciler;\n\t#id;\n\t#imDeliveryVersion;\n\t#imSteerVersion;\n\t#maxRememberedRequests;\n\t#now;\n\t#preflight;\n\t#start;\n\t#steer;\n\t#requests = /* @__PURE__ */ new Map();\n\t#deliveries = /* @__PURE__ */ new Map();\n\t#turns = /* @__PURE__ */ new Map();\n\t#steerRequests = /* @__PURE__ */ new Map();\n\t#steerDeliveries = /* @__PURE__ */ new Map();\n\tconstructor(options) {\n\t\tthis.admission = options.admission ?? new AdmissionController();\n\t\tthis.#bindingStore = options.bindingStore;\n\t\tthis.#reconciler = options.reconciler;\n\t\tthis.#id = options.id ?? randomUUID;\n\t\tthis.#imDeliveryVersion = options.imDeliveryVersion ?? (() => void 0);\n\t\tthis.#imSteerVersion = options.imSteerVersion ?? (() => void 0);\n\t\tthis.#maxRememberedRequests = options.maxRememberedRequests ?? 512;\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#preflight = options.preflight;\n\t\tthis.#start = options.start;\n\t\tthis.#steer = options.steer;\n\t\tif (!Number.isSafeInteger(this.#maxRememberedRequests) || this.#maxRememberedRequests < 1) throw new Error(\"maxRememberedRequests must be a positive safe integer\");\n\t}\n\tacceptSteer(request) {\n\t\tif (request.replyRole === \"observer\" && this.#imSteerVersion() !== 2) return Promise.resolve(deferredSteer(request, \"steer_unsupported\"));\n\t\tconst inputHash = computeRuntimeImSteerInputHash(request);\n\t\tconst requestHash = hashTuple([request.deliveryId, inputHash]);\n\t\tconst remembered = this.#steerRequests.get(request.requestId);\n\t\tif (remembered) return remembered.requestHash === requestHash ? remembered.decision : Promise.resolve(rejectedSteer(request, \"input_conflict\"));\n\t\tconst existing = this.#steerDeliveries.get(request.deliveryId);\n\t\tif (existing) {\n\t\t\tconst decision = existing.inputHash === inputHash ? existing.decision.then((result) => ({\n\t\t\t\t...result,\n\t\t\t\trequestId: request.requestId\n\t\t\t})) : Promise.resolve(rejectedSteer(request, \"input_conflict\"));\n\t\t\tthis.#rememberSteer(request.requestId, requestHash, decision);\n\t\t\treturn decision;\n\t\t}\n\t\tconst deadline = request.deadlineAt ? Date.parse(request.deadlineAt) : void 0;\n\t\tconst decision = deadline !== void 0 && deadline <= this.#now() ? Promise.resolve(rejectedSteer(request, \"invalid_input\")) : this.#steer?.(request) ?? Promise.resolve(deferredSteer(request, \"steer_unsupported\"));\n\t\tconst delivery = {\n\t\t\tinputHash,\n\t\t\tdecision\n\t\t};\n\t\tthis.#steerDeliveries.set(request.deliveryId, delivery);\n\t\tdecision.then((result) => {\n\t\t\tif (result.status === \"retry\" && this.#steerDeliveries.get(request.deliveryId) === delivery) this.#steerDeliveries.delete(request.deliveryId);\n\t\t});\n\t\tthis.#rememberSteer(request.requestId, requestHash, decision);\n\t\treturn decision;\n\t}\n\taccept(request) {\n\t\tif (request.replyRole === \"observer\" && this.#imDeliveryVersion() !== 2) return Promise.resolve({ result: rejected(request, \"session_not_ready\") });\n\t\tconst inputHash = computeDirectInputHash(request);\n\t\tconst requestHash = hashTuple([request.deliveryId, inputHash]);\n\t\tconst remembered = this.#requests.get(request.requestId);\n\t\tif (remembered) return remembered.requestHash === requestHash ? remembered.decision : Promise.resolve({ result: rejected(request, \"input_conflict\") });\n\t\tconst existingDelivery = this.#deliveries.get(request.deliveryId);\n\t\tif (existingDelivery) {\n\t\t\tconst decision = existingDelivery.inputHash === inputHash ? existingDelivery.decision.then((existing) => ({\n\t\t\t\t...existing,\n\t\t\t\tresult: {\n\t\t\t\t\t...existing.result,\n\t\t\t\t\trequestId: request.requestId\n\t\t\t\t}\n\t\t\t})) : Promise.resolve({ result: rejected(request, \"input_conflict\") });\n\t\t\tthis.#remember(request.requestId, requestHash, decision);\n\t\t\treturn decision;\n\t\t}\n\t\tconst deadline = request.deadlineAt ? Date.parse(request.deadlineAt) : void 0;\n\t\tif (deadline !== void 0 && deadline <= this.#now()) {\n\t\t\tconst decision = Promise.resolve({ result: rejected(request, \"turn_expired\") });\n\t\t\tthis.#remember(request.requestId, requestHash, decision);\n\t\t\treturn decision;\n\t\t}\n\t\tconst admission = this.admission.reserve(request.sessionId, request.agentId);\n\t\tif (!admission.accepted) {\n\t\t\tconst decision = this.#absorbedOrRejected(request, admission.reason);\n\t\t\tthis.#remember(request.requestId, requestHash, decision);\n\t\t\treturn decision;\n\t\t}\n\t\tconst turnId = this.#id();\n\t\tconst owner = {\n\t\t\tinputHash,\n\t\t\trequest,\n\t\t\treservation: admission.reservation,\n\t\t\tturnId,\n\t\t\tstarted: false\n\t\t};\n\t\tconst decision = this.#reconciler.withAgentLock(request.agentId, () => this.#prepare(owner));\n\t\towner.decision = decision;\n\t\tthis.#deliveries.set(request.deliveryId, owner);\n\t\tthis.#turns.set(turnId, owner);\n\t\tthis.#remember(request.requestId, requestHash, decision);\n\t\treturn decision;\n\t}\n\tasync markReporting(turnId, reportInput) {\n\t\tconst report = TurnReportRequestSchema.parse(reportInput);\n\t\tconst owner = this.#requireTurn(turnId);\n\t\tassertMatchingReport(owner, report);\n\t\tawait this.#reconciler.withAgentLock(owner.request.agentId, async () => {\n\t\t\tif (owner.reservation.phase === \"active\") owner.reservation.markReporting();\n\t\t\tawait this.#bindingStore.updateUnresolved(owner.request.agentId, owner.request.sessionId, turnId, \"reporting\", {\n\t\t\t\treport,\n\t\t\t\tresultHash: report.resultHash\n\t\t\t});\n\t\t\tthis.#reconciler.setActivity(owner.request.sessionId, {\n\t\t\t\tphase: \"reporting\",\n\t\t\t\tdeliveryId: owner.request.deliveryId,\n\t\t\t\tturnId\n\t\t\t});\n\t\t});\n\t}\n\tasync recordResult(turnId, resultHash) {\n\t\tconst owner = this.#requireTurn(turnId);\n\t\tawait this.#reconciler.withAgentLock(owner.request.agentId, async () => {\n\t\t\tawait this.#bindingStore.recordResult(owner.request.agentId, owner.request.sessionId, turnId, resultHash);\n\t\t\towner.reservation.release();\n\t\t\tthis.#reconciler.clearActivity(owner.request.sessionId, turnId);\n\t\t\tthis.#deliveries.delete(owner.request.deliveryId);\n\t\t\tthis.#turns.delete(turnId);\n\t\t});\n\t}\n\tgetTurn(turnId) {\n\t\treturn this.#turns.get(turnId);\n\t}\n\t/** Accepted Turns still under local custody (accepted, not yet recorded as reported). */\n\tget liveTurnCount() {\n\t\treturn this.#turns.size;\n\t}\n\tasync #prepare(owner) {\n\t\ttry {\n\t\t\tconst deliveryReason = this.#reconciler.checkDelivery(owner.request);\n\t\t\tif (deliveryReason) {\n\t\t\t\tthis.#discard(owner);\n\t\t\t\treturn { result: rejected(owner.request, deliveryReason) };\n\t\t\t}\n\t\t\tconst preflightReason = await this.#preflight?.(owner.request);\n\t\t\tif (preflightReason) {\n\t\t\t\tthis.#discard(owner);\n\t\t\t\treturn { result: rejected(owner.request, preflightReason) };\n\t\t\t}\n\t\t\tconst custody = await this.#bindingStore.recordAccepted(owner.request, owner.inputHash, owner.turnId);\n\t\t\tif (custody.status === \"recorded\") {\n\t\t\t\tthis.#discard(owner);\n\t\t\t\treturn { result: accepted(owner.request, custody.recorded.turnId) };\n\t\t\t}\n\t\t\tif (custody.status === \"absorbed\") {\n\t\t\t\tthis.#discard(owner);\n\t\t\t\treturn { result: absorbed(owner.request, custody.recorded.rootDeliveryId, custody.recorded.turnId) };\n\t\t\t}\n\t\t\tif (custody.status === \"existing\" && custody.unresolvedTurn.turnId !== owner.turnId) {\n\t\t\t\tthis.#discard(owner);\n\t\t\t\treturn { result: rejected(owner.request, \"session_recovery_required\") };\n\t\t\t}\n\t\t\tthis.#reconciler.setActivity(owner.request.sessionId, {\n\t\t\t\tphase: \"running\",\n\t\t\t\tdeliveryId: owner.request.deliveryId,\n\t\t\t\tturnId: owner.turnId\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tresult: accepted(owner.request, owner.turnId),\n\t\t\t\tonAcceptedSent: async () => {\n\t\t\t\t\tif (owner.started) return;\n\t\t\t\t\towner.started = true;\n\t\t\t\t\towner.reservation.markActive();\n\t\t\t\t\tthis.#reconciler.setActivity(owner.request.sessionId, {\n\t\t\t\t\t\tphase: \"running\",\n\t\t\t\t\t\tdeliveryId: owner.request.deliveryId,\n\t\t\t\t\t\tturnId: owner.turnId\n\t\t\t\t\t});\n\t\t\t\t\tawait this.#start?.(owner);\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthis.#discard(owner);\n\t\t\treturn { result: rejected(owner.request, mapStorageError(error)) };\n\t\t}\n\t}\n\tasync #absorbedOrRejected(request, reason) {\n\t\ttry {\n\t\t\tconst receipt = await this.#bindingStore.getAbsorbedReceipt(request);\n\t\t\tif (receipt) return { result: absorbed(request, receipt.rootDeliveryId, receipt.turnId) };\n\t\t} catch (error) {\n\t\t\tif (error instanceof SessionBindingConflictError && error.code === \"conflict\") return { result: rejected(request, \"input_conflict\") };\n\t\t}\n\t\treturn { result: rejected(request, reason) };\n\t}\n\t#discard(owner) {\n\t\towner.reservation.release();\n\t\tif (this.#deliveries.get(owner.request.deliveryId) === owner) this.#deliveries.delete(owner.request.deliveryId);\n\t\tif (this.#turns.get(owner.turnId) === owner) this.#turns.delete(owner.turnId);\n\t}\n\t#remember(requestId, requestHash, decision) {\n\t\tthis.#requests.set(requestId, {\n\t\t\trequestHash,\n\t\t\tdecision\n\t\t});\n\t\twhile (this.#requests.size > this.#maxRememberedRequests) {\n\t\t\tconst oldest = this.#requests.keys().next().value;\n\t\t\tif (oldest === void 0) break;\n\t\t\tthis.#requests.delete(oldest);\n\t\t}\n\t}\n\t#rememberSteer(requestId, requestHash, decision) {\n\t\tthis.#steerRequests.set(requestId, {\n\t\t\trequestHash,\n\t\t\tdecision\n\t\t});\n\t\twhile (this.#steerRequests.size > this.#maxRememberedRequests) {\n\t\t\tconst oldest = this.#steerRequests.keys().next().value;\n\t\t\tif (oldest === void 0) break;\n\t\t\tthis.#steerRequests.delete(oldest);\n\t\t}\n\t\twhile (this.#steerDeliveries.size > this.#maxRememberedRequests) {\n\t\t\tconst oldest = this.#steerDeliveries.keys().next().value;\n\t\t\tif (oldest === void 0) break;\n\t\t\tthis.#steerDeliveries.delete(oldest);\n\t\t}\n\t}\n\t#requireTurn(turnId) {\n\t\tconst owner = this.#turns.get(turnId);\n\t\tif (!owner) throw new Error(\"The live Turn owner does not exist\");\n\t\treturn owner;\n\t}\n};\nfunction accepted(request, turnId) {\n\treturn {\n\t\ttype: \"im:deliver:result\",\n\t\trequestId: request.requestId,\n\t\tdeliveryId: request.deliveryId,\n\t\tsessionId: request.sessionId,\n\t\tplacementGeneration: request.placementGeneration,\n\t\tstatus: \"accepted\",\n\t\tturnId\n\t};\n}\nfunction rejected(request, reason) {\n\treturn {\n\t\ttype: \"im:deliver:result\",\n\t\trequestId: request.requestId,\n\t\tdeliveryId: request.deliveryId,\n\t\tsessionId: request.sessionId,\n\t\tplacementGeneration: request.placementGeneration,\n\t\tstatus: \"rejected\",\n\t\treason\n\t};\n}\nfunction absorbed(request, rootDeliveryId, turnId) {\n\treturn {\n\t\ttype: \"im:deliver:result\",\n\t\trequestId: request.requestId,\n\t\tdeliveryId: request.deliveryId,\n\t\tsessionId: request.sessionId,\n\t\tplacementGeneration: request.placementGeneration,\n\t\tstatus: \"absorbed\",\n\t\trootDeliveryId,\n\t\tturnId\n\t};\n}\nfunction rejectedSteer(request, reason) {\n\treturn steerResult(request, \"rejected\", reason);\n}\nfunction deferredSteer(request, reason) {\n\treturn steerResult(request, \"deferred\", reason);\n}\nfunction steerResult(request, status, reason) {\n\treturn {\n\t\ttype: \"im:steer:result\",\n\t\trequestId: request.requestId,\n\t\tdeliveryId: request.deliveryId,\n\t\tsessionId: request.sessionId,\n\t\tplacementGeneration: request.placementGeneration,\n\t\trootDeliveryId: request.rootDeliveryId,\n\t\texpectedTurnId: request.expectedTurnId,\n\t\tstatus,\n\t\treason\n\t};\n}\nfunction mapStorageError(error) {\n\tif (error instanceof SessionBindingConflictError) {\n\t\tif (error.code === \"recovery_required\") return \"session_recovery_required\";\n\t\tif (error.code === \"stale\") return \"stale_configuration\";\n\t\treturn \"session_binding_conflict\";\n\t}\n\treturn \"provider_unavailable\";\n}\nfunction assertMatchingReport(owner, report) {\n\tif (report.turnId !== owner.turnId || report.deliveryId !== owner.request.deliveryId || report.sessionId !== owner.request.sessionId || report.agentId !== owner.request.agentId || report.placementGeneration !== owner.request.placementGeneration) throw new Error(\"The Turn Report does not match its live custody owner\");\n}\n//#endregion\n//#region src/runtime/runtime-connection-errors.ts\nvar RuntimeConnectionError = class extends Error {\n\tfatal;\n\tconstructor(message, fatal) {\n\t\tsuper(message);\n\t\tthis.fatal = fatal;\n\t\tthis.name = \"RuntimeConnectionError\";\n\t}\n};\nvar RuntimeSendError = class extends Error {\n\tcode;\n\tconstructor(code, message) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = \"RuntimeSendError\";\n\t}\n};\nvar RuntimeProtocolFallbackError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"The Server explicitly requires runtime protocol v1\");\n\t\tthis.name = \"RuntimeProtocolFallbackError\";\n\t}\n};\nfunction abortError() {\n\treturn new RuntimeSendError(\"aborted\", \"The runtime operation was aborted\");\n}\nfunction isAbortError(error) {\n\treturn error instanceof RuntimeSendError && error.code === \"aborted\";\n}\nfunction asError$1(error) {\n\treturn error instanceof Error ? error : /* @__PURE__ */ new Error(\"The runtime operation failed\");\n}\n//#endregion\n//#region src/runtime/runtime-connection-helpers.ts\n/**\n* Every frame the Server may send on the business channel.\n*\n* Two independent vocabularies share this channel. `ServerRuntimeBusinessFrameSchema` covers the\n* domain frames — deliveries, reconciles, report results. The runtime-credential control plane\n* (execution open/close, capability results, proxy tickets, the MCP gateway token) is its own union,\n* which the relay parses again itself once a frame is delivered.\n*\n* Both attempts are needed. A credential result that fails to parse here is treated as an invalid\n* frame and the connection is dropped, so the relay's request can never be answered. Nothing noticed\n* because the relay only runs in proxy mode, which is opt-in and off by default.\n*/\nfunction parseServerBusinessFrame(value) {\n\tconst domain = ServerRuntimeBusinessFrameSchema.safeParse(value);\n\tif (domain.success) return domain.data;\n\tconst credential = RuntimeCredentialServerFrameSchema.safeParse(value);\n\treturn credential.success ? credential.data : void 0;\n}\nfunction notifyTarget(protocolVersion, capabilities, frame, listener, logger) {\n\tif (protocolVersion !== RUNTIME_PROTOCOL_V2 || capabilities[RUNTIME_CAPABILITY.channelTarget] === void 0 || !(\"channelTarget\" in frame) || !frame.channelTarget) return;\n\ttry {\n\t\tlistener?.(frame.channelTarget);\n\t} catch {\n\t\tlogger.warn({ category: \"listener\" }, \"Runtime channel target listener failed\");\n\t}\n}\nfunction rawDataBuffer(data) {\n\tif (Buffer.isBuffer(data)) return data;\n\tif (data instanceof ArrayBuffer) return Buffer.from(data);\n\tif (Array.isArray(data)) return Buffer.concat(data);\n\treturn Buffer.from(data);\n}\nfunction safeJson(value) {\n\ttry {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction redactRuntimeReason(message) {\n\treturn redactForLog(message);\n}\nfunction protocolRejectionFields(attempt, state, message) {\n\treturn {\n\t\tattempt: attempt + 1,\n\t\tcategory: \"protocol\",\n\t\treason: redactRuntimeReason(message),\n\t\tstate\n\t};\n}\n//#endregion\n//#region src/runtime/runtime-connection.ts\nconst SERVER_CONTROL_FRAME_TYPES = /* @__PURE__ */ new Set([\n\t\"server:welcome\",\n\t\"auth:result\",\n\t\"computer:register:result\",\n\t\"heartbeat:result\",\n\t\"error\"\n]);\nconst PRIORITIES = [\n\t\"control\",\n\t\"result\",\n\t\"report\",\n\t\"trace\"\n];\nconst defaultScheduler = {\n\tclearTimeout: (timer) => clearTimeout(timer),\n\tsetTimeout: (callback, milliseconds) => setTimeout(callback, milliseconds)\n};\nconst defaultQueueLimits = {\n\tcontrol: 32,\n\tresult: 128,\n\treport: 128,\n\ttrace: 256\n};\nvar RuntimeConnection = class {\n\t#options;\n\t#logger;\n\t#scheduler;\n\t#now;\n\t#queueLimits;\n\t#queues = new Map(PRIORITIES.map((priority) => [priority, []]));\n\t#stateListeners = /* @__PURE__ */ new Set();\n\t#businessListeners = /* @__PURE__ */ new Set();\n\t#registeredWaiters = /* @__PURE__ */ new Set();\n\t#lifecycleAbort = new AbortController();\n\t#active;\n\t#connectionId;\n\t#hasRun = false;\n\t#running = false;\n\t#sendInFlight;\n\t#state = \"stopped\";\n\t#stopped = false;\n\t#protocolVersion = RUNTIME_PROTOCOL_VERSION;\n\t#negotiatedCapabilities = {};\n\t#supportedCapabilities = RUNTIME_CLIENT_CAPABILITY_OFFERS;\n\t#verifiedCapabilities = { imCredentialGrant: 0 };\n\t#verifiedCapabilitiesExpiresAt = 0;\n\t#providerReadiness = /* @__PURE__ */ new Map();\n\t#providerReadinessLeases = /* @__PURE__ */ new Map();\n\t#imCliReadiness = /* @__PURE__ */ new Map();\n\tconstructor(options) {\n\t\tthis.#options = options;\n\t\tthis.#logger = (options.logger ?? createLogger(\"connection\")).child({\n\t\t\tinstallationId: options.computer.computerId,\n\t\t\tinstanceId: options.instanceId\n\t\t});\n\t\tthis.#scheduler = options.scheduler ?? defaultScheduler;\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#queueLimits = {\n\t\t\t...defaultQueueLimits,\n\t\t\t...options.queueLimits\n\t\t};\n\t\tfor (const priority of PRIORITIES) if (!Number.isSafeInteger(this.#queueLimits[priority]) || this.#queueLimits[priority] < 1) throw new Error(`Runtime ${priority} queue limit must be a positive safe integer`);\n\t}\n\tget state() {\n\t\treturn this.#state;\n\t}\n\tget installationId() {\n\t\treturn this.#options.computer.computerId;\n\t}\n\tget serverUrl() {\n\t\treturn this.#options.computer.serverUrl;\n\t}\n\tget instanceId() {\n\t\treturn this.#options.instanceId;\n\t}\n\tsupportsCapability(capability) {\n\t\treturn this.#state === \"registered\" && this.#negotiatedCapabilities[capability] !== void 0;\n\t}\n\tcapabilityVersion(capability) {\n\t\treturn this.#state === \"registered\" ? this.#negotiatedCapabilities[capability] : void 0;\n\t}\n\t/** Composition must advertise only the credential path it actually installed. */\n\tsetCredentialProxyEnabled(enabled) {\n\t\tif (this.#hasRun) throw new Error(\"Credential proxy mode must be configured before connecting\");\n\t\tthis.#supportedCapabilities = { ...RUNTIME_CLIENT_CAPABILITY_OFFERS };\n\t\tif (!enabled) {\n\t\t\tdelete this.#supportedCapabilities[RUNTIME_CAPABILITY.runtimeCredential];\n\t\t\tdelete this.#supportedCapabilities[RUNTIME_CAPABILITY.providerProxy];\n\t\t}\n\t}\n\tsetVerifiedCapabilities(capabilities, validForMs = RUNTIME_CLIENT_CAPABILITY_TTL_MS) {\n\t\tif (!Number.isSafeInteger(validForMs) || validForMs < 1 || validForMs > RUNTIME_CLIENT_CAPABILITY_TTL_MS) throw new RuntimeConnectionError(\"Runtime capability validity is invalid\", true);\n\t\tthis.#verifiedCapabilities = { ...capabilities };\n\t\tthis.#verifiedCapabilitiesExpiresAt = this.#now() + validForMs;\n\t}\n\tsetProviderReadiness(observation, validForMs = RUNTIME_CLIENT_CAPABILITY_TTL_MS) {\n\t\tif (!Number.isSafeInteger(validForMs) || validForMs < 1 || validForMs > RUNTIME_CLIENT_CAPABILITY_TTL_MS) throw new RuntimeConnectionError(\"Runtime provider readiness validity is invalid\", true);\n\t\tthis.#providerReadiness.set(observation.provider, {\n\t\t\tobservation: { ...observation },\n\t\t\texpiresAt: this.#now() + validForMs\n\t\t});\n\t}\n\tleaseProviderReadiness(observation) {\n\t\tthis.setProviderReadiness(observation);\n\t\tconst lease = {\n\t\t\tobservation: { ...observation },\n\t\t\ttoken: Symbol(\"provider-readiness-lease\")\n\t\t};\n\t\tthis.#providerReadinessLeases.set(observation.provider, lease);\n\t\treturn () => {\n\t\t\tif (this.#providerReadinessLeases.get(observation.provider)?.token === lease.token) this.#providerReadinessLeases.delete(observation.provider);\n\t\t};\n\t}\n\tsetImCliReadiness(observation, validForMs = RUNTIME_CLIENT_CAPABILITY_TTL_MS) {\n\t\tif (!Number.isSafeInteger(validForMs) || validForMs < 1 || validForMs > RUNTIME_CLIENT_CAPABILITY_TTL_MS) throw new RuntimeConnectionError(\"IM CLI readiness validity is invalid\", true);\n\t\tthis.#imCliReadiness.set(observation.provider, {\n\t\t\tobservation: { ...observation },\n\t\t\texpiresAt: this.#now() + validForMs\n\t\t});\n\t}\n\t#currentCapabilities() {\n\t\treturn this.#now() <= this.#verifiedCapabilitiesExpiresAt ? { ...this.#verifiedCapabilities } : { imCredentialGrant: 0 };\n\t}\n\t#currentImCliReadiness() {\n\t\tconst now = this.#now();\n\t\treturn IM_CLI_PROVIDERS.flatMap((provider) => {\n\t\t\tconst current = this.#imCliReadiness.get(provider);\n\t\t\treturn current && now <= current.expiresAt ? [{ ...current.observation }] : [];\n\t\t});\n\t}\n\t#currentProviderReadiness(providers) {\n\t\tconst now = this.#now();\n\t\treturn providers.flatMap((provider) => {\n\t\t\tconst lease = this.#providerReadinessLeases.get(provider);\n\t\t\tif (lease) return [{ ...lease.observation }];\n\t\t\tconst current = this.#providerReadiness.get(provider);\n\t\t\treturn current && now <= current.expiresAt ? [{ ...current.observation }] : [];\n\t\t});\n\t}\n\tsubscribeState(listener) {\n\t\tthis.#stateListeners.add(listener);\n\t\tthis.#notifyStateListener(listener, this.#state);\n\t\treturn () => this.#stateListeners.delete(listener);\n\t}\n\tsubscribeBusinessFrames(listener) {\n\t\tthis.#businessListeners.add(listener);\n\t\treturn () => this.#businessListeners.delete(listener);\n\t}\n\twhenRegistered(signal) {\n\t\tif (this.#state === \"registered\") return Promise.resolve();\n\t\tif (this.#stopped || this.#hasRun && !this.#running) return Promise.reject(new RuntimeSendError(\"unavailable\", \"The runtime connection is stopped\"));\n\t\tif (signal?.aborted) return Promise.reject(abortError());\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst onAbort = () => {\n\t\t\t\tcleanup();\n\t\t\t\treject(abortError());\n\t\t\t};\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.#registeredWaiters.delete(waiter);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t};\n\t\t\tconst waiter = {\n\t\t\t\tcleanup,\n\t\t\t\treject: (error) => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t\tresolve: () => {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t};\n\t\t\tthis.#registeredWaiters.add(waiter);\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t});\n\t}\n\tasync run() {\n\t\tif (this.#hasRun) throw new RuntimeConnectionError(\"RuntimeConnection can only be run once\", true);\n\t\tthis.#hasRun = true;\n\t\tthis.#running = true;\n\t\tlet attempt = 0;\n\t\tlet terminalError;\n\t\ttry {\n\t\t\twhile (!this.#stopped) try {\n\t\t\t\tthis.#setState(\"connecting\");\n\t\t\t\tthis.#logger.debug({\n\t\t\t\t\tattempt: attempt + 1,\n\t\t\t\t\tstate: \"connecting\"\n\t\t\t\t}, \"Runtime connection attempt started\");\n\t\t\t\tawait this.#connectOnce(() => {\n\t\t\t\t\tattempt = 0;\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (this.#stopped || isAbortError(error)) break;\n\t\t\t\tif (error instanceof RuntimeProtocolFallbackError && this.#protocolVersion === RUNTIME_PROTOCOL_V2) throw new RuntimeConnectionError(\"Update the Server: required Context Tree support is unavailable\", true);\n\t\t\t\tif (error instanceof RuntimeConnectionError && error.fatal) {\n\t\t\t\t\tthis.#logger.error(protocolRejectionFields(attempt, this.#state, error.message), \"Runtime connection was rejected\");\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (error instanceof OpenTagApiError && ![\"transient\", \"rate_limit\"].includes(error.category)) {\n\t\t\t\t\tthis.#logger.error({\n\t\t\t\t\t\tattempt: attempt + 1,\n\t\t\t\t\t\tcategory: error.category,\n\t\t\t\t\t\tstate: this.#state\n\t\t\t\t\t}, \"Runtime authentication failed\");\n\t\t\t\t\tthrow new RuntimeConnectionError(`${error.message}; run opentag connect again`, true);\n\t\t\t\t}\n\t\t\t\tif (error instanceof Error && error.message.includes(\"not logged in\")) {\n\t\t\t\t\tthis.#logger.error({\n\t\t\t\t\t\tattempt: attempt + 1,\n\t\t\t\t\t\tcategory: \"credential\",\n\t\t\t\t\t\tstate: this.#state\n\t\t\t\t\t}, \"Runtime authentication failed\");\n\t\t\t\t\tthrow new RuntimeConnectionError(`${error.message}; run opentag connect first`, true);\n\t\t\t\t}\n\t\t\t\tattempt += 1;\n\t\t\t\tconst maximum = Math.min(3e4, 1e3 * 2 ** Math.min(attempt - 1, 5));\n\t\t\t\tconst jitter = Math.min(1, Math.max(0, this.#options.jitter?.() ?? Math.random()));\n\t\t\t\tconst delay = Math.floor(maximum * jitter);\n\t\t\t\tthis.#logger.warn({\n\t\t\t\t\tattempt,\n\t\t\t\t\tcategory: connectionErrorCategory(error),\n\t\t\t\t\tdelayMs: delay,\n\t\t\t\t\tstate: this.#state\n\t\t\t\t}, \"Runtime connection lost; retry scheduled\");\n\t\t\t\ttry {\n\t\t\t\t\tawait this.#waitForRetry(delay);\n\t\t\t\t} catch (retryError) {\n\t\t\t\t\tif (this.#stopped || isAbortError(retryError)) break;\n\t\t\t\t\tthrow retryError;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tterminalError = error instanceof Error ? error : /* @__PURE__ */ new Error(\"The runtime connection failed\");\n\t\t\tthrow terminalError;\n\t\t} finally {\n\t\t\tthis.#running = false;\n\t\t\tthis.#setState(\"stopped\");\n\t\t\tthis.#rejectRegisteredWaiters(terminalError ?? new RuntimeSendError(\"unavailable\", \"The runtime connection is stopped\"));\n\t\t\tthis.#rejectAllSends(new RuntimeSendError(\"unavailable\", \"The runtime connection is stopped\"));\n\t\t}\n\t}\n\tstop() {\n\t\tif (this.#stopped) return;\n\t\tthis.#stopped = true;\n\t\tthis.#lifecycleAbort.abort();\n\t\tthis.#setState(\"stopped\");\n\t\tthis.#rejectRegisteredWaiters(new RuntimeSendError(\"unavailable\", \"The runtime connection is stopped\"));\n\t\tthis.#rejectAllSends(new RuntimeSendError(\"unavailable\", \"The runtime connection is stopped\"));\n\t\tconst socket = this.#active;\n\t\tif (!socket) return;\n\t\tif (socket.readyState === WebSocket.CONNECTING) socket.terminate();\n\t\telse if (socket.readyState === WebSocket.OPEN) socket.close(1e3, \"Daemon shutting down\");\n\t}\n\tsend(frame, options = {}) {\n\t\tconst socket = this.#active;\n\t\tif (this.#state !== \"registered\" || !socket || socket.readyState !== WebSocket.OPEN) return Promise.reject(new RuntimeSendError(\"unavailable\", \"The runtime connection is not registered\"));\n\t\tif (options.signal?.aborted) return Promise.reject(abortError());\n\t\tif (typeof frame === \"object\" && frame !== null && \"type\" in frame && frame.type === \"turn:report\" && \"outgoingReplies\" in frame && frame.outgoingReplies !== void 0 && this.capabilityVersion(RUNTIME_CAPABILITY.turnReport) !== 2) return Promise.reject(new RuntimeSendError(\"capability_unavailable\", \"Turn reply snapshots require runtime.turnReport v2\"));\n\t\tlet serialized;\n\t\ttry {\n\t\t\tserialized = JSON.stringify(this.#outboundFrame(frame));\n\t\t} catch (error) {\n\t\t\tif (error instanceof RuntimeSendError) return Promise.reject(error);\n\t\t\treturn Promise.reject(new RuntimeSendError(\"frame_too_large\", \"The runtime frame cannot be serialized\"));\n\t\t}\n\t\tif (runtimeFrameByteLength(serialized) > RUNTIME_MAX_FRAME_BYTES) return Promise.reject(new RuntimeSendError(\"frame_too_large\", `Runtime frames cannot exceed ${RUNTIME_MAX_FRAME_BYTES} bytes`));\n\t\treturn this.#enqueue(socket, serialized, options);\n\t}\n\tasync #connectOnce(onRegistered) {\n\t\tthis.#lifecycleAbort.signal.throwIfAborted();\n\t\tconst socketOptions = {\n\t\t\theaders: {\n\t\t\t\t[PROVIDER_READINESS_V1_HEADER]: \"1\",\n\t\t\t\t[PROVIDER_READINESS_V2_HEADER]: \"2\"\n\t\t\t},\n\t\t\tmaxPayload: RUNTIME_MAX_FRAME_BYTES\n\t\t};\n\t\tconst socketUrl = runtimeWebSocketUrl(this.#options.computer.serverUrl);\n\t\tconst socket = this.#options.webSocketFactory?.(socketUrl, socketOptions) ?? new WebSocket(socketUrl, socketOptions);\n\t\tthis.#active = socket;\n\t\tthis.#connectionId = void 0;\n\t\tthis.#negotiatedCapabilities = {};\n\t\tconst instanceId = this.#options.instanceId;\n\t\tconst protocolVersion = this.#protocolVersion;\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tlet welcome;\n\t\t\tlet expectedNegotiatedCapabilities;\n\t\t\tlet authRequestId;\n\t\t\tlet registerRequestId;\n\t\t\tlet pendingHeartbeatRequestId;\n\t\t\tlet heartbeatTimer;\n\t\t\tlet heartbeatResultTimer;\n\t\t\tlet handshakeTimer;\n\t\t\tlet silenceTimer;\n\t\t\tlet settled = false;\n\t\t\tlet established = false;\n\t\t\tconst clearTimers = () => {\n\t\t\t\tfor (const timer of [\n\t\t\t\t\theartbeatTimer,\n\t\t\t\t\theartbeatResultTimer,\n\t\t\t\t\thandshakeTimer,\n\t\t\t\t\tsilenceTimer\n\t\t\t\t]) if (timer) this.#scheduler.clearTimeout(timer);\n\t\t\t};\n\t\t\tconst finish = (error) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tclearTimers();\n\t\t\t\tthis.#rejectSocketSends(socket, new RuntimeSendError(\"unavailable\", \"The runtime socket closed\"));\n\t\t\t\tif (this.#active === socket) this.#active = void 0;\n\t\t\t\tthis.#connectionId = void 0;\n\t\t\t\terror ? reject(error) : resolve();\n\t\t\t};\n\t\t\tconst failProtocol = (message, closeReason, fatal = true) => {\n\t\t\t\tsocket.close(4400, closeReason);\n\t\t\t\tfinish(new RuntimeConnectionError(message, fatal));\n\t\t\t};\n\t\t\tconst armSilence = () => {\n\t\t\t\tif (!welcome) return;\n\t\t\t\tif (silenceTimer) this.#scheduler.clearTimeout(silenceTimer);\n\t\t\t\tsilenceTimer = this.#scheduler.setTimeout(() => socket.terminate(), welcome.heartbeatTimeoutMs);\n\t\t\t};\n\t\t\tconst scheduleHeartbeat = () => {\n\t\t\t\tif (!welcome || settled || pendingHeartbeatRequestId) return;\n\t\t\t\tconst heartbeatPolicy = welcome;\n\t\t\t\theartbeatTimer = this.#scheduler.setTimeout(() => {\n\t\t\t\t\tif (settled || this.#state !== \"registered\" || this.#active !== socket) return;\n\t\t\t\t\tconst requestId = randomUUID();\n\t\t\t\t\tpendingHeartbeatRequestId = requestId;\n\t\t\t\t\tthis.send({\n\t\t\t\t\t\ttype: \"heartbeat\",\n\t\t\t\t\t\trequestId,\n\t\t\t\t\t\tinstallationId: this.#options.computer.computerId,\n\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\tcapabilities: this.#currentCapabilities(),\n\t\t\t\t\t\t...protocolVersion === RUNTIME_PROTOCOL_V2 ? { protocolVersion: RUNTIME_PROTOCOL_V2 } : {},\n\t\t\t\t\t\t...heartbeatPolicy.providerReadiness ? { providerReadiness: this.#currentProviderReadiness(heartbeatPolicy.providerReadiness.providers) } : {},\n\t\t\t\t\t\timCliReadiness: this.#currentImCliReadiness()\n\t\t\t\t\t}, {\n\t\t\t\t\t\tpriority: \"control\",\n\t\t\t\t\t\tdeadline: this.#now() + heartbeatPolicy.heartbeatTimeoutMs\n\t\t\t\t\t}).then(() => {\n\t\t\t\t\t\tif (settled || pendingHeartbeatRequestId !== requestId) return;\n\t\t\t\t\t\theartbeatResultTimer = this.#scheduler.setTimeout(() => socket.terminate(), heartbeatPolicy.heartbeatTimeoutMs);\n\t\t\t\t\t}, () => socket.terminate());\n\t\t\t\t}, heartbeatPolicy.heartbeatIntervalMs);\n\t\t\t};\n\t\t\thandshakeTimer = this.#scheduler.setTimeout(() => {\n\t\t\t\tsocket.terminate();\n\t\t\t\tfinish(new RuntimeConnectionError(\"The runtime handshake timed out\", false));\n\t\t\t}, this.#options.handshakeTimeoutMs ?? 1e4);\n\t\t\tsocket.on(\"open\", () => {\n\t\t\t\tif (settled || this.#stopped || this.#active !== socket) return;\n\t\t\t\tthis.#setState(\"authenticating\");\n\t\t\t\tauthRequestId = randomUUID();\n\t\t\t\tthis.#sendDirect(socket, protocolVersion === RUNTIME_PROTOCOL_V2 ? {\n\t\t\t\t\ttype: \"auth\",\n\t\t\t\t\trequestId: authRequestId,\n\t\t\t\t\tprotocolVersion: RUNTIME_PROTOCOL_V2,\n\t\t\t\t\tsupportedProtocolVersions: RUNTIME_SUPPORTED_PROTOCOL_VERSIONS,\n\t\t\t\t\tmachineToken: this.#options.machineToken\n\t\t\t\t} : {\n\t\t\t\t\ttype: \"auth\",\n\t\t\t\t\trequestId: authRequestId,\n\t\t\t\t\tprotocolVersion: RUNTIME_PROTOCOL_V1,\n\t\t\t\t\tmachineToken: this.#options.machineToken\n\t\t\t\t}).catch((error) => finish(asError$1(error)));\n\t\t\t});\n\t\t\tsocket.on(\"message\", (data, isBinary) => {\n\t\t\t\tif (settled || this.#active !== socket) return;\n\t\t\t\tif (isBinary) {\n\t\t\t\t\tfailProtocol(\"The server sent a binary runtime frame\", \"Binary frames are not supported\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst buffer = rawDataBuffer(data);\n\t\t\t\tif (buffer.byteLength > RUNTIME_MAX_FRAME_BYTES) {\n\t\t\t\t\tfailProtocol(\"The server sent an oversized runtime frame\", \"Runtime frame is too large\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst decoded = safeJson(buffer.toString(\"utf8\"));\n\t\t\t\tconst envelope = RuntimeFrameEnvelopeSchema.safeParse(decoded);\n\t\t\t\tif (!envelope.success) {\n\t\t\t\t\tfailProtocol(\"The server sent an invalid runtime frame\", \"Invalid server frame\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (envelope.data.type === \"server:welcome\" && envelope.data.protocolVersion !== protocolVersion) {\n\t\t\t\t\tsocket.close(4400, \"Protocol version unsupported\");\n\t\t\t\t\tfinish(new RuntimeConnectionError(\"The runtime protocol version is unsupported\", true));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst parsed = ServerRuntimeFrameSchema.safeParse(decoded);\n\t\t\t\tif (!parsed.success) {\n\t\t\t\t\tif (this.#state === \"registered\" && !SERVER_CONTROL_FRAME_TYPES.has(envelope.data.type) && (this.#options.parseBusinessFrame ?? parseServerBusinessFrame)) {\n\t\t\t\t\t\tlet businessFrame;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (protocolVersion === RUNTIME_PROTOCOL_V2 && envelope.data.connectionId !== this.#connectionId) {\n\t\t\t\t\t\t\t\tfailProtocol(\"The server sent a stale runtime connection fence\", \"Stale connection fence\");\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbusinessFrame = (this.#options.parseBusinessFrame ?? parseServerBusinessFrame)(protocolVersion === RUNTIME_PROTOCOL_V2 ? withoutConnectionId(decoded) : decoded);\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tbusinessFrame = void 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (businessFrame) {\n\t\t\t\t\t\t\tarmSilence();\n\t\t\t\t\t\t\tthis.#dispatchBusinessFrame(businessFrame);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfailProtocol(\"The server sent an invalid runtime frame\", \"Invalid server frame\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst frame = parsed.data;\n\t\t\t\tarmSilence();\n\t\t\t\tif (this.#state === \"authenticating\" && frame.type === \"auth:result\") {\n\t\t\t\t\tif (frame.requestId !== authRequestId) {\n\t\t\t\t\t\tfailProtocol(\"The server returned an unmatched auth result\", \"Auth request mismatch\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!frame.ok) {\n\t\t\t\t\t\tsocket.close(4403, \"Authentication rejected\");\n\t\t\t\t\t\tfinish(new RuntimeConnectionError(`Runtime authentication failed: ${frame.errorCode}`, true));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthis.#setState(\"welcoming\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (this.#state === \"welcoming\" && frame.type === \"server:welcome\") {\n\t\t\t\t\tif (frame.protocolVersion !== protocolVersion) {\n\t\t\t\t\t\tfailProtocol(\"The runtime protocol version is unsupported\", \"Protocol version unsupported\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (frame.protocolVersion === RUNTIME_PROTOCOL_V2) {\n\t\t\t\t\t\texpectedNegotiatedCapabilities = negotiateRuntimeCapabilities(this.#supportedCapabilities, frame.supportedCapabilities);\n\t\t\t\t\t\tconst missing = [...missingRuntimeCapabilities(frame.requiredClientCapabilities, expectedNegotiatedCapabilities), ...missingRuntimeCapabilities(RUNTIME_REQUIRED_SERVER_CAPABILITIES, expectedNegotiatedCapabilities)];\n\t\t\t\t\t\tif (missing.length > 0) {\n\t\t\t\t\t\t\tfailProtocol(`Required runtime capabilities are unavailable: ${[...new Set(missing)].sort().join(\", \")}`, \"Required capability unavailable\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\twelcome = frame;\n\t\t\t\t\tthis.#setState(\"registering\");\n\t\t\t\t\tregisterRequestId = randomUUID();\n\t\t\t\t\tconst registration = {\n\t\t\t\t\t\ttype: \"computer:register\",\n\t\t\t\t\t\trequestId: registerRequestId,\n\t\t\t\t\t\tinstallationId: this.#options.computer.computerId,\n\t\t\t\t\t\tinstanceId,\n\t\t\t\t\t\tdisplayName: this.#options.displayName,\n\t\t\t\t\t\tplatform: this.#options.platform,\n\t\t\t\t\t\tarch: this.#options.arch,\n\t\t\t\t\t\tclientVersion: this.#options.clientVersion,\n\t\t\t\t\t\tcapabilities: this.#currentCapabilities(),\n\t\t\t\t\t\t...welcome.providerReadiness ? { providerReadiness: this.#currentProviderReadiness(welcome.providerReadiness.providers) } : {},\n\t\t\t\t\t\timCliReadiness: this.#currentImCliReadiness()\n\t\t\t\t\t};\n\t\t\t\t\tthis.#sendDirect(socket, protocolVersion === RUNTIME_PROTOCOL_V2 ? {\n\t\t\t\t\t\t...registration,\n\t\t\t\t\t\tprotocolVersion: RUNTIME_PROTOCOL_V2,\n\t\t\t\t\t\tsupportedCapabilities: this.#supportedCapabilities,\n\t\t\t\t\t\trequiredServerCapabilities: RUNTIME_REQUIRED_SERVER_CAPABILITIES\n\t\t\t\t\t} : registration).catch((error) => finish(asError$1(error)));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (this.#state === \"registering\" && frame.type === \"computer:register:result\") {\n\t\t\t\t\tif (frame.requestId !== registerRequestId) {\n\t\t\t\t\t\tfailProtocol(\"The server returned an unmatched registration result\", \"Registration request mismatch\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!frame.ok || !welcome) {\n\t\t\t\t\t\tsocket.close(4403, \"Computer registration rejected\");\n\t\t\t\t\t\tfinish(new RuntimeConnectionError(`Computer registration failed: ${frame.errorCode}`, true));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (protocolVersion === RUNTIME_PROTOCOL_V2) {\n\t\t\t\t\t\tif (!(\"protocolVersion\" in frame) || frame.protocolVersion !== RUNTIME_PROTOCOL_V2 || !frame.connectionId || !frame.negotiatedCapabilities || !expectedNegotiatedCapabilities || !runtimeNegotiatedCapabilitiesEqual(frame.negotiatedCapabilities, expectedNegotiatedCapabilities)) {\n\t\t\t\t\t\t\tfailProtocol(\"The Server returned an invalid capability negotiation\", \"Capability mismatch\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.#connectionId = frame.connectionId;\n\t\t\t\t\t\tthis.#negotiatedCapabilities = { ...frame.negotiatedCapabilities };\n\t\t\t\t\t} else if (\"protocolVersion\" in frame) {\n\t\t\t\t\t\tfailProtocol(\"The Server returned an invalid legacy registration\", \"Registration version mismatch\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\testablished = true;\n\t\t\t\t\tif (handshakeTimer) this.#scheduler.clearTimeout(handshakeTimer);\n\t\t\t\t\tthis.#setState(\"registered\");\n\t\t\t\t\tthis.#resolveRegisteredWaiters();\n\t\t\t\t\tonRegistered();\n\t\t\t\t\tthis.#logger.info({ state: \"registered\" }, \"Runtime connection registered\");\n\t\t\t\t\tarmSilence();\n\t\t\t\t\tscheduleHeartbeat();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (this.#state === \"registered\" && frame.type === \"heartbeat:result\") {\n\t\t\t\t\tif (frame.requestId !== pendingHeartbeatRequestId) {\n\t\t\t\t\t\tfailProtocol(\"The server returned an unmatched heartbeat result\", \"Heartbeat request mismatch\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (protocolVersion === RUNTIME_PROTOCOL_V2 && (!(\"protocolVersion\" in frame) || frame.protocolVersion !== RUNTIME_PROTOCOL_V2 || frame.connectionId !== this.#connectionId) || protocolVersion === RUNTIME_PROTOCOL_V1 && \"protocolVersion\" in frame) {\n\t\t\t\t\t\tfailProtocol(\"The Server returned a stale heartbeat fence\", \"Heartbeat fence mismatch\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (!frame.ok) {\n\t\t\t\t\t\tsocket.close(4403, \"Heartbeat rejected\");\n\t\t\t\t\t\tfinish(new RuntimeConnectionError(`Runtime heartbeat failed: ${frame.errorCode}`, true));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tpendingHeartbeatRequestId = void 0;\n\t\t\t\t\tif (heartbeatResultTimer) this.#scheduler.clearTimeout(heartbeatResultTimer);\n\t\t\t\t\tnotifyTarget(protocolVersion, this.#negotiatedCapabilities, frame, this.#options.onChannelTarget, this.#logger);\n\t\t\t\t\tscheduleHeartbeat();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (frame.type === \"error\") {\n\t\t\t\t\tif (this.#state === \"authenticating\" && protocolVersion === RUNTIME_PROTOCOL_V2 && frame.code === \"PROTOCOL_VERSION_UNSUPPORTED\" && frame.requestId === authRequestId) {\n\t\t\t\t\t\tsocket.close(4400, \"Retrying runtime protocol v1\");\n\t\t\t\t\t\tfinish(new RuntimeProtocolFallbackError());\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst fatal = frame.code !== \"INTERNAL_ERROR\" && frame.code !== \"SERVICE_UNAVAILABLE\";\n\t\t\t\t\tsocket.close(fatal ? 4403 : 1011, frame.message.slice(0, 120));\n\t\t\t\t\tfinish(new RuntimeConnectionError(frame.message, fatal));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfailProtocol(\"The server runtime frame arrived out of order\", \"Frame out of order\");\n\t\t\t});\n\t\t\tsocket.on(\"close\", (code) => {\n\t\t\t\tif (this.#stopped) {\n\t\t\t\t\tfinish();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (code === 4e3) {\n\t\t\t\t\tfinish();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (code === 4001 || code >= 4400 && code < 4500) {\n\t\t\t\t\tfinish(new RuntimeConnectionError(\"The runtime connection was rejected\", true));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfinish(new RuntimeConnectionError(established ? \"The runtime connection closed\" : \"Could not establish runtime connection\", false));\n\t\t\t});\n\t\t\tsocket.on(\"error\", () => void 0);\n\t\t});\n\t}\n\t#enqueue(socket, serialized, options) {\n\t\tconst priority = options.priority ?? \"result\";\n\t\tconst queue = this.#queues.get(priority);\n\t\tif (!queue) return Promise.reject(new RuntimeSendError(\"overflow\", \"The runtime send priority is invalid\"));\n\t\tconst inFlightCount = this.#sendInFlight?.priority === priority ? 1 : 0;\n\t\tif (queue.length + inFlightCount >= this.#queueLimits[priority]) {\n\t\t\tif (priority !== \"trace\") socket.terminate();\n\t\t\treturn Promise.reject(new RuntimeSendError(\"overflow\", `The runtime ${priority} queue is full`));\n\t\t}\n\t\tconst deadline = options.deadline ?? this.#now() + (this.#options.backpressureDeadlineMs ?? 5e3);\n\t\tif (!Number.isFinite(deadline) || deadline <= this.#now()) return Promise.reject(new RuntimeSendError(\"deadline\", \"The runtime send deadline has expired\"));\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst entry = {\n\t\t\t\tdeadline,\n\t\t\t\tpriority,\n\t\t\t\treject,\n\t\t\t\tresolve,\n\t\t\t\tserialized,\n\t\t\t\tsettled: false,\n\t\t\t\tsignal: options.signal,\n\t\t\t\tsocket\n\t\t\t};\n\t\t\tconst expire = () => {\n\t\t\t\tif (entry.settled) return;\n\t\t\t\tthis.#removeQueuedEntry(entry);\n\t\t\t\tthis.#settleEntry(entry, new RuntimeSendError(\"deadline\", \"The runtime send deadline expired\"));\n\t\t\t\tif (priority !== \"trace\" && socket.readyState === WebSocket.OPEN) socket.terminate();\n\t\t\t};\n\t\t\tentry.timeout = this.#scheduler.setTimeout(expire, Math.max(1, deadline - this.#now()));\n\t\t\tif (entry.signal) {\n\t\t\t\tentry.onAbort = () => {\n\t\t\t\t\tif (entry.settled) return;\n\t\t\t\t\tthis.#removeQueuedEntry(entry);\n\t\t\t\t\tthis.#settleEntry(entry, abortError());\n\t\t\t\t};\n\t\t\t\tentry.signal.addEventListener(\"abort\", entry.onAbort, { once: true });\n\t\t\t}\n\t\t\tqueue.push(entry);\n\t\t\tthis.#drain();\n\t\t});\n\t}\n\t#outboundFrame(frame) {\n\t\tif (this.#protocolVersion !== RUNTIME_PROTOCOL_V2) return frame;\n\t\tif (!this.#connectionId || !frame || typeof frame !== \"object\" || Array.isArray(frame)) throw new RuntimeSendError(\"unavailable\", \"The runtime connection fence is unavailable\");\n\t\tconst record = frame;\n\t\tif (record.connectionId !== void 0 && record.connectionId !== this.#connectionId) throw new RuntimeSendError(\"unavailable\", \"The runtime frame carries a stale connection fence\");\n\t\treturn {\n\t\t\t...record,\n\t\t\tconnectionId: this.#connectionId\n\t\t};\n\t}\n\t#drain() {\n\t\tif (this.#sendInFlight || this.#state !== \"registered\") return;\n\t\tconst socket = this.#active;\n\t\tif (!socket || socket.readyState !== WebSocket.OPEN) return;\n\t\tlet entry;\n\t\tfor (const priority of PRIORITIES) {\n\t\t\tentry = this.#queues.get(priority)?.shift();\n\t\t\tif (entry) break;\n\t\t}\n\t\tif (!entry) return;\n\t\tif (entry.socket !== socket) {\n\t\t\tthis.#settleEntry(entry, new RuntimeSendError(\"unavailable\", \"The runtime socket was replaced\"));\n\t\t\tthis.#drain();\n\t\t\treturn;\n\t\t}\n\t\tif (entry.deadline <= this.#now()) {\n\t\t\tthis.#settleEntry(entry, new RuntimeSendError(\"deadline\", \"The runtime send deadline expired\"));\n\t\t\tif (entry.priority !== \"trace\") socket.terminate();\n\t\t\tthis.#drain();\n\t\t\treturn;\n\t\t}\n\t\tthis.#sendInFlight = entry;\n\t\ttry {\n\t\t\tsocket.send(entry.serialized, (error) => {\n\t\t\t\tif (this.#sendInFlight === entry) this.#sendInFlight = void 0;\n\t\t\t\tthis.#settleEntry(entry, error ? new RuntimeSendError(\"unavailable\", \"The runtime frame could not be sent\") : void 0);\n\t\t\t\tthis.#drain();\n\t\t\t});\n\t\t} catch {\n\t\t\tthis.#sendInFlight = void 0;\n\t\t\tthis.#settleEntry(entry, new RuntimeSendError(\"unavailable\", \"The runtime frame could not be sent\"));\n\t\t\tsocket.terminate();\n\t\t\tthis.#drain();\n\t\t}\n\t}\n\t#settleEntry(entry, error) {\n\t\tif (entry.settled) return;\n\t\tentry.settled = true;\n\t\tif (entry.timeout) this.#scheduler.clearTimeout(entry.timeout);\n\t\tif (entry.signal && entry.onAbort) entry.signal.removeEventListener(\"abort\", entry.onAbort);\n\t\terror ? entry.reject(error) : entry.resolve();\n\t}\n\t#removeQueuedEntry(entry) {\n\t\tconst queue = this.#queues.get(entry.priority);\n\t\tconst index = queue?.indexOf(entry) ?? -1;\n\t\tif (queue && index >= 0) queue.splice(index, 1);\n\t}\n\t#rejectSocketSends(socket, error) {\n\t\tif (this.#sendInFlight?.socket === socket) {\n\t\t\tconst inFlight = this.#sendInFlight;\n\t\t\tthis.#sendInFlight = void 0;\n\t\t\tthis.#settleEntry(inFlight, error);\n\t\t}\n\t\tfor (const queue of this.#queues.values()) for (const entry of [...queue]) {\n\t\t\tif (entry.socket !== socket) continue;\n\t\t\tthis.#removeQueuedEntry(entry);\n\t\t\tthis.#settleEntry(entry, error);\n\t\t}\n\t}\n\t#rejectAllSends(error) {\n\t\tif (this.#sendInFlight) {\n\t\t\tconst inFlight = this.#sendInFlight;\n\t\t\tthis.#sendInFlight = void 0;\n\t\t\tthis.#settleEntry(inFlight, error);\n\t\t}\n\t\tfor (const queue of this.#queues.values()) for (const entry of queue.splice(0)) this.#settleEntry(entry, error);\n\t}\n\tasync #sendDirect(socket, frame) {\n\t\tconst serialized = JSON.stringify(frame);\n\t\tif (runtimeFrameByteLength(serialized) > RUNTIME_MAX_FRAME_BYTES) throw new RuntimeSendError(\"frame_too_large\", \"The runtime control frame is too large\");\n\t\tif (socket.readyState !== WebSocket.OPEN || this.#active !== socket) throw new RuntimeSendError(\"unavailable\", \"The runtime socket is unavailable\");\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tsocket.send(serialized, (error) => {\n\t\t\t\terror ? reject(new RuntimeSendError(\"unavailable\", \"The runtime control frame could not be sent\")) : resolve();\n\t\t\t});\n\t\t});\n\t}\n\t#dispatchBusinessFrame(frame) {\n\t\tfor (const listener of this.#businessListeners) Promise.resolve().then(() => listener(frame)).catch((error) => this.#logger.warn({\n\t\t\tcategory: \"listener\",\n\t\t\terrorCategory: listenerFailureCategory(error),\n\t\t\tframeType: frame.type\n\t\t}, \"Runtime business frame listener failed\"));\n\t}\n\t#setState(state) {\n\t\tif (this.#state === state) return;\n\t\tthis.#state = state;\n\t\tthis.#logger.debug({ state }, \"Runtime connection state changed\");\n\t\tfor (const listener of this.#stateListeners) this.#notifyStateListener(listener, state);\n\t}\n\t#notifyStateListener(listener, state) {\n\t\ttry {\n\t\t\tlistener(state);\n\t\t} catch {\n\t\t\tthis.#logger.warn({\n\t\t\t\tcategory: \"listener\",\n\t\t\t\tstate\n\t\t\t}, \"Runtime connection state listener failed\");\n\t\t}\n\t}\n\t#resolveRegisteredWaiters() {\n\t\tfor (const waiter of [...this.#registeredWaiters]) waiter.resolve();\n\t}\n\t#rejectRegisteredWaiters(error) {\n\t\tfor (const waiter of [...this.#registeredWaiters]) waiter.reject(error);\n\t}\n\tasync #waitForRetry(milliseconds) {\n\t\tconst signal = this.#lifecycleAbort.signal;\n\t\tif (this.#options.waitForRetry) {\n\t\t\tawait raceWithAbort(this.#options.waitForRetry(milliseconds, signal), signal);\n\t\t\treturn;\n\t\t}\n\t\tawait new Promise((resolve, reject) => {\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(abortError());\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst timer = this.#scheduler.setTimeout(() => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve();\n\t\t\t}, milliseconds);\n\t\t\tconst onAbort = () => {\n\t\t\t\tthis.#scheduler.clearTimeout(timer);\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(abortError());\n\t\t\t};\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t});\n\t}\n};\nfunction listenerFailureCategory(error) {\n\tif (error instanceof RuntimeStorageError) return `runtime_storage_${error.code}`;\n\tif (error instanceof RuntimeSendError) return `runtime_send_${error.code}`;\n\tif (error instanceof RuntimeConnectionError) return \"runtime_connection\";\n\treturn error instanceof Error ? \"error\" : \"non_error\";\n}\nfunction connectionErrorCategory(error) {\n\tif (error instanceof OpenTagApiError) return error.category;\n\tif (error instanceof RuntimeConnectionError) return error.fatal ? \"protocol\" : \"transport\";\n\tif (error instanceof RuntimeSendError) return error.code;\n\treturn \"unexpected\";\n}\nfunction withoutConnectionId(value) {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return value;\n\tconst frame = { ...value };\n\tdelete frame.connectionId;\n\treturn frame;\n}\nasync function raceWithAbort(promise, signal) {\n\tif (signal.aborted) throw abortError();\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = () => {\n\t\t\tcleanup();\n\t\t\treject(abortError());\n\t\t};\n\t\tconst cleanup = () => signal.removeEventListener(\"abort\", onAbort);\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then((value) => {\n\t\t\tcleanup();\n\t\t\tresolve(value);\n\t\t}, (error) => {\n\t\t\tcleanup();\n\t\t\treject(error);\n\t\t});\n\t});\n}\n//#endregion\n//#region src/runtime/turn-report-owner.ts\nvar TurnReportOwnerStoppedError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"The Turn Report owner is stopped\");\n\t\tthis.name = \"TurnReportOwnerStoppedError\";\n\t}\n};\nvar TurnReportOwner = class {\n\t#connection;\n\t#id;\n\t#maxPending;\n\t#retryDelayMs;\n\t#metrics;\n\t#now;\n\t#onFailure;\n\t#persistence;\n\t#retryPolicy;\n\t#scheduler;\n\t#inFlight = /* @__PURE__ */ new Set();\n\t#pending = /* @__PURE__ */ new Map();\n\t#records = /* @__PURE__ */ new Map();\n\t#retryTimers = /* @__PURE__ */ new Map();\n\t#unsubscribe;\n\t#readyPromise;\n\t#stopped = false;\n\tconstructor(options) {\n\t\tthis.#connection = options.connection;\n\t\tthis.#id = options.id ?? randomUUID;\n\t\tthis.#maxPending = options.maxPending ?? 99;\n\t\tthis.#retryDelayMs = options.retryDelayMs ?? 5e3;\n\t\tthis.#metrics = options.metrics;\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#onFailure = options.onFailure;\n\t\tthis.#persistence = options.persistence;\n\t\tthis.#retryPolicy = normalizeRetryPolicy({\n\t\t\t...options.retryPolicy,\n\t\t\t...options.retryDelayMs ? { baseDelayMs: options.retryDelayMs } : {}\n\t\t});\n\t\tthis.#scheduler = options.scheduler ?? defaultRuntimeRetryScheduler;\n\t\tif (!Number.isSafeInteger(this.#maxPending) || this.#maxPending < 1) throw new Error(\"Turn Report pending limit must be a positive safe integer\");\n\t\tif (!Number.isSafeInteger(this.#retryDelayMs) || this.#retryDelayMs < 1) throw new Error(\"Turn Report retry delay must be a positive safe integer\");\n\t\tthis.#readyPromise = this.#hydrate();\n\t\tthis.#unsubscribe = this.#connection.subscribeState((state) => this.#onConnectionState(state));\n\t}\n\tget pendingCount() {\n\t\treturn this.#pending.size;\n\t}\n\tready() {\n\t\treturn this.#readyPromise;\n\t}\n\tgetState(turnId) {\n\t\treturn this.#records.get(turnId);\n\t}\n\tmetricsSnapshot() {\n\t\treturn this.#metrics?.snapshot();\n\t}\n\tcreate(input) {\n\t\tconst report = {\n\t\t\ttype: \"turn:report\",\n\t\t\trequestId: this.#id(),\n\t\t\t...input,\n\t\t\tresultHash: computeTurnResultHash(input)\n\t\t};\n\t\treturn TurnReportRequestSchema.parse(report);\n\t}\n\tsubmit(reportInput, confirm, options = {}) {\n\t\tif (this.#stopped) return Promise.reject(new TurnReportOwnerStoppedError());\n\t\tconst report = TurnReportRequestSchema.parse(reportInput);\n\t\tconst existing = this.#pending.get(report.turnId);\n\t\tif (existing) return this.#reusePending(existing, report, confirm, options);\n\t\tconst stored = this.#records.get(report.turnId);\n\t\tif (stored?.status === \"succeeded\") return Promise.resolve();\n\t\tif (this.#pending.size >= this.#maxPending) return Promise.reject(/* @__PURE__ */ new Error(\"The Turn Report owner reached its pending limit\"));\n\t\treturn this.#createPending(report, confirm, options, stored);\n\t}\n\t#reusePending(existing, report, confirm, options) {\n\t\tif (existing.report.requestId !== report.requestId || existing.report.resultHash !== report.resultHash) return Promise.reject(/* @__PURE__ */ new Error(\"A different Turn Report already owns this Turn\"));\n\t\tif (existing.settling) return existing.promise;\n\t\tif (options.onTerminal) {\n\t\t\tif (existing.serverStatus) this.#notifyTerminal(options.onTerminal, existing.serverStatus);\n\t\t\telse existing.terminalListeners.add(options.onTerminal);\n\t\t}\n\t\texisting.confirm = confirm;\n\t\tif (this.#connection.state === \"registered\" && !existing.serverStatus) {\n\t\t\tif (existing.sending) existing.resendRequested = true;\n\t\t\telse this.#send(existing);\n\t\t}\n\t\treturn existing.promise;\n\t}\n\t#createPending(report, confirm, options, stored) {\n\t\tlet resolvePromise;\n\t\tlet rejectPromise;\n\t\tconst promise = new Promise((resolve, reject) => {\n\t\t\tresolvePromise = resolve;\n\t\t\trejectPromise = reject;\n\t\t});\n\t\tconst record = stored?.status === \"dead-letter\" ? resetDeadLetterRecord(stored, this.#now()) : stored;\n\t\tconst pending = {\n\t\t\tcapabilityRejected: false,\n\t\t\treport,\n\t\t\tconfirm,\n\t\t\tconfirming: false,\n\t\t\tsettling: false,\n\t\t\tsending: false,\n\t\t\tresendRequested: false,\n\t\t\tpromise,\n\t\t\tresolve: () => resolvePromise?.(),\n\t\t\treject: (error) => rejectPromise?.(error),\n\t\t\tterminalListeners: new Set(options.onTerminal ? [options.onTerminal] : []),\n\t\t\trecord: record ?? {\n\t\t\t\tacceptedAt: this.#now(),\n\t\t\t\tattempts: 0,\n\t\t\t\tkey: report.turnId,\n\t\t\t\tkind: \"turn-report\",\n\t\t\t\tpayload: report,\n\t\t\t\tstatus: \"accepted\",\n\t\t\t\tupdatedAt: this.#now()\n\t\t\t},\n\t\t\tpersistencePending: true\n\t\t};\n\t\tthis.#pending.set(report.turnId, pending);\n\t\tthis.#track(this.#persist(pending.record).finally(() => {\n\t\t\tpending.persistencePending = false;\n\t\t}).then(() => {\n\t\t\tif (this.#connection.state === \"registered\") this.#send(pending);\n\t\t}).catch((error) => this.#handleFailure(pending, \"persist\", error)));\n\t\treturn promise;\n\t}\n\tasync handleResult(input) {\n\t\tconst result = TurnReportResultSchema.parse(input);\n\t\tconst pending = this.#pending.get(result.turnId);\n\t\tif (!pending) return false;\n\t\tif (result.requestId !== pending.report.requestId || result.resultHash !== pending.report.resultHash) return false;\n\t\tif (result.status === \"unsupported_capability\") {\n\t\t\tpending.capabilityRejected = true;\n\t\t\tthis.#clearRetry(pending);\n\t\t\treturn true;\n\t\t}\n\t\tif (result.status === \"conflict\" || result.status === \"stale_generation\") return this.#handleTerminalResult(pending, result.status);\n\t\tif (pending.confirming || !pending.confirm) return true;\n\t\treturn this.#confirmResult(pending);\n\t}\n\tasync #handleTerminalResult(pending, status) {\n\t\tpending.serverStatus = status;\n\t\tthis.#clearRetry(pending);\n\t\tconst failure = {\n\t\t\tcategory: \"conflict\",\n\t\t\tcode: status,\n\t\t\tmessage: `Server rejected the Turn Report: ${status}`,\n\t\t\tphase: \"request\",\n\t\t\trequestId: pending.report.requestId,\n\t\t\tretryability: \"never\"\n\t\t};\n\t\tthis.#emitFailure(failure);\n\t\ttry {\n\t\t\tif (!await this.#transition(pending, \"failed\", { lastError: failure })) return false;\n\t\t} catch (error) {\n\t\t\tthis.#settle(pending, {\n\t\t\t\tkind: \"reject\",\n\t\t\t\terror: asError(error)\n\t\t\t});\n\t\t\treturn true;\n\t\t}\n\t\tconst listeners = [...pending.terminalListeners];\n\t\tpending.terminalListeners.clear();\n\t\tfor (const listener of listeners) this.#notifyTerminal(listener, status);\n\t\treturn true;\n\t}\n\tasync #confirmResult(pending) {\n\t\tconst confirm = pending.confirm;\n\t\tif (!confirm) return true;\n\t\tpending.confirming = true;\n\t\tthis.#clearRetry(pending);\n\t\ttry {\n\t\t\tawait confirm();\n\t\t\tpending.confirming = false;\n\t\t\tpending.settling = true;\n\t\t\ttry {\n\t\t\t\tawait this.#transition(pending, \"succeeded\", { nextAttemptAt: void 0 }, { settling: true });\n\t\t\t\tif (!this.#releaseSettling(pending)) return true;\n\t\t\t\tthis.#settle(pending, { kind: \"resolve\" });\n\t\t\t} catch (error) {\n\t\t\t\tthis.#settle(pending, {\n\t\t\t\t\tkind: \"reject\",\n\t\t\t\t\terror: asError(error)\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tpending.confirming = false;\n\t\t\tawait this.#handleFailure(pending, \"confirmation\", error);\n\t\t}\n\t\treturn true;\n\t}\n\tget(turnId) {\n\t\tconst pending = this.#pending.get(turnId);\n\t\tif (!pending) return void 0;\n\t\treturn {\n\t\t\treport: pending.report,\n\t\t\t...pending.serverStatus ? { serverStatus: pending.serverStatus } : {}\n\t\t};\n\t}\n\trearmTerminal(claim) {\n\t\tif (this.#stopped) return false;\n\t\tconst pending = this.#pending.get(claim.turnId);\n\t\tif (!pending?.serverStatus || pending.settling || !reportMatchesRearmClaim(pending.report, claim)) return false;\n\t\tpending.serverStatus = void 0;\n\t\treturn true;\n\t}\n\tstop() {\n\t\tif (this.#stopped) return;\n\t\tthis.#stopped = true;\n\t\tthis.#unsubscribe();\n\t\tfor (const timer of this.#retryTimers.values()) timer.cancel();\n\t\tthis.#retryTimers.clear();\n\t\tconst error = new TurnReportOwnerStoppedError();\n\t\tfor (const pending of this.#pending.values()) this.#settle(pending, {\n\t\t\tkind: \"reject\",\n\t\t\terror\n\t\t});\n\t}\n\tasync settled() {\n\t\tawait this.#readyPromise.catch(() => void 0);\n\t\twhile (this.#inFlight.size > 0) await Promise.allSettled([...this.#inFlight]);\n\t}\n\t#onConnectionState(state) {\n\t\tif (state !== \"registered\" || this.#stopped) return;\n\t\tthis.#track(this.#readyPromise.then(() => {\n\t\t\tfor (const pending of this.#pending.values()) {\n\t\t\t\tthis.#clearRetry(pending);\n\t\t\t\tpending.capabilityRejected = false;\n\t\t\t\tif (pending.sending) pending.resendRequested = true;\n\t\t\t\telse this.#send(pending);\n\t\t\t}\n\t\t}));\n\t}\n\t#send(pending) {\n\t\tif (!this.#canWrite(pending) || !this.#canStartRunning(pending) || pending.sending || pending.serverStatus) return;\n\t\tif (!this.#canSendReport(pending)) return;\n\t\tthis.#clearRetry(pending);\n\t\tpending.sending = true;\n\t\tthis.#track(this.#transition(pending, \"running\", { nextAttemptAt: void 0 }).then((transitioned) => {\n\t\t\tif (transitioned && this.#canSendReport(pending)) return this.#connection.send(pending.report, { priority: \"report\" });\n\t\t}).catch((error) => {\n\t\t\tif (error instanceof RuntimeSendError && error.code === \"capability_unavailable\") {\n\t\t\t\tpending.capabilityRejected = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn this.#handleFailure(pending, \"transport\", error);\n\t\t}).finally(() => {\n\t\t\tpending.sending = false;\n\t\t\tif (pending.resendRequested && this.#isCurrent(pending) && this.#connection.state === \"registered\") {\n\t\t\t\tpending.resendRequested = false;\n\t\t\t\tthis.#send(pending);\n\t\t\t} else if (this.#isCurrent(pending) && !pending.serverStatus) {\n\t\t\t\tconst record = this.#records.get(pending.report.turnId);\n\t\t\t\tif (record) this.#scheduleRetry(pending, record);\n\t\t\t}\n\t\t}));\n\t}\n\t#scheduleRetry(pending, record) {\n\t\tif (this.#retryTimers.has(record.key) || this.#stopped || pending.serverStatus || pending.settling) return;\n\t\tif (!this.#canSendReport(pending)) return;\n\t\tconst delay = record.nextAttemptAt === void 0 ? this.#retryDelayMs : Math.max(0, record.nextAttemptAt - this.#now());\n\t\tconst timer = this.#scheduler.schedule(delay, () => {\n\t\t\tthis.#retryTimers.delete(record.key);\n\t\t\tif (this.#connection.state !== \"registered\") return;\n\t\t\tif (!this.#canSendReport(pending)) return;\n\t\t\tconst current = this.#records.get(record.key);\n\t\t\tif (!current || current.status === \"succeeded\" || pending.serverStatus || !this.#canWrite(pending)) return;\n\t\t\tif (current.status === \"retryable\") this.#track(this.#transition(pending, \"accepted\", { nextAttemptAt: void 0 }).then(() => this.#send(pending)).catch(() => void 0));\n\t\t\telse this.#track(this.#handleFailure(pending, \"transport\", /* @__PURE__ */ new Error(\"Turn Report acknowledgement timed out\")));\n\t\t});\n\t\tthis.#retryTimers.set(record.key, timer);\n\t}\n\t#clearRetry(pending) {\n\t\tconst timer = this.#retryTimers.get(pending.report.turnId);\n\t\tif (!timer) return;\n\t\ttimer.cancel();\n\t\tthis.#retryTimers.delete(pending.report.turnId);\n\t}\n\tasync #hydrate() {\n\t\tif (!this.#persistence) return;\n\t\tconst records = await this.#persistence.list(\"turn-report\");\n\t\tfor (const stored of records) {\n\t\t\tconst parsed = TurnReportRequestSchema.safeParse(stored.payload);\n\t\t\tif (!parsed.success) continue;\n\t\t\tlet record = {\n\t\t\t\t...stored,\n\t\t\t\tpayload: parsed.data\n\t\t\t};\n\t\t\tthis.#records.set(record.key, record);\n\t\t\tif (record.status === \"succeeded\" || record.status === \"dead-letter\") continue;\n\t\t\tif (record.status === \"failed\" && (record.lastError?.code === \"conflict\" || record.lastError?.code === \"stale_generation\")) {\n\t\t\t\tthis.#addHydratedPending(record, record.lastError.code);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (retryExhausted(this.#retryPolicy, record, this.#now())) {\n\t\t\t\trecord = {\n\t\t\t\t\t...record,\n\t\t\t\t\tstatus: \"dead-letter\",\n\t\t\t\t\tnextAttemptAt: void 0,\n\t\t\t\t\tupdatedAt: this.#now()\n\t\t\t\t};\n\t\t\t\tawait this.#persist(record);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (record.status === \"running\") {\n\t\t\t\trecord = {\n\t\t\t\t\t...record,\n\t\t\t\t\tstatus: \"retryable\",\n\t\t\t\t\tnextAttemptAt: this.#now(),\n\t\t\t\t\tupdatedAt: this.#now()\n\t\t\t\t};\n\t\t\t\tawait this.#persist(record);\n\t\t\t}\n\t\t\tthis.#addHydratedPending(record);\n\t\t}\n\t}\n\t#addHydratedPending(record, serverStatus) {\n\t\tlet resolvePromise;\n\t\tlet rejectPromise;\n\t\tconst promise = new Promise((resolve, reject) => {\n\t\t\tresolvePromise = resolve;\n\t\t\trejectPromise = reject;\n\t\t});\n\t\tconst pending = {\n\t\t\tcapabilityRejected: false,\n\t\t\treport: record.payload,\n\t\t\tconfirm: void 0,\n\t\t\tconfirming: false,\n\t\t\tsettling: false,\n\t\t\tsending: false,\n\t\t\tresendRequested: false,\n\t\t\tpromise,\n\t\t\tresolve: resolvePromise,\n\t\t\treject: rejectPromise,\n\t\t\trecord,\n\t\t\tpersistencePending: false,\n\t\t\t...serverStatus ? { serverStatus } : {},\n\t\t\tterminalListeners: /* @__PURE__ */ new Set()\n\t\t};\n\t\tpending.promise.catch(() => void 0);\n\t\tthis.#pending.set(record.key, pending);\n\t}\n\tasync #transition(pending, status, fields = {}, options = {}) {\n\t\tif (!options.detached && !this.#canWrite(pending, options.settling) || options.detached && this.#stopped) return void 0;\n\t\tconst record = this.#records.get(pending.report.turnId) ?? pending.record;\n\t\tconst next = {\n\t\t\t...record,\n\t\t\t...fields,\n\t\t\tstatus,\n\t\t\tupdatedAt: this.#now(),\n\t\t\tpayload: pending.report\n\t\t};\n\t\tthis.#metrics?.transition(\"turn-report\", record.status, status);\n\t\tawait this.#persist(next);\n\t\tif (!options.detached && !this.#isCurrent(pending)) return void 0;\n\t\tpending.record = next;\n\t\treturn next;\n\t}\n\tasync #handleFailure(pending, phase, error) {\n\t\tif (!this.#canWrite(pending) || pending.serverStatus) return;\n\t\tconst record = this.#records.get(pending.report.turnId) ?? pending.record;\n\t\tconst failure = durableFailureFromUnknown(pending.report.requestId, phase, error, phase === \"confirmation\" ? \"confirmation_failed\" : phase === \"transport\" ? \"transport_unavailable\" : \"runtime_failed\");\n\t\tthis.#emitFailure(failure);\n\t\tconst attempts = record.attempts + 1;\n\t\tconst now = this.#now();\n\t\tconst candidate = {\n\t\t\t...record,\n\t\t\tattempts,\n\t\t\tlastError: failure,\n\t\t\tupdatedAt: now\n\t\t};\n\t\tif (failure.retryability === \"never\" || retryExhausted(this.#retryPolicy, candidate, now)) {\n\t\t\tawait this.#transition(pending, \"dead-letter\", {\n\t\t\t\t...candidate,\n\t\t\t\tnextAttemptAt: void 0\n\t\t\t}).catch(() => void 0);\n\t\t\tthis.#settle(pending, {\n\t\t\t\tkind: \"reject\",\n\t\t\t\terror: new RuntimeDurabilityFailure(failure)\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tlet retryable;\n\t\ttry {\n\t\t\tretryable = await this.#transition(pending, \"retryable\", {\n\t\t\t\t...candidate,\n\t\t\t\tnextAttemptAt: now + retryDelay(this.#retryPolicy, attempts)\n\t\t\t});\n\t\t} catch {\n\t\t\tif (this.#isCurrent(pending)) this.#scheduleRetry(pending, {\n\t\t\t\t...candidate,\n\t\t\t\tnextAttemptAt: now + retryDelay(this.#retryPolicy, attempts)\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (!retryable) return;\n\t\tthis.#scheduleRetry(pending, retryable);\n\t}\n\tasync #persist(record) {\n\t\tawait this.#persistence?.write(record);\n\t\tthis.#records.set(record.key, record);\n\t}\n\t#isCurrent(pending) {\n\t\treturn this.#pending.get(pending.report.turnId) === pending;\n\t}\n\t#canWrite(pending, allowSettling = false) {\n\t\treturn !this.#stopped && this.#isCurrent(pending) && (allowSettling || !pending.persistencePending) && (allowSettling || !pending.settling);\n\t}\n\t#canStartRunning(pending) {\n\t\tconst record = this.#records.get(pending.report.turnId) ?? pending.record;\n\t\treturn record.status !== \"succeeded\" && record.status !== \"dead-letter\";\n\t}\n\t#canSendReport(pending) {\n\t\treturn !pending.capabilityRejected && (pending.report.outgoingReplies === void 0 || this.#connection.capabilityVersion?.(RUNTIME_CAPABILITY.turnReport) === 2);\n\t}\n\t#detach(pending) {\n\t\tif (!this.#isCurrent(pending)) return false;\n\t\tthis.#clearRetry(pending);\n\t\tthis.#pending.delete(pending.report.turnId);\n\t\treturn true;\n\t}\n\t#releaseSettling(pending) {\n\t\tif (!this.#isCurrent(pending)) return false;\n\t\tpending.settling = false;\n\t\treturn true;\n\t}\n\t#settle(pending, settlement, options = {}) {\n\t\tif (!options.detached && !this.#detach(pending)) return false;\n\t\tif (settlement.kind === \"resolve\") pending.resolve();\n\t\telse pending.reject(settlement.error);\n\t\treturn true;\n\t}\n\t#track(operation) {\n\t\tthis.#inFlight.add(operation);\n\t\toperation.then(() => this.#inFlight.delete(operation), () => this.#inFlight.delete(operation));\n\t\treturn operation;\n\t}\n\t#emitFailure(failure) {\n\t\ttry {\n\t\t\tthis.#onFailure?.(failure);\n\t\t} catch {}\n\t}\n\t#notifyTerminal(listener, status) {\n\t\ttry {\n\t\t\tlistener(status);\n\t\t} catch {}\n\t}\n};\nfunction resetDeadLetterRecord(record, acceptedAt) {\n\tconst { lastError: _lastError, nextAttemptAt: _nextAttemptAt, ...retained } = record;\n\treturn {\n\t\t...retained,\n\t\tacceptedAt,\n\t\tattempts: 0,\n\t\tstatus: \"accepted\",\n\t\tupdatedAt: acceptedAt\n\t};\n}\nfunction reportMatchesRearmClaim(report, claim) {\n\treturn report.agentId === claim.agentId && report.deliveryId === claim.deliveryId && report.placementGeneration === claim.placementGeneration && report.resultHash === claim.resultHash && report.sessionId === claim.sessionId && report.turnId === claim.turnId;\n}\nfunction asError(value) {\n\treturn value instanceof Error ? value : /* @__PURE__ */ new Error(\"Turn Report persistence failed\");\n}\nfunction normalizeRetryPolicy(overrides) {\n\tconst policy = {\n\t\t...DEFAULT_RUNTIME_RETRY_POLICY,\n\t\t...overrides\n\t};\n\tfor (const [name, value] of Object.entries(policy)) if (!Number.isSafeInteger(value) || value < 1) throw new Error(`Runtime retry ${name} must be a positive safe integer`);\n\treturn policy;\n}\n//#endregion\n//#region src/runtime/client-runtime-composition.ts\nconst DEFAULT_CAPABILITY_REFRESH_INTERVAL_MS = Math.floor(RUNTIME_CLIENT_CAPABILITY_TTL_MS / 2);\nconst DEFAULT_PROVIDER_PROBE_DEADLINE_MS = 1e4;\nfunction createLoginShellDiscovery() {\n\tlet enabled = false;\n\tfunction includeLoginShell() {\n\t\treturn enabled;\n\t}\n\treturn {\n\t\toptions: { includeLoginShell },\n\t\tenable() {\n\t\t\tenabled = true;\n\t\t}\n\t};\n}\nasync function waitForSharedRefresh(refresh, signal) {\n\tif (!signal) return refresh;\n\tsignal.throwIfAborted();\n\tlet rejectAborted;\n\tconst aborted = new Promise((_resolve, reject) => {\n\t\trejectAborted = reject;\n\t});\n\tconst onAbort = () => rejectAborted(signal.reason);\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\ttry {\n\t\tconst available = await Promise.race([refresh, aborted]);\n\t\tsignal.throwIfAborted();\n\t\treturn available;\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\nfunction providerProbeDeadline(value) {\n\tconst deadline = value ?? DEFAULT_PROVIDER_PROBE_DEADLINE_MS;\n\tif (!Number.isSafeInteger(deadline) || deadline < 1) throw new Error(\"Agent Runtime provider probe deadline must be a positive safe integer\");\n\treturn deadline;\n}\nfunction startSharedProviderRefresh(context, providerId) {\n\tconst controller = new AbortController();\n\tlet resolveOwner;\n\tlet rejectOwner;\n\tconst owner = {\n\t\tcontroller,\n\t\tpromise: new Promise((resolvePromise, rejectPromise) => {\n\t\t\tresolveOwner = resolvePromise;\n\t\t\trejectOwner = rejectPromise;\n\t\t}),\n\t\tsettled: false,\n\t\twaiters: 0\n\t};\n\tcontext.sharedProviderRefreshes.set(providerId, owner);\n\tconst deadlineError = /* @__PURE__ */ new Error(`Agent Runtime provider probe exceeded its deadline: ${providerId}`);\n\tconst deadlineTimer = setTimeout(() => controller.abort(deadlineError), context.providerProbeDeadlineMs);\n\tdeadlineTimer.unref();\n\trunSharedProviderRefresh(context, providerId, owner, deadlineError, deadlineTimer).then(resolveOwner, rejectOwner);\n\towner.promise.catch(() => void 0);\n\treturn owner;\n}\nasync function runSharedProviderRefresh(context, providerId, owner, deadlineError, deadlineTimer) {\n\tlet releaseReadiness;\n\ttry {\n\t\tconst provider = providerId;\n\t\tif (context.providers.isReady(providerId)) releaseReadiness = context.connection.leaseProviderReadiness({\n\t\t\tprovider,\n\t\t\tstatus: \"ready\"\n\t\t});\n\t\tif (!releaseReadiness) context.connection.setProviderReadiness({\n\t\t\tprovider,\n\t\t\tstatus: \"checking\"\n\t\t});\n\t\tconst ownerSignal = AbortSignal.any([context.readinessSignal, owner.controller.signal]);\n\t\tlet settled;\n\t\ttry {\n\t\t\tsettled = { available: await context.providers.refresh(providerId, ownerSignal) };\n\t\t} catch (error) {\n\t\t\tsettled = { error };\n\t\t}\n\t\treturn resolveSharedProviderRefreshResult(context, providerId, owner, deadlineError, settled);\n\t} finally {\n\t\towner.settled = true;\n\t\tclearTimeout(deadlineTimer);\n\t\treleaseReadiness?.();\n\t\tif (context.sharedProviderRefreshes.get(providerId) === owner) context.sharedProviderRefreshes.delete(providerId);\n\t}\n}\nfunction resolveSharedProviderRefreshResult(context, providerId, owner, deadlineError, settled) {\n\tif (context.sharedProviderRefreshes.get(providerId) !== owner) {\n\t\tif (\"error\" in settled) throw settled.error;\n\t\towner.controller.signal.throwIfAborted();\n\t\treturn settled.available;\n\t}\n\tif (\"error\" in settled) {\n\t\tif (context.readinessSignal.aborted || owner.controller.signal.reason !== deadlineError) throw settled.error;\n\t\tconst result = {\n\t\t\tready: false,\n\t\t\tissues: [{\n\t\t\t\tcode: \"temporarily_unavailable\",\n\t\t\t\tmessage: \"Provider readiness probe exceeded its deadline\"\n\t\t\t}]\n\t\t};\n\t\tcontext.providers.invalidate(providerId, result);\n\t\tcontext.connection.setProviderReadiness(providerReadiness(providerId, false, result));\n\t\treturn false;\n\t}\n\tcontext.connection.setProviderReadiness(providerReadiness(providerId, settled.available, context.providers.probeResult(providerId)));\n\treturn settled.available;\n}\nvar ComposedClientRuntime = class {\n\t#admission;\n\tbindingStore;\n\tcustody;\n\tcredentialEnvironment;\n\treconciler;\n\tsessionMessageInbox;\n\treportOwner;\n\tdurabilityMetrics;\n\trunner;\n\truntimeManager;\n\tworkspace;\n\t#providerCliReconciler;\n\t#providerCliTurnPlans;\n\t#runtime;\n\t#refreshCapability;\n\t#capabilityRefreshIntervalMs;\n\t#capabilityAbort;\n\t#capabilityTimer;\n\t#capabilityRefreshInFlight;\n\t#shutdownPromise;\n\t#stopped = false;\n\tconstructor(runtime, components) {\n\t\tthis.#runtime = runtime;\n\t\tthis.#admission = components.admission;\n\t\tthis.#providerCliReconciler = components.providerCliReconciler;\n\t\tthis.#providerCliTurnPlans = components.providerCliTurnPlans;\n\t\tthis.bindingStore = components.bindingStore;\n\t\tthis.custody = components.custody;\n\t\tthis.credentialEnvironment = components.credentialEnvironment;\n\t\tthis.reconciler = components.reconciler;\n\t\tthis.sessionMessageInbox = components.sessionMessageInbox;\n\t\tthis.reportOwner = components.reportOwner;\n\t\tthis.durabilityMetrics = components.durabilityMetrics;\n\t\tthis.runner = components.runner;\n\t\tthis.runtimeManager = components.runtimeManager;\n\t\tthis.workspace = components.workspace;\n\t\tthis.#refreshCapability = components.refreshCapability;\n\t\tthis.#capabilityRefreshIntervalMs = components.capabilityRefreshIntervalMs;\n\t\tthis.#capabilityAbort = components.capabilityAbort;\n\t}\n\tasync run() {\n\t\tthis.#startCapabilityMonitor();\n\t\ttry {\n\t\t\tawait this.#runtime.run();\n\t\t} finally {\n\t\t\tawait this.#shutdown();\n\t\t}\n\t}\n\t/**\n\t* Authoritative protected-work snapshot for the automatic-upgrade gate. The Session module owns\n\t* the bounded lifetime of every counted unit (Turn budgets, delivery deadlines, report retries\n\t* with terminal outcomes), so a caller may wait on `total === 0` indefinitely without adding a\n\t* force timeout of its own.\n\t*/\n\tprotectedWork() {\n\t\tconst reconcilerWork = this.reconciler.protectedWorkSnapshot();\n\t\tconst snapshot = {\n\t\t\tsessionActivities: reconcilerWork.activities.length,\n\t\t\tpendingRecoveries: reconcilerWork.recoveries.length,\n\t\t\tcustodyTurns: this.custody.liveTurnCount,\n\t\t\tactiveTurns: this.runner.activeCount,\n\t\t\tpendingReports: this.reportOwner.pendingCount,\n\t\t\tqueuedSessionMessages: this.sessionMessageInbox.pendingCount,\n\t\t\ttotal: 0\n\t\t};\n\t\tsnapshot.total = snapshot.sessionActivities + snapshot.pendingRecoveries + snapshot.custodyTurns + snapshot.activeTurns + snapshot.pendingReports + snapshot.queuedSessionMessages;\n\t\treturn snapshot;\n\t}\n\t/**\n\t* Close admission before the updater reads its zero-work snapshot. Already accepted Session\n\t* messages may still reserve capacity and drain; every new direct or Session delivery receives a\n\t* retryable `client_busy` result. The returned release function is used only when the attempt is\n\t* abandoned or fails — a successful install stays quiesced until supervisor handoff.\n\t*/\n\tquiesceForUpdate() {\n\t\tthis.#admission.pause();\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tthis.#admission.resume();\n\t\t};\n\t}\n\tstop() {\n\t\tif (this.#stopped) return;\n\t\tthis.#stopped = true;\n\t\tconst shutdown = this.#shutdown();\n\t\tthis.#runtime.stop();\n\t\t/* v8 ignore next -- shutdown failures surface through runtime state, not this detached promise. */\n\t\tshutdown.catch(() => void 0);\n\t}\n\t#shutdown() {\n\t\tthis.#stopped = true;\n\t\tthis.#shutdownPromise ??= this.#performShutdown();\n\t\treturn this.#shutdownPromise;\n\t}\n\tasync #performShutdown() {\n\t\tthis.#stopCapabilityMonitor();\n\t\tthis.#capabilityAbort.abort(/* @__PURE__ */ new Error(\"Client Runtime stopped\"));\n\t\tthis.sessionMessageInbox.stop();\n\t\tthis.runner.stop();\n\t\tawait Promise.all([\n\t\t\tthis.#capabilityRefreshInFlight?.catch(() => void 0),\n\t\t\tthis.runner.settled(),\n\t\t\tthis.sessionMessageInbox.settled()\n\t\t]);\n\t\ttry {\n\t\t\tawait this.runtimeManager.close();\n\t\t} finally {\n\t\t\tthis.reportOwner.stop();\n\t\t\tawait this.reportOwner.settled();\n\t\t\tawait this.credentialEnvironment.close();\n\t\t\tawait this.#providerCliTurnPlans?.recover();\n\t\t\tawait this.#providerCliReconciler?.close();\n\t\t}\n\t}\n\t#startCapabilityMonitor() {\n\t\tif (this.#capabilityTimer || this.#stopped) return;\n\t\tthis.#capabilityTimer = setInterval(() => {\n\t\t\tif (this.#capabilityRefreshInFlight || this.#stopped) return;\n\t\t\tconst refresh = this.#refreshCapability();\n\t\t\tthis.#capabilityRefreshInFlight = refresh;\n\t\t\trefresh.catch(() => void 0).finally(() => {\n\t\t\t\tthis.#providerCliReconciler?.refreshPublishedImCliReadiness().catch(() => void 0);\n\t\t\t\t/* v8 ignore else -- only the newest refresh clears the in-flight slot. */\n\t\t\t\tif (this.#capabilityRefreshInFlight === refresh) this.#capabilityRefreshInFlight = void 0;\n\t\t\t});\n\t\t}, this.#capabilityRefreshIntervalMs);\n\t\tthis.#capabilityTimer.unref();\n\t}\n\t#stopCapabilityMonitor() {\n\t\tif (!this.#capabilityTimer) return;\n\t\tclearInterval(this.#capabilityTimer);\n\t\tthis.#capabilityTimer = void 0;\n\t}\n};\nasync function materializeProductionProviderLayout(options, sourceEnvironment) {\n\tconst defaultHome = sourceEnvironment.HOME ?? homedir();\n\tconst configuredCodexHome = resolve(options.codexHome ?? sourceEnvironment.CODEX_HOME ?? join(defaultHome, \".codex\"));\n\tconst defaultClaudeCodeHome = resolve(join(defaultHome, \".claude\"));\n\tconst configuredClaudeCodeHome = resolve(options.claudeCodeHome ?? sourceEnvironment.CLAUDE_CONFIG_DIR ?? defaultClaudeCodeHome);\n\tconst configuredPiHome = resolve(options.piHome ?? sourceEnvironment.PI_CODING_AGENT_DIR ?? resolvePiHome(sourceEnvironment));\n\tconst configuredPiSessionDirectory = join(configuredPiHome, \"sessions\");\n\tawait mkdir(configuredCodexHome, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tawait mkdir(configuredClaudeCodeHome, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tawait mkdir(configuredPiHome, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tawait mkdir(configuredPiSessionDirectory, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tconst codexHome = await realpath(configuredCodexHome);\n\tconst claudeCodeHome = await realpath(configuredClaudeCodeHome);\n\tconst piHome = await realpath(configuredPiHome);\n\tconst piSessionDirectory = await realpath(configuredPiSessionDirectory);\n\tconst contextTreeBin = resolveOpenTagHomeLayout(options.home).contextTreeBin;\n\tconst withContextTreeOnPath = (environment) => prependPath(environment, contextTreeBin);\n\tconst canonicalDefaultClaudeCodeHome = await realpath(defaultClaudeCodeHome).catch(() => defaultClaudeCodeHome);\n\tconst loginShellDiscovery = createLoginShellDiscovery();\n\tconst discovery = loginShellDiscovery.options;\n\tconst contextTreeSkillsPath = resolveContextTreePackage()?.skillsPath;\n\treturn {\n\t\tclaudeCodeHome,\n\t\tcodexHome,\n\t\tloginShellDiscovery,\n\t\tpiHome,\n\t\tproviderHomes: {\n\t\t\tcodex: codexHome,\n\t\t\t\"claude-code\": claudeCodeHome,\n\t\t\tpi: piHome\n\t\t},\n\t\tproviderArtifactIdentities: {\n\t\t\tcodex: createHash(\"sha256\").update(codexHome, \"utf8\").digest(\"hex\"),\n\t\t\t\"claude-code\": createHash(\"sha256\").update(claudeCodeHome, \"utf8\").digest(\"hex\"),\n\t\t\tpi: createHash(\"sha256\").update(piHome, \"utf8\").digest(\"hex\")\n\t\t},\n\t\tdefaultFactories: [\n\t\t\tresolvedCodexFactory({\n\t\t\t\tclientVersion: options.clientVersion,\n\t\t\t\tcommand: options.codexCommand ?? \"codex\",\n\t\t\t\tcodexHome,\n\t\t\t\tdiscovery,\n\t\t\t\tenvironment: withContextTreeOnPath(codexAgentRuntimeEnvironment({\n\t\t\t\t\t...sourceEnvironment,\n\t\t\t\t\tCODEX_HOME: codexHome\n\t\t\t\t})),\n\t\t\t\tsourceEnvironment\n\t\t\t}),\n\t\t\tresolvedClaudeCodeFactory({\n\t\t\t\tclaudeCodeHome,\n\t\t\t\tcommand: options.claudeCodeCommand ?? \"claude\",\n\t\t\t\tdiscovery,\n\t\t\t\tenvironment: withContextTreeOnPath(claudeCodeProcessEnvironment(sourceEnvironment, claudeCodeHome, canonicalDefaultClaudeCodeHome)),\n\t\t\t\tsourceEnvironment\n\t\t\t}),\n\t\t\tresolvedPiFactory({\n\t\t\t\tcommand: options.piCommand ?? \"pi\",\n\t\t\t\tdiscovery,\n\t\t\t\tenvironment: withContextTreeOnPath(piAgentRuntimeEnvironment({\n\t\t\t\t\t...sourceEnvironment,\n\t\t\t\t\tPI_CODING_AGENT_DIR: piHome\n\t\t\t\t})),\n\t\t\t\tpiHome,\n\t\t\t\tsessionDirectory: piSessionDirectory,\n\t\t\t\tskillPaths: contextTreeSkillsPath ? [contextTreeSkillsPath] : [],\n\t\t\t\tsourceEnvironment\n\t\t\t})\n\t\t]\n\t};\n}\n/**\n* Build the Skill sync manager when the composition has both an API client and a machine token.\n* Without either there is nothing to authenticate a sync with, so runtime start skips it.\n*/\nfunction createSkillSyncManager(options, logger) {\n\tconst api = options.api;\n\tconst machineToken = options.machineToken;\n\tif (!api || !machineToken) return void 0;\n\treturn new SkillSyncManager({\n\t\tapi,\n\t\tlogger,\n\t\tmachineToken: async () => machineToken\n\t});\n}\nasync function createClientRuntime(connection, options) {\n\tconst moduleLogger = (module) => options.logger?.child({ module }) ?? createLogger(module);\n\tconst sourceEnvironment = options.environment ?? process.env;\n\toptions.signal?.throwIfAborted();\n\tconst layout = await materializeProductionProviderLayout(options, sourceEnvironment);\n\tconst { codexHome, loginShellDiscovery, providerArtifactIdentities, providerHomes } = layout;\n\toptions.signal?.throwIfAborted();\n\tconst factories = options.factories ?? (options.factory ? [options.factory] : layout.defaultFactories);\n\tconst providers = new AgentRuntimeProviderRegistry(factories.map((factory) => productionProviderRegistration(factory, providerArtifactIdentities, providerHomes)));\n\tconst capabilityAbort = new AbortController();\n\tconst readinessSignal = options.signal ? AbortSignal.any([options.signal, capabilityAbort.signal]) : capabilityAbort.signal;\n\tconst providerProbeDeadlineMs = providerProbeDeadline(options.providerProbeDeadlineMs);\n\tconst sharedProviderRefreshes = /* @__PURE__ */ new Map();\n\tconst liveSharedProviderRefresh = (providerId) => {\n\t\tconst owner = sharedProviderRefreshes.get(providerId);\n\t\tif (!owner || owner.settled || owner.controller.signal.aborted) return void 0;\n\t\treturn owner;\n\t};\n\tconst refreshProviderReadiness = async (providerId, signal) => {\n\t\tsignal?.throwIfAborted();\n\t\treadinessSignal.throwIfAborted();\n\t\tconst owner = liveSharedProviderRefresh(providerId) ?? startSharedProviderRefresh({\n\t\t\tconnection,\n\t\t\tproviders,\n\t\t\treadinessSignal,\n\t\t\tproviderProbeDeadlineMs,\n\t\t\tsharedProviderRefreshes\n\t\t}, providerId);\n\t\towner.waiters += 1;\n\t\ttry {\n\t\t\treturn await waitForSharedRefresh(owner.promise, signal);\n\t\t} finally {\n\t\t\towner.waiters -= 1;\n\t\t\tif (owner.waiters === 0 && !owner.settled) {\n\t\t\t\t/* v8 ignore else -- the shared map still holds this owner while its last waiter unwinds. */\n\t\t\t\tif (sharedProviderRefreshes.get(providerId) === owner) sharedProviderRefreshes.delete(providerId);\n\t\t\t\towner.controller.abort(/* @__PURE__ */ new Error(`Agent Runtime provider probe has no waiters: ${providerId}`));\n\t\t\t}\n\t\t}\n\t};\n\tconst refreshCapability = async () => {\n\t\tconst results = await Promise.allSettled([...providers.providerIds().map((providerId) => refreshProviderReadiness(providerId))]);\n\t\treadinessSignal.throwIfAborted();\n\t\tconst failures = results.flatMap((result) => result.status === \"rejected\" ? [result.reason] : []);\n\t\tif (failures.length > 0) throw new AggregateError(failures, \"Client capability refresh failed\");\n\t\tconnection.setVerifiedCapabilities({ imCredentialGrant: 1 });\n\t};\n\tconst ensureProviderReady = async (providerId, signal) => {\n\t\tif (providers.isReady(providerId)) return;\n\t\tif (!await refreshProviderReadiness(providerId, signal)) throw new AgentRuntimeProviderUnavailableError(providerId, providers.probeResult(providerId) ?? {\n\t\t\tready: false,\n\t\t\tissues: [{\n\t\t\t\tcode: \"temporarily_unavailable\",\n\t\t\t\tmessage: \"Provider readiness could not be established\"\n\t\t\t}]\n\t\t});\n\t};\n\ttry {\n\t\tawait refreshCapability();\n\t} catch (error) {\n\t\tcapabilityAbort.abort(error);\n\t\tthrow error;\n\t}\n\tloginShellDiscovery.enable();\n\tconst bindingStore = new SessionBindingStore({\n\t\thome: options.home,\n\t\tproviderArtifactIdentity: (providerId) => providers.artifactIdentity(providerId)\n\t});\n\tconst workspace = new AgentWorkspaceManager({\n\t\thome: options.home,\n\t\tbindingStore\n\t});\n\tconst credentialMode = options.credentialMode ?? \"legacy\";\n\tconnection.setCredentialProxyEnabled(credentialMode === \"proxy\");\n\tconst contextTree = new ContextTreeManager({\n\t\tenvironment: sourceEnvironment,\n\t\tcodexHome,\n\t\thome: options.home,\n\t\tlogger: moduleLogger(\"context-tree\"),\n\t\tmanagedCredentials: credentialMode === \"proxy\"\n\t});\n\tconst durabilityStore = options.durabilityStore ?? (options.serverDurability ? new ServerRuntimeDurabilityStore(options.serverDurability) : new FileRuntimeDurabilityStore(options.home));\n\tconst durabilityMetrics = options.durabilityMetrics ?? new RuntimeDurabilityMetrics();\n\tconst reportOwner = new TurnReportOwner({\n\t\tconnection,\n\t\tmetrics: durabilityMetrics,\n\t\tpersistence: durabilityStore\n\t});\n\tconst credentialEnvironment = createCredentialEnvironment(options, connection, moduleLogger(\"im-credential-environment\"), await resolveOptedInWebToolsExtensionPath(options, moduleLogger(\"web-tools\")));\n\tconst providerCliReconciler = new ProviderCliReconciler({\n\t\tconnection,\n\t\tlogger: moduleLogger(\"provider-cli-reconciler\"),\n\t\tmanager: new ProviderCliManager({ accountHome: resolveAccountHome() }),\n\t\trefreshRuntimeProvider: createRuntimeProviderReadinessRefresher(refreshProviderReadiness, providers),\n\t\tsignal: readinessSignal,\n\t\tvalidation: new ProviderCliValidationRunner({\n\t\t\thome: options.home,\n\t\t\topenProxyValidation: resolveProxyValidationOpener(options, credentialEnvironment),\n\t\t\tproxyCredentialMode: credentialMode === \"proxy\"\n\t\t})\n\t});\n\tawait mkdir(options.home, {\n\t\trecursive: true,\n\t\tmode: 448\n\t});\n\tconst providerCliTurnPlans = new ProviderCliTurnPlanManager({\n\t\taccountHome: resolveAccountHome(),\n\t\topenTagHome: options.home,\n\t\treadySelection: providerCliReconciler.readySelectionForRun.bind(providerCliReconciler),\n\t\trunnerInvocation: resolveProviderCliTurnRunnerInvocation()\n\t});\n\tawait providerCliTurnPlans.recover();\n\tconst proofManager = new SessionCliProofManager(options.home);\n\tconst skills = createSkillSyncManager(options, moduleLogger(\"skills\"));\n\tconst runtimeManager = new SessionRuntimeManager({\n\t\tenvironment: sourceEnvironment,\n\t\tbindingStore,\n\t\tcliCommand: options.cliCommand ?? \"opentag\",\n\t\tcleanupProviderEnvironment: (sessionId) => credentialEnvironment.cleanup(sessionId),\n\t\tcontextTree,\n\t\tcontextTreeEnvironment: (sessionId) => {\n\t\t\tconst hostSide = options.runtimeCredentials?.contextTreeEnvironment?.(sessionId);\n\t\t\tif (hostSide) return hostSide;\n\t\t\tif (options.runtimeCredentials?.sandboxForSession) return void 0;\n\t\t\treturn credentialEnvironment.executionEnvironmentForSession(sessionId);\n\t\t},\n\t\tensureProviderReady,\n\t\thome: options.home,\n\t\tproviders,\n\t\tproviderEnvironment: (sessionId) => credentialEnvironment.environmentForSession(sessionId),\n\t\tproviderEnvironmentPath: (sessionId) => credentialEnvironment.pathForSession(sessionId),\n\t\tproviderCliLaunchPath: (sessionId) => composeProviderCliLaunchPath(credentialEnvironment.shimDirForSession(sessionId), providerCliTurnPlans.sessionDir(sessionId)),\n\t\tproviderCliReplyWritableRoot: (sessionId) => ensurePrivateDirectory(providerCliTurnPlans.layout.plans, join(providerCliTurnPlans.sessionDir(sessionId), \"runs\")),\n\t\tslackConfigWritableRoot: (sessionId) => credentialEnvironment.activeSlackConfigDirForSession(sessionId),\n\t\tproofManager,\n\t\tskills,\n\t\tworkspace\n\t});\n\tconst reconciler = new SessionReconciler({\n\t\tinstallationId: connection.installationId,\n\t\tpreparation: runtimeManager,\n\t\tlocalPolicy: runtimeManager\n\t});\n\tconst admission = new AdmissionController();\n\tconst sessionMessageInbox = new SessionMessageInbox({\n\t\tadmission,\n\t\tcliCommand: options.cliCommand ?? \"opentag\",\n\t\tcredentialEnvironment,\n\t\timCredentialGrantVersion: connection.capabilityVersion.bind(connection, RUNTIME_CAPABILITY.imCredentialGrant),\n\t\tmetrics: durabilityMetrics,\n\t\tpersistence: durabilityStore,\n\t\treconciler,\n\t\truntimeManager,\n\t\tturnPlan: providerCliTurnPlans\n\t});\n\tawait Promise.all([reportOwner.ready(), sessionMessageInbox.ready()]);\n\tconst resourceFetcher = new ImResourceFetcher({\n\t\tinstanceId: connection.instanceId,\n\t\tapi: options.api,\n\t\tmachineToken: options.machineToken\n\t});\n\tconst mvpReportRecovery = new MvpTurnReportRecovery({\n\t\tbindingStore,\n\t\tlogger: moduleLogger(\"report-recovery\"),\n\t\treconciler,\n\t\treportOwner\n\t});\n\tlet runner;\n\tconst preflight = createClientRuntimePreflight({\n\t\tproviders,\n\t\tworkspace\n\t});\n\tconst custody = new TurnCustodyOwner({\n\t\tadmission,\n\t\tbindingStore,\n\t\timDeliveryVersion: connection.capabilityVersion.bind(connection, RUNTIME_CAPABILITY.imDelivery),\n\t\timSteerVersion: connection.capabilityVersion.bind(connection, RUNTIME_CAPABILITY.imSteer),\n\t\treconciler,\n\t\tpreflight,\n\t\t/* v8 ignore next -- late binding is required because custody and runner own each other. */\n\t\tstart: (owner) => runner.start(owner),\n\t\t/* v8 ignore next -- late binding is required because custody and runner own each other. */\n\t\tsteer: (request) => runner.steer(request)\n\t});\n\trunner = new AgentTurnRunner({\n\t\tbindingStore,\n\t\tconnection,\n\t\tcustody,\n\t\tlogger: moduleLogger(\"turn\"),\n\t\treportOwner,\n\t\tresourceFetcher,\n\t\truntimeManager,\n\t\tcredentialEnvironment,\n\t\tturnPlan: providerCliTurnPlans,\n\t\toutgoingReplies: createOutgoingReplyCollector(providerCliTurnPlans),\n\t\tagentErrorReporter: options.agentErrorReporter\n\t});\n\tconst availabilityTester = new AgentRuntimeAvailabilityTester({ factories: new Map(factories.map((factory) => [factory.manifest.providerId, factory])) });\n\treturn new ComposedClientRuntime(new ClientRuntime(connection, {\n\t\tcontextTreeSettings: new ContextTreeSettings({\n\t\t\thome: options.home,\n\t\t\tenvironment: sourceEnvironment,\n\t\t\thasAgentSessions: runtimeManager.hasAgentSessions.bind(runtimeManager),\n\t\t\texclusive: contextTree.runExclusive.bind(contextTree),\n\t\t\tmanagedCredentials: credentialMode === \"proxy\",\n\t\t\t...options.runtimeCredentials?.contextTreeManagementEnvironment ? { managedEnvironment: options.runtimeCredentials.contextTreeManagementEnvironment } : {}\n\t\t}),\n\t\tlogger: moduleLogger(\"client-runtime\"),\n\t\treconciler,\n\t\thandleSessionMessageDelivery: sessionMessageInbox.accept.bind(sessionMessageInbox),\n\t\tavailabilityTester,\n\t\t...createClientRuntimeHandlers(custody, reportOwner, mvpReportRecovery)\n\t}), {\n\t\tadmission,\n\t\tbindingStore,\n\t\tcustody,\n\t\tcredentialEnvironment,\n\t\tsessionMessageInbox,\n\t\treconciler,\n\t\treportOwner,\n\t\tdurabilityMetrics,\n\t\trunner,\n\t\truntimeManager,\n\t\tworkspace,\n\t\trefreshCapability,\n\t\tproviderCliReconciler,\n\t\tproviderCliTurnPlans,\n\t\tcapabilityAbort,\n\t\tcapabilityRefreshIntervalMs: Math.max(10, options.capabilityRefreshIntervalMs ?? DEFAULT_CAPABILITY_REFRESH_INTERVAL_MS)\n\t});\n}\nfunction providerReadiness(provider, available, result) {\n\tif (available) return {\n\t\tprovider,\n\t\tstatus: \"ready\"\n\t};\n\tif (result?.issues.some((issue) => issue.code === \"artifact_missing\")) return {\n\t\tprovider,\n\t\tstatus: \"install\"\n\t};\n\tif (result?.issues.some((issue) => issue.code === \"credential_missing\")) return {\n\t\tprovider,\n\t\tstatus: \"sign-in\"\n\t};\n\treturn {\n\t\tprovider,\n\t\tstatus: \"unavailable\"\n\t};\n}\n/**\n* Couples a fresh selected-Runtime probe with its detailed local result for one Server-owned\n* Computer preparation. Kept as a small factory so composition-level tests can exercise the exact\n* callback that the Provider CLI reconciler receives without touching the real account CLI home.\n*/\nfunction createRuntimeProviderReadinessRefresher(refreshProviderReadiness, providers) {\n\treturn async (provider) => {\n\t\treturn providerReadiness(provider, await refreshProviderReadiness(provider), providers.probeResult(provider));\n\t};\n}\n/**\n* Claude Code treats a set CLAUDE_CONFIG_DIR as a distinct credential record, even when the\n* value equals its own default. Omit the variable only when the resolved home is that default.\n* Exported so the CLI probes the same environment the daemon runs in.\n*/\nfunction claudeCodeProcessEnvironment(sourceEnvironment, claudeCodeHome, defaultClaudeCodeHome) {\n\tif (claudeCodeHome === defaultClaudeCodeHome) {\n\t\tconst environment = { ...sourceEnvironment };\n\t\tdelete environment.CLAUDE_CONFIG_DIR;\n\t\treturn claudeCodeAgentRuntimeEnvironment(environment);\n\t}\n\treturn claudeCodeAgentRuntimeEnvironment({\n\t\t...sourceEnvironment,\n\t\tCLAUDE_CONFIG_DIR: claudeCodeHome\n\t});\n}\nfunction productionProviderRegistration(factory, artifactIdentities, providerHomes) {\n\tconst providerId = factory.manifest.providerId;\n\tif (providerId !== \"codex\" && providerId !== \"claude-code\" && providerId !== \"pi\") throw new Error(`Production Client Runtime does not register the unreviewed provider: ${providerId}`);\n\tconst providerHome = providerHomes[providerId];\n\tconst common = {\n\t\tartifactIdentity: artifactIdentities[providerId],\n\t\tfactory,\n\t\tverifyArtifact: async (signal) => {\n\t\t\tsignal?.throwIfAborted();\n\t\t\tif (await realpath(providerHome) !== providerHome) throw new Error(`${factory.manifest.displayName} Home identity changed`);\n\t\t}\n\t};\n\tif (providerId === \"codex\") return {\n\t\t...common,\n\t\tpolicy: codexRuntimePolicy,\n\t\trequiresBindingReplacement: codexBindingRequiresHostedToolReplacement,\n\t\tvalidate: validateCodexRuntimePolicy\n\t};\n\tif (providerId === \"claude-code\") return {\n\t\t...common,\n\t\tpolicy: claudeCodeRuntimePolicy,\n\t\tvalidate: validateClaudeCodeRuntimePolicy\n\t};\n\treturn {\n\t\t...common,\n\t\tpolicy: piRuntimePolicy,\n\t\tvalidate: validatePiRuntimePolicy\n\t};\n}\nfunction prependPath(environment, directory, pathDelimiter = delimiter) {\n\tconst current = environment.PATH;\n\tif (!current) return {\n\t\t...environment,\n\t\tPATH: directory\n\t};\n\tif (current === directory || current.startsWith(`${directory}${pathDelimiter}`)) return environment;\n\treturn {\n\t\t...environment,\n\t\tPATH: `${directory}${pathDelimiter}${current}`\n\t};\n}\nfunction withSearchBinOnPath(environment, resolved, pathDelimiter = delimiter) {\n\tif (resolved.source === \"explicit\" || !resolved.searchDir) return environment;\n\tconst current = environment.PATH;\n\tif (!current) return {\n\t\t...environment,\n\t\tPATH: resolved.searchDir\n\t};\n\tif (current === resolved.searchDir || current.startsWith(`${resolved.searchDir}${pathDelimiter}`)) return environment;\n\treturn {\n\t\t...environment,\n\t\tPATH: `${resolved.searchDir}${pathDelimiter}${current}`\n\t};\n}\nfunction translateExecutableDiscoveryError(error, signal, artifactMessage) {\n\tif (signal?.aborted) throw error;\n\tif (error instanceof AgentRuntimeExecutableNotFoundError) return {\n\t\tready: false,\n\t\tissues: [{\n\t\t\tcode: \"artifact_missing\",\n\t\t\tmessage: artifactMessage\n\t\t}]\n\t};\n\tif (error instanceof AgentRuntimeExecutableDiscoveryError) return {\n\t\tready: false,\n\t\tissues: [{\n\t\t\tcode: \"temporarily_unavailable\",\n\t\t\tmessage: artifactMessage\n\t\t}]\n\t};\n\tthrow error;\n}\nasync function probeResolvedFactory(request, options) {\n\trequest.signal?.throwIfAborted();\n\tlet lastBinaryResult;\n\tconst candidates = iterateAgentRuntimeExecutables(options.provider, options.command, options.sourceEnvironment, options.discovery);\n\twhile (true) {\n\t\tconst candidateStep = await nextExecutableCandidate(candidates, request.signal, options.artifactMessage);\n\t\tif (\"result\" in candidateStep) return candidateStep.result;\n\t\tif (candidateStep.step.done) break;\n\t\trequest.signal?.throwIfAborted();\n\t\tconst environment = withSearchBinOnPath(options.environment, candidateStep.step.value, options.discovery?.pathDelimiter ?? delimiter);\n\t\tconst candidate = options.createCandidate(candidateStep.step.value.path, environment);\n\t\tconst result = await candidate.probe(request);\n\t\tif (result.ready) {\n\t\t\toptions.onReady(candidate);\n\t\t\treturn result;\n\t\t}\n\t\tif (!canAdvanceRuntimeCandidate(result)) return result;\n\t\tlastBinaryResult = result;\n\t}\n\treturn lastBinaryResult ?? {\n\t\tready: false,\n\t\tissues: [{\n\t\t\tcode: \"artifact_missing\",\n\t\t\tmessage: options.artifactMessage\n\t\t}]\n\t};\n}\nasync function nextExecutableCandidate(candidates, signal, artifactMessage) {\n\ttry {\n\t\treturn { step: await candidates.next() };\n\t} catch (error) {\n\t\treturn { result: translateExecutableDiscoveryError(error, signal, artifactMessage) };\n\t}\n}\nfunction resolvedCodexFactory(options) {\n\tlet readyFactory;\n\tconst createCandidate = options.createCandidateFactory ?? ((command, environment) => new CodexAgentRuntimeFactory({\n\t\tclientVersion: options.clientVersion,\n\t\tprocess: {\n\t\t\tcommand,\n\t\t\tenv: environment,\n\t\t\texpectedCodexHome: options.codexHome\n\t\t}\n\t}));\n\treturn {\n\t\tmanifest: CODEX_AGENT_RUNTIME_MANIFEST,\n\t\tprobe: (request) => probeResolvedFactory(request, {\n\t\t\tprovider: \"codex\",\n\t\t\tcommand: options.command,\n\t\t\tenvironment: options.environment,\n\t\t\tsourceEnvironment: options.sourceEnvironment,\n\t\t\tdiscovery: options.discovery,\n\t\t\tcreateCandidate,\n\t\t\tartifactMessage: \"Codex CLI could not be executed\",\n\t\t\tonReady: (factory) => {\n\t\t\t\treadyFactory = factory;\n\t\t\t}\n\t\t}),\n\t\tcreate(request) {\n\t\t\treturn requireReadyCodexFactory(readyFactory).create(request);\n\t\t},\n\t\tresume(request) {\n\t\t\treturn requireReadyCodexFactory(readyFactory).resume(request);\n\t\t}\n\t};\n}\nfunction requireReadyCodexFactory(factory) {\n\tif (!factory) throw new Error(\"Codex provider readiness has not been established\");\n\treturn factory;\n}\nfunction resolvedClaudeCodeFactory(options) {\n\tlet readyFactory;\n\tconst createCandidate = options.createCandidateFactory ?? ((command, environment) => new ClaudeCodeAgentRuntimeFactory({ process: {\n\t\tcommand,\n\t\tenv: environment\n\t} }));\n\treturn {\n\t\tmanifest: CLAUDE_CODE_AGENT_RUNTIME_MANIFEST,\n\t\tprobe: (request) => probeResolvedFactory(request, {\n\t\t\tprovider: \"claude-code\",\n\t\t\tcommand: options.command,\n\t\t\tenvironment: options.environment,\n\t\t\tsourceEnvironment: options.sourceEnvironment,\n\t\t\tdiscovery: options.discovery,\n\t\t\tcreateCandidate,\n\t\t\tartifactMessage: \"Claude Code CLI could not be executed\",\n\t\t\tonReady: (factory) => {\n\t\t\t\treadyFactory = factory;\n\t\t\t}\n\t\t}),\n\t\tcreate(request) {\n\t\t\treturn requireReadyClaudeCodeFactory(readyFactory).create(request);\n\t\t},\n\t\tresume(request) {\n\t\t\treturn requireReadyClaudeCodeFactory(readyFactory).resume(request);\n\t\t}\n\t};\n}\nfunction requireReadyClaudeCodeFactory(factory) {\n\tif (!factory) throw new Error(\"Claude Code provider readiness has not been established\");\n\treturn factory;\n}\nfunction resolvedPiFactory(options) {\n\tlet readyFactory;\n\tconst skillArgs = (options.skillPaths ?? []).flatMap((path) => [\"--skill\", path]);\n\tconst createCandidate = options.createCandidateFactory ?? ((command, environment) => new PiAgentRuntimeFactory({ process: {\n\t\targs: skillArgs,\n\t\tcommand,\n\t\tenv: environment,\n\t\tsessionDirectory: options.sessionDirectory\n\t} }));\n\treturn {\n\t\tmanifest: PI_AGENT_RUNTIME_MANIFEST,\n\t\tprobe: (request) => probeResolvedFactory(request, {\n\t\t\tprovider: \"pi\",\n\t\t\tcommand: options.command,\n\t\t\tenvironment: options.environment,\n\t\t\tsourceEnvironment: options.sourceEnvironment,\n\t\t\tdiscovery: options.discovery,\n\t\t\tcreateCandidate,\n\t\t\tartifactMessage: \"Pi CLI could not be executed\",\n\t\t\tonReady: (factory) => {\n\t\t\t\treadyFactory = factory;\n\t\t\t}\n\t\t}),\n\t\tcreate(request) {\n\t\t\treturn requireReadyPiFactory(readyFactory).create(request);\n\t\t},\n\t\tresume(request) {\n\t\t\treturn requireReadyPiFactory(readyFactory).resume(request);\n\t\t}\n\t};\n}\nfunction requireReadyPiFactory(factory) {\n\tif (!factory) throw new Error(\"Pi provider readiness has not been established\");\n\treturn factory;\n}\nfunction resolveCodexHome(environment = process.env) {\n\treturn resolve(environment.CODEX_HOME ?? join(environment.HOME ?? homedir(), \".codex\"));\n}\nfunction resolvePiHome(environment = process.env) {\n\treturn resolve(environment.PI_CODING_AGENT_DIR ?? join(environment.HOME ?? homedir(), \".pi\", \"agent\"));\n}\nfunction createClientRuntimePreflight(dependencies) {\n\treturn async (request) => {\n\t\tconst policyReason = dependencies.providers.validateConfiguration(request.runtime);\n\t\tif (policyReason) return policyReason;\n\t\ttry {\n\t\t\tawait dependencies.workspace.verifyAgent(request.runtime, computeRuntimeSnapshotHashes(request.runtime));\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\treturn error instanceof RuntimeStorageError ? \"session_binding_conflict\" : \"configuration_unsupported\";\n\t\t}\n\t};\n}\nfunction createClientRuntimeHandlers(custody, reportOwner, recovery) {\n\treturn {\n\t\thandleDelivery: (request) => custody.accept(request),\n\t\thandleSteer: (request) => custody.acceptSteer(request),\n\t\thandleTurnReportResult: (result) => reportOwner.handleResult(result).then(() => void 0),\n\t\tprepareReconcileResult: (request, result) => recovery.prepare(request, result),\n\t\tonReconcileResultSendFailed: (request, result) => recovery.cancel(request, result),\n\t\tonReconciled: (request, result) => recovery.afterReconciled(request, result)\n\t};\n}\nfunction createOutgoingReplyCollector(turnPlans) {\n\treturn {\n\t\tcollect: ({ sessionId, runId }) => collectOutgoingReplyReceipts({\n\t\t\tplansRoot: turnPlans.layout.plans,\n\t\t\tsessionDir: turnPlans.sessionDir(sessionId),\n\t\t\trunId\n\t\t}),\n\t\tcleanup: ({ sessionId, runId }) => cleanupOutgoingReplyRun({\n\t\t\tplansRoot: turnPlans.layout.plans,\n\t\t\tsessionDir: turnPlans.sessionDir(sessionId),\n\t\t\trunId\n\t\t})\n\t};\n}\n/**\n* Credential mode selection plus the Cloud host injection seam. Local proxy mode uses the\n* production defaults (loopback TLS, openssl CA, real WSS client); the parent harness can\n* inject its own data connection, CA, sandbox facts, clock, and scheduler.\n*/\nfunction createCredentialEnvironment(options, connection, logger, webToolsExtensionPath) {\n\tconst runtimeCredentials = options.runtimeCredentials;\n\treturn new RuntimeCredentialEnvironmentManager({\n\t\tconnection,\n\t\thome: options.home,\n\t\tlogger,\n\t\tmode: options.credentialMode ?? \"legacy\",\n\t\tserverUrl: connection.serverUrl,\n\t\t...runtimeCredentials?.dataConnectionFactory ? { dataConnectionFactory: runtimeCredentials.dataConnectionFactory } : {},\n\t\t...runtimeCredentials?.generateCa ? { generateCa: runtimeCredentials.generateCa } : {},\n\t\t...runtimeCredentials?.now ? { now: runtimeCredentials.now } : {},\n\t\t...runtimeCredentials?.openBudgetMs ? { openBudgetMs: runtimeCredentials.openBudgetMs } : {},\n\t\t...runtimeCredentials?.sandboxForSession ? { sandboxForSession: runtimeCredentials.sandboxForSession } : {},\n\t\t...runtimeCredentials?.scheduler ? { scheduler: runtimeCredentials.scheduler } : {},\n\t\t...webToolsExtensionPath && options.machineToken ? { webTools: {\n\t\t\textensionPath: webToolsExtensionPath,\n\t\t\tbearerToken: options.machineToken,\n\t\t\t...options.webTools?.fetchImpl ? { fetchImpl: options.webTools.fetchImpl } : {}\n\t\t} } : {}\n\t});\n}\n/**\n* Resolve the trusted extension artifact for the web tools opt-in. Proxy mode only: legacy mode\n* never opens executions, so web tools stay off regardless of the flag. A missing artifact is a\n* logged fail-closed, never a fallback path.\n*/\nasync function resolveOptedInWebToolsExtensionPath(options, logger) {\n\tif (!options.webTools?.enabled || (options.credentialMode ?? \"legacy\") !== \"proxy\") return void 0;\n\tconst path = await resolveWebToolsExtensionPath(options.webTools.extensionPath !== void 0 ? { explicitPath: options.webTools.extensionPath } : {});\n\tif (!path) logger.warn({ code: \"web_tools_artifact_missing\" }, \"The trusted web tools extension artifact is missing; web tools stay disabled\");\n\treturn path;\n}\n/**\n* Explicit `openProxyValidation` injection wins; otherwise proxy mode uses the trusted\n* manager-backed opener and legacy mode keeps the raw-grant readiness path unchanged.\n*/\nfunction resolveProxyValidationOpener(options, credentialEnvironment) {\n\tif (options.openProxyValidation) return options.openProxyValidation;\n\treturn options.credentialMode === \"proxy\" ? createProxyValidationOpener(credentialEnvironment) : void 0;\n}\n/**\n* Proxy readiness opens the Server-issued validation execution (`validationRunId`) through\n* the same trusted manager used for business Runs. No raw grant material is ever used, and\n* a request without Server authority is an explicit rejection rather than a fallback.\n*/\nfunction createProxyValidationOpener(credentialEnvironment) {\n\treturn async (request, signal) => {\n\t\tif (!request.validationRunId || !request.agentId) return void 0;\n\t\tconst session = await credentialEnvironment.prepareValidationSession({\n\t\t\tagentId: request.agentId,\n\t\t\tplacementGeneration: 1,\n\t\t\tvalidationRunId: request.validationRunId\n\t\t}, signal);\n\t\treturn {\n\t\t\targuments: session.arguments,\n\t\t\tenvironment: session.environment,\n\t\t\tsignal: session.signal,\n\t\t\tcleanup: () => session.cleanup()\n\t\t};\n\t};\n}\n/**\n* Proxy mode prepends the execution shim directory (git/gh) ahead of the Turn launcher\n* directory (slack/lark-cli) as one PATH prefix; legacy mode keeps the launcher only.\n*/\nfunction composeProviderCliLaunchPath(proxyShimDir, turnPlanDir) {\n\treturn proxyShimDir ? `${proxyShimDir}${delimiter}${turnPlanDir}` : turnPlanDir;\n}\n//#endregion\n//#region src/runtime/computer-identity.ts\nconst COMPUTER_IDENTITY_FILE_NAME = \"computer.json\";\nfunction computerIdentityPath(home) {\n\treturn join(resolveOpenTagHomeLayout(home).config, COMPUTER_IDENTITY_FILE_NAME);\n}\nfunction readComputerIdentity(home) {\n\treturn readPrivateJson(home, computerIdentityPath(home), validateIdentity);\n}\nasync function resolveComputerIdentity(home, serverUrl) {\n\tconst existing = await readComputerIdentity(home);\n\tif (existing) {\n\t\tif (existing.serverUrl !== serverUrl) throw new Error(\"This OpenTag home is bound to another server; choose a different OPENTAG_HOME\");\n\t\tawait writePrivateJson(home, computerIdentityPath(home), existing);\n\t\treturn existing;\n\t}\n\tconst identity = {\n\t\tversion: 2,\n\t\tcomputerId: randomUUID(),\n\t\tserverUrl\n\t};\n\tawait writePrivateJson(home, computerIdentityPath(home), identity);\n\treturn identity;\n}\n/** Allocates a new in-memory installation identity for create or repair without mutating the current binding. */\nasync function allocateComputerIdentity(home, serverUrl) {\n\tconst existing = await readComputerIdentity(home);\n\tif (existing && existing.serverUrl !== serverUrl) throw new Error(\"This OpenTag home is bound to another server; choose a different OPENTAG_HOME\");\n\treturn {\n\t\tversion: 2,\n\t\tcomputerId: randomUUID(),\n\t\tserverUrl\n\t};\n}\nasync function writeComputerIdentityAtomically(home, identity) {\n\tawait writePrivateJson(home, computerIdentityPath(home), validateIdentity(identity));\n}\nfunction validateIdentity(value) {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"The OpenTag computer identity file is invalid\");\n\tconst record = value;\n\tif (![1, 2].includes(record.version) || typeof record.computerId !== \"string\" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.computerId) || typeof record.serverUrl !== \"string\" || record.version === 1 && (Object.keys(record).length !== 4 || typeof record.userId !== \"string\") || record.version === 2 && Object.keys(record).length !== 3) throw new Error(\"The OpenTag computer identity file is invalid\");\n\treturn {\n\t\tversion: 2,\n\t\tcomputerId: record.computerId,\n\t\tserverUrl: record.serverUrl\n\t};\n}\n//#endregion\n//#region src/runtime/integration-cli-installation.ts\nconst INTEGRATION_CLIS = [{\n\tcli: \"feishu\",\n\tdisplayName: \"Lark CLI\",\n\tcommand: \"lark-cli\"\n}, {\n\tcli: \"slack\",\n\tdisplayName: \"Slack CLI\",\n\tcommand: \"slack\"\n}];\n/**\n* Install-only observation of Lark CLI and Slack CLI. This reuses the shared\n* spawn-free executable discovery and never inspects Provider CLI selection,\n* credentials, versions, or network endpoints.\n*/\nasync function probeIntegrationCliInstallations(options = {}) {\n\tconst { accountHome: requestedAccountHome, commands, environment = process.env, ...resolverOptions } = options;\n\tconst accountHome = requestedAccountHome ?? resolveAccountHome();\n\tconst wellKnownDirs = options.wellKnownDirs ?? ((home, platform) => [resolveProviderCliAccountLayout(accountHome, platform).bin, ...wellKnownAgentRuntimeBinDirs(home, platform)]);\n\treturn Promise.all(INTEGRATION_CLIS.map(async ({ cli, displayName, command }) => {\n\t\tconst probed = await probeInstalledCliCommand(commands?.[cli] ?? command, environment, {\n\t\t\t...resolverOptions,\n\t\t\tincludeLoginShell: false,\n\t\t\twellKnownDirs\n\t\t});\n\t\tif (probed.status === \"installed\") return {\n\t\t\tcli,\n\t\t\tdisplayName,\n\t\t\tstatus: \"installed\",\n\t\t\tpath: probed.path,\n\t\t\tsource: probed.source\n\t\t};\n\t\tif (probed.status === \"unknown\") return {\n\t\t\tcli,\n\t\t\tdisplayName,\n\t\t\tstatus: \"unknown\",\n\t\t\tdetail: probed.detail\n\t\t};\n\t\treturn {\n\t\t\tcli,\n\t\t\tdisplayName,\n\t\t\tstatus: \"not-installed\"\n\t\t};\n\t}));\n}\n//#endregion\n//#region src/runtime/local-computer-configuration.ts\n/** Strict, read-only inspection of the Computer identity and stored Computer credential. */\nasync function inspectLocalComputerConfiguration(home) {\n\tconst [identityResult, credentialsResult] = await Promise.allSettled([readComputerIdentity(home), readMachineCredentialsStrict(home)]);\n\tconst identity = inspectIdentity(identityResult);\n\tconst credentials = inspectCredentials(credentialsResult);\n\tif (identity.status !== \"valid\" || credentials.status !== \"valid\") return {\n\t\tidentity,\n\t\tcredentials,\n\t\tbinding: {\n\t\t\tstatus: \"invalid\",\n\t\t\tcredentialCount: credentials.value ? 1 : 0,\n\t\t\tdetail: \"A valid identity and Computer credential are required before their binding can be verified\"\n\t\t}\n\t};\n\tconst identityValue = identity.value;\n\tconst credentialsValue = credentials.value;\n\tif (!identityValue || !credentialsValue) return {\n\t\tidentity,\n\t\tcredentials,\n\t\tbinding: {\n\t\t\tstatus: \"invalid\",\n\t\t\tcredentialCount: 0,\n\t\t\tdetail: \"Validated local configuration is incomplete\"\n\t\t}\n\t};\n\tconst stored = credentialsValue.computer;\n\tif (stored.installationId !== identityValue.computerId) return {\n\t\tidentity,\n\t\tcredentials,\n\t\tbinding: {\n\t\t\tstatus: \"invalid\",\n\t\t\tcredentialCount: 1,\n\t\t\tdetail: \"Stored Computer credentials do not belong to the local Computer identity\"\n\t\t}\n\t};\n\ttry {\n\t\tif (normalizeServerUrl(stored.serverUrl) !== stored.serverUrl) return {\n\t\t\tidentity,\n\t\t\tcredentials,\n\t\t\tbinding: {\n\t\t\t\tstatus: \"invalid\",\n\t\t\t\tcredentialCount: 1,\n\t\t\t\tdetail: \"The stored Computer credential contains a non-canonical Server origin\"\n\t\t\t}\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tidentity,\n\t\t\tcredentials,\n\t\t\tbinding: {\n\t\t\t\tstatus: \"invalid\",\n\t\t\t\tcredentialCount: 1,\n\t\t\t\tdetail: \"The stored Computer credential contains an invalid Server origin\"\n\t\t\t}\n\t\t};\n\t}\n\tif (identityValue.serverUrl !== stored.serverUrl) return {\n\t\tidentity,\n\t\tcredentials,\n\t\tbinding: {\n\t\t\tstatus: \"invalid\",\n\t\t\tcredentialCount: 1,\n\t\t\tdetail: \"The Computer identity and stored credential refer to different Server origins\"\n\t\t}\n\t};\n\treturn {\n\t\tidentity,\n\t\tcredentials,\n\t\tbinding: {\n\t\t\tstatus: \"valid\",\n\t\t\tcredentialCount: 1,\n\t\t\tserverUrl: stored.serverUrl\n\t\t}\n\t};\n}\nfunction inspectIdentity(result) {\n\tif (result.status === \"rejected\") return {\n\t\tstatus: \"invalid\",\n\t\tdetail: safeErrorDetail(result.reason, \"Computer identity could not be read\")\n\t};\n\tif (!result.value) return {\n\t\tstatus: \"missing\",\n\t\tdetail: \"Computer identity is not configured\"\n\t};\n\ttry {\n\t\tif (normalizeServerUrl(result.value.serverUrl) !== result.value.serverUrl) return {\n\t\t\tstatus: \"invalid\",\n\t\t\tdetail: \"Computer identity contains a non-canonical Server origin\"\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tstatus: \"invalid\",\n\t\t\tdetail: \"Computer identity contains an invalid Server origin\"\n\t\t};\n\t}\n\treturn {\n\t\tstatus: \"valid\",\n\t\tvalue: result.value\n\t};\n}\nfunction inspectCredentials(result) {\n\tif (result.status === \"rejected\") return {\n\t\tstatus: \"invalid\",\n\t\tdetail: safeErrorDetail(result.reason, \"Computer credentials could not be read\")\n\t};\n\tif (!result.value) return {\n\t\tstatus: \"missing\",\n\t\tdetail: \"No Computer credentials are configured\"\n\t};\n\ttry {\n\t\tif (normalizeServerUrl(result.value.computer.serverUrl) !== result.value.computer.serverUrl) return {\n\t\t\tstatus: \"invalid\",\n\t\t\tdetail: \"A stored Computer credential contains a non-canonical Server origin\"\n\t\t};\n\t} catch {\n\t\treturn {\n\t\t\tstatus: \"invalid\",\n\t\t\tdetail: \"A stored Computer credential contains an invalid Server origin\"\n\t\t};\n\t}\n\treturn {\n\t\tstatus: \"valid\",\n\t\tvalue: result.value\n\t};\n}\nfunction safeErrorDetail(error, fallback) {\n\tif (!(error instanceof Error) || error.message.length === 0) return fallback;\n\treturn error.message.slice(0, 300);\n}\n//#endregion\n//#region src/runtime/provider-cli/types.ts\n/** Map the local state machine onto the coarse readiness vocabulary used by the Server wire. */\nfunction mapProviderCliLocalStateToReadiness(state) {\n\tswitch (state) {\n\t\tcase \"ready\": return \"ready\";\n\t\tcase \"absent\": return \"install\";\n\t\tcase \"checking\": return \"checking\";\n\t\tcase \"unavailable\": return \"unavailable\";\n\t}\n}\n//#endregion\n//#region src/runtime/update-manager.ts\nconst DEFAULT_CHECK_INTERVAL_MS = 5e3;\nconst QUIET_LOG_THROTTLE_MS = 6e4;\nconst defaultSleep = (milliseconds) => new Promise((resolve) => {\n\tsetTimeout(resolve, milliseconds).unref();\n});\n/**\n* Drives automatic upgrades for the portable install mode. One decision loop, one durable attempt\n* per exact target, monotonic SemVer comparisons only (never an automatic downgrade), and an\n* indefinite protected-work gate: the updater adds no force timeout of its own, because the Session\n* module already bounds every unit of protected work (Turn budgets, delivery deadlines, report\n* retries with terminal outcomes) and therefore owns hang prevention.\n*\n* npm-global installs never attach a manager: they upgrade only through the manual CLI command.\n*/\nvar UpdateManager = class {\n\t#options;\n\t#logger;\n\t#now;\n\t#sleep;\n\t#checkIntervalMs;\n\t#latestTarget;\n\t#deciding;\n\t#stopped = false;\n\t#blockedLoggedTarget;\n\tconstructor(options) {\n\t\tthis.#options = options;\n\t\tthis.#logger = (options.logger ?? createLogger(\"updater\")).child({ channel: options.channel });\n\t\tthis.#now = options.now ?? Date.now;\n\t\tthis.#sleep = options.sleep ?? defaultSleep;\n\t\tthis.#checkIntervalMs = positive(options.checkIntervalMs ?? DEFAULT_CHECK_INTERVAL_MS, \"checkIntervalMs\");\n\t}\n\t/**\n\t* Reconcile durable status with the binary that actually started. This runs once before runtime\n\t* traffic begins, so `daemon status` always has a current version even when no update has ever\n\t* been advertised. If a previously blocked/installed target is now the running version, the\n\t* supervisor handoff (or a manual restart) succeeded and that record converges to installed.\n\t*/\n\tasync syncRunningVersion() {\n\t\ttry {\n\t\t\tconst stored = await this.#options.loadState();\n\t\t\tconst state = stored ?? emptyState(this.#options.currentVersion);\n\t\t\tlet changed = stored === void 0 || state.currentVersion !== this.#options.currentVersion;\n\t\t\tstate.currentVersion = this.#options.currentVersion;\n\t\t\tif (state.target) {\n\t\t\t\tconst comparison = compareSemVer(state.target, this.#options.currentVersion);\n\t\t\t\tif (state.target === this.#options.currentVersion && state.state !== \"installed\") {\n\t\t\t\t\tstate.state = \"installed\";\n\t\t\t\t\tconst attempt = state.attempts[state.target];\n\t\t\t\t\tif (attempt) {\n\t\t\t\t\t\tattempt.finishedAt ??= new Date(this.#now()).toISOString();\n\t\t\t\t\t\tattempt.result = \"installed\";\n\t\t\t\t\t\tdelete attempt.failureReason;\n\t\t\t\t\t\tstate.lastAttempt = attempt;\n\t\t\t\t\t}\n\t\t\t\t\tchanged = true;\n\t\t\t\t} else if (comparison < 0) {\n\t\t\t\t\tstate.state = \"idle\";\n\t\t\t\t\tdelete state.target;\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (changed) await this.#options.saveState(state);\n\t\t} catch (error) {\n\t\t\tthis.#logger.warn({ error: error instanceof Error ? error.message : String(error) }, \"Automatic upgrade state could not be reconciled with the running version\");\n\t\t}\n\t}\n\t/** Record a Server-advertised channel target. Cheap and safe to call on every heartbeat. */\n\tobserve(advertisement) {\n\t\tif (this.#stopped) return;\n\t\tif (advertisement.channel !== this.#options.channel) {\n\t\t\tthis.#logger.warn({\n\t\t\t\tadvertisedChannel: advertisement.channel,\n\t\t\t\tversion: advertisement.version\n\t\t\t}, \"Server advertised a target for another channel; ignoring it\");\n\t\t\treturn;\n\t\t}\n\t\tif (advertisement.version === this.#options.currentVersion) {\n\t\t\tthis.#latestTarget = advertisement.version;\n\t\t\tthis.#logger.debug({ version: advertisement.version }, \"Server target matches the running version\");\n\t\t\tthis.#deciding ??= this.#recordSatisfiedTarget(advertisement.version).finally(() => {\n\t\t\t\tthis.#deciding = void 0;\n\t\t\t});\n\t\t\tthis.#deciding.catch((error) => {\n\t\t\t\tthis.#logger.warn({ error: error instanceof Error ? error.message : String(error) }, \"Automatic upgrade status could not record the satisfied channel target\");\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (compareSemVer(advertisement.version, this.#options.currentVersion) < 0) {\n\t\t\tthis.#logger.info({\n\t\t\t\tcurrent: this.#options.currentVersion,\n\t\t\t\ttarget: advertisement.version\n\t\t\t}, \"Server target is older than the running version; ignoring it\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.#latestTarget === advertisement.version) return;\n\t\tif (this.#latestTarget && compareSemVer(advertisement.version, this.#latestTarget) < 0) return;\n\t\tthis.#latestTarget = advertisement.version;\n\t\tthis.#logger.info({\n\t\t\tcurrent: this.#options.currentVersion,\n\t\t\ttarget: advertisement.version\n\t\t}, \"Server advertised a newer channel target\");\n\t\tthis.#deciding ??= this.#decide().finally(() => {\n\t\t\tthis.#deciding = void 0;\n\t\t});\n\t\tthis.#deciding.catch((error) => {\n\t\t\tthis.#logger.warn({ error: error instanceof Error ? error.message : String(error) }, \"Automatic upgrade decision failed\");\n\t\t});\n\t}\n\tasync #recordSatisfiedTarget(target) {\n\t\tconst stored = await this.#options.loadState();\n\t\tconst state = stored ?? emptyState(this.#options.currentVersion);\n\t\tconst attempt = state.attempts[target];\n\t\tconst desiredState = attempt?.result === \"installed\" ? \"installed\" : \"idle\";\n\t\tif (stored && state.currentVersion === this.#options.currentVersion && state.target === target && state.state === desiredState) return;\n\t\tstate.currentVersion = this.#options.currentVersion;\n\t\tstate.target = target;\n\t\tstate.state = desiredState;\n\t\tif (attempt?.result === \"installed\") state.lastAttempt = attempt;\n\t\tawait this.#options.saveState(state);\n\t}\n\tstop() {\n\t\tthis.#stopped = true;\n\t}\n\tasync #decide() {\n\t\twhile (!this.#stopped) {\n\t\t\tconst target = this.#latestTarget;\n\t\t\tif (!target) return;\n\t\t\tif (await this.#settleNonNewerTarget(target)) return;\n\t\t\tconst state = await this.#options.loadState() ?? emptyState(this.#options.currentVersion);\n\t\t\tstate.currentVersion = this.#options.currentVersion;\n\t\t\tif (await this.#settleExistingAttempt(target, state)) return;\n\t\t\tif (await this.#attemptTarget(target, state) === \"finished\") return;\n\t\t}\n\t}\n\tasync #settleNonNewerTarget(target) {\n\t\tif (target === this.#options.currentVersion) {\n\t\t\tawait this.#recordSatisfiedTarget(target);\n\t\t\treturn true;\n\t\t}\n\t\treturn compareSemVer(target, this.#options.currentVersion) < 0;\n\t}\n\tasync #settleExistingAttempt(target, state) {\n\t\tconst attempt = state.attempts[target];\n\t\tif (!attempt) return false;\n\t\tif (attempt.result === \"installed\") {\n\t\t\tstate.state = \"installed\";\n\t\t\tstate.target = target;\n\t\t\tstate.lastAttempt = attempt;\n\t\t\tawait this.#options.saveState(state);\n\t\t\treturn true;\n\t\t}\n\t\tattempt.result = \"failed\";\n\t\tattempt.finishedAt ??= new Date(this.#now()).toISOString();\n\t\tattempt.failureReason ??= \"The previous upgrade attempt was interrupted before it completed\";\n\t\tstate.state = \"blocked\";\n\t\tstate.target = target;\n\t\tstate.lastAttempt = attempt;\n\t\tawait this.#options.saveState(state);\n\t\tthis.#logBlockedTarget(target, attempt.failureReason);\n\t\treturn true;\n\t}\n\t#logBlockedTarget(target, failureReason) {\n\t\tif (this.#blockedLoggedTarget === target) return;\n\t\tthis.#blockedLoggedTarget = target;\n\t\tthis.#logger.warn({\n\t\t\ttarget,\n\t\t\tfailureReason\n\t\t}, \"Automatic upgrade is blocked after a failed attempt; run the CLI upgrade command to retry manually or wait for a newer target\");\n\t}\n\tasync #attemptTarget(target, state) {\n\t\tstate.state = \"awaiting_protected_work\";\n\t\tstate.target = target;\n\t\tawait this.#options.saveState(state);\n\t\tconst resumeAdmission = this.#options.quiesce?.() ?? (() => void 0);\n\t\tlet keepQuiesced = false;\n\t\ttry {\n\t\t\tawait this.#waitForProtectedWork(target);\n\t\t\tif (this.#stopped) return \"finished\";\n\t\t\tif (this.#latestTarget !== target) return \"superseded\";\n\t\t\tconst started = await this.#recordStartedAttempt(target, state);\n\t\t\tif (!await this.#executeAttempt(target, state, started)) return \"finished\";\n\t\t\tkeepQuiesced = true;\n\t\t\tawait this.#requestHandoff(target);\n\t\t\treturn \"finished\";\n\t\t} finally {\n\t\t\tif (!keepQuiesced) resumeAdmission();\n\t\t}\n\t}\n\tasync #recordStartedAttempt(target, state) {\n\t\tconst started = {\n\t\t\ttarget,\n\t\t\tstartedAt: new Date(this.#now()).toISOString()\n\t\t};\n\t\tstate.attempts[target] = started;\n\t\tstate.state = \"installing\";\n\t\tstate.target = target;\n\t\tstate.lastAttempt = started;\n\t\tawait this.#options.saveState(state);\n\t\treturn started;\n\t}\n\tasync #executeAttempt(target, state, started) {\n\t\ttry {\n\t\t\tawait this.#options.executeUpdate(target);\n\t\t} catch (error) {\n\t\t\tstarted.finishedAt = new Date(this.#now()).toISOString();\n\t\t\tstarted.result = \"failed\";\n\t\t\tstarted.failureReason = error instanceof Error ? error.message : String(error);\n\t\t\tstate.state = \"blocked\";\n\t\t\tstate.lastAttempt = started;\n\t\t\tawait this.#options.saveState(state);\n\t\t\tthis.#logger.warn({\n\t\t\t\ttarget,\n\t\t\t\tfailureReason: started.failureReason\n\t\t\t}, \"Automatic upgrade attempt failed; blocked until a new target or a manual upgrade\");\n\t\t\treturn false;\n\t\t}\n\t\tstarted.finishedAt = new Date(this.#now()).toISOString();\n\t\tstarted.result = \"installed\";\n\t\tstate.state = \"installed\";\n\t\tstate.lastAttempt = started;\n\t\ttry {\n\t\t\tawait this.#options.saveState(state);\n\t\t} catch (error) {\n\t\t\tthis.#logger.warn({\n\t\t\t\ttarget,\n\t\t\t\terror: error instanceof Error ? error.message : String(error)\n\t\t\t}, \"The update was installed but its durable state could not be recorded; continuing supervisor handoff\");\n\t\t}\n\t\treturn true;\n\t}\n\tasync #requestHandoff(target) {\n\t\ttry {\n\t\t\tawait this.#options.onHandoff();\n\t\t} catch (error) {\n\t\t\tthis.#logger.warn({\n\t\t\t\ttarget,\n\t\t\t\terror: error instanceof Error ? error.message : String(error)\n\t\t\t}, \"The supervisor handoff failed after a successful install; restart the daemon to run the new version\");\n\t\t}\n\t}\n\t/**\n\t* Wait for the Session module to report no protected work. Indefinite by design: there is no\n\t* force timeout here, because the Session module owns the bounded lifetime of every protected\n\t* unit. The wait is re-checked on a fixed cadence and logged at a throttled rate.\n\t*/\n\tasync #waitForProtectedWork(target) {\n\t\tlet lastLogAt = Number.NEGATIVE_INFINITY;\n\t\twhile (!this.#stopped) {\n\t\t\tconst work = this.#options.protectedWork();\n\t\t\tif (work.total === 0) return;\n\t\t\tconst now = this.#now();\n\t\t\tif (now - lastLogAt >= QUIET_LOG_THROTTLE_MS) {\n\t\t\t\tlastLogAt = now;\n\t\t\t\tthis.#logger.info({\n\t\t\t\t\ttarget,\n\t\t\t\t\tprotectedWork: work.total\n\t\t\t\t}, \"Automatic upgrade is waiting for protected work to finish\");\n\t\t\t}\n\t\t\tawait this.#sleep(this.#checkIntervalMs);\n\t\t}\n\t}\n};\nfunction emptyState(currentVersion) {\n\treturn {\n\t\tschemaVersion: 1,\n\t\tcurrentVersion,\n\t\tstate: \"idle\",\n\t\tattempts: {}\n\t};\n}\nfunction positive(value, name) {\n\tif (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive safe integer`);\n\treturn value;\n}\n//#endregion\nexport { ACCOUNT_IDENTITY_FILE_NAME, AGENT_RUNTIME_BINDING_MAX_BYTES, AGENT_RUNTIME_CONTRACT_VERSION, AGENT_RUNTIME_DESCRIPTION_MAX_BYTES, AGENT_RUNTIME_ID_MAX_BYTES, AGENT_RUNTIME_TEXT_MAX_BYTES, AccessTokenProvider, AdmissionController, AdmissionReservation, AgentProviderError, AgentRuntimeError, AgentRuntimeExecutableDiscoveryError, AgentRuntimeExecutableNotFoundError, AgentRuntimeProviderRegistry, AgentRuntimeProviderUnavailableError, AgentTurnRunner, AgentWorkspaceManager, BaseAgentRuntime, CLAUDE_CODE_AGENT_RUNTIME_MANIFEST, CLAUDE_CODE_MAX_LINE_BYTES, CLAUDE_CODE_MAX_STDERR_BYTES, CLIENT_ERROR_REPORT_TIMEOUT_MS, CODEX_AGENT_RUNTIME_APP_SERVER_ARGS, CODEX_AGENT_RUNTIME_MANIFEST, CODEX_APP_SERVER_MAX_LINE_BYTES, CODEX_APP_SERVER_MAX_STDERR_BYTES, CODEX_APP_SERVER_REQUEST_TIMEOUT_MS, COMPUTER_IDENTITY_FILE_NAME, CONTEXT_TREE_PACKAGED_SKILL_DIRECTORIES, CREDENTIALS_FILE_NAME, ClaudeCodeAgentRuntime, ClaudeCodeAgentRuntimeFactory, ClaudeCodeProcess, ClaudeCodeProcessError, ClientRuntime, ClientRuntimeProviderStartError, CloudSandboxCredentialBridge, CodexAgentRuntime, CodexAgentRuntimeFactory, CodexAppServerError, CodexAppServerProcess, ComposedClientRuntime, ContextTreeManager, DEFAULT_RUNTIME_RETRY_POLICY, FeishuTokenExchangeError, FileRuntimeDurabilityStore, ImCredentialEnvironmentError, ImCredentialEnvironmentManager, ImResourceFetcher, MACHINE_CREDENTIALS_FILE_NAME, MAX_PROVIDER_CLI_EXECUTABLE_BYTES, MAX_PROVIDER_CLI_TURN_IDENTITY_BYTES, MAX_PROVIDER_CLI_TURN_PLAN_BYTES, MemoryRuntimeDurabilityStore, OpenTagApi, OpenTagApiError, PI_AGENT_RUNTIME_MANIFEST, PI_RPC_MAX_LINE_BYTES, PI_RPC_MAX_STDERR_BYTES, PI_RPC_REQUEST_TIMEOUT_MS, PROCESS_ERROR_FLUSH_WAIT_MS, PROCESS_ERROR_REPORT_WAIT_MS, PROVIDER_CLI_CATALOG, PROVIDER_CLI_LOCK_BUSY_MAX_ATTEMPTS, PROVIDER_CLI_LOCK_BUSY_RETRY_DELAY_MS, PROVIDER_CLI_SELECTION_SCHEMA_VERSION, PROVIDER_CLI_TURN_PLAN_SCHEMA_VERSION, PiAgentRuntime, PiAgentRuntimeFactory, PiRpcError, PiRpcProcess, ProviderCliAccountError, ProviderCliArchiveError, ProviderCliInstallError, ProviderCliInstaller, ProviderCliLockBusyError, ProviderCliManager, ProviderCliReconciler, ProviderCliTurnPlanError, ProviderCliTurnPlanManager, ProviderCliValidationRunner, RUNNER_CLI_NAME, RUNNER_IDENTITY_SCHEMA_VERSION, RUNTIME_CREDENTIAL_CAPABILITY, RUNTIME_EXECUTION_MAX_LIFETIME_MS, RUNTIME_PROVIDER_ORIGIN_HEADER, RUNTIME_PROVIDER_PROXY_CAPABILITY, RUNTIME_PROVIDER_PROXY_PATH, RUNTIME_PROXY_ALLOWED_CONNECT_HOSTS, RUNTIME_PROXY_DATA_BINARY_FRAME_MAX_BYTES, RUNTIME_PROXY_DATA_CHUNK_BYTES, RUNTIME_PROXY_DATA_HEADER_MAX_BYTES, RUNTIME_PROXY_DATA_INITIAL_CREDIT_BYTES, RUNTIME_PROXY_DATA_MAX_STREAMS, RUNTIME_PROXY_GIT_HELPER_MARKER, RUNTIME_PROXY_HANDLE_PATH_PREFIX, RUNTIME_PROXY_PROVIDERS, RUNTIME_PROXY_SHIM_MARKER, RUNTIME_PROXY_TICKET_TTL_MS, RUNTIME_WEB_TOOLS_CAPABILITY, RuntimeConnection, RuntimeConnectionError, RuntimeCredentialEnvironmentManager, RuntimeCredentialRelay, RuntimeCredentialRelayError, RuntimeDurabilityFailure, RuntimeDurabilityMetrics, RuntimeProxyDataConnection, RuntimeProxyDataError, RuntimeProxyLoopbackAdapter, RuntimeProxyLoopbackError, RuntimeProxyMaterialStore, RuntimeSendError, RuntimeStorageError, SERVER_HEALTH_TIMEOUT_MS, SESSION_BINDING_SCHEMA_VERSION, SESSION_RECORDED_INPUT_LIMIT, SKILL_CONTENT_SIDECAR_FILE, SKILL_PULL_BUNDLE_TIMEOUT_MS, SKILL_SYNC_DEFAULT_BUDGET_MS, ServerHealthConfigurationError, ServerHealthHttpError, ServerHealthNetworkError, ServerHealthResponseError, ServerHealthTimeoutError, ServerRuntimeDurabilityStore, SessionBindingConflictError, SessionBindingStore, SessionCliProofManager, SessionMessageInbox, SessionReconciler, SessionRuntimeManager, SkillArchiveError, SkillSyncManager, StoredAccountIdentitySchema, TURN_TRACE_BATCH_SOFT_LIMIT_BYTES, TURN_TRACE_MAX_BUFFER_BYTES, TURN_TRACE_MAX_BUFFER_EVENTS, TURN_TRACE_SEND_DEADLINE_MS, TurnCustodyOwner, TurnReportOwner, TurnReportOwnerStoppedError, TurnTraceBuffer, UpdateManager, WebGatewayDispatchError, WebToolsClientError, WebToolsGatewayServer, WebToolsServerClient, accountIdentityMatchesCredentials, accountIdentityPath, agentRuntimePaths, allocateComputerIdentity, assembleContextTreeSkills, assertRealDirectory, assertWithin, buildAgentInput, buildClientErrorReport, buildRuntimeProxyEnvironment, buildSessionMessageInput, catalogExecutableDigests, checkServerHealth, classifyLarkAuthStatus, classifySlackAuthTest, classifySpawnFailure, claudeCodeAgentRuntimeEnvironment, claudeCodeProcessEnvironment, codexAgentRuntimeEnvironment, codexDesktopAppBinDirs, computeFileIdentity, computeTargetFingerprint, computerIdentityPath, configureClientLoggerContext, configureClientLoggerForService, copyIsolatedPiConfig, createClientRuntime, createLogger, createProviderCliFetcher, createRunnerIdentity, credentialsFingerprint, credentialsPath, defaultProviderCliExecFile, defaultProviderCliFetcher, defaultRuntimeProxyDataConnectionFactory, defaultRuntimeRetryScheduler, deriveProviderCliHomeNamespace, deriveProviderCliRunKey, deriveProviderCliSessionKey, deriveProviderCliValidationRequestKey, deriveRuntimeKey, describePlatform, detectProviderCliCandidates, ensurePrivateDirectory, exchangeFeishuTenantToken, executableFormatSupportsHost, executeProviderCliTurnPlan, extractBoundedJson, extractProviderCliExecutable, extractSkillArchive, findCatalogArtifact, findProviderCliCatalogEntry, generateExecutionCa, hashSkillDirectory, inspectExecutableFormat, inspectGlobalCommand, inspectLocalComputerConfiguration, inspectProviderCliLauncher, installProcessErrorReporting, isSkillMaterializationTarget, isSyncedWorkspace, iterateAgentRuntimeExecutables, linuxAmd64ProviderCliPlans, machineCredentialsPath, mapProviderCliLocalStateToReadiness, markSkillDirectoryManaged, normalizeServerUrl, packSkillDirectory, parseProviderCliTurnPlan, parseProviderCliTurnRunnerArgv, parseRunnerCliArgv, parseRunnerIdentity, parseRuntimeCredentialServerFrame, piAgentRuntimeEnvironment, prepareContextTreeHome, probeAgentRuntimeCliInstallations, probeIntegrationCliInstallations, probeProviderCliExecutable, probeRunnerTools, providerCliArtifactId, providerCliCommandForProvider, providerCliLauncherPath, providerCliLockFilePath, providerCliProbeEnvironment, providerCliSelectionTargetPath, providerCliStateFilePath, providerCliVersionDirPath, providerReadiness, rankProviderCliCandidates, readAccountIdentity, readBundleBody, readComputerIdentity, readCredentials, readDurableJson, readMachineCredentials, readMachineCredentialsStrict, readPrivateJson, readProviderCliSelection, readProviderCliTurnPlan, readSecureFile, readSessionCliProofFile, reconcileProviderCliLauncher, reconcileProviderCliShim, redactAcceptanceRecord, removeAccountIdentity, renderManagedSystemPrompt, renderProviderCliLauncher, renderProviderCliShim, renderProviderCliTurnLauncher, renderRuntimeProxyGitCredentialHelper, renderRuntimeProxyShim, reportClientError, requireProviderCliCatalogEntry, resolveAccountHome, resolveAgentRuntimeExecutable, resolveBoundAccountComputer, resolveCodexHome, resolveComputerIdentity, resolveContextTreeHome, resolveContextTreePackage, resolveMaterializationWorkspace, resolveOpenTagHome, resolveOpenTagHomeLayout, resolvePiHome, resolveProviderCliAccountLayout, resolveProviderCliArtifactUrl, resolveProviderCliTurnRunnerInvocation, resolveWebToolsExtensionPath, resolvedClaudeCodeFactory, resolvedCodexFactory, resolvedPiFactory, retryDelay, retryExhausted, rotateAccountIdentityFingerprint, runContextTreeCli, runProviderCliTurnRunner, runRunnerAcceptance, runRunnerCli, serializeEnvironment, sessionBindingPath, skillRootForProvider, snapshotPath, storeBoundAccountComputer, validatePrivateDirectory, verifyProviderCliCandidateFingerprint, verifySkillBundle, wellKnownAgentRuntimeBinDirs, withProviderCliLock, writeAccountIdentityAtomically, writeComputerIdentityAtomically, writeCredentialsAtomically, writeDurableFile, writeDurableJson, writeMachineCredentialsAtomically, writePrivateJson, writeProviderCliSelection };\n\n//# sourceMappingURL=index.mjs.map","import { type ClientLogger, createLogger, OpenTagApiError } from \"@opentag/client\";\nimport {\n  type ErrorRetryability,\n  redactSensitive,\n  type StructuredError,\n  StructuredErrorCategorySchema,\n  StructuredErrorPhaseSchema,\n  StructuredErrorSchema,\n} from \"@opentag/shared\";\n\n/** Process exit values shared by every user-facing CLI command. */\nexport const EXIT_CODES = {\n  success: 0,\n  failure: 1,\n  usage: 2,\n  serviceUnavailable: 3,\n  interrupted: 130,\n} as const;\n\nexport type CommandExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES];\nexport type CommandErrorCategory = StructuredError[\"category\"];\nexport type CommandRetryability = ErrorRetryability;\nexport type CommandPhase = StructuredError[\"phase\"];\n\ntype CommandErrorCodeFields = { code: string; category: CommandErrorCategory };\ntype CommandErrorRetryFields = { retryability: CommandRetryability; phase: CommandPhase };\ntype CommandErrorRequiredFields = CommandErrorCodeFields & CommandErrorRetryFields;\ntype CommandErrorFields = CommandErrorRequiredFields & { requestId?: string };\n\n/** Structured, transport-neutral CLI failure metadata. The Error message is the human detail. */\nexport class CommandError extends Error {\n  declare readonly code: string;\n  declare readonly category: CommandErrorCategory;\n  declare readonly retryability: CommandRetryability;\n  declare readonly phase: CommandPhase;\n  declare readonly requestId?: string;\n  readonly structuredError: StructuredError;\n\n  constructor(fields: CommandErrorFields, message: string, options?: ErrorOptions) {\n    const safeMessage = redactSecrets(message);\n    super(safeMessage, options);\n    this.name = \"CommandError\";\n    this.code = fields.code;\n    this.category = fields.category;\n    this.retryability = fields.retryability;\n    this.phase = fields.phase;\n    if (fields.requestId) this.requestId = fields.requestId;\n    this.structuredError = StructuredErrorSchema.parse({\n      code: this.code,\n      category: this.category,\n      retryability: this.retryability,\n      phase: this.phase,\n      ...(this.requestId ? { requestId: this.requestId.slice(0, 256) } : {}),\n      message: safeMessage.slice(0, 2_048),\n    });\n  }\n\n  toStructuredError(): StructuredError {\n    return this.structuredError;\n  }\n}\n\ntype SuccessCommandResult<T> = { ok: true; value: T; exitCode: typeof EXIT_CODES.success };\ntype FailureCommandResultBase<T> = { ok: false; error: CommandError; value?: T };\ntype FailureCommandResult<T> = FailureCommandResultBase<T> & { exitCode: Exclude<CommandExitCode, 0> };\nexport type CommandResult<T> = SuccessCommandResult<T> | FailureCommandResult<T>;\ntype CommandFormatValueOptions<T> = { formatValue?: (value: T) => string };\ntype CommandFormatWriterOptions = { stdout?: (chunk: string) => void; stderr?: (chunk: string) => void };\ntype CommandFormatOptions<T> = CommandFormatValueOptions<T> & CommandFormatWriterOptions;\nexport type CommandPresentationOptions<T> = { json?: boolean } & CommandFormatOptions<T>;\nexport type CommandExecutionOptions<T> = CommandPresentationOptions<T> & {\n  logger?: ClientLogger;\n  phase?: CommandPhase;\n};\n\n/** Convert errors from Commander, Zod, the API, and Node into one local contract. */\nexport function toCommandError(error: unknown, phase: CommandPhase = \"unknown\"): CommandError {\n  if (error instanceof CommandError) return error;\n  if (isZodError(error)) {\n    return new CommandError(\n      { code: \"VALIDATION_ERROR\", category: \"validation\", retryability: \"never\", phase: \"validation\" },\n      error.issues.map((issue) => `${issue.path.join(\".\") || \"input\"}: ${issue.message}`).join(\"; \"),\n      { cause: error },\n    );\n  }\n  if (error instanceof OpenTagApiError) {\n    const mapped = mapApiError(error);\n    return new CommandError(mapped, error.message, { cause: error });\n  }\n  if (isInterrupted(error)) {\n    return new CommandError(\n      { code: \"INTERRUPTED\", category: \"cancelled\", retryability: \"never\", phase: \"shutdown\" },\n      \"The operation was interrupted\",\n      { cause: error },\n    );\n  }\n\n  return classifyGenericError(error, phase);\n}\n\nfunction classifyGenericError(error: unknown, phase: CommandPhase): CommandError {\n  const candidate =\n    error !== null && typeof error === \"object\"\n      ? (error as { code?: unknown; category?: unknown; requestId?: unknown; message?: unknown })\n      : {};\n  const code = typeof candidate.code === \"string\" && candidate.code.length > 0 ? candidate.code : \"INTERNAL_ERROR\";\n  const message = typeof candidate.message === \"string\" ? candidate.message : String(error);\n  const requestId = typeof candidate.requestId === \"string\" ? candidate.requestId : undefined;\n  if (\n    StructuredErrorCategorySchema.safeParse(candidate.category).success &&\n    StructuredErrorPhaseSchema.safeParse((candidate as { phase?: unknown }).phase).success &&\n    isRetryability((candidate as { retryability?: unknown }).retryability)\n  ) {\n    return new CommandError(\n      {\n        code,\n        category: candidate.category as CommandErrorCategory,\n        retryability: (candidate as { retryability: CommandRetryability }).retryability,\n        phase: (candidate as { phase: CommandPhase }).phase,\n        ...(requestId ? { requestId } : {}),\n      },\n      message,\n      { cause: error },\n    );\n  }\n  if (candidate.category === \"validation\" || phase === \"validation\") {\n    return new CommandError({ code, category: \"validation\", retryability: \"never\", phase: \"validation\" }, message, {\n      cause: error,\n    });\n  }\n  if (isAuth(code, message, candidate.category)) {\n    return new CommandError(\n      {\n        code,\n        category: \"auth\",\n        retryability: \"after_auth\",\n        phase: \"authentication\",\n        ...(requestId ? { requestId } : {}),\n      },\n      message,\n      { cause: error },\n    );\n  }\n  if (isUnavailable(code, message, candidate.category)) {\n    return new CommandError(\n      {\n        code,\n        category: \"unavailable\",\n        retryability: \"backoff\",\n        phase: \"transport\",\n        ...(requestId ? { requestId } : {}),\n      },\n      message,\n      { cause: error },\n    );\n  }\n  return new CommandError(\n    { code, category: \"internal\", retryability: \"never\", phase, ...(requestId ? { requestId } : {}) },\n    message,\n    { cause: error },\n  );\n}\n\nfunction isAuth(code: string, message: string, category: unknown): boolean {\n  return (\n    category === \"auth\" ||\n    category === \"authentication\" ||\n    /^AUTH_/u.test(code) ||\n    /not logged in|authentication/iu.test(message)\n  );\n}\n\nfunction isUnavailable(code: string, message: string, category: unknown): boolean {\n  return (\n    category === \"unavailable\" ||\n    category === \"service-unavailable\" ||\n    category === \"transient\" ||\n    code === \"SERVICE_UNAVAILABLE\" ||\n    /(?:_UPSTREAM_)?UNAVAILABLE$/u.test(code) ||\n    /unavailable|timed out|connection refused/iu.test(message)\n  );\n}\n\n/** Present a result once. Human successes use stdout; all failures use redacted stderr. */\nexport function presentCommand<T>(\n  result: CommandResult<T>,\n  options: CommandPresentationOptions<T> = {},\n): CommandExitCode {\n  const stdout = options.stdout ?? ((chunk: string) => process.stdout.write(chunk));\n  const stderr = options.stderr ?? ((chunk: string) => process.stderr.write(chunk));\n  if (result.ok) {\n    const value = redactValue(result.value);\n    const output = options.json\n      ? JSON.stringify({ ok: true, result: value })\n      : (options.formatValue ?? ((item) => formatHumanValue(item)))(value);\n    stdout(`${output}\\n`);\n    return EXIT_CODES.success;\n  }\n  const error = result.error;\n  const value = result.value === undefined ? undefined : redactValue(result.value);\n  const output = options.json\n    ? JSON.stringify({\n        ok: false,\n        error: {\n          code: error.code,\n          category: error.category,\n          retryability: error.retryability,\n          phase: error.phase,\n          ...(error.requestId ? { requestId: error.requestId } : {}),\n          message: error.message,\n        },\n        ...(value === undefined ? {} : { result: value }),\n      })\n    : `${error.code}: ${error.message}${error.requestId ? ` (request ${error.requestId})` : \"\"}`;\n  stderr(`${output}\\n`);\n  return result.exitCode;\n}\n\nexport type CommandFailureObserver = (error: unknown, commandError: CommandError) => void;\n\nlet commandFailureObserver: CommandFailureObserver | undefined;\n\n/**\n * Observe every failure the shared execution path handles. Commands present their own failures and\n * return an exit code, so a process-level concern such as error reporting cannot see them from the\n * entry point's catch; this is the one seam that does. Returns the function that detaches it.\n */\nexport function observeCommandFailures(observer: CommandFailureObserver): () => void {\n  commandFailureObserver = observer;\n  return () => {\n    if (commandFailureObserver === observer) commandFailureObserver = undefined;\n  };\n}\n\n/** Run an operation through the shared result and presentation path. */\nexport async function executeCommand<T>(\n  operation: () => Promise<T>,\n  options: CommandExecutionOptions<T> = {},\n): Promise<CommandExitCode> {\n  try {\n    return presentCommand({ ok: true, value: await operation(), exitCode: EXIT_CODES.success }, options);\n  } catch (error) {\n    const commandError = toCommandError(error, options.phase);\n    const structuredError = commandError.toStructuredError();\n    (options.logger ?? createLogger(\"cli\")).error(\n      {\n        event: \"command.failure\",\n        error: structuredError,\n        code: structuredError.code,\n        category: structuredError.category,\n        retryability: structuredError.retryability,\n        phase: structuredError.phase,\n        ...(structuredError.requestId ? { requestId: structuredError.requestId } : {}),\n      },\n      \"CLI command failed\",\n    );\n    const exitCode = presentCommand(\n      { ok: false, error: commandError, exitCode: commandExitCode(commandError) },\n      options,\n    );\n    try {\n      commandFailureObserver?.(error, commandError);\n    } catch {\n      // An observer is a bystander; its failure must not change the answer already presented.\n    }\n    return exitCode;\n  }\n}\n\nfunction mapApiError(error: OpenTagApiError): Omit<ConstructorParameters<typeof CommandError>[0], never> {\n  switch (error.category) {\n    case \"credential\":\n      return {\n        code: error.code,\n        category: \"auth\",\n        retryability: \"after_auth\",\n        phase: \"authentication\",\n        ...(error.requestId ? { requestId: error.requestId } : {}),\n      };\n    case \"validation\":\n      return {\n        code: error.code,\n        category: \"validation\",\n        retryability: \"never\",\n        phase: \"validation\",\n        ...(error.requestId ? { requestId: error.requestId } : {}),\n      };\n    case \"rate_limit\":\n      return {\n        code: error.code,\n        category: \"rate_limit\",\n        retryability: \"backoff\",\n        phase: \"request\",\n        ...(error.requestId ? { requestId: error.requestId } : {}),\n      };\n    case \"transient\":\n      return {\n        code: error.code,\n        category: \"unavailable\",\n        retryability: \"backoff\",\n        phase: \"transport\",\n        ...(error.requestId ? { requestId: error.requestId } : {}),\n      };\n    default:\n      return {\n        code: error.code,\n        category: error.structuredError.category,\n        retryability: error.structuredError.retryability,\n        phase: error.structuredError.phase,\n        ...(error.requestId ? { requestId: error.requestId } : {}),\n      };\n  }\n}\n\nfunction isRetryability(value: unknown): value is CommandRetryability {\n  return value === \"never\" || value === \"immediate\" || value === \"backoff\" || value === \"after_auth\";\n}\n\nfunction isZodError(\n  error: unknown,\n): error is { issues: readonly { path: readonly (string | number)[]; message: string }[] } {\n  return (\n    error !== null &&\n    typeof error === \"object\" &&\n    (error as { name?: unknown }).name === \"ZodError\" &&\n    Array.isArray((error as { issues?: unknown }).issues)\n  );\n}\n\nexport function commandExitCode(error: CommandError): Exclude<CommandExitCode, typeof EXIT_CODES.success> {\n  if (error.category === \"validation\") return EXIT_CODES.usage;\n  if (error.category === \"unavailable\" || error.category === \"timeout\" || error.category === \"dependency\") {\n    return EXIT_CODES.serviceUnavailable;\n  }\n  if (error.category === \"cancelled\") return EXIT_CODES.interrupted;\n  return EXIT_CODES.failure;\n}\n\nfunction isInterrupted(error: unknown): boolean {\n  if (error instanceof Error && (error.name === \"AbortError\" || error.name === \"CanceledError\")) return true;\n  return isAbortSignal(error);\n}\n\nfunction isAbortSignal(error: unknown): error is AbortSignal {\n  return (\n    error !== null &&\n    typeof error === \"object\" &&\n    \"aborted\" in error &&\n    (error as { aborted?: unknown }).aborted === true &&\n    typeof (error as { addEventListener?: unknown }).addEventListener === \"function\"\n  );\n}\n\nfunction formatHumanValue(value: unknown): string {\n  if (typeof value === \"string\") return value;\n  return JSON.stringify(value) ?? \"null\";\n}\n\nfunction redactValue<T>(value: T): T {\n  return redactSensitive(value);\n}\n\n/*\n * Presentation redaction delegates to the shared implementation.\n *\n * This module used to keep its own key-pattern list, which drifted: it matched `authorization` as a\n * substring, so MCP's credential-free authorization summary was replaced wholesale and the CLI\n * printed `authKind none` for a stored Bearer key. The shared redactor is the single source of truth\n * for what counts as sensitive, and its exemptions are exact names rather than substrings.\n */\nexport function redactSecrets(value: string): string {\n  return redactSensitive(value);\n}\n","","import { type ChannelName, getChannelConfig } from \"@opentag/shared\";\nimport packageManifest from \"../package.json\" with { type: \"json\" };\n\nexport const CHANNEL: ChannelName = \"staging\";\nexport const CLI_PACKAGE_NAME = packageManifest.name;\nexport const CLI_VERSION = packageManifest.version;\n\nif (CLI_PACKAGE_NAME !== getChannelConfig(CHANNEL).packageName) {\n  throw new Error(`CLI package ${CLI_PACKAGE_NAME} does not match the ${CHANNEL} channel`);\n}\n","/**\n * CommanderError class\n */\nexport class CommanderError extends Error {\n  /**\n   * Constructs the CommanderError class\n   * @param {number} exitCode suggested exit code which could be used with process.exit\n   * @param {string} code an id string representing the error\n   * @param {string} message human-readable description of the error\n   */\n  constructor(exitCode, code, message) {\n    super(message);\n    // properly capture stack trace in Node.js\n    Error.captureStackTrace(this, this.constructor);\n    this.name = this.constructor.name;\n    this.code = code;\n    this.exitCode = exitCode;\n    this.nestedError = undefined;\n  }\n}\n\n/**\n * InvalidArgumentError class\n */\nexport class InvalidArgumentError extends CommanderError {\n  /**\n   * Constructs the InvalidArgumentError class\n   * @param {string} [message] explanation of why argument is invalid\n   */\n  constructor(message) {\n    super(1, 'commander.invalidArgument', message);\n    // properly capture stack trace in Node.js\n    Error.captureStackTrace(this, this.constructor);\n    this.name = this.constructor.name;\n  }\n}\n","import { InvalidArgumentError } from './error.js';\n\nexport class Argument {\n  /**\n   * Initialize a new command argument with the given name and description.\n   * The default is that the argument is required, and you can explicitly\n   * indicate this with <> around the name. Put [] around the name for an optional argument.\n   *\n   * @param {string} name\n   * @param {string} [description]\n   */\n\n  constructor(name, description) {\n    this.description = description || '';\n    this.variadic = false;\n    this.parseArg = undefined;\n    this.defaultValue = undefined;\n    this.defaultValueDescription = undefined;\n    this.argChoices = undefined;\n\n    switch (name[0]) {\n      case '<': // e.g. <required>\n        this.required = true;\n        this._name = name.slice(1, -1);\n        break;\n      case '[': // e.g. [optional]\n        this.required = false;\n        this._name = name.slice(1, -1);\n        break;\n      default:\n        this.required = true;\n        this._name = name;\n        break;\n    }\n\n    if (this._name.endsWith('...')) {\n      this.variadic = true;\n      this._name = this._name.slice(0, -3);\n    }\n  }\n\n  /**\n   * Return argument name.\n   *\n   * @return {string}\n   */\n\n  name() {\n    return this._name;\n  }\n\n  /**\n   * @package\n   */\n\n  _collectValue(value, previous) {\n    if (previous === this.defaultValue || !Array.isArray(previous)) {\n      return [value];\n    }\n\n    previous.push(value);\n    return previous;\n  }\n\n  /**\n   * Set the default value, and optionally supply the description to be displayed in the help.\n   *\n   * @param {*} value\n   * @param {string} [description]\n   * @return {Argument}\n   */\n\n  default(value, description) {\n    this.defaultValue = value;\n    this.defaultValueDescription = description;\n    return this;\n  }\n\n  /**\n   * Set the custom handler for processing CLI command arguments into argument values.\n   *\n   * @param {Function} [fn]\n   * @return {Argument}\n   */\n\n  argParser(fn) {\n    this.parseArg = fn;\n    return this;\n  }\n\n  /**\n   * Only allow argument value to be one of choices.\n   *\n   * @param {string[]} values\n   * @return {Argument}\n   */\n\n  choices(values) {\n    this.argChoices = values.slice();\n    this.parseArg = (arg, previous) => {\n      if (!this.argChoices.includes(arg)) {\n        throw new InvalidArgumentError(\n          `Allowed choices are ${this.argChoices.join(', ')}.`,\n        );\n      }\n      if (this.variadic) {\n        return this._collectValue(arg, previous);\n      }\n      return arg;\n    };\n    return this;\n  }\n\n  /**\n   * Make argument required.\n   *\n   * @returns {Argument}\n   */\n  argRequired() {\n    this.required = true;\n    return this;\n  }\n\n  /**\n   * Make argument optional.\n   *\n   * @returns {Argument}\n   */\n  argOptional() {\n    this.required = false;\n    return this;\n  }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nexport function humanReadableArgName(arg) {\n  const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n  return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n","import { humanReadableArgName } from './argument.js';\nimport { stripVTControlCharacters } from 'node:util';\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nexport class Help {\n  constructor() {\n    this.helpWidth = undefined;\n    this.minWidthToWrap = 40;\n    this.sortSubcommands = false;\n    this.sortOptions = false;\n    this.showGlobalOptions = false;\n  }\n\n  /**\n   * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n   * and just before calling `formatHelp()`.\n   *\n   * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.\n   *\n   * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions\n   */\n  prepareContext(contextOptions) {\n    this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;\n  }\n\n  /**\n   * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n   *\n   * @param {Command} cmd\n   * @returns {Command[]}\n   */\n\n  visibleCommands(cmd) {\n    const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n    const helpCommand = cmd._getHelpCommand();\n    if (helpCommand && !helpCommand._hidden) {\n      visibleCommands.push(helpCommand);\n    }\n    if (this.sortSubcommands) {\n      visibleCommands.sort((a, b) => {\n        // @ts-ignore: because overloaded return type\n        return a.name().localeCompare(b.name());\n      });\n    }\n    return visibleCommands;\n  }\n\n  /**\n   * Compare options for sort.\n   *\n   * @param {Option} a\n   * @param {Option} b\n   * @returns {number}\n   */\n  compareOptions(a, b) {\n    const getSortKey = (option) => {\n      // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n      return option.short\n        ? option.short.replace(/^-/, '')\n        : option.long.replace(/^--/, '');\n    };\n    return getSortKey(a).localeCompare(getSortKey(b));\n  }\n\n  /**\n   * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n   *\n   * @param {Command} cmd\n   * @returns {Option[]}\n   */\n\n  visibleOptions(cmd) {\n    const visibleOptions = cmd.options.filter((option) => !option.hidden);\n    // Built-in help option.\n    const helpOption = cmd._getHelpOption();\n    if (helpOption && !helpOption.hidden) {\n      // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n      const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n      const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n      if (!removeShort && !removeLong) {\n        visibleOptions.push(helpOption); // no changes needed\n      } else if (helpOption.long && !removeLong) {\n        visibleOptions.push(\n          cmd.createOption(helpOption.long, helpOption.description),\n        );\n      } else if (helpOption.short && !removeShort) {\n        visibleOptions.push(\n          cmd.createOption(helpOption.short, helpOption.description),\n        );\n      }\n    }\n    if (this.sortOptions) {\n      visibleOptions.sort(this.compareOptions);\n    }\n    return visibleOptions;\n  }\n\n  /**\n   * Get an array of the visible global options. (Not including help.)\n   *\n   * @param {Command} cmd\n   * @returns {Option[]}\n   */\n\n  visibleGlobalOptions(cmd) {\n    if (!this.showGlobalOptions) return [];\n\n    const globalOptions = [];\n    for (\n      let ancestorCmd = cmd.parent;\n      ancestorCmd;\n      ancestorCmd = ancestorCmd.parent\n    ) {\n      const visibleOptions = ancestorCmd.options.filter(\n        (option) => !option.hidden,\n      );\n      globalOptions.push(...visibleOptions);\n    }\n    if (this.sortOptions) {\n      globalOptions.sort(this.compareOptions);\n    }\n    return globalOptions;\n  }\n\n  /**\n   * Get an array of the arguments if any have a description.\n   *\n   * @param {Command} cmd\n   * @returns {Argument[]}\n   */\n\n  visibleArguments(cmd) {\n    // Side effect! Apply the legacy descriptions before the arguments are displayed.\n    if (cmd._argsDescription) {\n      cmd.registeredArguments.forEach((argument) => {\n        argument.description =\n          argument.description || cmd._argsDescription[argument.name()] || '';\n      });\n    }\n\n    // If there are any arguments with a description then return all the arguments.\n    if (cmd.registeredArguments.find((argument) => argument.description)) {\n      return cmd.registeredArguments;\n    }\n    return [];\n  }\n\n  /**\n   * Get the command term to show in the list of subcommands.\n   *\n   * @param {Command} cmd\n   * @returns {string}\n   */\n\n  subcommandTerm(cmd) {\n    // Legacy. Ignores custom usage string, and nested commands.\n    const args = cmd.registeredArguments\n      .map((arg) => humanReadableArgName(arg))\n      .join(' ');\n    return (\n      cmd._name +\n      (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n      (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n      (args ? ' ' + args : '')\n    );\n  }\n\n  /**\n   * Get the option term to show in the list of options.\n   *\n   * @param {Option} option\n   * @returns {string}\n   */\n\n  optionTerm(option) {\n    return option.flags;\n  }\n\n  /**\n   * Get the argument term to show in the list of arguments.\n   *\n   * @param {Argument} argument\n   * @returns {string}\n   */\n\n  argumentTerm(argument) {\n    return argument.name();\n  }\n\n  /**\n   * Get the longest command term length.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {number}\n   */\n\n  longestSubcommandTermLength(cmd, helper) {\n    return helper.visibleCommands(cmd).reduce((max, command) => {\n      return Math.max(\n        max,\n        this.displayWidth(\n          helper.styleSubcommandTerm(helper.subcommandTerm(command)),\n        ),\n      );\n    }, 0);\n  }\n\n  /**\n   * Get the longest option term length.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {number}\n   */\n\n  longestOptionTermLength(cmd, helper) {\n    return helper.visibleOptions(cmd).reduce((max, option) => {\n      return Math.max(\n        max,\n        this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n      );\n    }, 0);\n  }\n\n  /**\n   * Get the longest global option term length.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {number}\n   */\n\n  longestGlobalOptionTermLength(cmd, helper) {\n    return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n      return Math.max(\n        max,\n        this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n      );\n    }, 0);\n  }\n\n  /**\n   * Get the longest argument term length.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {number}\n   */\n\n  longestArgumentTermLength(cmd, helper) {\n    return helper.visibleArguments(cmd).reduce((max, argument) => {\n      return Math.max(\n        max,\n        this.displayWidth(\n          helper.styleArgumentTerm(helper.argumentTerm(argument)),\n        ),\n      );\n    }, 0);\n  }\n\n  /**\n   * Get the command usage to be displayed at the top of the built-in help.\n   *\n   * @param {Command} cmd\n   * @returns {string}\n   */\n\n  commandUsage(cmd) {\n    // Usage\n    let cmdName = cmd._name;\n    if (cmd._aliases[0]) {\n      cmdName = cmdName + '|' + cmd._aliases[0];\n    }\n    let ancestorCmdNames = '';\n    for (\n      let ancestorCmd = cmd.parent;\n      ancestorCmd;\n      ancestorCmd = ancestorCmd.parent\n    ) {\n      ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n    }\n    return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n  }\n\n  /**\n   * Get the description for the command.\n   *\n   * @param {Command} cmd\n   * @returns {string}\n   */\n\n  commandDescription(cmd) {\n    // @ts-ignore: because overloaded return type\n    return cmd.description();\n  }\n\n  /**\n   * Get the subcommand summary to show in the list of subcommands.\n   * (Fallback to description for backwards compatibility.)\n   *\n   * @param {Command} cmd\n   * @returns {string}\n   */\n\n  subcommandDescription(cmd) {\n    // @ts-ignore: because overloaded return type\n    return cmd.summary() || cmd.description();\n  }\n\n  /**\n   * Get the option description to show in the list of options.\n   *\n   * @param {Option} option\n   * @return {string}\n   */\n\n  optionDescription(option) {\n    const extraInfo = [];\n\n    if (option.argChoices) {\n      extraInfo.push(\n        // use stringify to match the display of the default value\n        `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n      );\n    }\n    if (option.defaultValue !== undefined) {\n      // default for boolean and negated more for programmer than end user,\n      // but show true/false for boolean option as may be for hand-rolled env or config processing.\n      const showDefault =\n        option.required ||\n        option.optional ||\n        (option.isBoolean() && typeof option.defaultValue === 'boolean');\n      if (showDefault) {\n        extraInfo.push(\n          `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n        );\n      }\n    }\n    // preset for boolean and negated are more for programmer than end user\n    if (option.presetArg !== undefined && option.optional) {\n      extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n    }\n    if (option.envVar !== undefined) {\n      extraInfo.push(`env: ${option.envVar}`);\n    }\n    if (extraInfo.length > 0) {\n      const extraDescription = `(${extraInfo.join(', ')})`;\n      if (option.description) {\n        return `${option.description} ${extraDescription}`;\n      }\n      return extraDescription;\n    }\n\n    return option.description;\n  }\n\n  /**\n   * Get the argument description to show in the list of arguments.\n   *\n   * @param {Argument} argument\n   * @return {string}\n   */\n\n  argumentDescription(argument) {\n    const extraInfo = [];\n    if (argument.argChoices) {\n      extraInfo.push(\n        // use stringify to match the display of the default value\n        `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n      );\n    }\n    if (argument.defaultValue !== undefined) {\n      extraInfo.push(\n        `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n      );\n    }\n    if (extraInfo.length > 0) {\n      const extraDescription = `(${extraInfo.join(', ')})`;\n      if (argument.description) {\n        return `${argument.description} ${extraDescription}`;\n      }\n      return extraDescription;\n    }\n    return argument.description;\n  }\n\n  /**\n   * Format a list of items, given a heading and an array of formatted items.\n   *\n   * @param {string} heading\n   * @param {string[]} items\n   * @param {Help} helper\n   * @returns string[]\n   */\n  formatItemList(heading, items, helper) {\n    if (items.length === 0) return [];\n\n    return [helper.styleTitle(heading), ...items, ''];\n  }\n\n  /**\n   * Group items by their help group heading.\n   *\n   * @param {Command[] | Option[]} unsortedItems\n   * @param {Command[] | Option[]} visibleItems\n   * @param {Function} getGroup\n   * @returns {Map<string, Command[] | Option[]>}\n   */\n  groupItems(unsortedItems, visibleItems, getGroup) {\n    const result = new Map();\n    // Add groups in order of appearance in unsortedItems.\n    unsortedItems.forEach((item) => {\n      const group = getGroup(item);\n      if (!result.has(group)) result.set(group, []);\n    });\n    // Add items in order of appearance in visibleItems.\n    visibleItems.forEach((item) => {\n      const group = getGroup(item);\n      if (!result.has(group)) {\n        result.set(group, []);\n      }\n      result.get(group).push(item);\n    });\n    return result;\n  }\n\n  /**\n   * Generate the built-in help text.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {string}\n   */\n\n  formatHelp(cmd, helper) {\n    const termWidth = helper.padWidth(cmd, helper);\n    const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called\n\n    function callFormatItem(term, description) {\n      return helper.formatItem(term, termWidth, description, helper);\n    }\n\n    // Usage\n    let output = [\n      `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n      '',\n    ];\n\n    // Description\n    const commandDescription = helper.commandDescription(cmd);\n    if (commandDescription.length > 0) {\n      output = output.concat([\n        helper.boxWrap(\n          helper.styleCommandDescription(commandDescription),\n          helpWidth,\n        ),\n        '',\n      ]);\n    }\n\n    // Arguments\n    const argumentList = helper.visibleArguments(cmd).map((argument) => {\n      return callFormatItem(\n        helper.styleArgumentTerm(helper.argumentTerm(argument)),\n        helper.styleArgumentDescription(helper.argumentDescription(argument)),\n      );\n    });\n    output = output.concat(\n      this.formatItemList('Arguments:', argumentList, helper),\n    );\n\n    // Options\n    const optionGroups = this.groupItems(\n      cmd.options,\n      helper.visibleOptions(cmd),\n      (option) => option.helpGroupHeading ?? 'Options:',\n    );\n    optionGroups.forEach((options, group) => {\n      const optionList = options.map((option) => {\n        return callFormatItem(\n          helper.styleOptionTerm(helper.optionTerm(option)),\n          helper.styleOptionDescription(helper.optionDescription(option)),\n        );\n      });\n      output = output.concat(this.formatItemList(group, optionList, helper));\n    });\n\n    if (helper.showGlobalOptions) {\n      const globalOptionList = helper\n        .visibleGlobalOptions(cmd)\n        .map((option) => {\n          return callFormatItem(\n            helper.styleOptionTerm(helper.optionTerm(option)),\n            helper.styleOptionDescription(helper.optionDescription(option)),\n          );\n        });\n      output = output.concat(\n        this.formatItemList('Global Options:', globalOptionList, helper),\n      );\n    }\n\n    // Commands\n    const commandGroups = this.groupItems(\n      cmd.commands,\n      helper.visibleCommands(cmd),\n      (sub) => sub.helpGroup() || 'Commands:',\n    );\n    commandGroups.forEach((commands, group) => {\n      const commandList = commands.map((sub) => {\n        return callFormatItem(\n          helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n          helper.styleSubcommandDescription(helper.subcommandDescription(sub)),\n        );\n      });\n      output = output.concat(this.formatItemList(group, commandList, helper));\n    });\n\n    return output.join('\\n');\n  }\n\n  /**\n   * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.\n   *\n   * @param {string} str\n   * @returns {number}\n   */\n  displayWidth(str) {\n    return stripVTControlCharacters(str).length;\n  }\n\n  /**\n   * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.\n   *\n   * @param {string} str\n   * @returns {string}\n   */\n  styleTitle(str) {\n    return str;\n  }\n\n  styleUsage(str) {\n    // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:\n    //    command subcommand [options] [command] <foo> [bar]\n    return str\n      .split(' ')\n      .map((word) => {\n        if (word === '[options]') return this.styleOptionText(word);\n        if (word === '[command]') return this.styleSubcommandText(word);\n        if (word[0] === '[' || word[0] === '<')\n          return this.styleArgumentText(word);\n        return this.styleCommandText(word); // Restrict to initial words?\n      })\n      .join(' ');\n  }\n  styleCommandDescription(str) {\n    return this.styleDescriptionText(str);\n  }\n  styleOptionDescription(str) {\n    return this.styleDescriptionText(str);\n  }\n  styleSubcommandDescription(str) {\n    return this.styleDescriptionText(str);\n  }\n  styleArgumentDescription(str) {\n    return this.styleDescriptionText(str);\n  }\n  styleDescriptionText(str) {\n    return str;\n  }\n  styleOptionTerm(str) {\n    return this.styleOptionText(str);\n  }\n  styleSubcommandTerm(str) {\n    // This is very like usage with lots of parts! Assume default string which is formed like:\n    //    subcommand [options] <foo> [bar]\n    return str\n      .split(' ')\n      .map((word) => {\n        if (word === '[options]') return this.styleOptionText(word);\n        if (word[0] === '[' || word[0] === '<')\n          return this.styleArgumentText(word);\n        return this.styleSubcommandText(word); // Restrict to initial words?\n      })\n      .join(' ');\n  }\n  styleArgumentTerm(str) {\n    return this.styleArgumentText(str);\n  }\n  styleOptionText(str) {\n    return str;\n  }\n  styleArgumentText(str) {\n    return str;\n  }\n  styleSubcommandText(str) {\n    return str;\n  }\n  styleCommandText(str) {\n    return str;\n  }\n\n  /**\n   * Calculate the pad width from the maximum term length.\n   *\n   * @param {Command} cmd\n   * @param {Help} helper\n   * @returns {number}\n   */\n\n  padWidth(cmd, helper) {\n    return Math.max(\n      helper.longestOptionTermLength(cmd, helper),\n      helper.longestGlobalOptionTermLength(cmd, helper),\n      helper.longestSubcommandTermLength(cmd, helper),\n      helper.longestArgumentTermLength(cmd, helper),\n    );\n  }\n\n  /**\n   * Detect manually wrapped and indented strings by checking for line break followed by whitespace.\n   *\n   * @param {string} str\n   * @returns {boolean}\n   */\n  preformatted(str) {\n    return /\\n[^\\S\\r\\n]/.test(str);\n  }\n\n  /**\n   * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n   *\n   * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n   *   TTT  DDD DDDD\n   *        DD DDD\n   *\n   * @param {string} term\n   * @param {number} termWidth\n   * @param {string} description\n   * @param {Help} helper\n   * @returns {string}\n   */\n  formatItem(term, termWidth, description, helper) {\n    const itemIndent = 2;\n    const itemIndentStr = ' '.repeat(itemIndent);\n    if (!description) return itemIndentStr + term;\n\n    // Pad the term out to a consistent width, so descriptions are aligned.\n    const paddedTerm = term.padEnd(\n      termWidth + term.length - helper.displayWidth(term),\n    );\n\n    // Format the description.\n    const spacerWidth = 2; // between term and description\n    const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called\n    const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;\n    let formattedDescription;\n    if (\n      remainingWidth < this.minWidthToWrap ||\n      helper.preformatted(description)\n    ) {\n      formattedDescription = description;\n    } else {\n      const wrappedDescription = helper.boxWrap(description, remainingWidth);\n      formattedDescription = wrappedDescription.replace(\n        /\\n/g,\n        '\\n' + ' '.repeat(termWidth + spacerWidth),\n      );\n    }\n\n    // Construct and overall indent.\n    return (\n      itemIndentStr +\n      paddedTerm +\n      ' '.repeat(spacerWidth) +\n      formattedDescription.replace(/\\n/g, `\\n${itemIndentStr}`)\n    );\n  }\n\n  /**\n   * Wrap a string at whitespace, preserving existing line breaks.\n   * Wrapping is skipped if the width is less than `minWidthToWrap`.\n   *\n   * @param {string} str\n   * @param {number} width\n   * @returns {string}\n   */\n  boxWrap(str, width) {\n    if (width < this.minWidthToWrap) return str;\n\n    const rawLines = str.split(/\\r\\n|\\n/);\n    // split up text by whitespace\n    const chunkPattern = /[\\s]*[^\\s]+/g;\n    const wrappedLines = [];\n    rawLines.forEach((line) => {\n      const chunks = line.match(chunkPattern);\n      if (chunks === null) {\n        wrappedLines.push('');\n        return;\n      }\n\n      let sumChunks = [chunks.shift()];\n      let sumWidth = this.displayWidth(sumChunks[0]);\n      chunks.forEach((chunk) => {\n        const visibleWidth = this.displayWidth(chunk);\n        // Accumulate chunks while they fit into width.\n        if (sumWidth + visibleWidth <= width) {\n          sumChunks.push(chunk);\n          sumWidth += visibleWidth;\n          return;\n        }\n        wrappedLines.push(sumChunks.join(''));\n\n        const nextChunk = chunk.trimStart(); // trim space at line break\n        sumChunks = [nextChunk];\n        sumWidth = this.displayWidth(nextChunk);\n      });\n      wrappedLines.push(sumChunks.join(''));\n    });\n\n    return wrappedLines.join('\\n');\n  }\n}\n","import { InvalidArgumentError } from './error.js';\n\nexport class Option {\n  /**\n   * Initialize a new `Option` with the given `flags` and `description`.\n   *\n   * @param {string} flags\n   * @param {string} [description]\n   */\n\n  constructor(flags, description) {\n    this.flags = flags;\n    this.description = description || '';\n\n    this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n    this.optional = flags.includes('['); // A value is optional when the option is specified.\n    // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n    this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n    this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n    const optionFlags = splitOptionFlags(flags);\n    this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).\n    this.long = optionFlags.longFlag;\n    this.negate = false;\n    if (this.long) {\n      this.negate = this.long.startsWith('--no-');\n    }\n    this.defaultValue = undefined;\n    this.defaultValueDescription = undefined;\n    this.presetArg = undefined;\n    this.envVar = undefined;\n    this.parseArg = undefined;\n    this.hidden = false;\n    this.argChoices = undefined;\n    this.conflictsWith = [];\n    this.implied = undefined;\n    this.helpGroupHeading = undefined; // soft initialised when option added to command\n  }\n\n  /**\n   * Set the default value, and optionally supply the description to be displayed in the help.\n   *\n   * @param {*} value\n   * @param {string} [description]\n   * @return {Option}\n   */\n\n  default(value, description) {\n    this.defaultValue = value;\n    this.defaultValueDescription = description;\n    return this;\n  }\n\n  /**\n   * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n   * The custom processing (parseArg) is called.\n   *\n   * @example\n   * new Option('--color').default('GREYSCALE').preset('RGB');\n   * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n   *\n   * @param {*} arg\n   * @return {Option}\n   */\n\n  preset(arg) {\n    this.presetArg = arg;\n    return this;\n  }\n\n  /**\n   * Add option name(s) that conflict with this option.\n   * An error will be displayed if conflicting options are found during parsing.\n   *\n   * @example\n   * new Option('--rgb').conflicts('cmyk');\n   * new Option('--js').conflicts(['ts', 'jsx']);\n   *\n   * @param {(string | string[])} names\n   * @return {Option}\n   */\n\n  conflicts(names) {\n    this.conflictsWith = this.conflictsWith.concat(names);\n    return this;\n  }\n\n  /**\n   * Specify implied option values for when this option is set and the implied options are not.\n   *\n   * The custom processing (parseArg) is not called on the implied values.\n   *\n   * @example\n   * program\n   *   .addOption(new Option('--log', 'write logging information to file'))\n   *   .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n   *\n   * @param {object} impliedOptionValues\n   * @return {Option}\n   */\n  implies(impliedOptionValues) {\n    let newImplied = impliedOptionValues;\n    if (typeof impliedOptionValues === 'string') {\n      // string is not documented, but easy mistake and we can do what user probably intended.\n      newImplied = { [impliedOptionValues]: true };\n    }\n    this.implied = Object.assign(this.implied || {}, newImplied);\n    return this;\n  }\n\n  /**\n   * Set environment variable to check for option value.\n   *\n   * An environment variable is only used if when processed the current option value is\n   * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n   *\n   * @param {string} name\n   * @return {Option}\n   */\n\n  env(name) {\n    this.envVar = name;\n    return this;\n  }\n\n  /**\n   * Set the custom handler for processing CLI option arguments into option values.\n   *\n   * @param {Function} [fn]\n   * @return {Option}\n   */\n\n  argParser(fn) {\n    this.parseArg = fn;\n    return this;\n  }\n\n  /**\n   * Whether the option is mandatory and must have a value after parsing.\n   *\n   * @param {boolean} [mandatory=true]\n   * @return {Option}\n   */\n\n  makeOptionMandatory(mandatory = true) {\n    this.mandatory = !!mandatory;\n    return this;\n  }\n\n  /**\n   * Hide option in help.\n   *\n   * @param {boolean} [hide=true]\n   * @return {Option}\n   */\n\n  hideHelp(hide = true) {\n    this.hidden = !!hide;\n    return this;\n  }\n\n  /**\n   * @package\n   */\n\n  _collectValue(value, previous) {\n    if (previous === this.defaultValue || !Array.isArray(previous)) {\n      return [value];\n    }\n\n    previous.push(value);\n    return previous;\n  }\n\n  /**\n   * Only allow option value to be one of choices.\n   *\n   * @param {string[]} values\n   * @return {Option}\n   */\n\n  choices(values) {\n    this.argChoices = values.slice();\n    this.parseArg = (arg, previous) => {\n      if (!this.argChoices.includes(arg)) {\n        throw new InvalidArgumentError(\n          `Allowed choices are ${this.argChoices.join(', ')}.`,\n        );\n      }\n      if (this.variadic) {\n        return this._collectValue(arg, previous);\n      }\n      return arg;\n    };\n    return this;\n  }\n\n  /**\n   * Return option name.\n   *\n   * @return {string}\n   */\n\n  name() {\n    if (this.long) {\n      return this.long.replace(/^--/, '');\n    }\n    return this.short.replace(/^-/, '');\n  }\n\n  /**\n   * Return option name, in a camelcase format that can be used\n   * as an object attribute key.\n   *\n   * @return {string}\n   */\n\n  attributeName() {\n    if (this.negate) {\n      return camelcase(this.name().replace(/^no-/, ''));\n    }\n    return camelcase(this.name());\n  }\n\n  /**\n   * Set the help group heading.\n   *\n   * @param {string} heading\n   * @return {Option}\n   */\n  helpGroup(heading) {\n    this.helpGroupHeading = heading;\n    return this;\n  }\n\n  /**\n   * Check if `arg` matches the short or long flag.\n   *\n   * @param {string} arg\n   * @return {boolean}\n   * @package\n   */\n\n  is(arg) {\n    return this.short === arg || this.long === arg;\n  }\n\n  /**\n   * Return whether a boolean option.\n   *\n   * Options are one of boolean, negated, required argument, or optional argument.\n   *\n   * @return {boolean}\n   * @package\n   */\n\n  isBoolean() {\n    return !this.required && !this.optional && !this.negate;\n  }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nexport class DualOptions {\n  /**\n   * @param {Option[]} options\n   */\n  constructor(options) {\n    this.positiveOptions = new Map();\n    this.negativeOptions = new Map();\n    this.dualOptions = new Set();\n    options.forEach((option) => {\n      if (option.negate) {\n        this.negativeOptions.set(option.attributeName(), option);\n      } else {\n        this.positiveOptions.set(option.attributeName(), option);\n      }\n    });\n    this.negativeOptions.forEach((value, key) => {\n      if (this.positiveOptions.has(key)) {\n        this.dualOptions.add(key);\n      }\n    });\n  }\n\n  /**\n   * Did the value come from the option, and not from possible matching dual option?\n   *\n   * @param {*} value\n   * @param {Option} option\n   * @returns {boolean}\n   */\n  valueFromOption(value, option) {\n    const optionKey = option.attributeName();\n    if (!this.dualOptions.has(optionKey)) return true;\n\n    // Use the value to deduce if (probably) came from the option.\n    const preset = this.negativeOptions.get(optionKey).presetArg;\n    const negativeValue = preset !== undefined ? preset : false;\n    return option.negate === (negativeValue === value);\n  }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n  return str.split('-').reduce((str, word) => {\n    return str + word[0].toUpperCase() + word.slice(1);\n  });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n  let shortFlag;\n  let longFlag;\n  // short flag, single dash and single character\n  const shortFlagExp = /^-[^-]$/;\n  // long flag, double dash and at least one character\n  const longFlagExp = /^--[^-]/;\n\n  const flagParts = flags.split(/[ |,]+/).concat('guard');\n  // Normal is short and/or long.\n  if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();\n  if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();\n  // Long then short. Rarely used but fine.\n  if (!shortFlag && shortFlagExp.test(flagParts[0]))\n    shortFlag = flagParts.shift();\n  // Allow two long flags, like '--ws, --workspace'\n  // This is the supported way to have a shortish option flag.\n  if (!shortFlag && longFlagExp.test(flagParts[0])) {\n    shortFlag = longFlag;\n    longFlag = flagParts.shift();\n  }\n\n  // Check for unprocessed flag. Fail noisily rather than silently ignore.\n  if (flagParts[0].startsWith('-')) {\n    const unsupportedFlag = flagParts[0];\n    const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;\n    if (/^-[^-][^-]/.test(unsupportedFlag))\n      throw new Error(\n        `${baseError}\n- a short flag is a single dash and a single character\n  - either use a single dash and a single character (for a short flag)\n  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,\n      );\n    if (shortFlagExp.test(unsupportedFlag))\n      throw new Error(`${baseError}\n- too many short flags`);\n    if (longFlagExp.test(unsupportedFlag))\n      throw new Error(`${baseError}\n- too many long flags`);\n\n    throw new Error(`${baseError}\n- unrecognised flag format`);\n  }\n  if (shortFlag === undefined && longFlag === undefined)\n    throw new Error(\n      `option creation failed due to no flags found in '${flags}'.`,\n    );\n\n  return { shortFlag, longFlag };\n}\n","const maxDistance = 3;\n\nfunction editDistance(a, b) {\n  // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance\n  // Calculating optimal string alignment distance, no substring is edited more than once.\n  // (Simple implementation.)\n\n  // Quick early exit, return worst case.\n  if (Math.abs(a.length - b.length) > maxDistance)\n    return Math.max(a.length, b.length);\n\n  // distance between prefix substrings of a and b\n  const d = [];\n\n  // pure deletions turn a into empty string\n  for (let i = 0; i <= a.length; i++) {\n    d[i] = [i];\n  }\n  // pure insertions turn empty string into b\n  for (let j = 0; j <= b.length; j++) {\n    d[0][j] = j;\n  }\n\n  // fill matrix\n  for (let j = 1; j <= b.length; j++) {\n    for (let i = 1; i <= a.length; i++) {\n      let cost;\n      if (a[i - 1] === b[j - 1]) {\n        cost = 0;\n      } else {\n        cost = 1;\n      }\n      d[i][j] = Math.min(\n        d[i - 1][j] + 1, // deletion\n        d[i][j - 1] + 1, // insertion\n        d[i - 1][j - 1] + cost, // substitution\n      );\n      // transposition\n      if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n        d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n      }\n    }\n  }\n\n  return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nexport function suggestSimilar(word, candidates) {\n  if (!candidates || candidates.length === 0) return '';\n  // remove possible duplicates\n  candidates = Array.from(new Set(candidates));\n\n  const searchingOptions = word.startsWith('--');\n  if (searchingOptions) {\n    word = word.slice(2);\n    candidates = candidates.map((candidate) => candidate.slice(2));\n  }\n\n  let similar = [];\n  let bestDistance = maxDistance;\n  const minSimilarity = 0.4;\n  candidates.forEach((candidate) => {\n    if (candidate.length <= 1) return; // no one character guesses\n\n    const distance = editDistance(word, candidate);\n    const length = Math.max(word.length, candidate.length);\n    const similarity = (length - distance) / length;\n    if (similarity > minSimilarity) {\n      if (distance < bestDistance) {\n        // better edit distance, throw away previous worse matches\n        bestDistance = distance;\n        similar = [candidate];\n      } else if (distance === bestDistance) {\n        similar.push(candidate);\n      }\n    }\n  });\n\n  similar.sort((a, b) => a.localeCompare(b));\n  if (searchingOptions) {\n    similar = similar.map((candidate) => `--${candidate}`);\n  }\n\n  if (similar.length > 1) {\n    return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n  }\n  if (similar.length === 1) {\n    return `\\n(Did you mean ${similar[0]}?)`;\n  }\n  return '';\n}\n","import { EventEmitter } from 'node:events';\nimport childProcess from 'node:child_process';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport process from 'node:process';\nimport { stripVTControlCharacters } from 'node:util';\n\nimport { Argument, humanReadableArgName } from './argument.js';\nimport { CommanderError } from './error.js';\nimport { Help } from './help.js';\nimport { Option, DualOptions } from './option.js';\nimport { suggestSimilar } from './suggestSimilar.js';\n\nexport class Command extends EventEmitter {\n  /**\n   * Initialize a new `Command`.\n   *\n   * @param {string} [name]\n   */\n\n  constructor(name) {\n    super();\n    /** @type {Command[]} */\n    this.commands = [];\n    /** @type {Option[]} */\n    this.options = [];\n    this.parent = null;\n    this._allowUnknownOption = false;\n    this._allowExcessArguments = false;\n    /** @type {Argument[]} */\n    this.registeredArguments = [];\n    this._args = this.registeredArguments; // deprecated old name\n    /** @type {string[]} */\n    this.args = []; // cli args with options removed\n    this.rawArgs = [];\n    this.processedArgs = []; // like .args but after custom processing and collecting variadic\n    this._scriptPath = null;\n    this._name = name || '';\n    this._optionValues = {};\n    this._optionValueSources = {}; // default, env, cli etc\n    this._storeOptionsAsProperties = false;\n    this._actionHandler = null;\n    this._executableHandler = false;\n    this._executableFile = null; // custom name for executable\n    this._executableDir = null; // custom search directory for subcommands\n    this._defaultCommandName = null;\n    this._exitCallback = null;\n    this._aliases = [];\n    this._combineFlagAndOptionalValue = true;\n    this._description = '';\n    this._summary = '';\n    this._argsDescription = undefined; // legacy\n    this._enablePositionalOptions = false;\n    this._passThroughOptions = false;\n    this._lifeCycleHooks = {}; // a hash of arrays\n    /** @type {(boolean | string)} */\n    this._showHelpAfterError = false;\n    this._showSuggestionAfterError = true;\n    this._savedState = null; // used in save/restoreStateBeforeParse\n\n    // see configureOutput() for docs\n    this._outputConfiguration = {\n      writeOut: (str) => process.stdout.write(str),\n      writeErr: (str) => process.stderr.write(str),\n      outputError: (str, write) => write(str),\n      getOutHelpWidth: () =>\n        process.stdout.isTTY ? process.stdout.columns : undefined,\n      getErrHelpWidth: () =>\n        process.stderr.isTTY ? process.stderr.columns : undefined,\n      getOutHasColors: () =>\n        useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),\n      getErrHasColors: () =>\n        useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),\n      stripColor: (str) => stripVTControlCharacters(str),\n    };\n\n    this._hidden = false;\n    /** @type {(Option | null | undefined)} */\n    this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n    this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n    /** @type {Command} */\n    this._helpCommand = undefined; // lazy initialised, inherited\n    this._helpConfiguration = {};\n    /** @type {string | undefined} */\n    this._helpGroupHeading = undefined; // soft initialised when added to parent\n    /** @type {string | undefined} */\n    this._defaultCommandGroup = undefined;\n    /** @type {string | undefined} */\n    this._defaultOptionGroup = undefined;\n  }\n\n  /**\n   * Copy settings that are useful to have in common across root command and subcommands.\n   *\n   * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n   *\n   * @param {Command} sourceCommand\n   * @return {Command} `this` command for chaining\n   */\n  copyInheritedSettings(sourceCommand) {\n    this._outputConfiguration = sourceCommand._outputConfiguration;\n    this._helpOption = sourceCommand._helpOption;\n    this._helpCommand = sourceCommand._helpCommand;\n    this._helpConfiguration = sourceCommand._helpConfiguration;\n    this._exitCallback = sourceCommand._exitCallback;\n    this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n    this._combineFlagAndOptionalValue =\n      sourceCommand._combineFlagAndOptionalValue;\n    this._allowExcessArguments = sourceCommand._allowExcessArguments;\n    this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n    this._showHelpAfterError = sourceCommand._showHelpAfterError;\n    this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n    return this;\n  }\n\n  /**\n   * @returns {Command[]}\n   * @private\n   */\n\n  _getCommandAndAncestors() {\n    const result = [];\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    for (let command = this; command; command = command.parent) {\n      result.push(command);\n    }\n    return result;\n  }\n\n  /**\n   * Define a command.\n   *\n   * There are two styles of command: pay attention to where to put the description.\n   *\n   * @example\n   * // Command implemented using action handler (description is supplied separately to `.command`)\n   * program\n   *   .command('clone <source> [destination]')\n   *   .description('clone a repository into a newly created directory')\n   *   .action((source, destination) => {\n   *     console.log('clone command called');\n   *   });\n   *\n   * // Command implemented using separate executable file (description is second parameter to `.command`)\n   * program\n   *   .command('start <service>', 'start named service')\n   *   .command('stop [service]', 'stop named service, or all if no name supplied');\n   *\n   * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n   * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n   * @param {object} [execOpts] - configuration options (for executable)\n   * @return {Command} returns new command for action handler, or `this` for executable command\n   */\n\n  command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n    let desc = actionOptsOrExecDesc;\n    let opts = execOpts;\n    if (typeof desc === 'object' && desc !== null) {\n      opts = desc;\n      desc = null;\n    }\n    opts = opts || {};\n    const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n    const cmd = this.createCommand(name);\n    if (desc) {\n      cmd.description(desc);\n      cmd._executableHandler = true;\n    }\n    if (opts.isDefault) this._defaultCommandName = cmd._name;\n    cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n    cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n    if (args) cmd.arguments(args);\n    this._registerCommand(cmd);\n    cmd.parent = this;\n    cmd.copyInheritedSettings(this);\n\n    if (desc) return this;\n    return cmd;\n  }\n\n  /**\n   * Factory routine to create a new unattached command.\n   *\n   * See .command() for creating an attached subcommand, which uses this routine to\n   * create the command. You can override createCommand to customise subcommands.\n   *\n   * @param {string} [name]\n   * @return {Command} new command\n   */\n\n  createCommand(name) {\n    return new Command(name);\n  }\n\n  /**\n   * You can customise the help with a subclass of Help by overriding createHelp,\n   * or by overriding Help properties using configureHelp().\n   *\n   * @return {Help}\n   */\n\n  createHelp() {\n    return Object.assign(new Help(), this.configureHelp());\n  }\n\n  /**\n   * You can customise the help by overriding Help properties using configureHelp(),\n   * or with a subclass of Help by overriding createHelp().\n   *\n   * @param {object} [configuration] - configuration options\n   * @return {(Command | object)} `this` command for chaining, or stored configuration\n   */\n\n  configureHelp(configuration) {\n    if (configuration === undefined) return this._helpConfiguration;\n\n    this._helpConfiguration = configuration;\n    return this;\n  }\n\n  /**\n   * The default output goes to stdout and stderr. You can customise this for special\n   * applications. You can also customise the display of errors by overriding outputError.\n   *\n   * The configuration properties are all functions:\n   *\n   *     // change how output being written, defaults to stdout and stderr\n   *     writeOut(str)\n   *     writeErr(str)\n   *     // change how output being written for errors, defaults to writeErr\n   *     outputError(str, write) // used for displaying errors and not used for displaying help\n   *     // specify width for wrapping help\n   *     getOutHelpWidth()\n   *     getErrHelpWidth()\n   *     // color support, currently only used with Help\n   *     getOutHasColors()\n   *     getErrHasColors()\n   *     stripColor() // used to remove ANSI escape codes if output does not have colors\n   *\n   * @param {object} [configuration] - configuration options\n   * @return {(Command | object)} `this` command for chaining, or stored configuration\n   */\n\n  configureOutput(configuration) {\n    if (configuration === undefined) return this._outputConfiguration;\n\n    this._outputConfiguration = {\n      ...this._outputConfiguration,\n      ...configuration,\n    };\n    return this;\n  }\n\n  /**\n   * Display the help or a custom message after an error occurs.\n   *\n   * @param {(boolean|string)} [displayHelp]\n   * @return {Command} `this` command for chaining\n   */\n  showHelpAfterError(displayHelp = true) {\n    if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n    this._showHelpAfterError = displayHelp;\n    return this;\n  }\n\n  /**\n   * Display suggestion of similar commands for unknown commands, or options for unknown options.\n   *\n   * @param {boolean} [displaySuggestion]\n   * @return {Command} `this` command for chaining\n   */\n  showSuggestionAfterError(displaySuggestion = true) {\n    this._showSuggestionAfterError = !!displaySuggestion;\n    return this;\n  }\n\n  /**\n   * Add a prepared subcommand.\n   *\n   * See .command() for creating an attached subcommand which inherits settings from its parent.\n   *\n   * @param {Command} cmd - new subcommand\n   * @param {object} [opts] - configuration options\n   * @return {Command} `this` command for chaining\n   */\n\n  addCommand(cmd, opts) {\n    if (!cmd._name) {\n      throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n    }\n\n    opts = opts || {};\n    if (opts.isDefault) this._defaultCommandName = cmd._name;\n    if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n    this._registerCommand(cmd);\n    cmd.parent = this;\n    cmd._checkForBrokenPassThrough();\n\n    return this;\n  }\n\n  /**\n   * Factory routine to create a new unattached argument.\n   *\n   * See .argument() for creating an attached argument, which uses this routine to\n   * create the argument. You can override createArgument to return a custom argument.\n   *\n   * @param {string} name\n   * @param {string} [description]\n   * @return {Argument} new argument\n   */\n\n  createArgument(name, description) {\n    return new Argument(name, description);\n  }\n\n  /**\n   * Define argument syntax for command.\n   *\n   * The default is that the argument is required, and you can explicitly\n   * indicate this with <> around the name. Put [] around the name for an optional argument.\n   *\n   * @example\n   * program.argument('<input-file>');\n   * program.argument('[output-file]');\n   *\n   * @param {string} name\n   * @param {string} [description]\n   * @param {(Function|*)} [parseArg] - custom argument processing function or default value\n   * @param {*} [defaultValue]\n   * @return {Command} `this` command for chaining\n   */\n  argument(name, description, parseArg, defaultValue) {\n    const argument = this.createArgument(name, description);\n    if (typeof parseArg === 'function') {\n      argument.default(defaultValue).argParser(parseArg);\n    } else {\n      argument.default(parseArg);\n    }\n    this.addArgument(argument);\n    return this;\n  }\n\n  /**\n   * Define argument syntax for command, adding multiple at once (without descriptions).\n   *\n   * See also .argument().\n   *\n   * @example\n   * program.arguments('<cmd> [env]');\n   *\n   * @param {string} names\n   * @return {Command} `this` command for chaining\n   */\n\n  arguments(names) {\n    names\n      .trim()\n      .split(/ +/)\n      .forEach((detail) => {\n        this.argument(detail);\n      });\n    return this;\n  }\n\n  /**\n   * Define argument syntax for command, adding a prepared argument.\n   *\n   * @param {Argument} argument\n   * @return {Command} `this` command for chaining\n   */\n  addArgument(argument) {\n    const previousArgument = this.registeredArguments.slice(-1)[0];\n    if (previousArgument?.variadic) {\n      throw new Error(\n        `only the last argument can be variadic '${previousArgument.name()}'`,\n      );\n    }\n    if (\n      argument.required &&\n      argument.defaultValue !== undefined &&\n      argument.parseArg === undefined\n    ) {\n      throw new Error(\n        `a default value for a required argument is never used: '${argument.name()}'`,\n      );\n    }\n    this.registeredArguments.push(argument);\n    return this;\n  }\n\n  /**\n   * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n   *\n   * @example\n   *    program.helpCommand('help [cmd]');\n   *    program.helpCommand('help [cmd]', 'show help');\n   *    program.helpCommand(false); // suppress default help command\n   *    program.helpCommand(true); // add help command even if no subcommands\n   *\n   * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n   * @param {string} [description] - custom description\n   * @return {Command} `this` command for chaining\n   */\n\n  helpCommand(enableOrNameAndArgs, description) {\n    if (typeof enableOrNameAndArgs === 'boolean') {\n      this._addImplicitHelpCommand = enableOrNameAndArgs;\n      if (enableOrNameAndArgs && this._defaultCommandGroup) {\n        // make the command to store the group\n        this._initCommandGroup(this._getHelpCommand());\n      }\n      return this;\n    }\n\n    const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n    const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);\n    const helpDescription = description ?? 'display help for command';\n\n    const helpCommand = this.createCommand(helpName);\n    helpCommand.helpOption(false);\n    if (helpArgs) helpCommand.arguments(helpArgs);\n    if (helpDescription) helpCommand.description(helpDescription);\n\n    this._addImplicitHelpCommand = true;\n    this._helpCommand = helpCommand;\n    // init group unless lazy create\n    if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);\n\n    return this;\n  }\n\n  /**\n   * Add prepared custom help command.\n   *\n   * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n   * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n   * @return {Command} `this` command for chaining\n   */\n  addHelpCommand(helpCommand, deprecatedDescription) {\n    // If not passed an object, call through to helpCommand for backwards compatibility,\n    // as addHelpCommand was originally used like helpCommand is now.\n    if (typeof helpCommand !== 'object') {\n      this.helpCommand(helpCommand, deprecatedDescription);\n      return this;\n    }\n\n    this._addImplicitHelpCommand = true;\n    this._helpCommand = helpCommand;\n    this._initCommandGroup(helpCommand);\n    return this;\n  }\n\n  /**\n   * Lazy create help command.\n   *\n   * @return {(Command|null)}\n   * @package\n   */\n  _getHelpCommand() {\n    const hasImplicitHelpCommand =\n      this._addImplicitHelpCommand ??\n      (this.commands.length &&\n        !this._actionHandler &&\n        !this._findCommand('help'));\n\n    if (hasImplicitHelpCommand) {\n      if (this._helpCommand === undefined) {\n        this.helpCommand(undefined, undefined); // use default name and description\n      }\n      return this._helpCommand;\n    }\n    return null;\n  }\n\n  /**\n   * Add hook for life cycle event.\n   *\n   * @param {string} event\n   * @param {Function} listener\n   * @return {Command} `this` command for chaining\n   */\n\n  hook(event, listener) {\n    const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n    if (!allowedValues.includes(event)) {\n      throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n    }\n    if (this._lifeCycleHooks[event]) {\n      this._lifeCycleHooks[event].push(listener);\n    } else {\n      this._lifeCycleHooks[event] = [listener];\n    }\n    return this;\n  }\n\n  /**\n   * Register callback to use as replacement for calling process.exit.\n   *\n   * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n   * @return {Command} `this` command for chaining\n   */\n\n  exitOverride(fn) {\n    if (fn) {\n      this._exitCallback = fn;\n    } else {\n      this._exitCallback = (err) => {\n        if (err.code !== 'commander.executeSubCommandAsync') {\n          throw err;\n        } else {\n          // Async callback from spawn events, not useful to throw.\n        }\n      };\n    }\n    return this;\n  }\n\n  /**\n   * Call process.exit, and _exitCallback if defined.\n   *\n   * @param {number} exitCode exit code for using with process.exit\n   * @param {string} code an id string representing the error\n   * @param {string} message human-readable description of the error\n   * @return never\n   * @private\n   */\n\n  _exit(exitCode, code, message) {\n    if (this._exitCallback) {\n      this._exitCallback(new CommanderError(exitCode, code, message));\n      // Expecting this line is not reached.\n    }\n    process.exit(exitCode);\n  }\n\n  /**\n   * Register callback `fn` for the command.\n   *\n   * @example\n   * program\n   *   .command('serve')\n   *   .description('start service')\n   *   .action(function() {\n   *      // do work here\n   *   });\n   *\n   * @param {Function} fn\n   * @return {Command} `this` command for chaining\n   */\n\n  action(fn) {\n    const listener = (args) => {\n      // The .action callback takes an extra parameter which is the command or options.\n      const expectedArgsCount = this.registeredArguments.length;\n      const actionArgs = args.slice(0, expectedArgsCount);\n      if (this._storeOptionsAsProperties) {\n        actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n      } else {\n        actionArgs[expectedArgsCount] = this.opts();\n      }\n      actionArgs.push(this);\n\n      return fn.apply(this, actionArgs);\n    };\n    this._actionHandler = listener;\n    return this;\n  }\n\n  /**\n   * Factory routine to create a new unattached option.\n   *\n   * See .option() for creating an attached option, which uses this routine to\n   * create the option. You can override createOption to return a custom option.\n   *\n   * @param {string} flags\n   * @param {string} [description]\n   * @return {Option} new option\n   */\n\n  createOption(flags, description) {\n    return new Option(flags, description);\n  }\n\n  /**\n   * Wrap parseArgs to catch 'commander.invalidArgument'.\n   *\n   * @param {(Option | Argument)} target\n   * @param {string} value\n   * @param {*} previous\n   * @param {string} invalidArgumentMessage\n   * @private\n   */\n\n  _callParseArg(target, value, previous, invalidArgumentMessage) {\n    try {\n      return target.parseArg(value, previous);\n    } catch (err) {\n      if (err.code === 'commander.invalidArgument') {\n        const message = `${invalidArgumentMessage} ${err.message}`;\n        this.error(message, { exitCode: err.exitCode, code: err.code });\n      }\n      throw err;\n    }\n  }\n\n  /**\n   * Check for option flag conflicts.\n   * Register option if no conflicts found, or throw on conflict.\n   *\n   * @param {Option} option\n   * @private\n   */\n\n  _registerOption(option) {\n    const matchingOption =\n      (option.short && this._findOption(option.short)) ||\n      (option.long && this._findOption(option.long));\n    if (matchingOption) {\n      const matchingFlag =\n        option.long && this._findOption(option.long)\n          ? option.long\n          : option.short;\n      throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n-  already used by option '${matchingOption.flags}'`);\n    }\n\n    this._initOptionGroup(option);\n    this.options.push(option);\n  }\n\n  /**\n   * Check for command name and alias conflicts with existing commands.\n   * Register command if no conflicts found, or throw on conflict.\n   *\n   * @param {Command} command\n   * @private\n   */\n\n  _registerCommand(command) {\n    const knownBy = (cmd) => {\n      return [cmd.name()].concat(cmd.aliases());\n    };\n\n    const alreadyUsed = knownBy(command).find((name) =>\n      this._findCommand(name),\n    );\n    if (alreadyUsed) {\n      const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n      const newCmd = knownBy(command).join('|');\n      throw new Error(\n        `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n      );\n    }\n\n    this._initCommandGroup(command);\n    this.commands.push(command);\n  }\n\n  /**\n   * Add an option.\n   *\n   * @param {Option} option\n   * @return {Command} `this` command for chaining\n   */\n  addOption(option) {\n    this._registerOption(option);\n\n    const oname = option.name();\n    const name = option.attributeName();\n\n    // store default value\n    if (option.defaultValue !== undefined) {\n      this.setOptionValueWithSource(name, option.defaultValue, 'default');\n    }\n\n    // handler for cli and env supplied values\n    const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n      // val is null for optional option used without an optional-argument.\n      // val is undefined for boolean and negated option.\n      if (val == null && option.presetArg !== undefined) {\n        val = option.presetArg;\n      }\n\n      // custom processing\n      const oldValue = this.getOptionValue(name);\n      if (val !== null && option.parseArg) {\n        val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n      } else if (val !== null && option.variadic) {\n        val = option._collectValue(val, oldValue);\n      }\n\n      // Fill-in appropriate missing values. Long winded but easy to follow.\n      if (val == null) {\n        if (option.negate) {\n          val = false;\n        } else if (option.isBoolean() || option.optional) {\n          val = true;\n        } else {\n          val = ''; // not normal, parseArg might have failed or be a mock function for testing\n        }\n      }\n      this.setOptionValueWithSource(name, val, valueSource);\n    };\n\n    this.on('option:' + oname, (val) => {\n      const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n      handleOptionValue(val, invalidValueMessage, 'cli');\n    });\n\n    if (option.envVar) {\n      this.on('optionEnv:' + oname, (val) => {\n        const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n        handleOptionValue(val, invalidValueMessage, 'env');\n      });\n    }\n\n    return this;\n  }\n\n  /**\n   * Internal implementation shared by .option() and .requiredOption()\n   *\n   * @return {Command} `this` command for chaining\n   * @private\n   */\n  _optionEx(config, flags, description, fn, defaultValue) {\n    if (typeof flags === 'object' && flags instanceof Option) {\n      throw new Error(\n        'To add an Option object use addOption() instead of option() or requiredOption()',\n      );\n    }\n    const option = this.createOption(flags, description);\n    option.makeOptionMandatory(!!config.mandatory);\n    if (typeof fn === 'function') {\n      option.default(defaultValue).argParser(fn);\n    } else if (fn instanceof RegExp) {\n      // deprecated\n      const regex = fn;\n      fn = (val, def) => {\n        const m = regex.exec(val);\n        return m ? m[0] : def;\n      };\n      option.default(defaultValue).argParser(fn);\n    } else {\n      option.default(fn);\n    }\n\n    return this.addOption(option);\n  }\n\n  /**\n   * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n   *\n   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n   * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n   *\n   * See the README for more details, and see also addOption() and requiredOption().\n   *\n   * @example\n   * program\n   *     .option('-p, --pepper', 'add pepper')\n   *     .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n   *     .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n   *     .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n   *\n   * @param {string} flags\n   * @param {string} [description]\n   * @param {(Function|*)} [parseArg] - custom option processing function or default value\n   * @param {*} [defaultValue]\n   * @return {Command} `this` command for chaining\n   */\n\n  option(flags, description, parseArg, defaultValue) {\n    return this._optionEx({}, flags, description, parseArg, defaultValue);\n  }\n\n  /**\n   * Add a required option which must have a value after parsing. This usually means\n   * the option must be specified on the command line. (Otherwise the same as .option().)\n   *\n   * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n   *\n   * @param {string} flags\n   * @param {string} [description]\n   * @param {(Function|*)} [parseArg] - custom option processing function or default value\n   * @param {*} [defaultValue]\n   * @return {Command} `this` command for chaining\n   */\n\n  requiredOption(flags, description, parseArg, defaultValue) {\n    return this._optionEx(\n      { mandatory: true },\n      flags,\n      description,\n      parseArg,\n      defaultValue,\n    );\n  }\n\n  /**\n   * Alter parsing of short flags with optional values.\n   *\n   * @example\n   * // for `.option('-f,--flag [value]'):\n   * program.combineFlagAndOptionalValue(true);  // `-f80` is treated like `--flag=80`, this is the default behaviour\n   * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n   *\n   * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n   * @return {Command} `this` command for chaining\n   */\n  combineFlagAndOptionalValue(combine = true) {\n    this._combineFlagAndOptionalValue = !!combine;\n    return this;\n  }\n\n  /**\n   * Allow unknown options on the command line.\n   *\n   * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n   * @return {Command} `this` command for chaining\n   */\n  allowUnknownOption(allowUnknown = true) {\n    this._allowUnknownOption = !!allowUnknown;\n    return this;\n  }\n\n  /**\n   * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n   *\n   * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n   * @return {Command} `this` command for chaining\n   */\n  allowExcessArguments(allowExcess = true) {\n    this._allowExcessArguments = !!allowExcess;\n    return this;\n  }\n\n  /**\n   * Enable positional options. Positional means global options are specified before subcommands which lets\n   * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n   * The default behaviour is non-positional and global options may appear anywhere on the command line.\n   *\n   * @param {boolean} [positional]\n   * @return {Command} `this` command for chaining\n   */\n  enablePositionalOptions(positional = true) {\n    this._enablePositionalOptions = !!positional;\n    return this;\n  }\n\n  /**\n   * Pass through options that come after command-arguments rather than treat them as command-options,\n   * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n   * positional options to have been enabled on the program (parent commands).\n   * The default behaviour is non-positional and options may appear before or after command-arguments.\n   *\n   * @param {boolean} [passThrough] for unknown options.\n   * @return {Command} `this` command for chaining\n   */\n  passThroughOptions(passThrough = true) {\n    this._passThroughOptions = !!passThrough;\n    this._checkForBrokenPassThrough();\n    return this;\n  }\n\n  /**\n   * @private\n   */\n\n  _checkForBrokenPassThrough() {\n    if (\n      this.parent &&\n      this._passThroughOptions &&\n      !this.parent._enablePositionalOptions\n    ) {\n      throw new Error(\n        `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n      );\n    }\n  }\n\n  /**\n   * Whether to store option values as properties on command object,\n   * or store separately (specify false). In both cases the option values can be accessed using .opts().\n   *\n   * @param {boolean} [storeAsProperties=true]\n   * @return {Command} `this` command for chaining\n   */\n\n  storeOptionsAsProperties(storeAsProperties = true) {\n    if (this.options.length) {\n      throw new Error('call .storeOptionsAsProperties() before adding options');\n    }\n    if (Object.keys(this._optionValues).length) {\n      throw new Error(\n        'call .storeOptionsAsProperties() before setting option values',\n      );\n    }\n    this._storeOptionsAsProperties = !!storeAsProperties;\n    return this;\n  }\n\n  /**\n   * Retrieve option value.\n   *\n   * @param {string} key\n   * @return {object} value\n   */\n\n  getOptionValue(key) {\n    if (this._storeOptionsAsProperties) {\n      return this[key];\n    }\n    return this._optionValues[key];\n  }\n\n  /**\n   * Store option value.\n   *\n   * @param {string} key\n   * @param {object} value\n   * @return {Command} `this` command for chaining\n   */\n\n  setOptionValue(key, value) {\n    return this.setOptionValueWithSource(key, value, undefined);\n  }\n\n  /**\n   * Store option value and where the value came from.\n   *\n   * @param {string} key\n   * @param {object} value\n   * @param {string} source - expected values are default/config/env/cli/implied\n   * @return {Command} `this` command for chaining\n   */\n\n  setOptionValueWithSource(key, value, source) {\n    if (this._storeOptionsAsProperties) {\n      this[key] = value;\n    } else {\n      this._optionValues[key] = value;\n    }\n    this._optionValueSources[key] = source;\n    return this;\n  }\n\n  /**\n   * Get source of option value.\n   * Expected values are default | config | env | cli | implied\n   *\n   * @param {string} key\n   * @return {string}\n   */\n\n  getOptionValueSource(key) {\n    return this._optionValueSources[key];\n  }\n\n  /**\n   * Get source of option value. See also .optsWithGlobals().\n   * Expected values are default | config | env | cli | implied\n   *\n   * @param {string} key\n   * @return {string}\n   */\n\n  getOptionValueSourceWithGlobals(key) {\n    // global overwrites local, like optsWithGlobals\n    let source;\n    this._getCommandAndAncestors().forEach((cmd) => {\n      if (cmd.getOptionValueSource(key) !== undefined) {\n        source = cmd.getOptionValueSource(key);\n      }\n    });\n    return source;\n  }\n\n  /**\n   * Get user arguments from implied or explicit arguments.\n   * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n   *\n   * @private\n   */\n\n  _prepareUserArgs(argv, parseOptions) {\n    if (argv !== undefined && !Array.isArray(argv)) {\n      throw new Error('first parameter to parse must be array or undefined');\n    }\n    parseOptions = parseOptions || {};\n\n    // auto-detect argument conventions if nothing supplied\n    if (argv === undefined && parseOptions.from === undefined) {\n      if (process.versions?.electron) {\n        parseOptions.from = 'electron';\n      }\n      // check node specific options for scenarios where user CLI args follow executable without scriptname\n      const execArgv = process.execArgv ?? [];\n      if (\n        execArgv.includes('-e') ||\n        execArgv.includes('--eval') ||\n        execArgv.includes('-p') ||\n        execArgv.includes('--print')\n      ) {\n        parseOptions.from = 'eval'; // internal usage, not documented\n      }\n    }\n\n    // default to using process.argv\n    if (argv === undefined) {\n      argv = process.argv;\n    }\n    this.rawArgs = argv.slice();\n\n    // extract the user args and scriptPath\n    let userArgs;\n    switch (parseOptions.from) {\n      case undefined:\n      case 'node':\n        this._scriptPath = argv[1];\n        userArgs = argv.slice(2);\n        break;\n      case 'electron':\n        // @ts-ignore: because defaultApp is an unknown property\n        if (process.defaultApp) {\n          this._scriptPath = argv[1];\n          userArgs = argv.slice(2);\n        } else {\n          userArgs = argv.slice(1);\n        }\n        break;\n      case 'user':\n        userArgs = argv.slice(0);\n        break;\n      case 'eval':\n        userArgs = argv.slice(1);\n        break;\n      default:\n        throw new Error(\n          `unexpected parse option { from: '${parseOptions.from}' }`,\n        );\n    }\n\n    // Find default name for program from arguments.\n    if (!this._name && this._scriptPath)\n      this.nameFromFilename(this._scriptPath);\n    this._name = this._name || 'program';\n\n    return userArgs;\n  }\n\n  /**\n   * Parse `argv`, setting options and invoking commands when defined.\n   *\n   * Use parseAsync instead of parse if any of your action handlers are async.\n   *\n   * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n   *\n   * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n   * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n   * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n   * - `'user'`: just user arguments\n   *\n   * @example\n   * program.parse(); // parse process.argv and auto-detect electron and special node flags\n   * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n   * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n   *\n   * @param {string[]} [argv] - optional, defaults to process.argv\n   * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n   * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n   * @return {Command} `this` command for chaining\n   */\n\n  parse(argv, parseOptions) {\n    this._prepareForParse();\n    const userArgs = this._prepareUserArgs(argv, parseOptions);\n    this._parseCommand([], userArgs);\n\n    return this;\n  }\n\n  /**\n   * Parse `argv`, setting options and invoking commands when defined.\n   *\n   * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n   *\n   * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n   * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n   * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n   * - `'user'`: just user arguments\n   *\n   * @example\n   * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n   * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n   * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n   *\n   * @param {string[]} [argv]\n   * @param {object} [parseOptions]\n   * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n   * @return {Promise}\n   */\n\n  async parseAsync(argv, parseOptions) {\n    this._prepareForParse();\n    const userArgs = this._prepareUserArgs(argv, parseOptions);\n    await this._parseCommand([], userArgs);\n\n    return this;\n  }\n\n  _prepareForParse() {\n    // Save the state the first time, then restore the state before each subsequent parse.\n    if (this._savedState === null) {\n      // Do the special default of lone negated option to true, now that we have all the options.\n      // Filter for negated options that have not been processed already.\n      this.options\n        .filter(\n          (option) =>\n            option.negate &&\n            option.defaultValue === undefined &&\n            this.getOptionValue(option.attributeName()) === undefined,\n        )\n        .forEach((option) => {\n          // check for lone negated option: --no-foo without a --foo option\n          const positiveLongFlag = option.long.replace(/^--no-/, '--');\n          if (!this._findOption(positiveLongFlag)) {\n            this.setOptionValueWithSource(\n              option.attributeName(),\n              true,\n              'default',\n            );\n          }\n        });\n\n      this.saveStateBeforeParse();\n    } else {\n      this.restoreStateBeforeParse();\n    }\n  }\n\n  /**\n   * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n   * Not usually called directly, but available for subclasses to save their custom state.\n   *\n   * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n   */\n  saveStateBeforeParse() {\n    this._savedState = {\n      // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing\n      _name: this._name,\n      // option values before parse have default values (including false for negated options)\n      // shallow clones\n      _optionValues: { ...this._optionValues },\n      _optionValueSources: { ...this._optionValueSources },\n    };\n  }\n\n  /**\n   * Restore state before parse for calls after the first.\n   * Not usually called directly, but available for subclasses to save their custom state.\n   *\n   * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n   */\n  restoreStateBeforeParse() {\n    if (this._storeOptionsAsProperties)\n      throw new Error(`Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties`);\n\n    // clear state from _prepareUserArgs\n    this._name = this._savedState._name;\n    this._scriptPath = null;\n    this.rawArgs = [];\n    // clear state from setOptionValueWithSource\n    this._optionValues = { ...this._savedState._optionValues };\n    this._optionValueSources = { ...this._savedState._optionValueSources };\n    // clear state from _parseCommand\n    this.args = [];\n    // clear state from _processArguments\n    this.processedArgs = [];\n  }\n\n  /**\n   * Throw if expected executable is missing. Add lots of help for author.\n   *\n   * @param {string} executableFile\n   * @param {string} executableDir\n   * @param {string} subcommandName\n   */\n  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {\n    if (fs.existsSync(executableFile)) return;\n\n    const executableDirMessage = executableDir\n      ? `searched for local subcommand relative to directory '${executableDir}'`\n      : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n    const executableMissing = `'${executableFile}' does not exist\n - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n    throw new Error(executableMissing);\n  }\n\n  /**\n   * Execute a sub-command executable.\n   *\n   * @private\n   */\n\n  _executeSubCommand(subcommand, args) {\n    args = args.slice();\n    const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n    function findFile(baseDir, baseName) {\n      // Look for specified file\n      const localBin = path.resolve(baseDir, baseName);\n      if (fs.existsSync(localBin)) return localBin;\n\n      // Stop looking if candidate already has an expected extension.\n      if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n      // Try all the extensions.\n      const foundExt = sourceExt.find((ext) =>\n        fs.existsSync(`${localBin}${ext}`),\n      );\n      if (foundExt) return `${localBin}${foundExt}`;\n\n      return undefined;\n    }\n\n    // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n    this._checkForMissingMandatoryOptions();\n    this._checkForConflictingOptions();\n\n    // executableFile and executableDir might be full path, or just a name\n    let executableFile =\n      subcommand._executableFile || `${this._name}-${subcommand._name}`;\n    let executableDir = this._executableDir || '';\n    if (this._scriptPath) {\n      let resolvedScriptPath; // resolve possible symlink for installed npm binary\n      try {\n        resolvedScriptPath = fs.realpathSync(this._scriptPath);\n      } catch {\n        resolvedScriptPath = this._scriptPath;\n      }\n      executableDir = path.resolve(\n        path.dirname(resolvedScriptPath),\n        executableDir,\n      );\n    }\n\n    // Look for a local file in preference to a command in PATH.\n    if (executableDir) {\n      let localFile = findFile(executableDir, executableFile);\n\n      // Legacy search using prefix of script name instead of command name\n      if (!localFile && !subcommand._executableFile && this._scriptPath) {\n        const legacyName = path.basename(\n          this._scriptPath,\n          path.extname(this._scriptPath),\n        );\n        if (legacyName !== this._name) {\n          localFile = findFile(\n            executableDir,\n            `${legacyName}-${subcommand._name}`,\n          );\n        }\n      }\n      executableFile = localFile || executableFile;\n    }\n\n    const launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n    let proc;\n    if (process.platform !== 'win32') {\n      if (launchWithNode) {\n        args.unshift(executableFile);\n        // add executable arguments to spawn\n        args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n        proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n      } else {\n        proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n      }\n    } else {\n      this._checkForMissingExecutable(\n        executableFile,\n        executableDir,\n        subcommand._name,\n      );\n      args.unshift(executableFile);\n      // add executable arguments to spawn\n      args = incrementNodeInspectorPort(process.execArgv).concat(args);\n      proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n    }\n\n    if (!proc.killed) {\n      // testing mainly to avoid leak warnings during unit tests with mocked spawn\n      const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n      signals.forEach((signal) => {\n        process.on(signal, () => {\n          if (proc.killed === false && proc.exitCode === null) {\n            // @ts-ignore because signals not typed to known strings\n            proc.kill(signal);\n          }\n        });\n      });\n    }\n\n    // By default terminate process when spawned process terminates.\n    const exitCallback = this._exitCallback;\n    proc.on('close', (code) => {\n      code = code ?? 1; // code is null if spawned process terminated due to a signal\n      if (!exitCallback) {\n        process.exit(code);\n      } else {\n        exitCallback(\n          new CommanderError(\n            code,\n            'commander.executeSubCommandAsync',\n            '(close)',\n          ),\n        );\n      }\n    });\n    proc.on('error', (err) => {\n      // @ts-ignore: because err.code is an unknown property\n      if (err.code === 'ENOENT') {\n        this._checkForMissingExecutable(\n          executableFile,\n          executableDir,\n          subcommand._name,\n        );\n        // @ts-ignore: because err.code is an unknown property\n      } else if (err.code === 'EACCES') {\n        throw new Error(`'${executableFile}' not executable`);\n      }\n      if (!exitCallback) {\n        process.exit(1);\n      } else {\n        const wrappedError = new CommanderError(\n          1,\n          'commander.executeSubCommandAsync',\n          '(error)',\n        );\n        wrappedError.nestedError = err;\n        exitCallback(wrappedError);\n      }\n    });\n\n    // Store the reference to the child process\n    this.runningCommand = proc;\n  }\n\n  /**\n   * @private\n   */\n\n  _dispatchSubcommand(commandName, operands, unknown) {\n    const subCommand = this._findCommand(commandName);\n    if (!subCommand) this.help({ error: true });\n\n    subCommand._prepareForParse();\n    let promiseChain;\n    promiseChain = this._chainOrCallSubCommandHook(\n      promiseChain,\n      subCommand,\n      'preSubcommand',\n    );\n    promiseChain = this._chainOrCall(promiseChain, () => {\n      if (subCommand._executableHandler) {\n        this._executeSubCommand(subCommand, operands.concat(unknown));\n      } else {\n        return subCommand._parseCommand(operands, unknown);\n      }\n    });\n    return promiseChain;\n  }\n\n  /**\n   * Invoke help directly if possible, or dispatch if necessary.\n   * e.g. help foo\n   *\n   * @private\n   */\n\n  _dispatchHelpCommand(subcommandName) {\n    if (!subcommandName) {\n      this.help();\n    }\n    const subCommand = this._findCommand(subcommandName);\n    if (subCommand && !subCommand._executableHandler) {\n      subCommand.help();\n    }\n\n    // Fallback to parsing the help flag to invoke the help.\n    return this._dispatchSubcommand(\n      subcommandName,\n      [],\n      [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n    );\n  }\n\n  /**\n   * Check this.args against expected this.registeredArguments.\n   *\n   * @private\n   */\n\n  _checkNumberOfArguments() {\n    // too few\n    this.registeredArguments.forEach((arg, i) => {\n      if (arg.required && this.args[i] == null) {\n        this.missingArgument(arg.name());\n      }\n    });\n    // too many\n    if (\n      this.registeredArguments.length > 0 &&\n      this.registeredArguments[this.registeredArguments.length - 1].variadic\n    ) {\n      return;\n    }\n    if (this.args.length > this.registeredArguments.length) {\n      this._excessArguments(this.args);\n    }\n  }\n\n  /**\n   * Process this.args using this.registeredArguments and save as this.processedArgs!\n   *\n   * @private\n   */\n\n  _processArguments() {\n    const myParseArg = (argument, value, previous) => {\n      // Extra processing for nice error message on parsing failure.\n      let parsedValue = value;\n      if (value !== null && argument.parseArg) {\n        const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n        parsedValue = this._callParseArg(\n          argument,\n          value,\n          previous,\n          invalidValueMessage,\n        );\n      }\n      return parsedValue;\n    };\n\n    this._checkNumberOfArguments();\n\n    const processedArgs = [];\n    this.registeredArguments.forEach((declaredArg, index) => {\n      let value = declaredArg.defaultValue;\n      if (declaredArg.variadic) {\n        // Collect together remaining arguments for passing together as an array.\n        if (index < this.args.length) {\n          value = this.args.slice(index);\n          if (declaredArg.parseArg) {\n            value = value.reduce((processed, v) => {\n              return myParseArg(declaredArg, v, processed);\n            }, declaredArg.defaultValue);\n          }\n        } else if (value === undefined) {\n          value = [];\n        }\n      } else if (index < this.args.length) {\n        value = this.args[index];\n        if (declaredArg.parseArg) {\n          value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n        }\n      }\n      processedArgs[index] = value;\n    });\n    this.processedArgs = processedArgs;\n  }\n\n  /**\n   * Once we have a promise we chain, but call synchronously until then.\n   *\n   * @param {(Promise|undefined)} promise\n   * @param {Function} fn\n   * @return {(Promise|undefined)}\n   * @private\n   */\n\n  _chainOrCall(promise, fn) {\n    // thenable\n    if (promise?.then && typeof promise.then === 'function') {\n      // already have a promise, chain callback\n      return promise.then(() => fn());\n    }\n    // callback might return a promise\n    return fn();\n  }\n\n  /**\n   *\n   * @param {(Promise|undefined)} promise\n   * @param {string} event\n   * @return {(Promise|undefined)}\n   * @private\n   */\n\n  _chainOrCallHooks(promise, event) {\n    let result = promise;\n    const hooks = [];\n    this._getCommandAndAncestors()\n      .reverse()\n      .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n      .forEach((hookedCommand) => {\n        hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n          hooks.push({ hookedCommand, callback });\n        });\n      });\n    if (event === 'postAction') {\n      hooks.reverse();\n    }\n\n    hooks.forEach((hookDetail) => {\n      result = this._chainOrCall(result, () => {\n        return hookDetail.callback(hookDetail.hookedCommand, this);\n      });\n    });\n    return result;\n  }\n\n  /**\n   *\n   * @param {(Promise|undefined)} promise\n   * @param {Command} subCommand\n   * @param {string} event\n   * @return {(Promise|undefined)}\n   * @private\n   */\n\n  _chainOrCallSubCommandHook(promise, subCommand, event) {\n    let result = promise;\n    if (this._lifeCycleHooks[event] !== undefined) {\n      this._lifeCycleHooks[event].forEach((hook) => {\n        result = this._chainOrCall(result, () => {\n          return hook(this, subCommand);\n        });\n      });\n    }\n    return result;\n  }\n\n  /**\n   * Process arguments in context of this command.\n   * Returns action result, in case it is a promise.\n   *\n   * @private\n   */\n\n  _parseCommand(operands, unknown) {\n    const parsed = this.parseOptions(unknown);\n    this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n    this._parseOptionsImplied();\n    operands = operands.concat(parsed.operands);\n    unknown = parsed.unknown;\n    this.args = operands.concat(unknown);\n\n    if (operands && this._findCommand(operands[0])) {\n      return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n    }\n    if (\n      this._getHelpCommand() &&\n      operands[0] === this._getHelpCommand().name()\n    ) {\n      return this._dispatchHelpCommand(operands[1]);\n    }\n    if (this._defaultCommandName) {\n      this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n      return this._dispatchSubcommand(\n        this._defaultCommandName,\n        operands,\n        unknown,\n      );\n    }\n    if (\n      this.commands.length &&\n      this.args.length === 0 &&\n      !this._actionHandler &&\n      !this._defaultCommandName\n    ) {\n      // probably missing subcommand and no handler, user needs help (and exit)\n      this.help({ error: true });\n    }\n\n    this._outputHelpIfRequested(parsed.unknown);\n    this._checkForMissingMandatoryOptions();\n    this._checkForConflictingOptions();\n\n    // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n    const checkForUnknownOptions = () => {\n      if (parsed.unknown.length > 0) {\n        this.unknownOption(parsed.unknown[0]);\n      }\n    };\n\n    const commandEvent = `command:${this.name()}`;\n    if (this._actionHandler) {\n      checkForUnknownOptions();\n      this._processArguments();\n\n      let promiseChain;\n      promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n      promiseChain = this._chainOrCall(promiseChain, () =>\n        this._actionHandler(this.processedArgs),\n      );\n      if (this.parent) {\n        promiseChain = this._chainOrCall(promiseChain, () => {\n          this.parent.emit(commandEvent, operands, unknown); // legacy\n        });\n      }\n      promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n      return promiseChain;\n    }\n    if (this.parent?.listenerCount(commandEvent)) {\n      checkForUnknownOptions();\n      this._processArguments();\n      this.parent.emit(commandEvent, operands, unknown); // legacy\n    } else if (operands.length) {\n      if (this._findCommand('*')) {\n        // legacy default command\n        return this._dispatchSubcommand('*', operands, unknown);\n      }\n      if (this.listenerCount('command:*')) {\n        // skip option check, emit event for possible misspelling suggestion\n        this.emit('command:*', operands, unknown);\n      } else if (this.commands.length) {\n        this.unknownCommand();\n      } else {\n        checkForUnknownOptions();\n        this._processArguments();\n      }\n    } else if (this.commands.length) {\n      checkForUnknownOptions();\n      // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n      this.help({ error: true });\n    } else {\n      checkForUnknownOptions();\n      this._processArguments();\n      // fall through for caller to handle after calling .parse()\n    }\n  }\n\n  /**\n   * Find matching command.\n   *\n   * @private\n   * @return {Command | undefined}\n   */\n  _findCommand(name) {\n    if (!name) return undefined;\n    return this.commands.find(\n      (cmd) => cmd._name === name || cmd._aliases.includes(name),\n    );\n  }\n\n  /**\n   * Return an option matching `arg` if any.\n   *\n   * @param {string} arg\n   * @return {Option}\n   * @package\n   */\n\n  _findOption(arg) {\n    return this.options.find((option) => option.is(arg));\n  }\n\n  /**\n   * Display an error message if a mandatory option does not have a value.\n   * Called after checking for help flags in leaf subcommand.\n   *\n   * @private\n   */\n\n  _checkForMissingMandatoryOptions() {\n    // Walk up hierarchy so can call in subcommand after checking for displaying help.\n    this._getCommandAndAncestors().forEach((cmd) => {\n      cmd.options.forEach((anOption) => {\n        if (\n          anOption.mandatory &&\n          cmd.getOptionValue(anOption.attributeName()) === undefined\n        ) {\n          cmd.missingMandatoryOptionValue(anOption);\n        }\n      });\n    });\n  }\n\n  /**\n   * Display an error message if conflicting options are used together in this.\n   *\n   * @private\n   */\n  _checkForConflictingLocalOptions() {\n    const definedNonDefaultOptions = this.options.filter((option) => {\n      const optionKey = option.attributeName();\n      if (this.getOptionValue(optionKey) === undefined) {\n        return false;\n      }\n      return this.getOptionValueSource(optionKey) !== 'default';\n    });\n\n    const optionsWithConflicting = definedNonDefaultOptions.filter(\n      (option) => option.conflictsWith.length > 0,\n    );\n\n    optionsWithConflicting.forEach((option) => {\n      const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n        option.conflictsWith.includes(defined.attributeName()),\n      );\n      if (conflictingAndDefined) {\n        this._conflictingOption(option, conflictingAndDefined);\n      }\n    });\n  }\n\n  /**\n   * Display an error message if conflicting options are used together.\n   * Called after checking for help flags in leaf subcommand.\n   *\n   * @private\n   */\n  _checkForConflictingOptions() {\n    // Walk up hierarchy so can call in subcommand after checking for displaying help.\n    this._getCommandAndAncestors().forEach((cmd) => {\n      cmd._checkForConflictingLocalOptions();\n    });\n  }\n\n  /**\n   * Parse options from `argv` removing known options,\n   * and return argv split into operands and unknown arguments.\n   *\n   * Side effects: modifies command by storing options. Does not reset state if called again.\n   *\n   * Examples:\n   *\n   *     argv => operands, unknown\n   *     --known kkk op => [op], []\n   *     op --known kkk => [op], []\n   *     sub --unknown uuu op => [sub], [--unknown uuu op]\n   *     sub -- --unknown uuu op => [sub --unknown uuu op], []\n   *\n   * @param {string[]} args\n   * @return {{operands: string[], unknown: string[]}}\n   */\n\n  parseOptions(args) {\n    const operands = []; // operands, not options or values\n    const unknown = []; // first unknown option and remaining unknown args\n    let dest = operands;\n\n    function maybeOption(arg) {\n      return arg.length > 1 && arg[0] === '-';\n    }\n\n    const negativeNumberArg = (arg) => {\n      // return false if not a negative number\n      if (!/^-(\\d+|\\d*\\.\\d+)(e[+-]?\\d+)?$/.test(arg)) return false;\n      // negative number is ok unless digit used as an option in command hierarchy\n      return !this._getCommandAndAncestors().some((cmd) =>\n        cmd.options\n          .map((opt) => opt.short)\n          .some((short) => /^-\\d$/.test(short)),\n      );\n    };\n\n    // parse options\n    let activeVariadicOption = null;\n    let activeGroup = null; // working through group of short options, like -abc\n    let i = 0;\n    while (i < args.length || activeGroup) {\n      const arg = activeGroup ?? args[i++];\n      activeGroup = null;\n\n      // literal\n      if (arg === '--') {\n        if (dest === unknown) dest.push(arg);\n        dest.push(...args.slice(i));\n        break;\n      }\n\n      if (\n        activeVariadicOption &&\n        (!maybeOption(arg) || negativeNumberArg(arg))\n      ) {\n        this.emit(`option:${activeVariadicOption.name()}`, arg);\n        continue;\n      }\n      activeVariadicOption = null;\n\n      if (maybeOption(arg)) {\n        const option = this._findOption(arg);\n        // recognised option, call listener to assign value with possible custom processing\n        if (option) {\n          if (option.required) {\n            const value = args[i++];\n            if (value === undefined) this.optionMissingArgument(option);\n            this.emit(`option:${option.name()}`, value);\n          } else if (option.optional) {\n            let value = null;\n            // historical behaviour is optional value is following arg unless an option\n            if (\n              i < args.length &&\n              (!maybeOption(args[i]) || negativeNumberArg(args[i]))\n            ) {\n              value = args[i++];\n            }\n            this.emit(`option:${option.name()}`, value);\n          } else {\n            // boolean flag\n            this.emit(`option:${option.name()}`);\n          }\n          activeVariadicOption = option.variadic ? option : null;\n          continue;\n        }\n      }\n\n      // Look for combo options following single dash, eat first one if known.\n      if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n        const option = this._findOption(`-${arg[1]}`);\n        if (option) {\n          if (\n            option.required ||\n            (option.optional && this._combineFlagAndOptionalValue)\n          ) {\n            // option with value following in same argument\n            this.emit(`option:${option.name()}`, arg.slice(2));\n          } else {\n            // boolean option\n            this.emit(`option:${option.name()}`);\n            // remove the processed option and keep processing group\n            activeGroup = `-${arg.slice(2)}`;\n          }\n          continue;\n        }\n      }\n\n      // Look for known long flag with value, like --foo=bar\n      if (/^--[^=]+=/.test(arg)) {\n        const index = arg.indexOf('=');\n        const option = this._findOption(arg.slice(0, index));\n        if (option && (option.required || option.optional)) {\n          this.emit(`option:${option.name()}`, arg.slice(index + 1));\n          continue;\n        }\n      }\n\n      // Not a recognised option by this command.\n      // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n      // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n      // A negative number in a leaf command is not an unknown option.\n      if (\n        dest === operands &&\n        maybeOption(arg) &&\n        !(this.commands.length === 0 && negativeNumberArg(arg))\n      ) {\n        dest = unknown;\n      }\n\n      // If using positionalOptions, stop processing our options at subcommand.\n      if (\n        (this._enablePositionalOptions || this._passThroughOptions) &&\n        operands.length === 0 &&\n        unknown.length === 0\n      ) {\n        if (this._findCommand(arg)) {\n          operands.push(arg);\n          unknown.push(...args.slice(i));\n          break;\n        } else if (\n          this._getHelpCommand() &&\n          arg === this._getHelpCommand().name()\n        ) {\n          operands.push(arg, ...args.slice(i));\n          break;\n        } else if (this._defaultCommandName) {\n          unknown.push(arg, ...args.slice(i));\n          break;\n        }\n      }\n\n      // If using passThroughOptions, stop processing options at first command-argument.\n      if (this._passThroughOptions) {\n        dest.push(arg, ...args.slice(i));\n        break;\n      }\n\n      // add arg\n      dest.push(arg);\n    }\n\n    return { operands, unknown };\n  }\n\n  /**\n   * Return an object containing local option values as key-value pairs.\n   *\n   * @return {object}\n   */\n  opts() {\n    if (this._storeOptionsAsProperties) {\n      // Preserve original behaviour so backwards compatible when still using properties\n      const result = {};\n      const len = this.options.length;\n\n      for (let i = 0; i < len; i++) {\n        const key = this.options[i].attributeName();\n        result[key] =\n          key === this._versionOptionName ? this._version : this[key];\n      }\n      return result;\n    }\n\n    return this._optionValues;\n  }\n\n  /**\n   * Return an object containing merged local and global option values as key-value pairs.\n   *\n   * @return {object}\n   */\n  optsWithGlobals() {\n    // globals overwrite locals\n    return this._getCommandAndAncestors().reduce(\n      (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n      {},\n    );\n  }\n\n  /**\n   * Display error message and exit (or call exitOverride).\n   *\n   * @param {string} message\n   * @param {object} [errorOptions]\n   * @param {string} [errorOptions.code] - an id string representing the error\n   * @param {number} [errorOptions.exitCode] - used with process.exit\n   */\n  error(message, errorOptions) {\n    // output handling\n    this._outputConfiguration.outputError(\n      `${message}\\n`,\n      this._outputConfiguration.writeErr,\n    );\n    if (typeof this._showHelpAfterError === 'string') {\n      this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n    } else if (this._showHelpAfterError) {\n      this._outputConfiguration.writeErr('\\n');\n      this.outputHelp({ error: true });\n    }\n\n    // exit handling\n    const config = errorOptions || {};\n    const exitCode = config.exitCode || 1;\n    const code = config.code || 'commander.error';\n    this._exit(exitCode, code, message);\n  }\n\n  /**\n   * Apply any option related environment variables, if option does\n   * not have a value from cli or client code.\n   *\n   * @private\n   */\n  _parseOptionsEnv() {\n    this.options.forEach((option) => {\n      if (option.envVar && option.envVar in process.env) {\n        const optionKey = option.attributeName();\n        // Priority check. Do not overwrite cli or options from unknown source (client-code).\n        if (\n          this.getOptionValue(optionKey) === undefined ||\n          ['default', 'config', 'env'].includes(\n            this.getOptionValueSource(optionKey),\n          )\n        ) {\n          if (option.required || option.optional) {\n            // option can take a value\n            // keep very simple, optional always takes value\n            this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n          } else {\n            // boolean\n            // keep very simple, only care that envVar defined and not the value\n            this.emit(`optionEnv:${option.name()}`);\n          }\n        }\n      }\n    });\n  }\n\n  /**\n   * Apply any implied option values, if option is undefined or default value.\n   *\n   * @private\n   */\n  _parseOptionsImplied() {\n    const dualHelper = new DualOptions(this.options);\n    const hasCustomOptionValue = (optionKey) => {\n      return (\n        this.getOptionValue(optionKey) !== undefined &&\n        !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n      );\n    };\n    this.options\n      .filter(\n        (option) =>\n          option.implied !== undefined &&\n          hasCustomOptionValue(option.attributeName()) &&\n          dualHelper.valueFromOption(\n            this.getOptionValue(option.attributeName()),\n            option,\n          ),\n      )\n      .forEach((option) => {\n        Object.keys(option.implied)\n          .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n          .forEach((impliedKey) => {\n            this.setOptionValueWithSource(\n              impliedKey,\n              option.implied[impliedKey],\n              'implied',\n            );\n          });\n      });\n  }\n\n  /**\n   * Argument `name` is missing.\n   *\n   * @param {string} name\n   * @private\n   */\n\n  missingArgument(name) {\n    const message = `error: missing required argument '${name}'`;\n    this.error(message, { code: 'commander.missingArgument' });\n  }\n\n  /**\n   * `Option` is missing an argument.\n   *\n   * @param {Option} option\n   * @private\n   */\n\n  optionMissingArgument(option) {\n    const message = `error: option '${option.flags}' argument missing`;\n    this.error(message, { code: 'commander.optionMissingArgument' });\n  }\n\n  /**\n   * `Option` does not have a value, and is a mandatory option.\n   *\n   * @param {Option} option\n   * @private\n   */\n\n  missingMandatoryOptionValue(option) {\n    const message = `error: required option '${option.flags}' not specified`;\n    this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n  }\n\n  /**\n   * `Option` conflicts with another option.\n   *\n   * @param {Option} option\n   * @param {Option} conflictingOption\n   * @private\n   */\n  _conflictingOption(option, conflictingOption) {\n    // The calling code does not know whether a negated option is the source of the\n    // value, so do some work to take an educated guess.\n    const findBestOptionFromValue = (option) => {\n      const optionKey = option.attributeName();\n      const optionValue = this.getOptionValue(optionKey);\n      const negativeOption = this.options.find(\n        (target) => target.negate && optionKey === target.attributeName(),\n      );\n      const positiveOption = this.options.find(\n        (target) => !target.negate && optionKey === target.attributeName(),\n      );\n      if (\n        negativeOption &&\n        ((negativeOption.presetArg === undefined && optionValue === false) ||\n          (negativeOption.presetArg !== undefined &&\n            optionValue === negativeOption.presetArg))\n      ) {\n        return negativeOption;\n      }\n      return positiveOption || option;\n    };\n\n    const getErrorMessage = (option) => {\n      const bestOption = findBestOptionFromValue(option);\n      const optionKey = bestOption.attributeName();\n      const source = this.getOptionValueSource(optionKey);\n      if (source === 'env') {\n        return `environment variable '${bestOption.envVar}'`;\n      }\n      return `option '${bestOption.flags}'`;\n    };\n\n    const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n    this.error(message, { code: 'commander.conflictingOption' });\n  }\n\n  /**\n   * Unknown option `flag`.\n   *\n   * @param {string} flag\n   * @private\n   */\n\n  unknownOption(flag) {\n    if (this._allowUnknownOption) return;\n    let suggestion = '';\n\n    if (flag.startsWith('--') && this._showSuggestionAfterError) {\n      // Looping to pick up the global options too\n      let candidateFlags = [];\n      // eslint-disable-next-line @typescript-eslint/no-this-alias\n      let command = this;\n      do {\n        const moreFlags = command\n          .createHelp()\n          .visibleOptions(command)\n          .filter((option) => option.long)\n          .map((option) => option.long);\n        candidateFlags = candidateFlags.concat(moreFlags);\n        command = command.parent;\n      } while (command && !command._enablePositionalOptions);\n      suggestion = suggestSimilar(flag, candidateFlags);\n    }\n\n    const message = `error: unknown option '${flag}'${suggestion}`;\n    this.error(message, { code: 'commander.unknownOption' });\n  }\n\n  /**\n   * Excess arguments, more than expected.\n   *\n   * @param {string[]} receivedArgs\n   * @private\n   */\n\n  _excessArguments(receivedArgs) {\n    if (this._allowExcessArguments) return;\n\n    const expected = this.registeredArguments.length;\n    const s = expected === 1 ? '' : 's';\n    const received = receivedArgs.length;\n    const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n    const details = receivedArgs.join(', ');\n    const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;\n    this.error(message, { code: 'commander.excessArguments' });\n  }\n\n  /**\n   * Unknown command.\n   *\n   * @private\n   */\n\n  unknownCommand() {\n    const unknownName = this.args[0];\n    let suggestion = '';\n\n    if (this._showSuggestionAfterError) {\n      const candidateNames = [];\n      this.createHelp()\n        .visibleCommands(this)\n        .forEach((command) => {\n          candidateNames.push(command.name());\n          // just visible alias\n          if (command.alias()) candidateNames.push(command.alias());\n        });\n      suggestion = suggestSimilar(unknownName, candidateNames);\n    }\n\n    const message = `error: unknown command '${unknownName}'${suggestion}`;\n    this.error(message, { code: 'commander.unknownCommand' });\n  }\n\n  /**\n   * Get or set the program version.\n   *\n   * This method auto-registers the \"-V, --version\" option which will print the version number.\n   *\n   * You can optionally supply the flags and description to override the defaults.\n   *\n   * @param {string} [str]\n   * @param {string} [flags]\n   * @param {string} [description]\n   * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n   */\n\n  version(str, flags, description) {\n    if (str === undefined) return this._version;\n    this._version = str;\n    flags = flags || '-V, --version';\n    description = description || 'output the version number';\n    const versionOption = this.createOption(flags, description);\n    this._versionOptionName = versionOption.attributeName();\n    this._registerOption(versionOption);\n\n    this.on('option:' + versionOption.name(), () => {\n      this._outputConfiguration.writeOut(`${str}\\n`);\n      this._exit(0, 'commander.version', str);\n    });\n    return this;\n  }\n\n  /**\n   * Set the description.\n   *\n   * @param {string} [str]\n   * @param {object} [argsDescription]\n   * @return {(string|Command)}\n   */\n  description(str, argsDescription) {\n    if (str === undefined && argsDescription === undefined)\n      return this._description;\n    this._description = str;\n    if (argsDescription) {\n      this._argsDescription = argsDescription;\n    }\n    return this;\n  }\n\n  /**\n   * Set the summary. Used when listed as subcommand of parent.\n   *\n   * @param {string} [str]\n   * @return {(string|Command)}\n   */\n  summary(str) {\n    if (str === undefined) return this._summary;\n    this._summary = str;\n    return this;\n  }\n\n  /**\n   * Set an alias for the command.\n   *\n   * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n   *\n   * @param {string} [alias]\n   * @return {(string|Command)}\n   */\n\n  alias(alias) {\n    if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n    /** @type {Command} */\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    let command = this;\n    if (\n      this.commands.length !== 0 &&\n      this.commands[this.commands.length - 1]._executableHandler\n    ) {\n      // assume adding alias for last added executable subcommand, rather than this\n      command = this.commands[this.commands.length - 1];\n    }\n\n    if (alias === command._name)\n      throw new Error(\"Command alias can't be the same as its name\");\n    const matchingCommand = this.parent?._findCommand(alias);\n    if (matchingCommand) {\n      // c.f. _registerCommand\n      const existingCmd = [matchingCommand.name()]\n        .concat(matchingCommand.aliases())\n        .join('|');\n      throw new Error(\n        `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n      );\n    }\n\n    command._aliases.push(alias);\n    return this;\n  }\n\n  /**\n   * Set aliases for the command.\n   *\n   * Only the first alias is shown in the auto-generated help.\n   *\n   * @param {string[]} [aliases]\n   * @return {(string[]|Command)}\n   */\n\n  aliases(aliases) {\n    // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n    if (aliases === undefined) return this._aliases;\n\n    aliases.forEach((alias) => this.alias(alias));\n    return this;\n  }\n\n  /**\n   * Set / get the command usage `str`.\n   *\n   * @param {string} [str]\n   * @return {(string|Command)}\n   */\n\n  usage(str) {\n    if (str === undefined) {\n      if (this._usage) return this._usage;\n\n      const args = this.registeredArguments.map((arg) => {\n        return humanReadableArgName(arg);\n      });\n      return []\n        .concat(\n          this.options.length || this._helpOption !== null ? '[options]' : [],\n          this.commands.length ? '[command]' : [],\n          this.registeredArguments.length ? args : [],\n        )\n        .join(' ');\n    }\n\n    this._usage = str;\n    return this;\n  }\n\n  /**\n   * Get or set the name of the command.\n   *\n   * @param {string} [str]\n   * @return {(string|Command)}\n   */\n\n  name(str) {\n    if (str === undefined) return this._name;\n    this._name = str;\n    return this;\n  }\n\n  /**\n   * Set/get the help group heading for this subcommand in parent command's help.\n   *\n   * @param {string} [heading]\n   * @return {Command | string}\n   */\n\n  helpGroup(heading) {\n    if (heading === undefined) return this._helpGroupHeading ?? '';\n    this._helpGroupHeading = heading;\n    return this;\n  }\n\n  /**\n   * Set/get the default help group heading for subcommands added to this command.\n   * (This does not override a group set directly on the subcommand using .helpGroup().)\n   *\n   * @example\n   * program.commandsGroup('Development Commands:);\n   * program.command('watch')...\n   * program.command('lint')...\n   * ...\n   *\n   * @param {string} [heading]\n   * @returns {Command | string}\n   */\n  commandsGroup(heading) {\n    if (heading === undefined) return this._defaultCommandGroup ?? '';\n    this._defaultCommandGroup = heading;\n    return this;\n  }\n\n  /**\n   * Set/get the default help group heading for options added to this command.\n   * (This does not override a group set directly on the option using .helpGroup().)\n   *\n   * @example\n   * program\n   *   .optionsGroup('Development Options:')\n   *   .option('-d, --debug', 'output extra debugging')\n   *   .option('-p, --profile', 'output profiling information')\n   *\n   * @param {string} [heading]\n   * @returns {Command | string}\n   */\n  optionsGroup(heading) {\n    if (heading === undefined) return this._defaultOptionGroup ?? '';\n    this._defaultOptionGroup = heading;\n    return this;\n  }\n\n  /**\n   * @param {Option} option\n   * @private\n   */\n  _initOptionGroup(option) {\n    if (this._defaultOptionGroup && !option.helpGroupHeading)\n      option.helpGroup(this._defaultOptionGroup);\n  }\n\n  /**\n   * @param {Command} cmd\n   * @private\n   */\n  _initCommandGroup(cmd) {\n    if (this._defaultCommandGroup && !cmd.helpGroup())\n      cmd.helpGroup(this._defaultCommandGroup);\n  }\n\n  /**\n   * Set the name of the command from script filename, such as process.argv[1],\n   * or import.meta.filename.\n   *\n   * (Used internally and public although not documented in README.)\n   *\n   * @example\n   * program.nameFromFilename(import.meta.filename);\n   *\n   * @param {string} filename\n   * @return {Command}\n   */\n\n  nameFromFilename(filename) {\n    this._name = path.basename(filename, path.extname(filename));\n\n    return this;\n  }\n\n  /**\n   * Get or set the directory for searching for executable subcommands of this command.\n   *\n   * @example\n   * program.executableDir(import.meta.dirname);\n   * // or\n   * program.executableDir('subcommands');\n   *\n   * @param {string} [path]\n   * @return {(string|null|Command)}\n   */\n\n  executableDir(path) {\n    if (path === undefined) return this._executableDir;\n    this._executableDir = path;\n    return this;\n  }\n\n  /**\n   * Return program help documentation.\n   *\n   * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n   * @return {string}\n   */\n\n  helpInformation(contextOptions) {\n    const helper = this.createHelp();\n    const context = this._getOutputContext(contextOptions);\n    helper.prepareContext({\n      error: context.error,\n      helpWidth: context.helpWidth,\n      outputHasColors: context.hasColors,\n    });\n    const text = helper.formatHelp(this, helper);\n    if (context.hasColors) return text;\n    return this._outputConfiguration.stripColor(text);\n  }\n\n  /**\n   * @typedef HelpContext\n   * @type {object}\n   * @property {boolean} error\n   * @property {number} helpWidth\n   * @property {boolean} hasColors\n   * @property {function} write - includes stripColor if needed\n   *\n   * @returns {HelpContext}\n   * @private\n   */\n\n  _getOutputContext(contextOptions) {\n    contextOptions = contextOptions || {};\n    const error = !!contextOptions.error;\n    let baseWrite;\n    let hasColors;\n    let helpWidth;\n    if (error) {\n      baseWrite = (str) => this._outputConfiguration.writeErr(str);\n      hasColors = this._outputConfiguration.getErrHasColors();\n      helpWidth = this._outputConfiguration.getErrHelpWidth();\n    } else {\n      baseWrite = (str) => this._outputConfiguration.writeOut(str);\n      hasColors = this._outputConfiguration.getOutHasColors();\n      helpWidth = this._outputConfiguration.getOutHelpWidth();\n    }\n    const write = (str) => {\n      if (!hasColors) str = this._outputConfiguration.stripColor(str);\n      return baseWrite(str);\n    };\n    return { error, write, hasColors, helpWidth };\n  }\n\n  /**\n   * Output help information for this command.\n   *\n   * Outputs built-in help, and custom text added using `.addHelpText()`.\n   *\n   * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n   */\n\n  outputHelp(contextOptions) {\n    let deprecatedCallback;\n    if (typeof contextOptions === 'function') {\n      deprecatedCallback = contextOptions;\n      contextOptions = undefined;\n    }\n\n    const outputContext = this._getOutputContext(contextOptions);\n    /** @type {HelpTextEventContext} */\n    const eventContext = {\n      error: outputContext.error,\n      write: outputContext.write,\n      command: this,\n    };\n\n    this._getCommandAndAncestors()\n      .reverse()\n      .forEach((command) => command.emit('beforeAllHelp', eventContext));\n    this.emit('beforeHelp', eventContext);\n\n    let helpInformation = this.helpInformation({ error: outputContext.error });\n    if (deprecatedCallback) {\n      helpInformation = deprecatedCallback(helpInformation);\n      if (\n        typeof helpInformation !== 'string' &&\n        !Buffer.isBuffer(helpInformation)\n      ) {\n        throw new Error('outputHelp callback must return a string or a Buffer');\n      }\n    }\n    outputContext.write(helpInformation);\n\n    if (this._getHelpOption()?.long) {\n      this.emit(this._getHelpOption().long); // deprecated\n    }\n    this.emit('afterHelp', eventContext);\n    this._getCommandAndAncestors().forEach((command) =>\n      command.emit('afterAllHelp', eventContext),\n    );\n  }\n\n  /**\n   * You can pass in flags and a description to customise the built-in help option.\n   * Pass in false to disable the built-in help option.\n   *\n   * @example\n   * program.helpOption('-?, --help' 'show help'); // customise\n   * program.helpOption(false); // disable\n   *\n   * @param {(string | boolean)} flags\n   * @param {string} [description]\n   * @return {Command} `this` command for chaining\n   */\n\n  helpOption(flags, description) {\n    // Support enabling/disabling built-in help option.\n    if (typeof flags === 'boolean') {\n      if (flags) {\n        if (this._helpOption === null) this._helpOption = undefined; // reenable\n        if (this._defaultOptionGroup) {\n          // make the option to store the group\n          this._initOptionGroup(this._getHelpOption());\n        }\n      } else {\n        this._helpOption = null; // disable\n      }\n      return this;\n    }\n\n    // Customise flags and description.\n    this._helpOption = this.createOption(\n      flags ?? '-h, --help',\n      description ?? 'display help for command',\n    );\n    // init group unless lazy create\n    if (flags || description) this._initOptionGroup(this._helpOption);\n\n    return this;\n  }\n\n  /**\n   * Lazy create help option.\n   * Returns null if has been disabled with .helpOption(false).\n   *\n   * @returns {(Option | null)} the help option\n   * @package\n   */\n  _getHelpOption() {\n    // Lazy create help option on demand.\n    if (this._helpOption === undefined) {\n      this.helpOption(undefined, undefined);\n    }\n    return this._helpOption;\n  }\n\n  /**\n   * Supply your own option to use for the built-in help option.\n   * This is an alternative to using helpOption() to customise the flags and description etc.\n   *\n   * @param {Option} option\n   * @return {Command} `this` command for chaining\n   */\n  addHelpOption(option) {\n    this._helpOption = option;\n    this._initOptionGroup(option);\n    return this;\n  }\n\n  /**\n   * Output help information and exit.\n   *\n   * Outputs built-in help, and custom text added using `.addHelpText()`.\n   *\n   * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n   */\n\n  help(contextOptions) {\n    this.outputHelp(contextOptions);\n    let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number\n    if (\n      exitCode === 0 &&\n      contextOptions &&\n      typeof contextOptions !== 'function' &&\n      contextOptions.error\n    ) {\n      exitCode = 1;\n    }\n    // message: do not have all displayed text available so only passing placeholder.\n    this._exit(exitCode, 'commander.help', '(outputHelp)');\n  }\n\n  /**\n   * // Do a little typing to coordinate emit and listener for the help text events.\n   * @typedef HelpTextEventContext\n   * @type {object}\n   * @property {boolean} error\n   * @property {Command} command\n   * @property {function} write\n   */\n\n  /**\n   * Add additional text to be displayed with the built-in help.\n   *\n   * Position is 'before' or 'after' to affect just this command,\n   * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n   *\n   * @param {string} position - before or after built-in help\n   * @param {(string | Function)} text - string to add, or a function returning a string\n   * @return {Command} `this` command for chaining\n   */\n\n  addHelpText(position, text) {\n    const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n    if (!allowedValues.includes(position)) {\n      throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n    }\n\n    const helpEvent = `${position}Help`;\n    this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {\n      let helpStr;\n      if (typeof text === 'function') {\n        helpStr = text({ error: context.error, command: context.command });\n      } else {\n        helpStr = text;\n      }\n      // Ignore falsy value when nothing to output.\n      if (helpStr) {\n        context.write(`${helpStr}\\n`);\n      }\n    });\n    return this;\n  }\n\n  /**\n   * Output help information if help flags specified\n   *\n   * @param {Array} args - array of options to search for help flags\n   * @private\n   */\n\n  _outputHelpIfRequested(args) {\n    const helpOption = this._getHelpOption();\n    const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n    if (helpRequested) {\n      this.outputHelp();\n      // (Do not have all displayed text available so only passing placeholder.)\n      this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n    }\n  }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n  // Testing for these options:\n  //  --inspect[=[host:]port]\n  //  --inspect-brk[=[host:]port]\n  //  --inspect-port=[host:]port\n  return args.map((arg) => {\n    if (!arg.startsWith('--inspect')) {\n      return arg;\n    }\n    let debugOption;\n    let debugHost = '127.0.0.1';\n    let debugPort = '9229';\n    let match;\n    if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n      // e.g. --inspect\n      debugOption = match[1];\n    } else if (\n      (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n    ) {\n      debugOption = match[1];\n      if (/^\\d+$/.test(match[3])) {\n        // e.g. --inspect=1234\n        debugPort = match[3];\n      } else {\n        // e.g. --inspect=localhost\n        debugHost = match[3];\n      }\n    } else if (\n      (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n    ) {\n      // e.g. --inspect=localhost:1234\n      debugOption = match[1];\n      debugHost = match[3];\n      debugPort = match[4];\n    }\n\n    if (debugOption && debugPort !== '0') {\n      return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n    }\n    return arg;\n  });\n}\n\n/**\n * Exported for using from tests, not otherwise used outside this file.\n *\n * @returns {boolean | undefined}\n * @package\n */\nexport function useColor() {\n  // Test for common conventions.\n  // NB: the observed behaviour is in combination with how author adds color! For example:\n  //   - we do not test NODE_DISABLE_COLORS, but util:styletext does\n  //   - we do test NO_COLOR, but Chalk does not\n  //\n  // References:\n  // https://no-color.org\n  // https://bixense.com/clicolors/\n  // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109\n  // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33\n  // (https://force-color.org recent web page from 2023, does not match major javascript implementations)\n\n  if (\n    process.env.NO_COLOR ||\n    process.env.FORCE_COLOR === '0' ||\n    process.env.FORCE_COLOR === 'false'\n  )\n    return false;\n  if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)\n    return true;\n  return undefined;\n}\n","import { Argument } from './lib/argument.js';\nimport { Command } from './lib/command.js';\nimport { CommanderError, InvalidArgumentError } from './lib/error.js';\nimport { Help } from './lib/help.js';\nimport { Option } from './lib/option.js';\n\nexport const program = new Command();\n\nexport const createCommand = (name) => new Command(name);\nexport const createOption = (flags, description) =>\n  new Option(flags, description);\nexport const createArgument = (name, description) =>\n  new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexport { Command, Option, Argument, Help };\nexport { CommanderError, InvalidArgumentError };\nexport { InvalidArgumentError as InvalidOptionArgumentError }; // Deprecated\n","import { getChannelConfig } from \"@opentag/shared\";\nimport { CHANNEL } from \"../../build-info.js\";\n\nexport const channelConfig = getChannelConfig(CHANNEL);\n","let channelDefaultHomeApplied = false;\n\nexport function markChannelDefaultHomeApplied(): void {\n  channelDefaultHomeApplied = true;\n}\n\nexport function wasChannelDefaultHomeApplied(): boolean {\n  return channelDefaultHomeApplied;\n}\n","import { channelConfig } from \"./config.js\";\nimport { markChannelDefaultHomeApplied } from \"./home-source.js\";\n\n/**\n * The environment variable the daemon service definitions and channel tooling use to name the\n * OpenTag home. It is the same one every channel's service template embeds; do not hard-code a\n * second spelling in repair commands that must reach a custom `--home`.\n */\nexport const OPEN_TAG_HOME_ENVIRONMENT_VARIABLE = \"OPENTAG_HOME\";\n\n/** Return the command environment with the channel home selected, without mutating process.env. */\nexport function resolveChannelEnvironment(environment: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {\n  const result = { ...environment };\n  if (!result[OPEN_TAG_HOME_ENVIRONMENT_VARIABLE]) {\n    result[OPEN_TAG_HOME_ENVIRONMENT_VARIABLE] = channelConfig.defaultHome;\n    markChannelDefaultHomeApplied();\n  }\n  return result;\n}\n","import * as client from \"@opentag/client\";\nimport { channelConfig } from \"../channel/config.js\";\nimport { resolveChannelEnvironment } from \"../channel/environment.js\";\n\ntype CommandContextAuthOptions = { accessToken?: string; api?: client.OpenTagApi; requireAuth?: boolean };\ntype CommandContextLocationOptions = { environment?: NodeJS.ProcessEnv; home?: string; serverUrl?: string };\nexport type CommandContextOptions = CommandContextAuthOptions & CommandContextLocationOptions;\ntype CommandContextIdentityAccess = { readonly accessToken?: string; readonly api?: client.OpenTagApi };\ntype CommandContextIdentity = CommandContextIdentityAccess & { readonly credentials?: client.StoredCredentials };\ntype CommandContextLocation = { readonly environment: NodeJS.ProcessEnv; readonly home: string };\nexport type CommandContext = CommandContextIdentity & CommandContextLocation;\n\n/** Resolve home, credentials, token, and API from one detached command context. */\nexport async function resolveCommandContext(options: CommandContextOptions = {}): Promise<CommandContext> {\n  const environment = resolveChannelEnvironment(options.environment ?? process.env);\n  const home = options.home ?? client.resolveOpenTagHome(environment);\n  if (options.serverUrl) return { api: new client.OpenTagApi(options.serverUrl), environment, home };\n  if (!options.requireAuth && !options.api && !options.accessToken) {\n    return { environment, home };\n  }\n  if (options.api && options.accessToken) {\n    return { accessToken: options.accessToken, api: options.api, environment, home };\n  }\n  if (options.api || options.accessToken) {\n    throw new Error(\"Command context test dependencies must provide both api and accessToken\");\n  }\n  const credentials = await client.readCredentials(home);\n  if (!credentials) {\n    const [computerIdentity, machineCredentials] = await Promise.all([\n      client.readComputerIdentity(home),\n      client.readMachineCredentials(home),\n    ]);\n    const recordedServerUrl = computerIdentity?.serverUrl ?? machineCredentials?.computer.serverUrl;\n    if (recordedServerUrl) {\n      throw new Error(\n        `OpenTag is not logged in: this OpenTag home has machine credentials (computer-credentials.json/computer.json) but no Account credentials (credentials.json). Get an Account login code issued by the server (today via POST /api/v1/me/connect-codes), then run ${channelConfig.binName} login --server ${recordedServerUrl} -- <code>.`,\n      );\n    }\n    throw new Error(\"OpenTag is not logged in; run login first\");\n  }\n  const accessToken = await new client.AccessTokenProvider({ home }).getAccessToken();\n  return { accessToken, api: new client.OpenTagApi(credentials.serverUrl), credentials, environment, home };\n}\n","import type { OpenTagApi } from \"@opentag/client\";\nimport type { MCPAgentServer, MCPExtraHeaders, MCPProbeResponse, MCPServer, MCPServerDetail } from \"@opentag/shared\";\nimport { resolveCommandContext } from \"../command/context.js\";\n\n/**\n * Shared plumbing for the MCP commands.\n *\n * The CLI is a thin presentation layer over the management API: it resolves the Server definition\n * once, then hands the concrete id to the Agent-scoped work, because every per-Agent route is keyed\n * by the Server's id rather than its name.\n */\n\nexport interface McpApiClient\n  extends Pick<\n    OpenTagApi,\n    | \"listMcpServers\"\n    | \"createMcpServer\"\n    | \"getMcpServer\"\n    | \"updateMcpServer\"\n    | \"removeMcpServer\"\n    | \"listAgentMcpServers\"\n    | \"listAvailableMcpServers\"\n    | \"attachMcpServer\"\n    | \"updateAgentMcpServer\"\n    | \"detachMcpServer\"\n    | \"setMcpAuthorization\"\n    | \"revokeMcpAuthorization\"\n    | \"startMcpOAuth\"\n    | \"probeMcpServer\"\n  > {}\n\nexport interface McpCommandDependencies {\n  accessToken?: string;\n  api?: McpApiClient;\n  home?: string;\n}\n\nexport async function resolveMcpCommandContext(\n  options: McpCommandDependencies,\n): Promise<{ accessToken: string; api: McpApiClient }> {\n  if ((options.api && !options.accessToken) || (options.accessToken && !options.api)) {\n    throw new Error(\"MCP command test dependencies must provide both api and accessToken\");\n  }\n  const context = await resolveCommandContext({\n    accessToken: options.accessToken,\n    api: options.api as OpenTagApi | undefined,\n    home: options.home,\n    requireAuth: true,\n  });\n  if (!context.api || !context.accessToken) throw new Error(\"Command context did not resolve an authenticated API\");\n  return { api: context.api, accessToken: context.accessToken };\n}\n\n/**\n * Resolve a Server by name or id. A name is the human-facing handle and an id is what the API uses,\n * so both are accepted and the response keeps its id.\n */\nexport async function resolveMcpServer(reference: string, options: McpCommandDependencies = {}): Promise<MCPServer> {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  const { servers } = await api.listMcpServers(accessToken);\n  const match = servers.find((server) => server.id === reference || server.name === reference);\n  if (!match) throw new Error(`No MCP Server named or identified by \"${reference}\"`);\n  return match;\n}\n\n/** Collect repeated `--extra-header name=value` flags into one map, rejecting a duplicate name. */\nexport function extraHeadersFrom(entries: readonly string[] | undefined): MCPExtraHeaders | undefined {\n  if (!entries || entries.length === 0) return undefined;\n  const headers: Record<string, string> = {};\n  for (const entry of entries) {\n    const separator = entry.indexOf(\"=\");\n    if (separator <= 0) throw new Error(`--extra-header expects name=value, received \"${entry}\"`);\n    const name = entry.slice(0, separator).trim().toLowerCase();\n    const value = entry.slice(separator + 1);\n    if (name.length === 0) throw new Error(\"--extra-header requires a header name\");\n    if (name in headers) throw new Error(`--extra-header repeats \"${name}\"`);\n    headers[name] = value;\n  }\n  return headers;\n}\n\nexport function formatMcpServer(server: MCPServer): string {\n  return [\n    `id\\t${server.id}`,\n    `name\\t${server.name}`,\n    `description\\t${server.description ?? \"-\"}`,\n    `url\\t${server.url}`,\n    // Never a statement of what the Server requires: it is only the prefill for a new authorization.\n    `defaultAuthKind\\t${server.defaultAuthKind} (prefill for a new authorization only)`,\n    `authHeader\\t${server.authHeader}`,\n    `authScheme\\t${server.authScheme === \"\" ? \"(sent verbatim)\" : server.authScheme}`,\n    `extraHeaders\\t${formatHeaders(server.extraHeaders)}`,\n    `revision\\t${server.revision}`,\n    `boundAgentCount\\t${server.boundAgentCount}`,\n    `authorizedAgentCount\\t${server.authorizedAgentCount}`,\n    `lastProbedAt\\t${server.lastProbedAt ?? \"-\"}`,\n  ].join(\"\\n\");\n}\n\nexport function formatMcpServerList(servers: readonly MCPServer[]): string {\n  if (servers.length === 0) return \"No MCP Servers configured\";\n  return [\n    [\"NAME\", \"URL\", \"AGENTS\", \"AUTHORIZED\", \"LAST PROBED\"].join(\"\\t\"),\n    ...servers.map((server) =>\n      [\n        server.name,\n        server.url,\n        String(server.boundAgentCount),\n        String(server.authorizedAgentCount),\n        server.lastProbedAt ?? \"-\",\n      ].join(\"\\t\"),\n    ),\n  ].join(\"\\n\");\n}\n\n/**\n * One row per mounted Server. The four states are printed as independent fields rather than folded\n * into one status, because \"disabled\" and \"unauthorized\" are different problems with different\n * fixes: a disabled Server needs no reauthorization, an unauthorized one does.\n */\nexport function formatAgentMcpServers(servers: readonly MCPAgentServer[]): string {\n  if (servers.length === 0) return \"No MCP Servers mounted\";\n  return [\n    [\"NAME\", \"MOUNT\", \"AUTH KIND\", \"AUTH STATUS\", \"PROBE\", \"TOOLS\", \"EXPIRES\"].join(\"\\t\"),\n    ...servers.map((entry) => {\n      const authorization = entry.authorization;\n      return [\n        entry.name,\n        entry.enabled ? \"enabled\" : \"disabled\",\n        authorization?.kind ?? \"none\",\n        authorization?.status ?? \"none\",\n        describeProbe(authorization),\n        authorization?.toolsCount === null || authorization?.toolsCount === undefined\n          ? \"-\"\n          : `${authorization.toolsCount}${authorization.toolsTruncated ? \" (truncated)\" : \"\"}`,\n        authorization?.accessTokenExpiresAt ?? \"-\",\n      ].join(\"\\t\");\n    }),\n  ].join(\"\\n\");\n}\n\nexport function describeProbe(authorization: MCPAgentServer[\"authorization\"]): string {\n  if (!authorization) return \"not authorized\";\n  if (authorization.probeState === \"succeeded\") return `probed ${authorization.probedAt ?? \"-\"}`;\n  if (authorization.probeState === \"failed\") return `failed: ${authorization.probeError ?? \"-\"}`;\n  return \"pending\";\n}\n\nexport function formatHeaders(headers: Record<string, string>): string {\n  const entries = Object.entries(headers);\n  return entries.length === 0 ? \"-\" : entries.map(([name, value]) => `${name}=${value}`).join(\", \");\n}\n\n/** One Agent's effective configuration, with each field's provenance so a user can see what applies. */\nexport function formatAgentServerRow(entry: MCPAgentServer): string {\n  const authorization = entry.authorization;\n  return [\n    `name\\t${entry.name}`,\n    `mount\\t${entry.enabled ? \"enabled\" : \"disabled\"}`,\n    `authKind\\t${authorization?.kind ?? \"none\"}`,\n    `authStatus\\t${authorization?.status ?? \"none\"}`,\n    `probeState\\t${authorization?.probeState ?? \"not authorized\"}`,\n    `probeError\\t${authorization?.probeError ?? \"-\"}`,\n    `toolsCount\\t${authorization?.toolsCount ?? \"-\"}${authorization?.toolsTruncated ? \" (truncated)\" : \"\"}`,\n    `effectiveUrl\\t${entry.effective.url}\\t${entry.overridden.url ? \"overridden\" : \"inherited\"}`,\n    `effectiveAuthHeader\\t${entry.effective.authHeader}\\t${entry.overridden.authHeader ? \"overridden\" : \"inherited\"}`,\n    `effectiveAuthScheme\\t${entry.effective.authScheme === \"\" ? \"(verbatim)\" : entry.effective.authScheme}\\t${entry.overridden.authScheme ? \"overridden\" : \"inherited\"}`,\n    `effectiveExtraHeaders\\t${formatHeaders(entry.effective.extraHeaders)}\\t${entry.overridden.extraHeaders ? \"overridden\" : \"inherited\"}`,\n  ].join(\"\\n\");\n}\n\n/** The started OAuth flow plus, when the caller waited, the probe result the authorization produced. */\nexport function formatAuthorization(value: {\n  server: MCPServer;\n  started: { authorizationUrl: string; expiresAt: string };\n  probe?: MCPProbeResponse;\n}): string {\n  return [\n    `server\\t${value.server.name}`,\n    `authorizationUrl\\t${value.started.authorizationUrl}`,\n    `expiresAt\\t${value.started.expiresAt}`,\n    `probeState\\t${value.probe?.probeState ?? \"pending\"}`,\n    `toolsCount\\t${value.probe?.toolsCount ?? \"-\"}${value.probe?.toolsTruncated ? \" (truncated)\" : \"\"}`,\n    `protocolEra\\t${value.probe?.protocolEra ?? \"-\"}`,\n  ].join(\"\\n\");\n}\n\nexport function formatProbe(value: MCPProbeResponse): string {\n  return [\n    `probeState\\t${value.probeState}`,\n    `probeError\\t${value.probeError ?? \"-\"}`,\n    `toolsCount\\t${value.toolsCount ?? \"-\"}`,\n    // A separate field as well as the inline marker: a script needs to branch on truncation, and a\n    // suffix glued to another field cannot be parsed without string surgery.\n    `toolsTruncated\\t${value.toolsTruncated}`,\n    `protocolEra\\t${value.protocolEra ?? \"-\"}`,\n    `protocolVersion\\t${value.protocolVersion ?? \"-\"}`,\n  ].join(\"\\n\");\n}\n\n/**\n * A Server definition together with its Agent matrix, and one Agent's effective view when asked.\n *\n * The definition's own fields come first: `mcp show <server>` without `--agent` is a request about\n * the definition, so reporting only the matrix would answer a different question than the one asked.\n */\nexport function formatMcpShow(value: { server: MCPServerDetail; agentView?: MCPAgentServer }): string {\n  const lines = [\n    formatMcpServer(value.server.server),\n    `agentCount\\t${value.server.agents.length}`,\n    ...value.server.agents.map((agent) =>\n      [\n        \"agent\",\n        agent.agentName,\n        agent.enabled ? \"enabled\" : \"disabled\",\n        agent.authorization?.kind ?? \"none\",\n        agent.authorization?.status ?? \"unauthorized\",\n        agent.protocolEra ?? \"-\",\n      ].join(\"\\t\"),\n    ),\n  ];\n  if (value.agentView) lines.push(formatAgentServerRow(value.agentView));\n  return lines.join(\"\\n\");\n}\n","import type {\n  CreateMCPServerRequest,\n  MCPAuthKind,\n  MCPProbeResponse,\n  MCPServer,\n  MCPServerDetail,\n  SetMCPAuthorizationRequest,\n  StartMCPOAuthResponse,\n  UpdateMCPBindingRequest,\n  UpdateMCPServerRequest,\n} from \"@opentag/shared\";\nimport { extraHeadersFrom, type McpCommandDependencies, resolveMcpCommandContext, resolveMcpServer } from \"./shared.js\";\n\n/**\n * The MCP operations the CLI performs, each a thin call over the management API.\n *\n * Two rules are enforced here rather than left to the caller:\n *\n * - A bearer key is never accepted as a positional argument by default. `--bearer-key` exists for\n *   scripts that have no other choice, but the documented paths are `--bearer-key-stdin` and the\n *   hidden interactive prompt, because a command-line argument lands in shell history and in `ps`.\n * - \"Restore inheritance\" and \"override with nothing\" are separate actions for the extra headers, so\n *   a user can drop the shared `x-workspace-id` for one Agent without deleting it for everyone.\n */\n\nexport interface McpCreateOptions {\n  name: string;\n  url: string;\n  defaultAuthKind?: MCPAuthKind;\n  authHeader?: string;\n  authScheme?: string;\n  extraHeader?: string[];\n}\n\nexport async function runMcpCreate(\n  options: McpCreateOptions,\n  dependencies: McpCommandDependencies = {},\n): Promise<MCPServer> {\n  const { api, accessToken } = await resolveMcpCommandContext(dependencies);\n  const headers = extraHeadersFrom(options.extraHeader);\n  const input: CreateMCPServerRequest = {\n    name: options.name,\n    url: options.url,\n    defaultAuthKind: options.defaultAuthKind ?? \"oauth\",\n    ...(options.authHeader === undefined ? {} : { authHeader: options.authHeader }),\n    ...(options.authScheme === undefined ? {} : { authScheme: options.authScheme }),\n    ...(headers === undefined ? {} : { extraHeaders: headers }),\n  };\n  return await api.createMcpServer(accessToken, input);\n}\n\nexport async function runMcpList(options: McpCommandDependencies = {}): Promise<MCPServer[]> {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  return (await api.listMcpServers(accessToken)).servers;\n}\n\nexport async function runMcpShow(\n  reference: string,\n  options: McpCommandDependencies & { agentId?: string } = {},\n): Promise<{ server: MCPServerDetail; agentView?: Awaited<ReturnType<typeof loadAgentView>> }> {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  const server = await resolveMcpServer(reference, options);\n  const detail = await api.getMcpServer(accessToken, server.id);\n  if (!options.agentId) return { server: detail };\n  return { server: detail, agentView: await loadAgentView(server.id, options.agentId, api, accessToken) };\n}\n\nasync function loadAgentView(\n  mcpServerId: string,\n  agentId: string,\n  api: Awaited<ReturnType<typeof resolveMcpCommandContext>>[\"api\"],\n  accessToken: string,\n) {\n  const { servers } = await api.listAgentMcpServers(accessToken, agentId);\n  const entry = servers.find((candidate) => candidate.mcpServerId === mcpServerId);\n  if (!entry) throw new Error(\"The Agent does not mount this MCP Server\");\n  return entry;\n}\n\nexport interface McpUpdateOptions {\n  description?: string;\n  url?: string;\n  defaultAuthKind?: MCPAuthKind;\n  authHeader?: string;\n  authScheme?: string;\n  extraHeader?: string[];\n  /**\n   * Both spellings clear the definition's extra headers, and they are one action here.\n   *\n   * At the Agent level the pair is genuinely different — `null` restores inheritance while `{}`\n   * means \"send none\" — but the shared definition has no inherited value to restore, so its\n   * `extra_headers` is never null and \"clear\" and \"empty\" are the same write. The flag is still\n   * accepted so a user who learned the Agent-level vocabulary is not surprised by an error.\n   */\n  clearExtraHeaders?: boolean;\n  emptyExtraHeaders?: boolean;\n  expectedRevision?: number;\n}\n\nexport async function runMcpUpdate(\n  reference: string,\n  options: McpUpdateOptions,\n  dependencies: McpCommandDependencies = {},\n): Promise<MCPServer> {\n  const { api, accessToken } = await resolveMcpCommandContext(dependencies);\n  const server = await resolveMcpServer(reference, dependencies);\n  const headers = extraHeadersFrom(options.extraHeader);\n  const input: UpdateMCPServerRequest = {\n    expectedRevision: options.expectedRevision ?? server.revision,\n    ...(options.description === undefined ? {} : { description: options.description }),\n    ...(options.url === undefined ? {} : { url: options.url }),\n    ...(options.defaultAuthKind === undefined ? {} : { defaultAuthKind: options.defaultAuthKind }),\n    ...(options.authHeader === undefined ? {} : { authHeader: options.authHeader }),\n    ...(options.authScheme === undefined ? {} : { authScheme: options.authScheme }),\n    ...(headers === undefined ? {} : { extraHeaders: headers }),\n    ...(options.clearExtraHeaders === true || options.emptyExtraHeaders === true ? { clearExtraHeaders: true } : {}),\n  };\n  return await api.updateMcpServer(accessToken, server.id, input);\n}\n\nexport async function runMcpRemove(reference: string, options: McpCommandDependencies = {}): Promise<MCPServer> {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  const server = await resolveMcpServer(reference, options);\n  await api.removeMcpServer(accessToken, server.id);\n  return server;\n}\n\nexport async function runAgentMcpList(agentId: string, options: McpCommandDependencies = {}) {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  return (await api.listAgentMcpServers(accessToken, agentId)).servers;\n}\n\nexport async function runAgentMcpAvailable(agentId: string, options: McpCommandDependencies = {}) {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  return (await api.listAvailableMcpServers(accessToken, agentId)).servers;\n}\n\nexport async function runAgentMcpAttach(\n  agentId: string,\n  reference: string,\n  enabled: boolean,\n  options: McpCommandDependencies = {},\n) {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  const server = await resolveMcpServer(reference, options);\n  return await api.attachMcpServer(accessToken, agentId, { mcpServerId: server.id, enabled });\n}\n\nexport async function runAgentMcpDetach(\n  agentId: string,\n  reference: string,\n  options: McpCommandDependencies = {},\n): Promise<void> {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  const server = await resolveMcpServer(reference, options);\n  await api.detachMcpServer(accessToken, agentId, server.id);\n}\n\nexport async function runAgentMcpEnable(\n  agentId: string,\n  reference: string,\n  enabled: boolean,\n  options: McpCommandDependencies = {},\n) {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  const server = await resolveMcpServer(reference, options);\n  return await api.updateAgentMcpServer(accessToken, agentId, server.id, { enabled });\n}\n\nexport interface AgentMcpConfigOptions {\n  url?: string;\n  authHeader?: string;\n  authScheme?: string;\n  extraHeader?: string[];\n  clearUrl?: boolean;\n  clearAuthHeader?: boolean;\n  clearAuthScheme?: boolean;\n  clearExtraHeaders?: boolean;\n  emptyExtraHeaders?: boolean;\n}\n\n/**\n * Write this Agent's overrides. `--clear-*` restores inheritance, while `--empty-extra-headers`\n * records an explicit empty set; the two are different states and the API models both.\n */\nexport async function runAgentMcpConfig(\n  agentId: string,\n  reference: string,\n  options: AgentMcpConfigOptions,\n  dependencies: McpCommandDependencies = {},\n) {\n  const { api, accessToken } = await resolveMcpCommandContext(dependencies);\n  const server = await resolveMcpServer(reference, dependencies);\n  const headers = extraHeadersFrom(options.extraHeader);\n  const input: UpdateMCPBindingRequest = {\n    ...(options.url === undefined ? {} : { url: options.url }),\n    ...(options.clearUrl === true ? { clearUrl: true } : {}),\n    ...(options.authHeader === undefined ? {} : { authHeader: options.authHeader }),\n    ...(options.clearAuthHeader === true ? { clearAuthHeader: true } : {}),\n    ...(options.authScheme === undefined ? {} : { authScheme: options.authScheme }),\n    ...(options.clearAuthScheme === true ? { clearAuthScheme: true } : {}),\n    ...(headers === undefined ? {} : { extraHeaders: headers }),\n    ...(options.clearExtraHeaders === true ? { clearExtraHeaders: true } : {}),\n    ...(options.emptyExtraHeaders === true ? { emptyExtraHeaders: true } : {}),\n  };\n  return await api.updateAgentMcpServer(accessToken, agentId, server.id, input);\n}\n\n/**\n * Write this Agent's Bearer key (or declare it anonymous). Exactly one of the three key sources is\n * used, and the interactive prompt is preferred over `--bearer-key` because an argument is visible\n * to any other process on the machine and lands in the shell's history file.\n */\nexport async function runMcpUse(\n  agentId: string,\n  reference: string,\n  input: { kind: \"bearer\" | \"none\"; bearerKey?: string },\n  dependencies: McpCommandDependencies = {},\n) {\n  const { api, accessToken } = await resolveMcpCommandContext(dependencies);\n  const server = await resolveMcpServer(reference, dependencies);\n  const body: SetMCPAuthorizationRequest =\n    input.kind === \"bearer\" ? { kind: \"bearer\", bearerKey: requireKey(input.bearerKey) } : { kind: \"none\" };\n  return await api.setMcpAuthorization(accessToken, agentId, server.id, body);\n}\n\nfunction requireKey(value: string | undefined): string {\n  if (!value || value.length === 0) throw new Error(\"A bearer key is required for a bearer authorization\");\n  return value;\n}\n\nexport async function readBearerKeyFromStdin(): Promise<string> {\n  const chunks: Buffer[] = [];\n  for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));\n  const value = Buffer.concat(chunks).toString(\"utf8\").trim();\n  if (value.length === 0) throw new Error(\"No bearer key was read from standard input\");\n  return value;\n}\n\n/** A hidden interactive read: the typed key is never echoed and never enters the process arguments. */\nexport async function promptForBearerKey(): Promise<string> {\n  const input = process.stdin;\n  const output = process.stdout;\n  if (!input.isTTY || !output.isTTY) {\n    throw new Error(\"A bearer key is required; pipe it with --bearer-key-stdin when not interactive\");\n  }\n  output.write(\"Bearer key: \");\n  const wasRaw = input.isRaw;\n  input.setRawMode(true);\n  input.resume();\n  try {\n    const key = await readHiddenLine(input);\n    output.write(\"\\n\");\n    if (key.length === 0) throw new Error(\"No bearer key was entered\");\n    return key;\n  } catch (error) {\n    output.write(\"\\n\");\n    throw error;\n  } finally {\n    input.setRawMode(wasRaw);\n    input.pause();\n  }\n}\n\n/**\n * Accumulate raw-mode keystrokes until Enter. Escapes are handled by code unit, because in raw mode\n * each key arrives as its own escape sequence: `\\u007f` is the terminal's backspace, and `\\u0003` is\n * the user aborting rather than a character to store.\n */\nasync function readHiddenLine(input: NodeJS.ReadStream): Promise<string> {\n  return await new Promise<string>((resolve, reject) => {\n    let value = \"\";\n    const onData = (chunk: Buffer) => {\n      const outcome = consumeKeystrokes(value, chunk.toString(\"utf8\"));\n      value = outcome.value;\n      if (outcome.done === undefined) return;\n      input.off(\"data\", onData);\n      if (outcome.done instanceof Error) reject(outcome.done);\n      else resolve(outcome.value);\n    };\n    input.on(\"data\", onData);\n  });\n}\n\ntype KeystrokeOutcome = { value: string; done?: undefined } | { value: string; done: Error | true };\n\nfunction consumeKeystrokes(current: string, chunk: string): KeystrokeOutcome {\n  let value = current;\n  for (const character of chunk) {\n    if (character === \"\\u0003\") return { value, done: new Error(\"Cancelled\") };\n    if (character === \"\\r\" || character === \"\\n\") return { value, done: true };\n    if (character === \"\\u007f\") value = value.slice(0, -1);\n    else value += character;\n  }\n  return { value };\n}\n\nexport async function runMcpAuthorize(\n  agentId: string,\n  reference: string,\n  options: { scopes?: string[]; noWait?: boolean },\n  dependencies: McpCommandDependencies & {\n    /**\n     * Called the moment the URL exists, before any waiting.\n     *\n     * The wait below can last the flow's full ten minutes, and the URL is the one thing the user\n     * must act on to make it end. Reporting it only after the wait — which is what happened when the\n     * command returned a single formatted result — meant the default invocation printed nothing at\n     * all and then timed out, so `--no-wait` was the only usable form.\n     */\n    onStarted?: (started: StartMCPOAuthResponse) => void;\n  } = {},\n): Promise<{ server: MCPServer; started: StartMCPOAuthResponse; probe?: MCPProbeResponse }> {\n  const { api, accessToken } = await resolveMcpCommandContext(dependencies);\n  const server = await resolveMcpServer(reference, dependencies);\n  const started = await api.startMcpOAuth(accessToken, agentId, server.id, {\n    ...(options.scopes ? { scopes: options.scopes } : {}),\n  });\n  dependencies.onStarted?.(started);\n  if (options.noWait) return { server, started };\n  const probe = await waitForAuthorization(api, accessToken, agentId, server.id);\n  return { server, started, ...(probe ? { probe } : {}) };\n}\n\n/**\n * Poll until the row is authorized and probed, or the state's own 10-minute lifetime lapses. The\n * timeout matches the flow's expiry rather than being an independent guess, so the CLI never waits\n * on a state the server has already discarded.\n */\nasync function waitForAuthorization(\n  api: Awaited<ReturnType<typeof resolveMcpCommandContext>>[\"api\"],\n  accessToken: string,\n  agentId: string,\n  mcpServerId: string,\n  timeoutMs = 10 * 60 * 1000,\n  intervalMs = 2_000,\n): Promise<MCPProbeResponse | undefined> {\n  const deadline = Date.now() + timeoutMs;\n  for (;;) {\n    const { servers } = await api.listAgentMcpServers(accessToken, agentId);\n    const entry = servers.find((candidate) => candidate.mcpServerId === mcpServerId);\n    const authorization = entry?.authorization;\n    /*\n     * A failure code ends the wait.\n     *\n     * A denial or a terminal exchange failure on a row that already held a working credential leaves\n     * `status: active` deliberately — the old credential is still valid and must not be destroyed — so\n     * `status` alone cannot tell this wait that the flow ended. `failureCode` is what records it.\n     */\n    if (authorization?.failureCode) {\n      throw new Error(`The authorization failed with ${authorization.failureCode}`);\n    }\n    if (authorization?.status === \"active\" && authorization.probeState !== \"pending\") {\n      return {\n        probeState: authorization.probeState,\n        probeError: authorization.probeError,\n        toolsCount: authorization.toolsCount,\n        toolsTruncated: authorization.toolsTruncated,\n        protocolEra: entry?.snapshot?.protocolEra ?? null,\n        protocolVersion: entry?.snapshot?.protocolVersion ?? null,\n      };\n    }\n    if (authorization && authorization.status !== \"pending\" && authorization.status !== \"active\") {\n      throw new Error(`The authorization ended in state \"${authorization.status}\"`);\n    }\n    if (Date.now() >= deadline) throw new Error(\"Timed out waiting for the authorization to finish\");\n    await new Promise((resolve) => setTimeout(resolve, intervalMs));\n  }\n}\n\nexport async function runMcpRevoke(agentId: string, reference: string, options: McpCommandDependencies = {}) {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  const server = await resolveMcpServer(reference, options);\n  return await api.revokeMcpAuthorization(accessToken, agentId, server.id);\n}\n\nexport async function runMcpProbe(\n  agentId: string,\n  reference: string,\n  options: McpCommandDependencies = {},\n): Promise<MCPProbeResponse> {\n  const { api, accessToken } = await resolveMcpCommandContext(options);\n  const server = await resolveMcpServer(reference, options);\n  return await api.probeMcpServer(accessToken, agentId, server.id);\n}\n","import type { MCPAuthKind } from \"@opentag/shared\";\n\n/**\n * The raw Commander option bags, mapped into the typed inputs the core operations take.\n *\n * These live apart from the command wiring so each mapping is a plain function of its options: the\n * command actions stay one call each, and an option's absence-versus-empty distinction is stated in\n * one place instead of being re-derived inline for every command.\n */\n\nexport interface RawOptions {\n  [key: string]: unknown;\n}\n\n/** Repeated `--extra-header <name=value>` flags arrive as a growing array. */\nexport function collectOption(value: string, previous: string[]): string[] {\n  return [...previous, value];\n}\n\nexport function optionalString(value: unknown): string | undefined {\n  return value === undefined ? undefined : String(value);\n}\n\nexport function optionalNumber(value: unknown): number | undefined {\n  return value === undefined ? undefined : Number(value);\n}\n\nexport function optionalList(values: unknown): string[] | undefined {\n  return Array.isArray(values) ? (values as string[]) : undefined;\n}\n\nexport function authKindOf(value: unknown): MCPAuthKind {\n  if (value === \"none\" || value === \"bearer\" || value === \"oauth\") return value;\n  throw new Error(\"--default-auth must be oauth, bearer, or none\");\n}\n\nexport function splitList(value: string): string[] {\n  return value\n    .split(\",\")\n    .map((entry) => entry.trim())\n    .filter((entry) => entry.length > 0);\n}\n\n/**\n * Resolve how `mcp use` should obtain the Bearer key: an explicit `--kind none` declaration, a piped\n * stdin read, the hidden prompt, or — as a last resort — the visible `--bearer-key` argument.\n *\n * The order is deliberate: the piped and prompted paths are preferred over the argument because an\n * argument is readable by every other process on the machine and lands in the shell's history file,\n * and a caller that asked for `none` while also supplying a key is confused rather than intentional.\n */\nexport function resolveBearerKeySource(options: {\n  kind?: unknown;\n  bearerKey?: unknown;\n  bearerKeyStdin?: unknown;\n}): { kind: \"none\" } | { kind: \"bearer\"; source: \"stdin\" | \"prompt\" | \"argument\"; value?: string } {\n  if (options.kind === \"none\") {\n    if (options.bearerKey !== undefined || options.bearerKeyStdin === true) {\n      throw new Error(\"An anonymous authorization carries no key\");\n    }\n    return { kind: \"none\" };\n  }\n  /*\n   * `oauth` is not this command's kind. It used to fall through to Bearer, so\n   * `mcp use --kind oauth --bearer-key <value>` wrote a Bearer key while the caller believed they\n   * were starting an OAuth flow — a silent kind change, which is exactly what this feature's per-Agent\n   * authorization must not do. `mcp authorize` owns OAuth and is named in the message.\n   */\n  if (options.kind !== undefined && options.kind !== \"bearer\") {\n    throw new Error(\"--kind must be bearer or none; use `mcp authorize` to start an OAuth flow\");\n  }\n  if (options.bearerKeyStdin === true) return { kind: \"bearer\", source: \"stdin\" };\n  if (options.bearerKey === undefined) return { kind: \"bearer\", source: \"prompt\" };\n  return { kind: \"bearer\", source: \"argument\", value: String(options.bearerKey) };\n}\n\n/** Spread-friendly form: the key is present only when the flag was given. */\nexport function whenDefined<T>(key: string, value: T | undefined): Record<string, T> {\n  return value === undefined ? {} : { [key]: value };\n}\n\nexport function whenTrue(key: string, value: unknown): Record<string, true> {\n  return value === true ? { [key]: true } : {};\n}\n","import type { MCPAgentServer } from \"@opentag/shared\";\nimport type { Command } from \"commander\";\nimport { executeCommand } from \"../../core/command/policy.js\";\nimport {\n  promptForBearerKey,\n  readBearerKeyFromStdin,\n  runAgentMcpAttach,\n  runAgentMcpConfig,\n  runAgentMcpDetach,\n  runAgentMcpEnable,\n  runAgentMcpList,\n  runMcpAuthorize,\n  runMcpCreate,\n  runMcpList,\n  runMcpProbe,\n  runMcpRemove,\n  runMcpRevoke,\n  runMcpShow,\n  runMcpUpdate,\n  runMcpUse,\n} from \"../../core/mcp/operations.js\";\nimport {\n  formatAgentMcpServers,\n  formatAgentServerRow,\n  formatAuthorization,\n  formatMcpServer,\n  formatMcpServerList,\n  formatMcpShow,\n  formatProbe,\n} from \"../../core/mcp/shared.js\";\nimport {\n  authKindOf,\n  collectOption as collect,\n  optionalList,\n  optionalNumber,\n  optionalString,\n  resolveBearerKeySource,\n  splitList,\n  whenDefined,\n  whenTrue,\n} from \"./options.js\";\n\n/**\n * `mcp` — the Account-level Server pool and per-Agent authorization.\n *\n * The Server definition carries no credential and no switch, so there is no `--enable`/`--disable`\n * here: enabling happens per Agent, under `agent mcp`. Every authorization command names its Agent,\n * because authorization is strictly per Agent and there is no Account-level fallback to write to.\n */\nexport function registerMcpCommand(program: Command): void {\n  const mcp = program.command(\"mcp\").description(\"Manage MCP (Model Context Protocol) Servers\");\n\n  mcp\n    .command(\"add\")\n    .description(\"Register a shared MCP Server definition\")\n    .requiredOption(\"--name <name>\", \"unique handle within the Account: lowercase letters, numbers, and hyphens\")\n    .requiredOption(\"--url <url>\", \"the MCP endpoint\")\n    .option(\"--default-auth <kind>\", \"prefill for a new authorization: oauth | bearer | none\", \"oauth\")\n    /*\n     * No `--description` on create: a definition's description is what a probe discovered, and\n     * nothing can be probed before the definition exists. The first successful probe fills it in;\n     * `mcp update --description` is how an operator replaces it.\n     */\n    .option(\"--auth-header <name>\", \"authorization header name used by a bearer authorization\")\n    .option(\"--auth-scheme <scheme>\", \"scheme prefixed to the bearer value; empty sends it verbatim\")\n    .option(\"--extra-header <name=value>\", \"additional static header sent on every request (repeatable)\", collect, [])\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: Record<string, unknown>) => {\n      process.exitCode = await executeCommand(\n        () =>\n          runMcpCreate({\n            name: String(options.name),\n            url: String(options.url),\n            defaultAuthKind: authKindOf(options.defaultAuth),\n            ...whenDefined(\"authHeader\", optionalString(options.authHeader)),\n            ...whenDefined(\"authScheme\", optionalString(options.authScheme)),\n            ...whenDefined(\"extraHeader\", optionalList(options.extraHeader)),\n          }),\n        { json: options.json === true, formatValue: formatMcpServer, phase: \"request\" },\n      );\n    });\n\n  mcp\n    .command(\"list\")\n    .description(\"List the Account's MCP Server definitions\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(() => runMcpList(), {\n        json: options.json === true,\n        formatValue: formatMcpServerList,\n        phase: \"request\",\n      });\n    });\n\n  mcp\n    .command(\"show <server>\")\n    .description(\"Show one Server definition, and one Agent's effective view with --agent\")\n    .option(\"--agent <agent-id>\", \"also show this Agent's effective configuration and overrides\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (server: string, options: { agent?: string; json?: boolean }) => {\n      process.exitCode = await executeCommand(\n        () => runMcpShow(server, options.agent === undefined ? {} : { agentId: options.agent }),\n        {\n          json: options.json === true,\n          formatValue: (value) => formatMcpShow(value),\n          phase: \"request\",\n        },\n      );\n    });\n\n  mcp\n    .command(\"update <server>\")\n    .description(\"Edit the shared definition, which affects every Agent that mounts it\")\n    .option(\"--description <text>\", \"override the probed description, at most 1024 bytes\")\n    .option(\"--url <url>\", \"the MCP endpoint\")\n    .option(\"--default-auth <kind>\", \"prefill for a new authorization: oauth | bearer | none\")\n    .option(\"--auth-header <name>\", \"authorization header name used by a bearer authorization\")\n    .option(\"--auth-scheme <scheme>\", \"scheme prefixed to the bearer value; empty sends it verbatim\")\n    .option(\"--extra-header <name=value>\", \"additional static header (repeatable)\", collect, [])\n    .option(\"--clear-extra-headers\", \"remove the definition's extra headers\")\n    .option(\"--empty-extra-headers\", \"same as --clear-extra-headers at the definition level\")\n    .option(\"--expected-revision <n>\", \"require this revision, for optimistic concurrency\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (server: string, options: Record<string, unknown>) => {\n      process.exitCode = await executeCommand(\n        () =>\n          runMcpUpdate(server, {\n            ...whenDefined(\"description\", optionalString(options.description)),\n            ...whenDefined(\"url\", optionalString(options.url)),\n            ...whenDefined(\n              \"defaultAuthKind\",\n              options.defaultAuth === undefined ? undefined : authKindOf(options.defaultAuth),\n            ),\n            ...whenDefined(\"authHeader\", optionalString(options.authHeader)),\n            ...whenDefined(\"authScheme\", optionalString(options.authScheme)),\n            ...whenDefined(\"extraHeader\", optionalList(options.extraHeader)),\n            ...whenTrue(\"clearExtraHeaders\", options.clearExtraHeaders),\n            ...whenTrue(\"emptyExtraHeaders\", options.emptyExtraHeaders),\n            ...whenDefined(\"expectedRevision\", optionalNumber(options.expectedRevision)),\n          }),\n        { json: options.json === true, formatValue: formatMcpServer, phase: \"request\" },\n      );\n    });\n\n  mcp\n    .command(\"remove <server>\")\n    .description(\"Delete a Server definition; refused while any Agent still mounts it\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (server: string, options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(\n        async () => {\n          const removed = await runMcpRemove(server);\n          return `Removed MCP Server ${removed.name}`;\n        },\n        { json: options.json === true, phase: \"request\" },\n      );\n    });\n\n  mcp\n    .command(\"use <server>\")\n    .description(\"Authorize one Agent with a Bearer key, or declare it anonymous\")\n    .requiredOption(\"--agent <agent-id>\", \"the Agent this authorization belongs to\")\n    .option(\"--kind <kind>\", \"bearer | none\", \"bearer\")\n    .option(\"--bearer-key-stdin\", \"read the key from standard input (preferred)\")\n    .option(\"--bearer-key <value>\", \"UNSAFE: the key as an argument, visible in shell history and ps\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (server: string, options: Record<string, unknown>) => {\n      process.exitCode = await executeCommand(() => runMcpUseWithOptions(String(options.agent), server, options), {\n        json: options.json === true,\n        formatValue: formatAgentServerRow,\n        phase: \"request\",\n      });\n    });\n\n  mcp\n    .command(\"authorize <server>\")\n    .description(\"Authorize one Agent by OAuth, or declare it anonymous\")\n    .requiredOption(\"--agent <agent-id>\", \"the Agent this authorization belongs to\")\n    .option(\"--kind <kind>\", \"oauth | none; `none` declares an anonymous authorization instead\", \"oauth\")\n    .option(\"--scopes <list>\", \"comma-separated scopes to request\")\n    .option(\"--no-wait\", \"return as soon as the URL is issued, without waiting for the probe\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (server: string, options: Record<string, unknown>) => {\n      /*\n       * `oauth` and `none` are the two kinds this command owns. `none` is an ordinary pick here\n       * because it needs nothing from the user, whereas a Bearer authorization needs a key and so\n       * has its own command. Both are real rows, so neither is reachable only by implication.\n       */\n      if (options.kind !== undefined && options.kind !== \"oauth\" && options.kind !== \"none\") {\n        process.exitCode = await executeCommand(\n          async () => {\n            throw new Error(\"--kind must be oauth or none; use `mcp use` to write a Bearer key\");\n          },\n          { json: options.json === true, phase: \"validation\" },\n        );\n        return;\n      }\n      if (options.kind === \"none\") {\n        process.exitCode = await executeCommand(() => runMcpUse(String(options.agent), server, { kind: \"none\" }), {\n          json: options.json === true,\n          formatValue: formatAgentServerRow,\n          phase: \"request\",\n        });\n        return;\n      }\n      process.exitCode = await executeCommand(\n        () =>\n          runMcpAuthorize(\n            String(options.agent),\n            server,\n            {\n              ...whenDefined(\"scopes\", options.scopes === undefined ? undefined : splitList(String(options.scopes))),\n              ...(options.wait === false ? { noWait: true } : {}),\n            },\n            {\n              /*\n               * Printed to stderr as soon as it exists, because the wait that follows can run the\n               * flow's full ten minutes and this URL is what the user must open to end it. stderr\n               * rather than stdout so `--json` still emits exactly one JSON document on stdout.\n               */\n              onStarted: (started) => {\n                process.stderr.write(`Open this URL to authorize:\\n${started.authorizationUrl}\\n`);\n              },\n            },\n          ),\n        { json: options.json === true, formatValue: formatAuthorization, phase: \"request\" },\n      );\n    });\n\n  mcp\n    .command(\"revoke <server>\")\n    .description(\"Drop one Agent's credential for a Server, keeping the mount\")\n    .requiredOption(\"--agent <agent-id>\", \"the Agent whose authorization is dropped\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (server: string, options: Record<string, unknown>) => {\n      process.exitCode = await executeCommand(() => runMcpRevoke(String(options.agent), server), {\n        json: options.json === true,\n        formatValue: formatAgentServerRow,\n        phase: \"request\",\n      });\n    });\n\n  mcp\n    .command(\"probe <server>\")\n    .description(\"Re-probe one Agent's credential for a Server, refreshing its tool snapshot\")\n    .requiredOption(\"--agent <agent-id>\", \"the Agent whose credential is used\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (server: string, options: Record<string, unknown>) => {\n      process.exitCode = await executeCommand(() => runMcpProbe(String(options.agent), server), {\n        json: options.json === true,\n        formatValue: formatProbe,\n        phase: \"request\",\n      });\n    });\n}\n\n/** `agent mcp` — the per-Agent mount, its enable switch, and its overrides. */\nexport function registerAgentMcpCommands(agentCommand: Command): void {\n  const mcp = agentCommand.command(\"mcp\").description(\"Manage this Agent's MCP Servers\");\n\n  mcp\n    .command(\"list <agent-id>\")\n    .description(\"List the MCP Servers this Agent mounts, with its four independent states\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId: string, options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(() => runAgentMcpList(agentId), {\n        json: options.json === true,\n        formatValue: formatAgentMcpServers,\n        phase: \"request\",\n      });\n    });\n\n  mcp\n    .command(\"attach <agent-id> <server>\")\n    .description(\"Mount a Server for this Agent; it may be authorized afterwards\")\n    .option(\"--disabled\", \"mount it without enabling it\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId: string, server: string, options: { disabled?: boolean; json?: boolean }) => {\n      process.exitCode = await executeCommand(() => runAgentMcpAttach(agentId, server, options.disabled !== true), {\n        json: options.json === true,\n        formatValue: formatAgentServerRow,\n        phase: \"request\",\n      });\n    });\n\n  mcp\n    .command(\"detach <agent-id> <server>\")\n    .description(\"Unmount a Server from this Agent, dropping its credential for this Agent\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId: string, server: string, options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(\n        async () => {\n          await runAgentMcpDetach(agentId, server);\n          return `Detached ${server} from Agent ${agentId}`;\n        },\n        { json: options.json === true, phase: \"request\" },\n      );\n    });\n\n  for (const [name, enabled] of [\n    [\"enable\", true],\n    [\"disable\", false],\n  ] as const) {\n    mcp\n      .command(`${name} <agent-id> <server>`)\n      .description(\n        enabled\n          ? \"Enable a mounted Server; the credential is untouched and stays usable\"\n          : \"Disable a mounted Server; the mount and credential are kept\",\n      )\n      .option(\"--json\", \"print JSON\")\n      .action(async (agentId: string, server: string, options: { json?: boolean }) => {\n        process.exitCode = await executeCommand(() => runAgentMcpEnable(agentId, server, enabled), {\n          json: options.json === true,\n          formatValue: formatAgentServerRow,\n          phase: \"request\",\n        });\n      });\n  }\n\n  mcp\n    .command(\"config <agent-id> <server>\")\n    .description(\"Write this Agent's overrides of the shared definition\")\n    .option(\"--url <url>\", \"override the endpoint for this Agent\")\n    .option(\"--auth-header <name>\", \"override the bearer authorization header name\")\n    .option(\"--auth-scheme <scheme>\", \"override the bearer scheme; an empty value sends the key verbatim\")\n    .option(\"--extra-header <name=value>\", \"override the extra headers (repeatable)\", collect, [])\n    .option(\"--clear-url\", \"restore the shared endpoint\")\n    .option(\"--clear-auth-header\", \"restore the shared authorization header name\")\n    .option(\"--clear-auth-scheme\", \"restore the shared authorization scheme\")\n    .option(\"--clear-extra-headers\", \"inherit the shared extra headers again\")\n    .option(\"--empty-extra-headers\", \"send no extra headers for this Agent, without touching the shared set\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId: string, server: string, options: Record<string, unknown>) => {\n      process.exitCode = await executeCommand(\n        () =>\n          runAgentMcpConfig(agentId, server, {\n            ...whenDefined(\"url\", optionalString(options.url)),\n            ...whenDefined(\"authHeader\", optionalString(options.authHeader)),\n            ...whenDefined(\"authScheme\", optionalString(options.authScheme)),\n            ...whenDefined(\"extraHeader\", optionalList(options.extraHeader)),\n            ...whenTrue(\"clearUrl\", options.clearUrl),\n            ...whenTrue(\"clearAuthHeader\", options.clearAuthHeader),\n            ...whenTrue(\"clearAuthScheme\", options.clearAuthScheme),\n            ...whenTrue(\"clearExtraHeaders\", options.clearExtraHeaders),\n            ...whenTrue(\"emptyExtraHeaders\", options.emptyExtraHeaders),\n          }),\n        { json: options.json === true, formatValue: formatAgentServerRow, phase: \"request\" },\n      );\n    });\n}\n\n/**\n * `mcp use`: resolve the key source, read the key with the chosen method, then hand one typed call to\n * the core operation, so the command action stays a single expression.\n */\nasync function runMcpUseWithOptions(\n  agentId: string,\n  server: string,\n  options: Record<string, unknown>,\n): Promise<MCPAgentServer> {\n  const source = resolveBearerKeySource(options);\n  if (source.kind === \"none\") return await runMcpUse(agentId, server, { kind: \"none\" });\n  if (source.source === \"stdin\") {\n    return await runMcpUse(agentId, server, { kind: \"bearer\", bearerKey: await readBearerKeyFromStdin() });\n  }\n  if (source.source === \"prompt\") {\n    return await runMcpUse(agentId, server, { kind: \"bearer\", bearerKey: await promptForBearerKey() });\n  }\n  return await runMcpUse(agentId, server, { kind: \"bearer\", bearerKey: source.value as string });\n}\n","import type { AgentAdminConfig, ListAgentsResponse } from \"@opentag/shared\";\nimport type { AgentBindResult, AgentCreateResult } from \"./mutations.js\";\n\nexport function formatAgentCreated(result: AgentCreateResult): string {\n  const created = `Created Agent ${result.agent.id} (${result.agent.name})`;\n  return result.agent.computerId\n    ? `${created} on Computer ${result.agent.computerId}`\n    : `${created} without a Computer`;\n}\n\nexport function formatAgentBound(result: AgentBindResult): string {\n  return `Bound Agent ${result.agent.id} (${result.agent.name}) to Computer ${result.agent.computerId}`;\n}\n\n/**\n * How an absent Computer is written in the machine-readable output. An empty field reads as a value\n * that went missing; an Agent with no Computer is a stated fact, and it is the one thing about the\n * Agent that a reader of this output most needs to see. It cannot be mistaken for an identifier.\n */\nconst NO_COMPUTER = \"none\";\n\nexport function formatAgentList(response: ListAgentsResponse): string {\n  if (response.agents.length === 0) return \"No Agents registered\";\n  return response.agents\n    .map((agent) =>\n      [\n        agent.name,\n        agent.id,\n        agent.displayName,\n        agent.status,\n        agent.runtimeProvider,\n        agent.computer?.computerId ?? NO_COMPUTER,\n        agent.receiveMode,\n      ].join(\"\\t\"),\n    )\n    .join(\"\\n\");\n}\n\nexport function formatAgent(agent: AgentAdminConfig): string {\n  return [\n    `id\\t${agent.id}`,\n    `name\\t${agent.name}`,\n    `displayName\\t${agent.displayName}`,\n    `createdByUserId\\t${agent.createdByUserId}`,\n    `computerId\\t${agent.computerId ?? NO_COMPUTER}`,\n    `runtimeProvider\\t${agent.runtimeProvider}`,\n    `receiveMode\\t${agent.receiveMode}`,\n    `status\\t${agent.status}`,\n    `revision\\t${agent.revision}`,\n    `runtimeConfig.revision\\t${agent.runtimeConfig.revision}`,\n    `runtimeConfig.model\\t${agent.runtimeConfig.model ?? \"\"}`,\n    `runtimeConfig.reasoningEffort\\t${agent.runtimeConfig.reasoningEffort ?? \"\"}`,\n    `runtimeConfig.instructions\\t${JSON.stringify(agent.runtimeConfig.instructions)}`,\n    `runtimeConfig.maxDurationMs\\t${agent.runtimeConfig.maxDurationMs ?? \"\"}`,\n  ].join(\"\\n\");\n}\n","import type { OpenTagApi } from \"@opentag/client\";\nimport { resolveCommandContext } from \"../command/context.js\";\n\nexport interface AgentApiClient\n  extends Pick<\n    OpenTagApi,\n    | \"createAgent\"\n    | \"listAgents\"\n    | \"getAgent\"\n    | \"getAgentConfig\"\n    | \"updateAgent\"\n    | \"suspendAgent\"\n    | \"reactivateAgent\"\n    | \"rebindAgentComputer\"\n    | \"deleteAgent\"\n    | \"listAccountComputers\"\n    | \"me\"\n    | \"getAgentImBinding\"\n    | \"getAgentImBindingConfig\"\n    | \"createFeishuSetupAttempt\"\n    | \"getFeishuSetupAttempt\"\n    | \"cancelFeishuSetupAttempt\"\n    | \"getImBindingDiagnostics\"\n    | \"disableImBinding\"\n  > {}\n\nexport interface AgentCommandDependencies {\n  accessToken?: string;\n  api?: AgentApiClient;\n  home?: string;\n}\n\nexport async function resolveAgentCommandContext(\n  options: AgentCommandDependencies,\n): Promise<{ accessToken: string; api: AgentApiClient }> {\n  if ((options.api && !options.accessToken) || (options.accessToken && !options.api)) {\n    throw new Error(\"Agent command test dependencies must provide both api and accessToken\");\n  }\n  const context = await resolveCommandContext({\n    accessToken: options.accessToken,\n    api: options.api as OpenTagApi | undefined,\n    home: options.home,\n    requireAuth: true,\n  });\n  if (!context.api || !context.accessToken) throw new Error(\"Command context did not resolve an authenticated API\");\n  return { api: context.api, accessToken: context.accessToken };\n}\n","import { readFile } from \"node:fs/promises\";\nimport type { AccountComputerSummary, AgentAdminConfig, ListAccountComputersResponse } from \"@opentag/shared\";\nimport {\n  CreateAgentRequestSchema,\n  CreateAgentRuntimeConfigSchema,\n  type UpdateAgentRequest,\n  UpdateAgentRequestSchema,\n  UpdateAgentRuntimeConfigSchema,\n} from \"@opentag/shared\";\nimport { type AgentCommandDependencies, resolveAgentCommandContext } from \"./context.js\";\n\nexport interface AgentCreateOptions extends AgentCommandDependencies {\n  computerId?: string;\n  displayName: string;\n  instructions?: string;\n  instructionsFile?: string;\n  maxDurationMs?: number | string;\n  model?: string;\n  name: string;\n  reasoningEffort?: string;\n  runtimeProvider: string;\n}\n\nexport interface AgentCreateResult {\n  agent: AgentAdminConfig;\n  warning?: string;\n}\n\nexport interface AgentBindOptions extends AgentCommandDependencies {\n  computerId?: string;\n}\n\nexport interface AgentBindResult {\n  agent: AgentAdminConfig;\n  warning?: string;\n}\n\nexport interface AgentUpdateOptions extends AgentCommandDependencies {\n  clearMaxDuration?: boolean;\n  clearModel?: boolean;\n  clearReasoningEffort?: boolean;\n  displayName?: string;\n  instructions?: string;\n  instructionsFile?: string;\n  maxDurationMs?: number | string;\n  model?: string;\n  reasoningEffort?: string;\n}\n\n/**\n * Resolves the Computer an Agent runs on. Having none to select is no longer a failure: an Agent can\n * exist before a Computer does and be bound afterwards. An ambiguous choice still is, because\n * guessing which machine the Account meant would silently place the Agent on the wrong one.\n */\nexport function selectComputer(\n  response: ListAccountComputersResponse,\n  requestedComputerId?: string,\n): AccountComputerSummary | undefined {\n  if (requestedComputerId) {\n    const selected = response.computers.find((computer) => computer.computerId === requestedComputerId);\n    if (!selected) throw new Error(`Computer \"${requestedComputerId}\" is not owned by this Account`);\n    return selected;\n  }\n  if (response.computers.length > 1) throw new Error(\"Multiple Computers are available; use --computer <uuid>\");\n  return response.computers[0];\n}\n\nexport async function runAgentCreate(options: AgentCreateOptions): Promise<AgentCreateResult> {\n  const runtimeConfig = await createRuntimeConfig(options);\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  const computers = await api.listAccountComputers(accessToken);\n  const computer = selectComputer(computers, options.computerId);\n  const input = CreateAgentRequestSchema.parse({\n    name: options.name,\n    displayName: options.displayName,\n    runtimeProvider: options.runtimeProvider,\n    ...(computer ? { computerId: computer.computerId } : {}),\n    ...(runtimeConfig ? { runtimeConfig } : {}),\n  });\n  const agent = await api.createAgent(accessToken, input);\n  if (!computer) {\n    return {\n      agent,\n      warning: \"This Account has no Computer; connect one with `opentag connect` before the Agent can run\",\n    };\n  }\n  return {\n    agent,\n    ...(computer.connectionStatus === \"offline\"\n      ? { warning: `Computer ${computer.computerId} is offline; the Agent configuration was created` }\n      : {}),\n  };\n}\n\nexport async function runAgentBind(agentId: string, options: AgentBindOptions): Promise<AgentBindResult> {\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  const computers = await api.listAccountComputers(accessToken);\n  const computer = selectComputer(computers, options.computerId);\n  if (!computer) throw new Error(\"No Computer is registered; start the daemon first\");\n  const agent = await api.rebindAgentComputer(accessToken, agentId, computer.computerId);\n  return {\n    agent,\n    ...(computer.connectionStatus === \"offline\"\n      ? { warning: `Computer ${computer.computerId} is offline; the Agent was bound to it anyway` }\n      : {}),\n  };\n}\n\nexport async function runAgentUpdate(agentId: string, options: AgentUpdateOptions): Promise<AgentAdminConfig> {\n  const mutation = await updateMutation(options);\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  const current = await api.getAgentConfig(accessToken, agentId);\n  const input = UpdateAgentRequestSchema.parse({\n    ...mutation,\n    expectedRevision: current.revision,\n  });\n  return api.updateAgent(accessToken, agentId, input);\n}\n\nexport async function runAgentDelete(agentId: string, options: AgentCommandDependencies = {}): Promise<string> {\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  await api.deleteAgent(accessToken, agentId);\n  return `Deleted Agent ${agentId}`;\n}\n\nexport async function runAgentSuspend(\n  agentId: string,\n  options: AgentCommandDependencies = {},\n): Promise<AgentAdminConfig> {\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  return api.suspendAgent(accessToken, agentId);\n}\n\nexport async function runAgentReactivate(\n  agentId: string,\n  options: AgentCommandDependencies = {},\n): Promise<AgentAdminConfig> {\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  return api.reactivateAgent(accessToken, agentId);\n}\n\nasync function createRuntimeConfig(options: AgentCreateOptions) {\n  assertInstructionsSource(options);\n  const runtimeConfig = {\n    ...(options.model !== undefined ? { model: options.model } : {}),\n    ...(options.reasoningEffort !== undefined ? { reasoningEffort: options.reasoningEffort } : {}),\n    ...(options.instructions !== undefined || options.instructionsFile !== undefined\n      ? { instructions: await readInstructions(options) }\n      : {}),\n    ...(options.maxDurationMs !== undefined ? { maxDurationMs: parseMaxDuration(options.maxDurationMs) } : {}),\n  };\n  return Object.keys(runtimeConfig).length > 0 ? CreateAgentRuntimeConfigSchema.parse(runtimeConfig) : undefined;\n}\n\nasync function updateMutation(options: AgentUpdateOptions): Promise<Omit<UpdateAgentRequest, \"expectedRevision\">> {\n  assertInstructionsSource(options);\n  assertExclusive(options.model, options.clearModel, \"--model\", \"--clear-model\");\n  assertExclusive(\n    options.reasoningEffort,\n    options.clearReasoningEffort,\n    \"--reasoning-effort\",\n    \"--clear-reasoning-effort\",\n  );\n  assertExclusive(options.maxDurationMs, options.clearMaxDuration, \"--max-duration-ms\", \"--clear-max-duration\");\n\n  const runtimeConfigInput = {\n    ...(options.model !== undefined || options.clearModel ? { model: options.clearModel ? null : options.model } : {}),\n    ...(options.reasoningEffort !== undefined || options.clearReasoningEffort\n      ? { reasoningEffort: options.clearReasoningEffort ? null : options.reasoningEffort }\n      : {}),\n    ...(options.instructions !== undefined || options.instructionsFile !== undefined\n      ? { instructions: await readInstructions(options) }\n      : {}),\n    ...(options.maxDurationMs !== undefined || options.clearMaxDuration\n      ? { maxDurationMs: options.clearMaxDuration ? null : parseMaxDuration(options.maxDurationMs) }\n      : {}),\n  };\n  const runtimeConfig =\n    Object.keys(runtimeConfigInput).length > 0 ? UpdateAgentRuntimeConfigSchema.parse(runtimeConfigInput) : undefined;\n  if (options.displayName === undefined && runtimeConfig === undefined) {\n    throw new Error(\"No Agent changes were provided; specify a profile or runtime setting option\");\n  }\n  const preflight = UpdateAgentRequestSchema.parse({\n    expectedRevision: 1,\n    ...(options.displayName !== undefined ? { displayName: options.displayName } : {}),\n    ...(runtimeConfig ? { runtimeConfig } : {}),\n  });\n  const { expectedRevision: _expectedRevision, ...mutation } = preflight;\n  return mutation;\n}\n\nexport function assertInstructionsSource(options: { instructions?: string; instructionsFile?: string }): void {\n  if (options.instructions !== undefined && options.instructionsFile !== undefined) {\n    throw new Error(\"--instructions and --instructions-file cannot be used together\");\n  }\n}\n\nexport function assertExclusive(\n  value: unknown,\n  clear: boolean | undefined,\n  valueFlag: string,\n  clearFlag: string,\n): void {\n  if (value !== undefined && clear) throw new Error(`${valueFlag} and ${clearFlag} cannot be used together`);\n}\n\nexport async function readInstructions(options: { instructions?: string; instructionsFile?: string }): Promise<string> {\n  if (options.instructionsFile !== undefined) return readFile(options.instructionsFile, \"utf8\");\n  return options.instructions ?? \"\";\n}\n\nfunction parseMaxDuration(value: number | string | undefined): number {\n  if (value === undefined) throw new Error(\"--max-duration-ms requires a value\");\n  if (typeof value === \"number\") {\n    if (Number.isSafeInteger(value) && value > 0) return value;\n  } else if (/^[1-9][0-9]*$/.test(value)) {\n    const parsed = Number(value);\n    if (Number.isSafeInteger(parsed)) return parsed;\n  }\n  throw new Error(\"--max-duration-ms must be a positive base-10 safe integer\");\n}\n","import type { Command } from \"commander\";\nimport { formatAgentBound } from \"../../core/agent/formatting.js\";\nimport { runAgentBind } from \"../../core/agent/mutations.js\";\nimport { executeCommand, redactSecrets } from \"../../core/command/policy.js\";\n\nexport function registerAgentBindCommand(agent: Command): void {\n  agent\n    .command(\"bind <agent-id>\")\n    .description(\"Bind an Agent to a Computer owned by this Account\")\n    .option(\"--computer <uuid>\", \"Computer owned by this Account\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId, options) => {\n      process.exitCode = await executeCommand(\n        async () => {\n          const result = await runAgentBind(agentId, { computerId: options.computer });\n          if (result.warning) process.stderr.write(`${redactSecrets(result.warning)}\\n`);\n          return result;\n        },\n        { json: options.json === true, formatValue: formatAgentBound, phase: \"request\" },\n      );\n    });\n}\n","import { type Command, Option } from \"commander\";\nimport { formatAgentCreated } from \"../../core/agent/formatting.js\";\nimport { runAgentCreate } from \"../../core/agent/mutations.js\";\nimport { executeCommand, redactSecrets } from \"../../core/command/policy.js\";\n\nexport function registerAgentCreateCommand(agent: Command): void {\n  agent\n    .command(\"create\")\n    .requiredOption(\"--name <name>\", \"canonical Agent name\")\n    .requiredOption(\"--display-name <display-name>\", \"human-facing Agent name\")\n    .requiredOption(\"--provider <provider>\", \"runtime provider: codex, claude-code, or pi\")\n    .option(\"--computer <uuid>\", \"Computer owned by this Account\")\n    .option(\"--model <model>\", \"exact model ID for the selected runtime\")\n    .option(\"--reasoning-effort <effort>\", \"reasoning effort for the selected runtime\")\n    .addOption(new Option(\"--instructions <text>\", \"Agent runtime instructions\").conflicts(\"instructionsFile\"))\n    .addOption(\n      new Option(\"--instructions-file <path>\", \"read Agent instructions from a UTF-8 file\").conflicts(\"instructions\"),\n    )\n    .option(\n      \"--max-duration-ms <integer>\",\n      \"maximum duration of one Turn in milliseconds; omit to use the OpenTag default\",\n    )\n    .option(\"--json\", \"print JSON\")\n    .action(async (options) => {\n      process.exitCode = await executeCommand(\n        async () => {\n          const result = await runAgentCreate({\n            name: options.name,\n            displayName: options.displayName,\n            runtimeProvider: options.provider,\n            computerId: options.computer,\n            model: options.model,\n            reasoningEffort: options.reasoningEffort,\n            instructions: options.instructions,\n            instructionsFile: options.instructionsFile,\n            maxDurationMs: options.maxDurationMs,\n          });\n          if (result.warning) process.stderr.write(`${redactSecrets(result.warning)}\\n`);\n          return result;\n        },\n        { json: options.json === true, formatValue: formatAgentCreated, phase: \"request\" },\n      );\n    });\n}\n","import type { Command } from \"commander\";\nimport { runAgentDelete } from \"../../core/agent/mutations.js\";\nimport { executeCommand } from \"../../core/command/policy.js\";\n\nexport function registerAgentDeleteCommand(agent: Command): void {\n  agent\n    .command(\"delete <agent-id>\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId, options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(() => runAgentDelete(agentId), {\n        json: options.json === true,\n        phase: \"request\",\n      });\n    });\n}\n","import type { FeishuSetupAttempt, ImBindingAdminDetail, ImBindingDiagnostics, ReceiveMode } from \"@opentag/shared\";\nimport { type AgentCommandDependencies, resolveAgentCommandContext } from \"./context.js\";\n\nexport async function runImBindingShow(\n  agentId: string,\n  options: AgentCommandDependencies = {},\n): Promise<ImBindingAdminDetail | undefined> {\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  return api.getAgentImBindingConfig(accessToken, agentId);\n}\n\nexport async function runImBindingConnectFeishu(\n  agentId: string,\n  intent: \"create\" | \"reauthorize\" | \"replace\",\n  options: AgentCommandDependencies = {},\n): Promise<FeishuSetupAttempt> {\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  return api.createFeishuSetupAttempt(accessToken, agentId, intent);\n}\n\nexport async function runImBindingDiagnose(\n  agentId: string,\n  options: AgentCommandDependencies = {},\n): Promise<ImBindingDiagnostics> {\n  const imBinding = await runImBindingShow(agentId, options);\n  if (!imBinding) throw new Error(\"The Agent has no IM binding\");\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  return api.getImBindingDiagnostics(accessToken, imBinding.id);\n}\n\nexport async function runImBindingDisable(agentId: string, options: AgentCommandDependencies = {}): Promise<void> {\n  const imBinding = await runImBindingShow(agentId, options);\n  if (!imBinding) return;\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  await api.disableImBinding(accessToken, imBinding.id);\n}\n\nexport async function runReceiveModeSet(\n  agentId: string,\n  receiveMode: ReceiveMode,\n  options: AgentCommandDependencies = {},\n) {\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  const current = await api.getAgentConfig(accessToken, agentId);\n  return api.updateAgent(accessToken, agentId, { expectedRevision: current.revision, receiveMode });\n}\n\nexport function formatImBinding(summary: ImBindingAdminDetail | undefined): string {\n  if (!summary) return \"No IM binding configured\";\n  const identity =\n    summary.identity.provider === \"feishu\"\n      ? `${summary.identity.appId} · ${summary.identity.teamId ?? \"provider Team pending first event\"}`\n      : `${summary.identity.appId} · ${summary.identity.teamId} · ${summary.identity.botUserId}`;\n  return [\n    `provider\\t${summary.provider}`,\n    `identity\\t${identity}`,\n    `receiveMode\\t${summary.receiveMode}`,\n    `credentialGeneration\\t${summary.credentialGeneration}`,\n    `reauthorizationRequired\\t${summary.reauthorizationRequired}`,\n    `lastValidatedAt\\t${summary.lastValidatedAt ?? \"-\"}`,\n    `lastRuntimeObservationAt\\t${summary.lastRuntimeObservationAt ?? \"-\"}`,\n  ].join(\"\\n\");\n}\n\nexport function formatFeishuSetup(attempt: FeishuSetupAttempt): string {\n  return [\n    `attemptId\\t${attempt.id}`,\n    `state\\t${attempt.state}`,\n    `qrUrl\\t${attempt.qrUrl ?? \"-\"}`,\n    `expiresAt\\t${attempt.expiresAt}`,\n    `errorCode\\t${attempt.errorCode ?? \"-\"}`,\n    ...(attempt.activation\n      ? [\n          `authorization\\tSaved; OpenTag will connect automatically when requirements are ready. No new scan is needed.`,\n          `appId\\t${attempt.activation.appId}`,\n          `waitingFor\\t${activationReason(attempt.activation.reason)}`,\n          `missingScopes\\t${attempt.activation.missingScopes.join(\",\") || \"-\"}`,\n          `nextCheckAt\\t${attempt.activation.nextCheckAt}`,\n        ]\n      : []),\n  ].join(\"\\n\");\n}\n\nfunction activationReason(reason: NonNullable<FeishuSetupAttempt[\"activation\"]>[\"reason\"]): string {\n  switch (reason) {\n    case \"permissions_pending\":\n      return \"Administrator approval of all required permissions\";\n    case \"app_unavailable\":\n      return \"Application installation or enablement\";\n    case \"runtime_unavailable\":\n      return \"Agent runtime readiness\";\n    case \"temporary_failure\":\n      return \"Temporary check failure; retrying automatically\";\n    case \"checking\":\n      return \"Connection verification in progress\";\n  }\n}\n\nexport function formatImBindingDiagnostics(value: ImBindingDiagnostics): string {\n  return [\n    `provider\\t${value.provider}`,\n    `ready\\t${value.ready}`,\n    `credentialGeneration\\t${value.credentialGeneration}`,\n    `credentialStatus\\t${value.credentialStatus}`,\n    `requiredCapabilities\\t${value.requiredCapabilities.join(\",\") || \"-\"}`,\n    `grantedCapabilities\\t${value.grantedCapabilities.join(\",\") || \"-\"}`,\n    `missingCapabilities\\t${value.missingCapabilities.join(\",\") || \"-\"}`,\n    `reauthorizationRequired\\t${value.reauthorizationRequired}`,\n    `slackAppIdEvidence\\t${value.slackAppId ? `${value.slackAppId.value} (${value.slackAppId.evidence}; ingress match required)` : \"-\"}`,\n    `slackIdentityClosure\\t${value.slackIdentityClosure ? `${value.slackIdentityClosure.status}${value.slackIdentityClosure.verifiedAt ? ` (${value.slackIdentityClosure.verifiedAt})` : \"\"}` : \"-\"}`,\n    `agentRuntimeReadiness\\t${value.agentRuntimeReadiness}`,\n    `providerCliReadiness\\t${value.providerCliReadiness}`,\n    `providerCliReason\\t${value.providerCliReason ?? \"-\"}`,\n    `credentialExecutionReadiness\\t${value.credentialExecutionReadiness}`,\n    `credentialExecutionReason\\t${value.credentialExecutionReason ?? \"-\"}`,\n    `connection\\t${value.connection ? `${value.connection.state} (observed ${value.connection.observedAt})` : \"not applicable\"}`,\n    `lastInboundAt\\t${value.lastInboundAt ?? \"-\"}`,\n    `lastValidatedAt\\t${value.lastValidatedAt ?? \"-\"}`,\n    `lastRuntimeObservationAt\\t${value.lastRuntimeObservationAt ?? \"-\"}`,\n    `lastErrorCode\\t${value.lastErrorCode ?? \"-\"}`,\n  ].join(\"\\n\");\n}\n","import type { Command } from \"commander\";\nimport {\n  formatFeishuSetup,\n  formatImBinding,\n  formatImBindingDiagnostics,\n  runImBindingConnectFeishu,\n  runImBindingDiagnose,\n  runImBindingDisable,\n  runImBindingShow,\n  runReceiveModeSet,\n} from \"../../core/agent/im.js\";\nimport { executeCommand } from \"../../core/command/policy.js\";\n\nexport function registerAgentImBindingCommands(agent: Command): void {\n  const imBinding = agent.command(\"im\").description(\"Manage an Agent IM binding\");\n  imBinding\n    .command(\"show <agent-id>\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId, options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(() => runImBindingShow(agentId), {\n        json: options.json === true,\n        formatValue: formatImBinding,\n        phase: \"request\",\n      });\n    });\n  for (const [name, intent] of [\n    [\"connect-feishu\", \"create\"],\n    [\"reauthorize-feishu\", \"reauthorize\"],\n  ] as const) {\n    imBinding\n      .command(`${name} <agent-id>`)\n      .option(\"--json\", \"print JSON\")\n      .action(async (agentId, options: { json?: boolean }) => {\n        process.exitCode = await executeCommand(() => runImBindingConnectFeishu(agentId, intent), {\n          json: options.json === true,\n          formatValue: formatFeishuSetup,\n          phase: \"request\",\n        });\n      });\n  }\n  imBinding\n    .command(\"diagnose <agent-id>\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId, options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(() => runImBindingDiagnose(agentId), {\n        json: options.json === true,\n        formatValue: formatImBindingDiagnostics,\n        phase: \"request\",\n      });\n    });\n  imBinding\n    .command(\"disable <agent-id>\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId, options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(\n        async () => {\n          await runImBindingDisable(agentId);\n          return `Disabled IM binding for Agent ${agentId}`;\n        },\n        { json: options.json === true, phase: \"request\" },\n      );\n    });\n\n  const receiveMode = agent.command(\"receive-mode\").description(\"Manage Agent IM receive mode\");\n  receiveMode\n    .command(\"set <agent-id> <mode>\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId, mode, options: { json?: boolean }) => {\n      if (mode !== \"all-message\" && mode !== \"mention-only\") {\n        throw new Error(\"Receive mode must be all-message or mention-only\");\n      }\n      process.exitCode = await executeCommand(\n        async () => {\n          const updated = await runReceiveModeSet(agentId, mode === \"all-message\" ? \"all_message\" : \"mention_only\");\n          return `Updated Agent ${updated.id} receive mode to ${updated.receiveMode}`;\n        },\n        { json: options.json === true, phase: \"validation\" },\n      );\n    });\n}\n","import type { Command } from \"commander\";\nimport { formatAgent } from \"../../core/agent/formatting.js\";\nimport { runAgentReactivate, runAgentSuspend } from \"../../core/agent/mutations.js\";\nimport { executeCommand } from \"../../core/command/policy.js\";\n\nexport function registerAgentLifecycleCommands(agent: Command): void {\n  for (const [name, run] of [\n    [\"suspend\", runAgentSuspend],\n    [\"reactivate\", runAgentReactivate],\n  ] as const) {\n    agent\n      .command(`${name} <agent-id>`)\n      .option(\"--json\", \"print JSON\")\n      .action(async (agentId, options: { json?: boolean }) => {\n        process.exitCode = await executeCommand(() => run(agentId), {\n          json: options.json === true,\n          formatValue: formatAgent,\n          phase: \"request\",\n        });\n      });\n  }\n}\n","import type { AgentAdminConfig, ListAgentsResponse } from \"@opentag/shared\";\nimport { type AgentCommandDependencies, resolveAgentCommandContext } from \"./context.js\";\n\nexport type AgentListOptions = AgentCommandDependencies;\n\nexport async function runAgentList(options: AgentListOptions = {}): Promise<ListAgentsResponse> {\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  return api.listAgents(accessToken);\n}\n\nexport async function runAgentShow(agentId: string, options: AgentCommandDependencies = {}): Promise<AgentAdminConfig> {\n  const { api, accessToken } = await resolveAgentCommandContext(options);\n  return api.getAgentConfig(accessToken, agentId);\n}\n","import type { Command } from \"commander\";\nimport { formatAgentList } from \"../../core/agent/formatting.js\";\nimport { runAgentList } from \"../../core/agent/queries.js\";\nimport { executeCommand } from \"../../core/command/policy.js\";\n\nexport function registerAgentListCommand(agent: Command): void {\n  agent\n    .command(\"list\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(() => runAgentList(), {\n        json: options.json === true,\n        formatValue: formatAgentList,\n        phase: \"request\",\n      });\n    });\n}\n","import { randomUUID } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { type OpenTagApi, OpenTagApiError, readComputerIdentity, readSessionCliProofFile } from \"@opentag/client\";\nimport {\n  SESSION_CLI_DEFAULT_LIMIT,\n  type SessionCliCommandResponse,\n  SessionCliCreateRequestSchema,\n  SessionCliListQuerySchema,\n  type SessionCliListResponse,\n  SessionCliSendRequestSchema,\n} from \"@opentag/shared\";\nimport { resolveCommandContext } from \"../command/context.js\";\nimport { redactSecrets } from \"../command/policy.js\";\n\nexport interface SessionMessageOptions {\n  message?: string;\n  messageFile?: string;\n  messageId?: string;\n}\n\nexport class SessionCommandRequestError extends Error {\n  readonly code: string;\n  readonly messageId: string;\n  readonly status: \"rejected\" | \"unknown\";\n\n  constructor(messageId: string, cause: unknown) {\n    const message = cause instanceof Error ? cause.message : \"Session request failed\";\n    super(message, { cause });\n    this.name = \"SessionCommandRequestError\";\n    this.messageId = messageId;\n    this.status = cause instanceof OpenTagApiError && cause.category !== \"transient\" ? \"rejected\" : \"unknown\";\n    this.code = cause instanceof OpenTagApiError ? cause.code : \"transport_error\";\n  }\n}\n\nexport async function resolveSessionProofContext(\n  environment: NodeJS.ProcessEnv = process.env,\n): Promise<{ api: OpenTagApi; proof: string }> {\n  const proofPath = environment.OPENTAG_SESSION_PROOF_FILE;\n  if (!proofPath) {\n    throw new Error(\n      \"Session commands are available only inside an OpenTag-managed Agent Session (runtime context missing)\",\n    );\n  }\n  const serverUrl = environment.OPENTAG_SESSION_SERVER_URL;\n  if (serverUrl) {\n    // E8 Cloud Session: the trusted Runner publishes the exact Server endpoint alongside the\n    // managed proof, and no Computer identity file exists inside the Sandbox. There is no login\n    // or Computer-binding step; the proof alone authorizes the call.\n    const proof = await readSessionCliProofFile(proofPath);\n    const cloudContext = await resolveCommandContext({ environment, serverUrl });\n    if (!cloudContext.api) throw new Error(\"Command context did not resolve an API\");\n    return { api: cloudContext.api, proof: proof.token };\n  }\n  const context = await resolveCommandContext({ environment });\n  const home = context.home;\n  const identity = await readComputerIdentity(home);\n  if (!identity) {\n    throw new Error(\n      \"Session commands are available only inside an OpenTag-managed Agent Session (Computer binding missing)\",\n    );\n  }\n  const proof = await readSessionCliProofFile(proofPath);\n  const apiContext = await resolveCommandContext({ environment, home, serverUrl: identity.serverUrl });\n  if (!apiContext.api) throw new Error(\"Command context did not resolve an API\");\n  return { api: apiContext.api, proof: proof.token };\n}\n\nexport async function runSessionCreate(\n  options: SessionMessageOptions & { model?: string; reasoningEffort?: string; maxDurationMs?: number },\n): Promise<SessionCliCommandResponse> {\n  const message = await resolveMessage(options);\n  const input = SessionCliCreateRequestSchema.parse({\n    messageId: options.messageId ?? randomUUID(),\n    message,\n    model: options.model,\n    reasoningEffort: options.reasoningEffort,\n    maxDurationMs: options.maxDurationMs,\n  });\n  const runtime = await resolveSessionProofContext();\n  return requestWithRetryKey(input.messageId, () => runtime.api.createInternalSession(runtime.proof, input));\n}\n\nexport async function runSessionSend(\n  targetSessionId: string,\n  options: SessionMessageOptions,\n): Promise<SessionCliCommandResponse> {\n  const message = await resolveMessage(options);\n  const input = SessionCliSendRequestSchema.parse({\n    messageId: options.messageId ?? randomUUID(),\n    targetSessionId,\n    message,\n  });\n  const runtime = await resolveSessionProofContext();\n  return requestWithRetryKey(input.messageId, () => runtime.api.sendSessionMessage(runtime.proof, input));\n}\n\nexport async function requestWithRetryKey<T>(messageId: string, request: () => Promise<T>): Promise<T> {\n  try {\n    return await request();\n  } catch (error) {\n    throw new SessionCommandRequestError(messageId, error);\n  }\n}\n\nexport async function runSessionList(options: {\n  recursive?: boolean;\n  limit?: number;\n  cursor?: string;\n  since?: string;\n}): Promise<SessionCliListResponse> {\n  const input = SessionCliListQuerySchema.parse({\n    recursive: options.recursive ?? false,\n    limit: options.limit ?? SESSION_CLI_DEFAULT_LIMIT,\n    cursor: options.cursor,\n    since: options.since,\n  });\n  const runtime = await resolveSessionProofContext();\n  return runtime.api.listInternalSessions(runtime.proof, input);\n}\n\nexport function formatSessionCommandResult(result: SessionCliCommandResponse): string {\n  return [\n    `status=${result.status}`,\n    `messageId=${result.messageId}`,\n    ...(result.sessionId ? [`sessionId=${result.sessionId}`] : []),\n    ...(result.code ? [`code=${result.code}`] : []),\n  ].join(\" \");\n}\n\nexport function formatSessionCommandError(error: SessionCommandRequestError, json: boolean): string {\n  const result = {\n    status: error.status,\n    messageId: error.messageId,\n    code: error.code,\n    message: redactSecrets(error.message),\n  };\n  return json\n    ? JSON.stringify(result)\n    : `status=${result.status} messageId=${result.messageId} code=${result.code} message=${JSON.stringify(result.message)}`;\n}\n\nexport function formatSessionList(result: SessionCliListResponse): string {\n  const header = \"SESSION ID\\tPARENT SESSION\\tCREATED\\tLAST MESSAGE\\tOUTCOME\\tTASK\";\n  const rows = result.items.map((item) =>\n    [\n      item.sessionId,\n      item.parentSessionId,\n      item.createdAt,\n      item.lastMessageAt,\n      item.lastDeliveryOutcome,\n      item.taskPreview.replaceAll(\"\\t\", \" \").replaceAll(\"\\n\", \" \"),\n    ].join(\"\\t\"),\n  );\n  if (result.nextCursor) rows.push(`Next cursor: ${result.nextCursor}`);\n  return [header, ...rows].join(\"\\n\");\n}\n\nasync function resolveMessage(options: SessionMessageOptions): Promise<string> {\n  if ((options.message === undefined) === (options.messageFile === undefined)) {\n    throw new Error(\"Exactly one of --message and --message-file is required\");\n  }\n  const message =\n    options.message ??\n    (options.messageFile === \"-\" ? await readStandardInput() : await readFile(options.messageFile as string, \"utf8\"));\n  if (!message) throw new Error(\"Session messages cannot be empty\");\n  return message;\n}\n\nasync function readStandardInput(): Promise<string> {\n  process.stdin.setEncoding(\"utf8\");\n  let value = \"\";\n  for await (const chunk of process.stdin) value += chunk;\n  return value;\n}\n","import type { OpenTagApi } from \"@opentag/client\";\nimport {\n  type AgentAdminConfig,\n  type MCPAgentServer,\n  type MCPAvailableServer,\n  type UpdateSelfAgentRuntimeConfig,\n  UpdateSelfAgentRuntimeConfigSchema,\n} from \"@opentag/shared\";\nimport { CommandError } from \"../command/policy.js\";\nimport { resolveSessionProofContext } from \"../session/index.js\";\nimport { assertExclusive, assertInstructionsSource, readInstructions } from \"./mutations.js\";\n\n/**\n * `agent self`: the Agent reading and changing its own configuration from inside a managed Session.\n *\n * The Session proof is the only credential. No command accepts an Agent id, because the Server\n * resolves the Agent from the proof and a request can never address a different Agent. Outside a\n * managed Session every command fails before any network call; the Account surface\n * (`agent update`, `agent mcp`) is the human-facing equivalent.\n */\n\nexport interface AgentSelfApiClient\n  extends Pick<\n    OpenTagApi,\n    | \"getRuntimeAgentConfig\"\n    | \"updateRuntimeAgentConfig\"\n    | \"listRuntimeAgentMcpServers\"\n    | \"listRuntimeAgentAvailableMcpServers\"\n    | \"attachRuntimeAgentMcpServer\"\n    | \"updateRuntimeAgentMcpBinding\"\n    | \"detachRuntimeAgentMcpServer\"\n  > {}\n\nexport interface AgentSelfDependencies {\n  api?: AgentSelfApiClient;\n  environment?: NodeJS.ProcessEnv;\n  proof?: string;\n}\n\nexport interface AgentSelfUpdateOptions extends AgentSelfDependencies {\n  clearModel?: boolean;\n  clearReasoningEffort?: boolean;\n  instructions?: string;\n  instructionsFile?: string;\n  model?: string;\n  reasoningEffort?: string;\n}\n\ninterface AgentSelfContext {\n  api: AgentSelfApiClient;\n  proof: string;\n}\n\nasync function resolveAgentSelfContext(dependencies: AgentSelfDependencies): Promise<AgentSelfContext> {\n  if ((dependencies.api && !dependencies.proof) || (dependencies.proof && !dependencies.api)) {\n    throw new Error(\"Agent self command test dependencies must provide both api and proof\");\n  }\n  if (dependencies.api && dependencies.proof) return { api: dependencies.api, proof: dependencies.proof };\n  const environment = dependencies.environment ?? process.env;\n  if (!environment.OPENTAG_SESSION_PROOF_FILE) {\n    throw new CommandError(\n      { code: \"AGENT_SELF_SESSION_REQUIRED\", category: \"validation\", retryability: \"never\", phase: \"validation\" },\n      \"agent self commands run only inside an OpenTag-managed Agent Session; use `agent update` or `agent mcp` with an Account login instead\",\n    );\n  }\n  const { api, proof } = await resolveSessionProofContext(environment);\n  return { api, proof };\n}\n\nexport async function runAgentSelfShow(dependencies: AgentSelfDependencies = {}): Promise<AgentAdminConfig> {\n  const { api, proof } = await resolveAgentSelfContext(dependencies);\n  return api.getRuntimeAgentConfig(proof);\n}\n\nexport async function runAgentSelfUpdate(options: AgentSelfUpdateOptions): Promise<AgentAdminConfig> {\n  const runtimeConfig = await selfRuntimeConfig(options);\n  const { api, proof } = await resolveAgentSelfContext(options);\n  const current = await api.getRuntimeAgentConfig(proof);\n  return api.updateRuntimeAgentConfig(proof, { expectedRevision: current.revision, runtimeConfig });\n}\n\nexport async function runAgentSelfMcpList(dependencies: AgentSelfDependencies = {}): Promise<MCPAgentServer[]> {\n  const { api, proof } = await resolveAgentSelfContext(dependencies);\n  return (await api.listRuntimeAgentMcpServers(proof)).servers;\n}\n\nexport async function runAgentSelfMcpAvailable(\n  dependencies: AgentSelfDependencies = {},\n): Promise<MCPAvailableServer[]> {\n  const { api, proof } = await resolveAgentSelfContext(dependencies);\n  return (await api.listRuntimeAgentAvailableMcpServers(proof)).servers;\n}\n\nexport async function runAgentSelfMcpAttach(\n  reference: string,\n  enabled: boolean,\n  dependencies: AgentSelfDependencies = {},\n): Promise<MCPAgentServer> {\n  const { api, proof } = await resolveAgentSelfContext(dependencies);\n  const { servers } = await api.listRuntimeAgentAvailableMcpServers(proof);\n  const server = servers.find((entry) => entry.id === reference || entry.name === reference);\n  if (!server) {\n    throw new Error(\n      `No unmounted Account MCP Server named or identified by \"${reference}\"; see agent self mcp available`,\n    );\n  }\n  return api.attachRuntimeAgentMcpServer(proof, { mcpServerId: server.id, enabled });\n}\n\nexport async function runAgentSelfMcpEnable(\n  reference: string,\n  enabled: boolean,\n  dependencies: AgentSelfDependencies = {},\n): Promise<MCPAgentServer> {\n  const { api, proof } = await resolveAgentSelfContext(dependencies);\n  const mounted = await resolveMounted(api, proof, reference);\n  return api.updateRuntimeAgentMcpBinding(proof, mounted.mcpServerId, { enabled });\n}\n\nexport async function runAgentSelfMcpDetach(\n  reference: string,\n  dependencies: AgentSelfDependencies = {},\n): Promise<MCPAgentServer> {\n  const { api, proof } = await resolveAgentSelfContext(dependencies);\n  const mounted = await resolveMounted(api, proof, reference);\n  await api.detachRuntimeAgentMcpServer(proof, mounted.mcpServerId);\n  return mounted;\n}\n\nasync function resolveMounted(api: AgentSelfApiClient, proof: string, reference: string): Promise<MCPAgentServer> {\n  const { servers } = await api.listRuntimeAgentMcpServers(proof);\n  const match = servers.find((entry) => entry.mcpServerId === reference || entry.name === reference);\n  if (!match) throw new Error(`This Agent does not mount an MCP Server named or identified by \"${reference}\"`);\n  return match;\n}\n\nasync function selfRuntimeConfig(options: AgentSelfUpdateOptions): Promise<UpdateSelfAgentRuntimeConfig> {\n  assertInstructionsSource(options);\n  assertExclusive(options.model, options.clearModel, \"--model\", \"--clear-model\");\n  assertExclusive(\n    options.reasoningEffort,\n    options.clearReasoningEffort,\n    \"--reasoning-effort\",\n    \"--clear-reasoning-effort\",\n  );\n  const input = {\n    ...(options.model !== undefined || options.clearModel ? { model: options.clearModel ? null : options.model } : {}),\n    ...(options.reasoningEffort !== undefined || options.clearReasoningEffort\n      ? { reasoningEffort: options.clearReasoningEffort ? null : options.reasoningEffort }\n      : {}),\n    ...(options.instructions !== undefined || options.instructionsFile !== undefined\n      ? { instructions: await readInstructions(options) }\n      : {}),\n  };\n  if (Object.keys(input).length === 0) {\n    throw new Error(\"No Agent changes were provided; specify --instructions, --model, or --reasoning-effort\");\n  }\n  return UpdateSelfAgentRuntimeConfigSchema.parse(input);\n}\n","import type { MCPAvailableServer } from \"@opentag/shared\";\nimport { type Command, Option } from \"commander\";\nimport { formatAgent } from \"../../core/agent/formatting.js\";\nimport {\n  runAgentSelfMcpAttach,\n  runAgentSelfMcpAvailable,\n  runAgentSelfMcpDetach,\n  runAgentSelfMcpEnable,\n  runAgentSelfMcpList,\n  runAgentSelfShow,\n  runAgentSelfUpdate,\n} from \"../../core/agent/self.js\";\nimport { executeCommand } from \"../../core/command/policy.js\";\nimport { formatAgentMcpServers, formatAgentServerRow } from \"../../core/mcp/shared.js\";\n\ninterface JsonOption {\n  json?: boolean;\n}\n\n/**\n * `agent self` — the running Agent inspects and changes its own configuration.\n *\n * Available only inside an OpenTag-managed Agent Session: the Session proof names the Agent, so no\n * command takes an Agent id. The surface is narrower than `agent update` / `agent mcp` on purpose;\n * display name, receive mode, Turn duration, MCP endpoint overrides, and MCP credentials stay with\n * the Account.\n */\nexport function registerAgentSelfCommands(agent: Command): void {\n  const self = agent\n    .command(\"self\")\n    .description(\"Inspect and change this Agent's own configuration (inside a managed Session only)\");\n\n  self\n    .command(\"show\")\n    .description(\"Show this Agent's configuration, including instructions and model\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: JsonOption) => {\n      process.exitCode = await executeCommand(() => runAgentSelfShow(), {\n        json: options.json === true,\n        formatValue: formatAgent,\n        phase: \"request\",\n      });\n    });\n\n  self\n    .command(\"update\")\n    .description(\n      \"Change this Agent's instructions, model, or reasoning effort; the next Turn starts a new provider conversation\",\n    )\n    .addOption(new Option(\"--model <model>\", \"exact model ID for this Agent's runtime\").conflicts(\"clearModel\"))\n    .addOption(new Option(\"--clear-model\", \"let the runtime manage model selection\").conflicts(\"model\"))\n    .addOption(\n      new Option(\"--reasoning-effort <effort>\", \"reasoning effort for this Agent's runtime\").conflicts(\n        \"clearReasoningEffort\",\n      ),\n    )\n    .addOption(\n      new Option(\"--clear-reasoning-effort\", \"let the runtime manage reasoning effort\").conflicts(\"reasoningEffort\"),\n    )\n    .addOption(new Option(\"--instructions <text>\", \"replace this Agent's instructions\").conflicts(\"instructionsFile\"))\n    .addOption(\n      new Option(\"--instructions-file <path>\", \"replace instructions from a UTF-8 file\").conflicts(\"instructions\"),\n    )\n    .option(\"--json\", \"print JSON\")\n    .action(async (options) => {\n      process.exitCode = await executeCommand(\n        () =>\n          runAgentSelfUpdate({\n            model: options.model,\n            clearModel: options.clearModel,\n            reasoningEffort: options.reasoningEffort,\n            clearReasoningEffort: options.clearReasoningEffort,\n            instructions: options.instructions,\n            instructionsFile: options.instructionsFile,\n          }),\n        { json: options.json === true, formatValue: formatAgent, phase: \"request\" },\n      );\n    });\n\n  registerAgentSelfMcpCommands(self);\n}\n\nfunction registerAgentSelfMcpCommands(self: Command): void {\n  const mcp = self.command(\"mcp\").description(\"Manage the MCP Servers this Agent mounts\");\n\n  mcp\n    .command(\"list\")\n    .description(\"List the MCP Servers this Agent mounts\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: JsonOption) => {\n      process.exitCode = await executeCommand(() => runAgentSelfMcpList(), {\n        json: options.json === true,\n        formatValue: formatAgentMcpServers,\n        phase: \"request\",\n      });\n    });\n\n  mcp\n    .command(\"available\")\n    .description(\"List Account MCP Servers this Agent does not mount yet\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: JsonOption) => {\n      process.exitCode = await executeCommand(() => runAgentSelfMcpAvailable(), {\n        json: options.json === true,\n        formatValue: formatAvailableServers,\n        phase: \"request\",\n      });\n    });\n\n  mcp\n    .command(\"attach <server>\")\n    .description(\"Mount an Account MCP Server; one that needs a credential must be authorized by a human\")\n    .option(\"--disabled\", \"mount it without enabling it\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (server: string, options: JsonOption & { disabled?: boolean }) => {\n      process.exitCode = await executeCommand(() => runAgentSelfMcpAttach(server, options.disabled !== true), {\n        json: options.json === true,\n        formatValue: formatAgentServerRow,\n        phase: \"request\",\n      });\n    });\n\n  mcp\n    .command(\"detach <server>\")\n    .description(\"Unmount an MCP Server; this drops this Agent's credential for it\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (server: string, options: JsonOption) => {\n      process.exitCode = await executeCommand(\n        async () => {\n          const detached = await runAgentSelfMcpDetach(server);\n          return `Detached ${detached.name} (${detached.mcpServerId})`;\n        },\n        { json: options.json === true, phase: \"request\" },\n      );\n    });\n\n  for (const [name, enabled] of [\n    [\"enable\", true],\n    [\"disable\", false],\n  ] as const) {\n    mcp\n      .command(`${name} <server>`)\n      .description(\n        enabled ? \"Enable a mounted MCP Server\" : \"Disable a mounted MCP Server; mount and credential are kept\",\n      )\n      .option(\"--json\", \"print JSON\")\n      .action(async (server: string, options: JsonOption) => {\n        process.exitCode = await executeCommand(() => runAgentSelfMcpEnable(server, enabled), {\n          json: options.json === true,\n          formatValue: formatAgentServerRow,\n          phase: \"request\",\n        });\n      });\n  }\n}\n\nfunction formatAvailableServers(servers: readonly MCPAvailableServer[]): string {\n  if (servers.length === 0) return \"No unmounted Account MCP Servers\";\n  return [\n    [\"NAME\", \"ID\", \"DESCRIPTION\"].join(\"\\t\"),\n    ...servers.map((server) => [server.name, server.id, server.description ?? \"-\"].join(\"\\t\")),\n  ].join(\"\\n\");\n}\n","import type { Command } from \"commander\";\nimport { formatAgent } from \"../../core/agent/formatting.js\";\nimport { runAgentShow } from \"../../core/agent/queries.js\";\nimport { executeCommand } from \"../../core/command/policy.js\";\n\nexport function registerAgentShowCommand(agent: Command): void {\n  agent\n    .command(\"show <agent-id>\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId, options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(() => runAgentShow(agentId), {\n        json: options.json === true,\n        formatValue: formatAgent,\n        phase: \"request\",\n      });\n    });\n}\n","import { type Command, Option } from \"commander\";\nimport { formatAgent } from \"../../core/agent/formatting.js\";\nimport { runAgentUpdate } from \"../../core/agent/mutations.js\";\nimport { executeCommand } from \"../../core/command/policy.js\";\n\nexport function registerAgentUpdateCommand(agent: Command): void {\n  agent\n    .command(\"update <agent-id>\")\n    .option(\"--display-name <display-name>\", \"new human-facing Agent name\")\n    .addOption(new Option(\"--model <model>\", \"exact model ID for the selected runtime\").conflicts(\"clearModel\"))\n    .addOption(new Option(\"--clear-model\", \"let the runtime manage model selection\").conflicts(\"model\"))\n    .addOption(\n      new Option(\"--reasoning-effort <effort>\", \"reasoning effort for the selected runtime\").conflicts(\n        \"clearReasoningEffort\",\n      ),\n    )\n    .addOption(\n      new Option(\"--clear-reasoning-effort\", \"let the runtime manage reasoning effort\").conflicts(\"reasoningEffort\"),\n    )\n    .addOption(new Option(\"--instructions <text>\", \"Agent runtime instructions\").conflicts(\"instructionsFile\"))\n    .addOption(\n      new Option(\"--instructions-file <path>\", \"read Agent instructions from a UTF-8 file\").conflicts(\"instructions\"),\n    )\n    .addOption(\n      new Option(\"--max-duration-ms <integer>\", \"maximum duration of one Turn in milliseconds\").conflicts(\n        \"clearMaxDuration\",\n      ),\n    )\n    .addOption(new Option(\"--clear-max-duration\", \"use the OpenTag default Turn duration\").conflicts(\"maxDurationMs\"))\n    .option(\"--json\", \"print JSON\")\n    .action(async (agentId, options) => {\n      process.exitCode = await executeCommand(\n        () =>\n          runAgentUpdate(agentId, {\n            displayName: options.displayName,\n            model: options.model,\n            clearModel: options.clearModel,\n            reasoningEffort: options.reasoningEffort,\n            clearReasoningEffort: options.clearReasoningEffort,\n            instructions: options.instructions,\n            instructionsFile: options.instructionsFile,\n            maxDurationMs: options.maxDurationMs,\n            clearMaxDuration: options.clearMaxDuration,\n          }),\n        { json: options.json === true, formatValue: formatAgent, phase: \"request\" },\n      );\n    });\n}\n","import type { Command } from \"commander\";\nimport { registerAgentMcpCommands } from \"../mcp/index.js\";\nimport { registerAgentBindCommand } from \"./bind.js\";\nimport { registerAgentCreateCommand } from \"./create.js\";\nimport { registerAgentDeleteCommand } from \"./delete.js\";\nimport { registerAgentImBindingCommands } from \"./im.js\";\nimport { registerAgentLifecycleCommands } from \"./lifecycle.js\";\nimport { registerAgentListCommand } from \"./list.js\";\nimport { registerAgentSelfCommands } from \"./self.js\";\nimport { registerAgentShowCommand } from \"./show.js\";\nimport { registerAgentUpdateCommand } from \"./update.js\";\n\nexport function registerAgentCommand(program: Command): void {\n  const agent = program.command(\"agent\").description(\"Manage Agents available to the current Account\");\n  registerAgentCreateCommand(agent);\n  registerAgentListCommand(agent);\n  registerAgentShowCommand(agent);\n  registerAgentUpdateCommand(agent);\n  registerAgentBindCommand(agent);\n  registerAgentLifecycleCommands(agent);\n  registerAgentDeleteCommand(agent);\n  registerAgentImBindingCommands(agent);\n  registerAgentMcpCommands(agent);\n  registerAgentSelfCommands(agent);\n}\n","import { join } from \"node:path\";\nimport { resolveOpenTagHomeLayout } from \"@opentag/client\";\n\nexport interface DaemonPaths {\n  clientLog: string;\n  config: string;\n  daemonEnvironment: string;\n  daemonOwner: string;\n  daemonState: string;\n  daemonStderrLog: string;\n  daemonStdoutLog: string;\n  home: string;\n  logs: string;\n  serviceOperation: string;\n  serviceState: string;\n  serviceTargetOperation: string;\n  serviceWrapper(serviceId: string): string;\n}\n\nexport function resolveDaemonPaths(home: string): DaemonPaths {\n  const layout = resolveOpenTagHomeLayout(home);\n  return {\n    clientLog: join(layout.logs, \"client.log\"),\n    config: layout.config,\n    daemonEnvironment: join(layout.config, \"daemon.env\"),\n    daemonOwner: join(layout.daemonState, \"owner.json\"),\n    daemonState: layout.daemonState,\n    daemonStderrLog: join(layout.logs, \"daemon.stderr.log\"),\n    daemonStdoutLog: join(layout.logs, \"daemon.stdout.log\"),\n    home: layout.home,\n    logs: layout.logs,\n    serviceOperation: join(layout.serviceState, \"operation.json\"),\n    serviceState: layout.serviceState,\n    serviceTargetOperation: join(layout.serviceState, \"target-operation.json\"),\n    serviceWrapper: (serviceId) => join(layout.serviceState, serviceId),\n  };\n}\n","/** Build a detached child-process environment without changing the parent process. */\nexport function buildChildEnvironment(\n  baseEnvironment: NodeJS.ProcessEnv,\n  options: { keys?: readonly string[]; overrides?: NodeJS.ProcessEnv } = {},\n): NodeJS.ProcessEnv {\n  const keys = options.keys ?? Object.keys(baseEnvironment);\n  const environment: NodeJS.ProcessEnv = {};\n  for (const key of keys) {\n    const value = baseEnvironment[key];\n    if (value !== undefined) environment[key] = value;\n  }\n  for (const [key, value] of Object.entries(options.overrides ?? {})) {\n    if (value !== undefined) environment[key] = value;\n  }\n  return environment;\n}\n","import { execFile } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { lstat, open, readFile, rename, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { ensurePrivateDirectory, validatePrivateDirectory } from \"@opentag/client\";\nimport { buildChildEnvironment } from \"../command/environment.js\";\n\nexport interface ProcessLeaseRecord {\n  pid: number;\n  processStartId: string;\n  startedAt: string;\n}\n\nexport interface ProcessFileLease<T extends ProcessLeaseRecord> {\n  path: string;\n  record: T;\n  release(): Promise<void>;\n}\n\nexport type ProcessLeaseInspection<T extends ProcessLeaseRecord> =\n  | { state: \"missing\" }\n  | { record: T; state: \"live\" | \"stale\" };\n\nexport interface ProcessLeaseOptions<T extends ProcessLeaseRecord> {\n  createRecord(processStartId: string): T;\n  fileName: string;\n  getProcessIdentity?: (pid: number) => Promise<ProcessIdentityInspection>;\n  getId(record: T): string;\n  parseRecord(value: unknown): T;\n  rootDirectory?: string;\n}\n\nexport type ProcessIdentityInspection = { id: string; state: \"identified\" } | { state: \"gone\" | \"unverifiable\" };\n\nexport interface ProcessIdentityInspectionDependencies {\n  inspectDarwin?: (pid: number) => Promise<ProcessIdentityInspection>;\n  isProcessAlive?: (pid: number) => boolean;\n  platform?: NodeJS.Platform;\n  readLinuxProcessFile?: (path: string) => Promise<string>;\n}\n\nexport interface DarwinProcessIdentityInspectionDependencies {\n  isProcessAlive?: (pid: number) => boolean;\n  readProcessStart?: (pid: number, environment: NodeJS.ProcessEnv) => Promise<string | undefined>;\n}\n\nexport class ProcessLeaseBusyError extends Error {\n  override readonly name = \"ProcessLeaseBusyError\";\n\n  constructor(readonly pid: number) {\n    super(`A live process already owns this operation (pid ${pid})`);\n  }\n}\n\nexport class ProcessLeaseMalformedError extends Error {\n  override readonly name = \"ProcessLeaseMalformedError\";\n}\n\nexport class ProcessLeaseUnverifiableError extends Error {\n  override readonly name = \"ProcessLeaseUnverifiableError\";\n}\n\nexport async function acquireProcessFileLease<T extends ProcessLeaseRecord>(\n  home: string,\n  options: ProcessLeaseOptions<T>,\n): Promise<ProcessFileLease<T>> {\n  await ensurePrivateDirectory(options.rootDirectory ?? home, home);\n  const path = join(home, options.fileName);\n  const getProcessIdentity = options.getProcessIdentity ?? inspectProcessIdentity;\n  const currentIdentity = await getProcessIdentity(process.pid);\n  if (currentIdentity.state !== \"identified\") {\n    throw new ProcessLeaseUnverifiableError(\n      \"Cannot determine the current process start identity; refusing acquisition\",\n    );\n  }\n  const guard = await acquireLeaseMutationGuard(home, options.fileName, getProcessIdentity, currentIdentity.id);\n  try {\n    let existing: T | undefined;\n    try {\n      existing = await readProcessLease(path, options.parseRecord);\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n    }\n    if (existing) {\n      const identity = await getProcessIdentity(existing.pid);\n      if (identity.state === \"unverifiable\") {\n        throw new ProcessLeaseUnverifiableError(\n          `Cannot verify whether process ${existing.pid} still owns ${options.fileName}; refusing takeover`,\n        );\n      }\n      if (identity.state === \"identified\" && identity.id === existing.processStartId) {\n        throw new ProcessLeaseBusyError(existing.pid);\n      }\n      await rename(path, `${path}.stale.${options.getId(existing)}.${randomUUID()}`);\n    }\n    const record = options.createRecord(currentIdentity.id);\n    await createLeaseFile(path, record);\n    return leaseFor(path, record, options.getId, options.parseRecord);\n  } finally {\n    await guard.release();\n  }\n}\n\nexport async function inspectProcessFileLease<T extends ProcessLeaseRecord>(\n  home: string,\n  options: Omit<ProcessLeaseOptions<T>, \"createRecord\">,\n): Promise<ProcessLeaseInspection<T>> {\n  if (!(await validatePrivateDirectory(options.rootDirectory ?? home, home))) return { state: \"missing\" };\n  const path = join(home, options.fileName);\n  let record: T;\n  try {\n    record = await readProcessLease(path, options.parseRecord);\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { state: \"missing\" };\n    throw error;\n  }\n  const identity = await (options.getProcessIdentity ?? inspectProcessIdentity)(record.pid);\n  if (identity.state === \"unverifiable\") {\n    throw new ProcessLeaseUnverifiableError(\n      `Cannot verify whether process ${record.pid} still owns ${options.fileName}`,\n    );\n  }\n  const live = identity.state === \"identified\" && identity.id === record.processStartId;\n  return { record, state: live ? \"live\" : \"stale\" };\n}\n\ninterface LeaseMutationGuard extends ProcessLeaseRecord {\n  guardId: string;\n}\n\nasync function acquireLeaseMutationGuard(\n  home: string,\n  fileName: string,\n  getProcessIdentity: (pid: number) => Promise<ProcessIdentityInspection>,\n  processStartId: string,\n): Promise<ProcessFileLease<LeaseMutationGuard>> {\n  const path = join(home, `.${fileName}.acquire`);\n  const record: LeaseMutationGuard = {\n    guardId: randomUUID(),\n    pid: process.pid,\n    processStartId,\n    startedAt: new Date().toISOString(),\n  };\n  try {\n    await createLeaseFile(path, record);\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") throw error;\n    const existing = await readProcessLease(path, parseMutationGuard);\n    const currentIdentity = await getProcessIdentity(existing.pid);\n    if (currentIdentity.state === \"unverifiable\") {\n      throw new ProcessLeaseUnverifiableError(\n        `Cannot verify the process holding the acquisition guard at ${path}; refusing takeover`,\n      );\n    }\n    if (currentIdentity.state === \"identified\" && currentIdentity.id === existing.processStartId) {\n      throw new ProcessLeaseBusyError(existing.pid);\n    }\n    throw new ProcessLeaseMalformedError(\n      `A stale process lease acquisition guard remains at ${path}; refusing unsafe automatic recovery`,\n    );\n  }\n  return leaseFor(path, record, (value) => value.guardId, parseMutationGuard);\n}\n\nasync function createLeaseFile<T>(path: string, record: T): Promise<void> {\n  let handle: Awaited<ReturnType<typeof open>> | undefined;\n  try {\n    handle = await open(path, \"wx\", 0o600);\n    await handle.writeFile(`${JSON.stringify(record)}\\n`);\n    await handle.sync();\n    await handle.close();\n  } catch (error) {\n    await handle?.close().catch(() => undefined);\n    if (handle) await rm(path, { force: true }).catch(() => undefined);\n    throw error;\n  }\n}\n\nfunction leaseFor<T extends ProcessLeaseRecord>(\n  path: string,\n  record: T,\n  getId: (record: T) => string,\n  parseRecord: (value: unknown) => T,\n): ProcessFileLease<T> {\n  return {\n    path,\n    record,\n    release: async () => {\n      let current: T;\n      try {\n        current = await readProcessLease(path, parseRecord);\n      } catch (error) {\n        if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return;\n        throw error;\n      }\n      if (getId(current) !== getId(record)) return;\n      await rm(path);\n    },\n  };\n}\n\nasync function readProcessLease<T extends ProcessLeaseRecord>(\n  path: string,\n  parseRecord: (value: unknown) => T,\n): Promise<T> {\n  const status = await lstat(path);\n  if (!status.isFile() || status.isSymbolicLink()) {\n    throw new ProcessLeaseMalformedError(\"The process lease must be a real regular file\");\n  }\n  let value: unknown;\n  try {\n    value = JSON.parse(await readFile(path, \"utf8\"));\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === \"ENOENT\") throw error;\n    throw new ProcessLeaseMalformedError(\"The process lease record is malformed\", { cause: error });\n  }\n  try {\n    return parseRecord(value);\n  } catch (error) {\n    if (error instanceof ProcessLeaseMalformedError) throw error;\n    throw new ProcessLeaseMalformedError(\"The process lease record is malformed\", { cause: error });\n  }\n}\n\nfunction isProcessAlive(pid: number): boolean {\n  try {\n    process.kill(pid, 0);\n    return true;\n  } catch (error) {\n    return (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n  }\n}\n\nfunction parseMutationGuard(value: unknown): LeaseMutationGuard {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n    throw new ProcessLeaseMalformedError(\"The process lease acquisition guard is malformed\");\n  }\n  const record = value as Record<string, unknown>;\n  if (\n    typeof record.guardId !== \"string\" ||\n    typeof record.pid !== \"number\" ||\n    !Number.isInteger(record.pid) ||\n    record.pid <= 0 ||\n    typeof record.processStartId !== \"string\" ||\n    record.processStartId.length === 0 ||\n    typeof record.startedAt !== \"string\"\n  ) {\n    throw new ProcessLeaseMalformedError(\"The process lease acquisition guard is malformed\");\n  }\n  return record as unknown as LeaseMutationGuard;\n}\n\nexport async function inspectProcessIdentity(\n  pid: number,\n  dependencies: ProcessIdentityInspectionDependencies = {},\n): Promise<ProcessIdentityInspection> {\n  const processIsAlive = dependencies.isProcessAlive ?? isProcessAlive;\n  if (!processIsAlive(pid)) return { state: \"gone\" };\n  const platform = dependencies.platform ?? process.platform;\n  if (platform === \"linux\") {\n    const readProcessFile = dependencies.readLinuxProcessFile ?? ((path: string) => readFile(path, \"utf8\"));\n    try {\n      const [stat, bootId] = await Promise.all([\n        readProcessFile(`/proc/${pid}/stat`),\n        readProcessFile(\"/proc/sys/kernel/random/boot_id\"),\n      ]);\n      const fields = stat\n        .slice(stat.lastIndexOf(\")\") + 2)\n        .trim()\n        .split(/\\s+/u);\n      const startTicks = fields[19];\n      return startTicks\n        ? { id: `linux:${bootId.trim()}:${startTicks}`, state: \"identified\" }\n        : { state: \"unverifiable\" };\n    } catch {\n      return processIsAlive(pid) ? { state: \"unverifiable\" } : { state: \"gone\" };\n    }\n  }\n  if (platform === \"darwin\") {\n    return (dependencies.inspectDarwin ?? inspectDarwinProcessIdentity)(pid);\n  }\n  return pid === process.pid\n    ? { id: `self:${Math.floor(performance.timeOrigin)}`, state: \"identified\" }\n    : { state: \"unverifiable\" };\n}\n\nexport async function inspectDarwinProcessIdentity(\n  pid: number,\n  dependencies: DarwinProcessIdentityInspectionDependencies = {},\n): Promise<ProcessIdentityInspection> {\n  const environment = buildChildEnvironment(process.env, {\n    keys: [\"LANG\", \"LC_ALL\", \"TZ\"],\n    overrides: { LANG: \"C\", LC_ALL: \"C\", TZ: \"UTC\" },\n  });\n  const startedAt = await (dependencies.readProcessStart ?? readDarwinProcessStart)(pid, environment);\n  if (startedAt) return { id: `darwin:${startedAt}`, state: \"identified\" };\n  return (dependencies.isProcessAlive ?? isProcessAlive)(pid) ? { state: \"unverifiable\" } : { state: \"gone\" };\n}\n\nfunction readDarwinProcessStart(pid: number, environment: NodeJS.ProcessEnv): Promise<string | undefined> {\n  return new Promise((resolveStart) => {\n    execFile(\n      \"ps\",\n      [\"-o\", \"lstart=\", \"-p\", String(pid)],\n      {\n        encoding: \"utf8\",\n        env: environment,\n        timeout: 5_000,\n      },\n      (error, stdout) => {\n        const startedAt = String(stdout ?? \"\").trim();\n        resolveStart(!error && startedAt ? startedAt : undefined);\n      },\n    );\n  });\n}\n","import { randomUUID } from \"node:crypto\";\nimport { basename } from \"node:path\";\nimport { resolveDaemonPaths } from \"./paths.js\";\nimport {\n  acquireProcessFileLease,\n  inspectProcessFileLease,\n  type ProcessFileLease,\n  ProcessLeaseBusyError,\n  type ProcessLeaseInspection,\n  ProcessLeaseMalformedError,\n  ProcessLeaseUnverifiableError,\n} from \"./process-lease.js\";\n\nexport interface DaemonOwner {\n  home: string;\n  instanceId: string;\n  ownerId: string;\n  pid: number;\n  processStartId: string;\n  startedAt: string;\n}\n\nexport interface DaemonOwnerLease {\n  owner: DaemonOwner;\n  release(): Promise<void>;\n}\n\nexport class DaemonOwnerStartupError extends Error {\n  override readonly name = \"DaemonOwnerStartupError\";\n\n  constructor(\n    readonly code: \"BUSY\" | \"MALFORMED\" | \"UNVERIFIABLE\",\n    message: string,\n    options?: ErrorOptions,\n  ) {\n    super(message, options);\n  }\n}\n\nexport async function acquireDaemonOwner(home: string, instanceId: string): Promise<DaemonOwnerLease> {\n  const paths = resolveDaemonPaths(home);\n  let lease: ProcessFileLease<DaemonOwner>;\n  try {\n    lease = await acquireProcessFileLease(paths.daemonState, {\n      createRecord: (processStartId) => ({\n        home,\n        instanceId,\n        ownerId: randomUUID(),\n        pid: process.pid,\n        processStartId,\n        startedAt: new Date().toISOString(),\n      }),\n      fileName: basename(paths.daemonOwner),\n      getId: (owner) => owner.ownerId,\n      parseRecord: parseOwner,\n      rootDirectory: paths.home,\n    });\n  } catch (error) {\n    if (error instanceof ProcessLeaseBusyError) {\n      throw new DaemonOwnerStartupError(\n        \"BUSY\",\n        `An OpenTag daemon is already running for this home (pid ${error.pid})`,\n        {\n          cause: error,\n        },\n      );\n    }\n    throw normalizeOwnerError(error);\n  }\n\n  return {\n    owner: lease.record,\n    release: lease.release,\n  };\n}\n\nexport async function inspectDaemonOwner(home: string): Promise<ProcessLeaseInspection<DaemonOwner>> {\n  const paths = resolveDaemonPaths(home);\n  try {\n    return await inspectProcessFileLease(paths.daemonState, {\n      fileName: basename(paths.daemonOwner),\n      getId: (owner) => owner.ownerId,\n      parseRecord: parseOwner,\n      rootDirectory: paths.home,\n    });\n  } catch (error) {\n    throw normalizeOwnerError(error);\n  }\n}\n\nfunction parseOwner(value: unknown): DaemonOwner {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n    throw new Error(\"The daemon owner record is malformed; refusing automatic recovery\");\n  }\n  const record = value as Record<string, unknown>;\n  if (\n    typeof record.home !== \"string\" ||\n    typeof record.instanceId !== \"string\" ||\n    typeof record.ownerId !== \"string\" ||\n    typeof record.pid !== \"number\" ||\n    !Number.isInteger(record.pid) ||\n    record.pid <= 0 ||\n    typeof record.processStartId !== \"string\" ||\n    record.processStartId.length === 0 ||\n    typeof record.startedAt !== \"string\"\n  ) {\n    throw new Error(\"The daemon owner record is malformed; refusing automatic recovery\");\n  }\n  return record as unknown as DaemonOwner;\n}\n\nfunction normalizeOwnerError(error: unknown): Error {\n  if (error instanceof ProcessLeaseMalformedError) {\n    return new DaemonOwnerStartupError(\n      \"MALFORMED\",\n      \"The daemon owner record is malformed; refusing automatic recovery\",\n      {\n        cause: error,\n      },\n    );\n  }\n  if (error instanceof ProcessLeaseUnverifiableError) {\n    return new DaemonOwnerStartupError(\"UNVERIFIABLE\", error.message, { cause: error });\n  }\n  return error instanceof Error ? error : new Error(String(error));\n}\n","export type DaemonServiceState = \"active\" | \"inactive\" | \"not-installed\" | \"unknown\";\nexport type DaemonServicePlatform = \"launchd\" | \"systemd\" | \"unsupported\";\n\nexport interface RuntimeOwnerInfo {\n  consistency: \"consistent\" | \"malformed\" | \"missing\" | \"stale\" | \"unmanaged\" | \"unverified\";\n  pid?: number;\n}\n\nexport interface DaemonServiceInfo {\n  configuredHome?: string;\n  currentHome: string;\n  definitionPath: string;\n  detail?: string;\n  drifted?: boolean;\n  logHint: string;\n  pid?: number;\n  platform: DaemonServicePlatform;\n  runtimeOwner?: RuntimeOwnerInfo;\n  serviceId: string;\n  state: DaemonServiceState;\n}\n\nexport interface ResolvedCliInvocation {\n  args: string[];\n  program: string;\n}\n\nexport interface CommandRunOptions {\n  env?: NodeJS.ProcessEnv;\n  timeoutMs: number;\n}\n\nexport interface CommandResult {\n  code: number | null;\n  stderr: string;\n  stdout: string;\n  timedOut: boolean;\n}\n\nexport interface ServiceRunner {\n  run(program: string, args: readonly string[], options: CommandRunOptions): Promise<CommandResult>;\n}\n\nexport interface DaemonServiceBackend {\n  readonly platform: DaemonServicePlatform;\n  installAndStart(): Promise<DaemonServiceInfo>;\n  preflight(): Promise<void>;\n  /**\n   * Rewrite the on-disk service definition from the current binary's templates without restarting\n   * the service. Used by the portable upgrade handoff so the definition the supervisor reloads\n   * comes from the newly installed version.\n   */\n  refreshDefinition(): Promise<DaemonServiceInfo>;\n  restart(): Promise<DaemonServiceInfo>;\n  start(): Promise<DaemonServiceInfo>;\n  status(): Promise<DaemonServiceInfo>;\n  stop(): Promise<DaemonServiceInfo>;\n  uninstall(): Promise<DaemonServiceInfo>;\n}\n\nexport type DaemonServiceErrorCode =\n  | \"BUSY\"\n  | \"CONFIGURATION\"\n  | \"MANAGER_UNAVAILABLE\"\n  | \"NOT_INSTALLED\"\n  | \"OPERATION_FAILED\"\n  | \"UNSUPPORTED_PLATFORM\";\n\nexport class DaemonServiceError extends Error {\n  override readonly name = \"DaemonServiceError\";\n\n  constructor(\n    readonly code: DaemonServiceErrorCode,\n    message: string,\n    options?: ErrorOptions,\n  ) {\n    super(message, options);\n  }\n}\n","import { execFile } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { access, chmod, lstat, mkdir, open, readFile, realpath, rename, rm, stat } from \"node:fs/promises\";\nimport { basename, delimiter, dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { ensurePrivateDirectory } from \"@opentag/client\";\nimport { buildChildEnvironment } from \"../../command/environment.js\";\nimport { resolveDaemonPaths } from \"../paths.js\";\nimport {\n  acquireProcessFileLease,\n  ProcessLeaseBusyError,\n  ProcessLeaseMalformedError,\n  ProcessLeaseUnverifiableError,\n} from \"../process-lease.js\";\nimport {\n  type CommandResult,\n  DaemonServiceError,\n  type DaemonServiceErrorCode,\n  type ResolvedCliInvocation,\n  type ServiceRunner,\n} from \"./types.js\";\n\nconst COMMAND_TIMEOUT_MS = 15_000;\n\ninterface ServiceOperationRecord {\n  operationId: string;\n  pid: number;\n  processStartId: string;\n  startedAt: string;\n}\n\nexport interface ServiceOperationLease {\n  release(): Promise<void>;\n}\n\nexport interface ServiceIdentity {\n  launchdLabel: string;\n  launchdPlistName: string;\n  launchdWrapperName: string;\n  systemdUnitName: string;\n}\n\nexport const defaultServiceRunner: ServiceRunner = {\n  async run(program, args, options) {\n    const resolvedProgram = await resolveServiceManagerExecutable(program);\n    return new Promise<CommandResult>((complete) => {\n      execFile(\n        resolvedProgram,\n        [...args],\n        {\n          encoding: \"utf8\",\n          env: options.env ?? buildChildEnvironment(process.env),\n          maxBuffer: 1024 * 1024,\n          timeout: options.timeoutMs,\n        },\n        (error, stdout, stderr) => {\n          const commandError = error as NodeJS.ErrnoException & { killed?: boolean; signal?: string };\n          complete({\n            code: error ? (typeof commandError.code === \"number\" ? commandError.code : null) : 0,\n            stderr: String(stderr ?? \"\").trim(),\n            stdout: String(stdout ?? \"\").trim(),\n            timedOut: Boolean(error && commandError.killed && commandError.signal),\n          });\n        },\n      );\n    });\n  },\n};\n\nconst SERVICE_MANAGER_LOCATIONS = {\n  darwin: {\n    launchctl: [\"/bin/launchctl\"],\n  },\n  linux: {\n    loginctl: [\"/run/current-system/systemd/bin/loginctl\", \"/usr/bin/loginctl\", \"/bin/loginctl\"],\n    systemctl: [\"/run/current-system/systemd/bin/systemctl\", \"/usr/bin/systemctl\", \"/bin/systemctl\"],\n  },\n} as const;\n\nexport async function resolveServiceManagerExecutable(\n  program: string,\n  platform: NodeJS.Platform = process.platform,\n  dependencies: {\n    access?: (path: string, mode: number) => Promise<void>;\n    stat?: (path: string) => Promise<{ isFile(): boolean }>;\n  } = {},\n): Promise<string> {\n  const platformLocations =\n    platform === \"darwin\"\n      ? SERVICE_MANAGER_LOCATIONS.darwin\n      : platform === \"linux\"\n        ? SERVICE_MANAGER_LOCATIONS.linux\n        : undefined;\n  const managerName = isAbsolute(program) ? basename(program) : program;\n  if (!platformLocations || !(managerName in platformLocations)) {\n    throw new DaemonServiceError(\n      \"MANAGER_UNAVAILABLE\",\n      `The ${program} service manager is not governed on ${platform}`,\n    );\n  }\n  const candidates = platformLocations[managerName as keyof typeof platformLocations] as readonly string[];\n  const allowedCandidates = isAbsolute(program) ? candidates.filter((candidate) => candidate === program) : candidates;\n  if (allowedCandidates.length === 0) {\n    throw new DaemonServiceError(\"MANAGER_UNAVAILABLE\", `The service manager path is not supported: ${program}`);\n  }\n  const checkAccess = dependencies.access ?? access;\n  const checkStat = dependencies.stat ?? stat;\n  for (const candidate of allowedCandidates) {\n    try {\n      if (!(await checkStat(candidate)).isFile()) continue;\n      await checkAccess(candidate, constants.X_OK);\n      return candidate;\n    } catch {\n      // Continue through the reviewed absolute location list only.\n    }\n  }\n  throw new DaemonServiceError(\n    \"MANAGER_UNAVAILABLE\",\n    `The ${program} service manager is unavailable at supported system locations`,\n  );\n}\n\nexport function deriveServiceIdentity(serviceId: string): ServiceIdentity {\n  return {\n    launchdLabel: serviceId,\n    launchdPlistName: `${serviceId}.plist`,\n    launchdWrapperName: serviceId,\n    systemdUnitName: `${serviceId}.service`,\n  };\n}\n\nexport async function resolveCliInvocation(options: {\n  argv?: readonly string[];\n  binName: string;\n  cwd?: string;\n  env?: NodeJS.ProcessEnv;\n  execPath?: string;\n}): Promise<ResolvedCliInvocation> {\n  const environment = options.env ?? process.env;\n  const bin = await findExecutable(options.binName, environment.PATH);\n  if (bin) return { args: [], program: await realpath(bin).catch(() => bin) };\n\n  const argv = options.argv ?? process.argv;\n  const script = argv[1];\n  if (!script) {\n    throw new DaemonServiceError(\"CONFIGURATION\", \"Cannot resolve the OpenTag CLI entry script\");\n  }\n  const program = options.execPath ?? process.execPath;\n  if (!isAbsolute(program)) {\n    throw new DaemonServiceError(\"CONFIGURATION\", \"The Node.js executable path must be absolute\");\n  }\n  const scriptPath = isAbsolute(script) ? script : resolve(options.cwd ?? process.cwd(), script);\n  return {\n    args: [await realpath(scriptPath).catch(() => scriptPath)],\n    program: await realpath(program).catch(() => program),\n  };\n}\n\nexport function buildServicePath(\n  invocation: ResolvedCliInvocation,\n  platform: \"darwin\" | \"linux\",\n  sourcePath?: string,\n): string {\n  const base =\n    platform === \"darwin\"\n      ? [\"/usr/local/bin\", \"/opt/homebrew/bin\", \"/usr/bin\", \"/bin\"]\n      : [\"/usr/local/bin\", \"/usr/bin\", \"/bin\"];\n  const inherited = (sourcePath ?? \"\")\n    .split(delimiter)\n    .map((entry) => entry.trim())\n    .filter((entry) => entry.length > 0 && isAbsolute(entry));\n  return [...new Set([dirname(invocation.program), dirname(process.execPath), ...inherited, ...base])].join(delimiter);\n}\n\nexport function invocationArguments(invocation: ResolvedCliInvocation): string[] {\n  return [invocation.program, ...invocation.args, \"daemon\", \"service-run\"];\n}\n\nexport function quoteSystemdToken(value: string): string {\n  return `\"${value\n    .replace(/\\\\/g, \"\\\\\\\\\")\n    .replace(/\\n/g, \"\\\\n\")\n    .replace(/\\r/g, \"\\\\r\")\n    .replace(/\\t/g, \"\\\\t\")\n    .replace(/\"/g, '\\\\\"')\n    .replace(/%/g, \"%%\")}\"`;\n}\n\nexport function quoteSystemdEnvironment(name: string, value: string): string {\n  return `Environment=${quoteSystemdToken(`${name}=${value}`)}`;\n}\n\nexport function quotePosix(value: string): string {\n  return `'${value.replace(/'/g, `'\"'\"'`)}'`;\n}\n\nexport function escapeXml(value: string): string {\n  return value\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&apos;\");\n}\n\nexport async function writeFileAtomically(\n  path: string,\n  content: string,\n  mode: number,\n  directoryMode = 0o700,\n  containmentRoot?: string,\n): Promise<void> {\n  const parent = dirname(path);\n  if (containmentRoot) {\n    await ensurePrivateDirectory(containmentRoot, parent);\n  } else {\n    await mkdir(parent, { recursive: true, mode: directoryMode });\n  }\n  const temporaryPath = join(parent, `.${randomUUID()}.tmp`);\n  try {\n    const handle = await open(temporaryPath, \"wx\", mode);\n    try {\n      await handle.writeFile(content);\n      await handle.sync();\n    } finally {\n      await handle.close();\n    }\n    await chmod(temporaryPath, mode);\n    await rename(temporaryPath, path);\n  } catch (error) {\n    await rm(temporaryPath, { force: true }).catch(() => undefined);\n    throw error;\n  }\n}\n\nexport async function readRegularFile(path: string): Promise<string | undefined> {\n  try {\n    const status = await lstat(path);\n    if (!status.isFile() || status.isSymbolicLink()) {\n      throw new DaemonServiceError(\"CONFIGURATION\", `Expected a regular file at ${path}`);\n    }\n    return await readFile(path, \"utf8\");\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n    throw error;\n  }\n}\n\nexport async function runRequired(\n  runner: ServiceRunner,\n  program: string,\n  args: readonly string[],\n  operation: string,\n  timeoutMs = COMMAND_TIMEOUT_MS,\n): Promise<CommandResult> {\n  const result = await runner.run(program, args, { timeoutMs });\n  if (result.code === 0 && !result.timedOut) return result;\n  const detail = result.timedOut\n    ? `timed out after ${timeoutMs}ms`\n    : result.stderr || `exited with code ${result.code}`;\n  throw new DaemonServiceError(\"OPERATION_FAILED\", `${operation} failed: ${detail}`);\n}\n\nexport async function acquireServiceOperationLease(home: string): Promise<ServiceOperationLease> {\n  const paths = resolveDaemonPaths(home);\n  return acquireMappedOperationLease(\n    paths.home,\n    paths.serviceState,\n    basename(paths.serviceOperation),\n    \"Another daemon service operation\",\n  );\n}\n\nexport async function acquireServiceTargetLease(\n  channelDefaultHome: string,\n  serviceId: string,\n): Promise<ServiceOperationLease> {\n  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(serviceId)) {\n    throw new DaemonServiceError(\"CONFIGURATION\", \"The daemon service ID is invalid\");\n  }\n  const paths = resolveDaemonPaths(channelDefaultHome);\n  return acquireMappedOperationLease(\n    paths.home,\n    paths.serviceState,\n    basename(paths.serviceTargetOperation),\n    `Another ${serviceId} service-target operation`,\n  );\n}\n\nasync function acquireMappedOperationLease(\n  root: string,\n  directory: string,\n  fileName: string,\n  busyLabel: string,\n): Promise<ServiceOperationLease> {\n  try {\n    const lease = await acquireProcessFileLease<ServiceOperationRecord>(directory, {\n      createRecord: (processStartId) => ({\n        operationId: randomUUID(),\n        pid: process.pid,\n        processStartId,\n        startedAt: new Date().toISOString(),\n      }),\n      fileName,\n      getId: (record) => record.operationId,\n      parseRecord: parseServiceOperation,\n      rootDirectory: root,\n    });\n    return { release: lease.release };\n  } catch (error) {\n    if (error instanceof ProcessLeaseBusyError) {\n      throw new DaemonServiceError(\"BUSY\", `${busyLabel} is already running (pid ${error.pid})`, {\n        cause: error,\n      });\n    }\n    if (error instanceof ProcessLeaseMalformedError) {\n      throw new DaemonServiceError(\"CONFIGURATION\", error.message, { cause: error });\n    }\n    if (error instanceof ProcessLeaseUnverifiableError) {\n      throw new DaemonServiceError(\"CONFIGURATION\", error.message, { cause: error });\n    }\n    throw error;\n  }\n}\n\nexport function serviceError(code: DaemonServiceErrorCode, message: string, cause?: unknown): DaemonServiceError {\n  return new DaemonServiceError(code, message, cause === undefined ? undefined : { cause });\n}\n\nexport function isManagerNotLoaded(result: CommandResult): boolean {\n  const detail = `${result.stdout}\\n${result.stderr}`.toLowerCase();\n  return (\n    result.code !== 0 &&\n    (detail.includes(\"not loaded\") ||\n      detail.includes(\"could not find service\") ||\n      detail.includes(\"not found\") ||\n      detail.includes(\"no such process\"))\n  );\n}\n\nexport async function pathExists(path: string): Promise<boolean> {\n  try {\n    await access(path);\n    return true;\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n    throw error;\n  }\n}\n\nexport async function preflightHomeDirectory(home: string): Promise<void> {\n  if (!isAbsolute(home)) {\n    throw new DaemonServiceError(\"CONFIGURATION\", \"The OpenTag home path must be absolute\");\n  }\n  let current = home;\n  for (;;) {\n    try {\n      const status = await lstat(current);\n      if (!status.isDirectory() || status.isSymbolicLink()) {\n        throw new DaemonServiceError(\n          \"CONFIGURATION\",\n          `The OpenTag home must resolve beneath a real directory: ${current}`,\n        );\n      }\n      await access(current, constants.W_OK | constants.X_OK);\n      return;\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n        if (error instanceof DaemonServiceError) throw error;\n        throw new DaemonServiceError(\"CONFIGURATION\", `The OpenTag home is not writable: ${home}`, { cause: error });\n      }\n      const parent = dirname(current);\n      if (parent === current) {\n        throw new DaemonServiceError(\"CONFIGURATION\", `Cannot find a writable parent for the OpenTag home: ${home}`);\n      }\n      current = parent;\n    }\n  }\n}\n\nexport async function canonicalizeServiceHome(path: string): Promise<string> {\n  if (!isAbsolute(path)) {\n    throw new DaemonServiceError(\"CONFIGURATION\", \"The OpenTag home path must be absolute\");\n  }\n  const missingSegments: string[] = [];\n  let current = resolve(path);\n  for (;;) {\n    try {\n      const canonicalParent = await realpath(current);\n      return resolve(canonicalParent, ...missingSegments);\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n        throw new DaemonServiceError(\"CONFIGURATION\", `Cannot canonicalize the OpenTag home path: ${path}`, {\n          cause: error,\n        });\n      }\n      const parent = dirname(current);\n      if (parent === current) {\n        throw new DaemonServiceError(\"CONFIGURATION\", `Cannot canonicalize the OpenTag home path: ${path}`);\n      }\n      missingSegments.unshift(basename(current));\n      current = parent;\n    }\n  }\n}\n\nexport function sleep(milliseconds: number): Promise<void> {\n  return new Promise((complete) => setTimeout(complete, milliseconds));\n}\n\nfunction parseServiceOperation(value: unknown): ServiceOperationRecord {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n    throw new Error(\"The service operation lease is malformed\");\n  }\n  const record = value as Record<string, unknown>;\n  if (\n    typeof record.operationId !== \"string\" ||\n    typeof record.pid !== \"number\" ||\n    !Number.isInteger(record.pid) ||\n    record.pid <= 0 ||\n    typeof record.processStartId !== \"string\" ||\n    record.processStartId.length === 0 ||\n    typeof record.startedAt !== \"string\"\n  ) {\n    throw new Error(\"The service operation lease is malformed\");\n  }\n  return record as unknown as ServiceOperationRecord;\n}\n\nasync function findExecutable(binName: string, pathValue: string | undefined): Promise<string | undefined> {\n  for (const directory of pathValue?.split(delimiter).filter(Boolean) ?? []) {\n    const candidate = join(directory, binName);\n    try {\n      await access(candidate, constants.X_OK);\n      return candidate;\n    } catch {\n      // Continue searching PATH.\n    }\n  }\n  return undefined;\n}\n","import { rm } from \"node:fs/promises\";\nimport { userInfo } from \"node:os\";\nimport { join } from \"node:path\";\nimport { ensurePrivateDirectory } from \"@opentag/client\";\nimport { resolveDaemonPaths } from \"../paths.js\";\nimport {\n  buildServicePath,\n  deriveServiceIdentity,\n  escapeXml,\n  invocationArguments,\n  isManagerNotLoaded,\n  quotePosix,\n  readRegularFile,\n  runRequired,\n  sleep,\n  writeFileAtomically,\n} from \"./shared.js\";\nimport type { DaemonServiceBackend, DaemonServiceInfo, ResolvedCliInvocation, ServiceRunner } from \"./types.js\";\nimport { DaemonServiceError } from \"./types.js\";\n\nconst LAUNCHD_TIMEOUT_MS = 15_000;\n\nexport interface LaunchdBackendOptions {\n  activationAttempts?: number;\n  activationDelayMs?: number;\n  evictionAttempts?: number;\n  evictionDelayMs?: number;\n  home: string;\n  invocation: ResolvedCliInvocation;\n  launchctl?: string;\n  runner: ServiceRunner;\n  serviceId: string;\n  sourcePath?: string;\n  sleep?: (milliseconds: number) => Promise<void>;\n  uid?: number;\n  userHome?: string;\n}\n\nexport function renderLaunchdWrapper(invocation: ResolvedCliInvocation): string {\n  return `#!/bin/sh\\nexec ${invocationArguments(invocation).map(quotePosix).join(\" \")}\\n`;\n}\n\nexport function renderLaunchdPlist(options: {\n  home: string;\n  label: string;\n  path: string;\n  stderrPath: string;\n  stdoutPath: string;\n  wrapperPath: string;\n}): string {\n  return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n  <key>Label</key>\n  <string>${escapeXml(options.label)}</string>\n  <key>ProgramArguments</key>\n  <array>\n    <string>${escapeXml(options.wrapperPath)}</string>\n  </array>\n  <key>RunAtLoad</key>\n  <true/>\n  <key>KeepAlive</key>\n  <dict>\n    <key>SuccessfulExit</key>\n    <false/>\n  </dict>\n  <key>ThrottleInterval</key>\n  <integer>10</integer>\n  <key>EnvironmentVariables</key>\n  <dict>\n    <key>PATH</key>\n    <string>${escapeXml(options.path)}</string>\n    <key>OPENTAG_SERVICE_MODE</key>\n    <string>1</string>\n    <key>OPENTAG_HOME</key>\n    <string>${escapeXml(options.home)}</string>\n  </dict>\n  <key>StandardOutPath</key>\n  <string>${escapeXml(options.stdoutPath)}</string>\n  <key>StandardErrorPath</key>\n  <string>${escapeXml(options.stderrPath)}</string>\n</dict>\n</plist>\n`;\n}\n\nexport function createLaunchdBackend(options: LaunchdBackendOptions): DaemonServiceBackend {\n  const identity = deriveServiceIdentity(options.serviceId);\n  const account = options.uid === undefined || options.userHome === undefined ? userInfo() : undefined;\n  const uid = options.uid ?? account?.uid;\n  const userHome = options.userHome ?? account?.homedir;\n  if (uid === undefined || userHome === undefined) {\n    throw new DaemonServiceError(\"CONFIGURATION\", \"The operating system account record is incomplete\");\n  }\n  const domain = `gui/${uid}`;\n  const target = `${domain}/${identity.launchdLabel}`;\n  const launchctl = options.launchctl ?? \"launchctl\";\n  const plistPath = join(userHome, \"Library\", \"LaunchAgents\", identity.launchdPlistName);\n  const paths = resolveDaemonPaths(options.home);\n  const wrapperPath = paths.serviceWrapper(identity.launchdWrapperName);\n  const logDirectory = paths.logs;\n  const stdoutPath = paths.daemonStdoutLog;\n  const stderrPath = paths.daemonStderrLog;\n  const servicePath = buildServicePath(options.invocation, \"darwin\", options.sourcePath);\n  const expectedWrapper = renderLaunchdWrapper(options.invocation);\n  const expectedPlist = renderLaunchdPlist({\n    home: options.home,\n    label: identity.launchdLabel,\n    path: servicePath,\n    stderrPath,\n    stdoutPath,\n    wrapperPath,\n  });\n  const wait = options.sleep ?? sleep;\n  const activationAttempts = options.activationAttempts ?? 50;\n  const activationDelayMs = options.activationDelayMs ?? 100;\n  const evictionAttempts = options.evictionAttempts ?? 20;\n  const evictionDelayMs = options.evictionDelayMs ?? 100;\n\n  const readStatus = async (failOnTimeout = false): Promise<DaemonServiceInfo> => {\n    const plist = await readRegularFile(plistPath);\n    if (plist === undefined) {\n      const orphaned = await options.runner.run(launchctl, [\"print\", target], { timeoutMs: LAUNCHD_TIMEOUT_MS });\n      if (orphaned.timedOut) {\n        if (failOnTimeout) {\n          throw new DaemonServiceError(\"OPERATION_FAILED\", \"launchd activation status check timed out\");\n        }\n        return info(\"unknown\", {\n          detail: \"launchctl could not verify whether a definition-less service target is loaded\",\n          drifted: true,\n        });\n      }\n      if (orphaned.code === 0) {\n        return info(\"unknown\", {\n          detail: \"launchd still has the service target loaded even though its plist definition is missing\",\n          drifted: true,\n        });\n      }\n      return isManagerNotLoaded(orphaned)\n        ? info(\"not-installed\", { drifted: true })\n        : info(\"unknown\", {\n            detail: orphaned.stderr || orphaned.stdout || `launchctl exited with code ${orphaned.code}`,\n            drifted: true,\n          });\n    }\n    const wrapper = await readRegularFile(wrapperPath);\n    const configuredHome = extractLaunchdHome(plist);\n    if (!configuredHome) {\n      return info(\"unknown\", {\n        detail: \"The installed LaunchAgent does not contain a valid OPENTAG_HOME\",\n        drifted: true,\n      });\n    }\n    const result = await options.runner.run(launchctl, [\"print\", target], { timeoutMs: LAUNCHD_TIMEOUT_MS });\n    const drifted = plist !== expectedPlist || wrapper !== expectedWrapper;\n    if (result.timedOut) {\n      if (failOnTimeout) {\n        throw new DaemonServiceError(\"OPERATION_FAILED\", \"launchd activation status check timed out\");\n      }\n      return info(\"unknown\", { configuredHome, detail: \"launchctl print timed out\", drifted });\n    }\n    if (result.code !== 0) {\n      return isManagerNotLoaded(result)\n        ? info(\"inactive\", { configuredHome, drifted })\n        : info(\"unknown\", { configuredHome, detail: result.stderr || \"launchctl print failed\", drifted });\n    }\n    const pid = parseLaunchdPid(result.stdout);\n    const processState = parseLaunchdState(result.stdout);\n    if (processState === \"running\" && pid) return info(\"active\", { configuredHome, drifted, pid });\n    if (processState && processState !== \"running\") {\n      return info(\"inactive\", {\n        configuredHome,\n        detail: `LaunchAgent is loaded but process state is ${processState}`,\n        drifted,\n      });\n    }\n    return info(\"unknown\", {\n      configuredHome,\n      detail:\n        processState === \"running\"\n          ? \"LaunchAgent is running without a valid PID\"\n          : \"LaunchAgent process state is unavailable\",\n      drifted,\n    });\n  };\n  const status = (): Promise<DaemonServiceInfo> => readStatus();\n\n  const preflight = async (): Promise<void> => {\n    const result = await options.runner.run(launchctl, [\"print\", domain], { timeoutMs: LAUNCHD_TIMEOUT_MS });\n    if (result.code !== 0 || result.timedOut) {\n      throw new DaemonServiceError(\n        \"MANAGER_UNAVAILABLE\",\n        `The launchd user domain is unavailable: ${result.timedOut ? \"command timed out\" : result.stderr || \"unknown error\"}`,\n      );\n    }\n  };\n\n  const bootout = async (): Promise<void> => {\n    const result = await options.runner.run(launchctl, [\"bootout\", target], { timeoutMs: LAUNCHD_TIMEOUT_MS });\n    if (result.code !== 0 && !isManagerNotLoaded(result)) {\n      throw new DaemonServiceError(\"OPERATION_FAILED\", `launchd bootout failed: ${result.stderr || \"unknown error\"}`);\n    }\n  };\n\n  const waitForEviction = async (): Promise<void> => {\n    for (let attempt = 0; attempt < evictionAttempts; attempt += 1) {\n      const result = await options.runner.run(launchctl, [\"print\", target], { timeoutMs: LAUNCHD_TIMEOUT_MS });\n      if (isManagerNotLoaded(result)) return;\n      if (result.timedOut) throw new DaemonServiceError(\"OPERATION_FAILED\", \"launchd eviction check timed out\");\n      await wait(evictionDelayMs);\n    }\n    throw new DaemonServiceError(\"OPERATION_FAILED\", `launchd did not evict ${identity.launchdLabel}`);\n  };\n\n  const bootstrap = async (): Promise<void> => {\n    let result = await options.runner.run(launchctl, [\"bootstrap\", domain, plistPath], {\n      timeoutMs: LAUNCHD_TIMEOUT_MS,\n    });\n    if (result.code !== 0 || result.timedOut) {\n      await wait(evictionDelayMs);\n      result = await options.runner.run(launchctl, [\"bootstrap\", domain, plistPath], { timeoutMs: LAUNCHD_TIMEOUT_MS });\n    }\n    if (result.code !== 0 || result.timedOut) {\n      throw new DaemonServiceError(\n        \"OPERATION_FAILED\",\n        `launchd bootstrap failed: ${result.timedOut ? \"command timed out\" : result.stderr || \"unknown error\"}`,\n      );\n    }\n  };\n\n  const waitForActivation = async (): Promise<DaemonServiceInfo> => {\n    let current: DaemonServiceInfo | undefined;\n    for (let attempt = 0; attempt < activationAttempts; attempt += 1) {\n      current = await readStatus(true);\n      if (current.state === \"active\") return current;\n      if (attempt + 1 < activationAttempts) await wait(activationDelayMs);\n    }\n    const lastState = current ? `; last state: ${current.state}${current.detail ? ` (${current.detail})` : \"\"}` : \"\";\n    throw new DaemonServiceError(\n      \"OPERATION_FAILED\",\n      `launchd reported that the OpenTag service did not become active${lastState}`,\n    );\n  };\n\n  return {\n    platform: \"launchd\",\n    preflight,\n    async installAndStart() {\n      await preflight();\n      await ensurePrivateDirectory(paths.home, logDirectory);\n      await writeFileAtomically(wrapperPath, expectedWrapper, 0o700, 0o700, paths.home);\n      await writeFileAtomically(plistPath, expectedPlist, 0o644, 0o700);\n      await bootout();\n      await waitForEviction();\n      await bootstrap();\n      await runRequired(options.runner, launchctl, [\"enable\", target], \"launchd enable\");\n      return waitForActivation();\n    },\n    async start() {\n      await preflight();\n      if ((await readRegularFile(plistPath)) === undefined) {\n        throw new DaemonServiceError(\"NOT_INSTALLED\", \"The daemon service is not installed; run daemon install\");\n      }\n      const current = await status();\n      if (current.state === \"active\") return current;\n      const loaded = await options.runner.run(launchctl, [\"print\", target], { timeoutMs: LAUNCHD_TIMEOUT_MS });\n      if (loaded.timedOut) {\n        throw new DaemonServiceError(\"OPERATION_FAILED\", \"launchd start state check timed out\");\n      }\n      if (loaded.code === 0) {\n        await runRequired(options.runner, launchctl, [\"kickstart\", \"-k\", target], \"launchd kickstart\");\n      } else if (isManagerNotLoaded(loaded)) {\n        await bootstrap();\n      } else {\n        throw new DaemonServiceError(\n          \"OPERATION_FAILED\",\n          `launchd start state check failed: ${loaded.stderr || \"unknown error\"}`,\n        );\n      }\n      return waitForActivation();\n    },\n    async stop() {\n      if ((await readRegularFile(plistPath)) === undefined) return info(\"not-installed\", { drifted: true });\n      await bootout();\n      await waitForEviction();\n      return status();\n    },\n    async refreshDefinition() {\n      await preflight();\n      const plist = await readRegularFile(plistPath);\n      if (plist === undefined) {\n        throw new DaemonServiceError(\"NOT_INSTALLED\", \"The daemon service is not installed; run daemon install\");\n      }\n      const wrapper = await readRegularFile(wrapperPath);\n      // Rewrite the definition files only: never bootout the label here, because the caller is the\n      // running daemon handing off to the supervisor, and bootout would kill it before the handoff.\n      // launchd re-reads the wrapper path on every restart, so the refreshed wrapper and plist take\n      // effect the next time the supervisor starts the service.\n      if (wrapper !== expectedWrapper) {\n        await writeFileAtomically(wrapperPath, expectedWrapper, 0o700, 0o700, paths.home);\n      }\n      if (plist !== expectedPlist) {\n        await writeFileAtomically(plistPath, expectedPlist, 0o644, 0o700);\n      }\n      return status();\n    },\n    async restart() {\n      await preflight();\n      if ((await readRegularFile(plistPath)) === undefined) {\n        throw new DaemonServiceError(\"NOT_INSTALLED\", \"The daemon service is not installed; run daemon install\");\n      }\n      await bootout();\n      await waitForEviction();\n      await bootstrap();\n      return waitForActivation();\n    },\n    status,\n    async uninstall() {\n      if ((await readRegularFile(plistPath)) === undefined) return info(\"not-installed\", { drifted: true });\n      await bootout();\n      await waitForEviction();\n      await rm(plistPath);\n      await rm(wrapperPath, { force: true });\n      return info(\"not-installed\", { drifted: true });\n    },\n  };\n\n  function info(\n    state: DaemonServiceInfo[\"state\"],\n    extra: Partial<\n      Omit<DaemonServiceInfo, \"currentHome\" | \"definitionPath\" | \"logHint\" | \"platform\" | \"serviceId\" | \"state\">\n    > = {},\n  ): DaemonServiceInfo {\n    return {\n      currentHome: options.home,\n      definitionPath: plistPath,\n      logHint: `${paths.clientLog} (fallback: ${stdoutPath} / ${stderrPath})`,\n      platform: \"launchd\",\n      serviceId: options.serviceId,\n      state,\n      ...extra,\n    };\n  }\n}\n\nexport function extractLaunchdHome(plist: string): string | undefined {\n  const match = plist.match(/<key>OPENTAG_HOME<\\/key>\\s*<string>([^<]*)<\\/string>/u);\n  return match?.[1]\n    ?.replace(/&apos;/g, \"'\")\n    .replace(/&quot;/g, '\"')\n    .replace(/&gt;/g, \">\")\n    .replace(/&lt;/g, \"<\")\n    .replace(/&amp;/g, \"&\");\n}\n\nfunction parseLaunchdPid(output: string): number | undefined {\n  const match = output.match(/\\bpid\\s*=\\s*(\\d+)/u);\n  if (!match?.[1]) return undefined;\n  const pid = Number.parseInt(match[1], 10);\n  return pid > 0 ? pid : undefined;\n}\n\nfunction parseLaunchdState(output: string): string | undefined {\n  return output.match(/^\\s*state\\s*=\\s*([^\\s]+)\\s*$/mu)?.[1]?.toLowerCase();\n}\n","import { rm } from \"node:fs/promises\";\nimport { userInfo } from \"node:os\";\nimport { join } from \"node:path\";\nimport { SUPERVISOR_RESTART_EXIT_CODE } from \"../handoff.js\";\nimport { resolveDaemonPaths } from \"../paths.js\";\nimport {\n  buildServicePath,\n  deriveServiceIdentity,\n  invocationArguments,\n  quoteSystemdEnvironment,\n  quoteSystemdToken,\n  readRegularFile,\n  runRequired,\n  writeFileAtomically,\n} from \"./shared.js\";\nimport type { ResolvedCliInvocation, ServiceRunner } from \"./types.js\";\nimport { type DaemonServiceBackend, DaemonServiceError, type DaemonServiceInfo } from \"./types.js\";\n\nconst SYSTEMD_TIMEOUT_MS = 15_000;\n\nexport interface SystemdBackendOptions {\n  home: string;\n  invocation: ResolvedCliInvocation;\n  runner: ServiceRunner;\n  serviceId: string;\n  sourcePath?: string;\n  systemctl?: string;\n  uid?: number;\n  userHome?: string;\n  username?: string;\n}\n\nexport function renderSystemdUnit(options: {\n  home: string;\n  invocation: ResolvedCliInvocation;\n  path: string;\n  serviceId: string;\n}): string {\n  const command = invocationArguments(options.invocation).map(quoteSystemdToken).join(\" \");\n  return `[Unit]\nDescription=OpenTag daemon (${options.serviceId})\nStartLimitIntervalSec=300\nStartLimitBurst=10\n\n[Service]\nType=simple\nExecStart=${command}\n# Exit code ${SUPERVISOR_RESTART_EXIT_CODE} is the reserved supervisor-restart handoff: a clean exit\n# that still forces a restart, used by the portable upgrade after the new version is live on disk.\nRestart=on-failure\nRestartSec=10\nSuccessExitStatus=0 ${SUPERVISOR_RESTART_EXIT_CODE}\nRestartForceExitStatus=${SUPERVISOR_RESTART_EXIT_CODE}\nKillSignal=SIGTERM\nKillMode=mixed\nTimeoutStopSec=30\nStandardOutput=journal\nStandardError=journal\nSyslogIdentifier=${options.serviceId}\n${quoteSystemdEnvironment(\"PATH\", options.path)}\n${quoteSystemdEnvironment(\"OPENTAG_SERVICE_MODE\", \"1\")}\n${quoteSystemdEnvironment(\"OPENTAG_HOME\", options.home)}\n\n[Install]\nWantedBy=default.target\n`;\n}\n\nexport function createSystemdBackend(options: SystemdBackendOptions): DaemonServiceBackend {\n  const identity = deriveServiceIdentity(options.serviceId);\n  const paths = resolveDaemonPaths(options.home);\n  const account =\n    options.userHome === undefined || options.uid === undefined || options.username === undefined\n      ? userInfo()\n      : undefined;\n  const userHome = options.userHome ?? account?.homedir;\n  const uid = options.uid ?? account?.uid;\n  const username = options.username ?? account?.username;\n  if (userHome === undefined || uid === undefined || username === undefined) {\n    throw new DaemonServiceError(\"CONFIGURATION\", \"The operating system account record is incomplete\");\n  }\n  const unitPath = join(userHome, \".config\", \"systemd\", \"user\", identity.systemdUnitName);\n  const systemctl = options.systemctl ?? \"systemctl\";\n  const servicePath = buildServicePath(options.invocation, \"linux\", options.sourcePath);\n  const expected = renderSystemdUnit({\n    home: options.home,\n    invocation: options.invocation,\n    path: servicePath,\n    serviceId: options.serviceId,\n  });\n\n  const status = async (): Promise<DaemonServiceInfo> => {\n    const definition = await readRegularFile(unitPath);\n    if (definition === undefined) {\n      const orphaned = await options.runner.run(\n        systemctl,\n        [\"--user\", \"show\", identity.systemdUnitName, \"--property\", \"LoadState\", \"--value\"],\n        { timeoutMs: SYSTEMD_TIMEOUT_MS },\n      );\n      if (orphaned.timedOut) {\n        return info(\"unknown\", {\n          detail: \"systemctl could not verify whether a definition-less service target is loaded\",\n          drifted: true,\n        });\n      }\n      const loadState = orphaned.stdout.trim();\n      if (orphaned.code === 0 && loadState === \"not-found\") {\n        return info(\"not-installed\", { drifted: true });\n      }\n      if (orphaned.code === 0) {\n        return info(\"unknown\", {\n          detail: `systemd still has the service target loaded (${loadState || \"unknown state\"}) even though its unit definition is missing`,\n          drifted: true,\n        });\n      }\n      return info(\"unknown\", {\n        detail: orphaned.stderr || orphaned.stdout || `systemctl exited with code ${orphaned.code}`,\n        drifted: true,\n      });\n    }\n    const configuredHome = extractSystemdHome(definition);\n    if (!configuredHome) {\n      return info(\"unknown\", {\n        detail: \"The installed systemd unit does not contain a valid OPENTAG_HOME\",\n        drifted: true,\n      });\n    }\n    const active = await options.runner.run(systemctl, [\"--user\", \"is-active\", identity.systemdUnitName], {\n      timeoutMs: SYSTEMD_TIMEOUT_MS,\n    });\n    if (active.timedOut) {\n      return info(\"unknown\", {\n        configuredHome,\n        detail: \"systemctl is-active timed out\",\n        drifted: definition !== expected,\n      });\n    }\n    if (active.code !== 0 && ![\"inactive\", \"failed\", \"deactivating\"].includes(active.stdout.trim())) {\n      return info(\"unknown\", {\n        configuredHome,\n        detail: active.stderr || active.stdout || `systemctl exited with code ${active.code}`,\n        drifted: definition !== expected,\n      });\n    }\n    if (active.code !== 0) return info(\"inactive\", { configuredHome, drifted: definition !== expected });\n\n    const pidResult = await options.runner.run(\n      systemctl,\n      [\"--user\", \"show\", identity.systemdUnitName, \"--property\", \"MainPID\", \"--value\"],\n      { timeoutMs: SYSTEMD_TIMEOUT_MS },\n    );\n    if (pidResult.timedOut) {\n      return info(\"unknown\", {\n        configuredHome,\n        detail: \"systemctl MainPID query timed out\",\n        drifted: definition !== expected,\n      });\n    }\n    if (pidResult.code !== 0) {\n      return info(\"unknown\", {\n        configuredHome,\n        detail: pidResult.stderr || pidResult.stdout || `systemctl MainPID query exited with code ${pidResult.code}`,\n        drifted: definition !== expected,\n      });\n    }\n    const parsedPid = Number.parseInt(pidResult.stdout, 10);\n    if (!Number.isInteger(parsedPid) || parsedPid <= 0) {\n      return info(\"unknown\", {\n        configuredHome,\n        detail: \"systemctl reported an invalid MainPID\",\n        drifted: definition !== expected,\n      });\n    }\n    return info(\"active\", {\n      configuredHome,\n      drifted: definition !== expected,\n      pid: parsedPid,\n    });\n  };\n\n  const preflight = async (): Promise<void> => {\n    if (uid === 0) {\n      throw new DaemonServiceError(\"UNSUPPORTED_PLATFORM\", \"OpenTag supports only non-root user systemd services\");\n    }\n    const result = await options.runner.run(systemctl, [\"--user\", \"show-environment\"], {\n      timeoutMs: SYSTEMD_TIMEOUT_MS,\n    });\n    if (result.code !== 0 || result.timedOut) {\n      throw new DaemonServiceError(\n        \"MANAGER_UNAVAILABLE\",\n        `The user systemd manager is unavailable: ${result.timedOut ? \"command timed out\" : result.stderr || \"unknown error\"}`,\n      );\n    }\n  };\n\n  return {\n    platform: \"systemd\",\n    preflight,\n    async installAndStart() {\n      await preflight();\n      const previous = await status();\n      const drifted = previous.drifted ?? true;\n      await writeFileAtomically(unitPath, expected, 0o644, 0o700);\n      await runRequired(options.runner, systemctl, [\"--user\", \"daemon-reload\"], \"systemd daemon-reload\");\n      await runRequired(options.runner, systemctl, [\"--user\", \"enable\", identity.systemdUnitName], \"systemd enable\");\n      if ((previous.state === \"active\" || previous.state === \"unknown\") && drifted) {\n        await runRequired(\n          options.runner,\n          systemctl,\n          [\"--user\", \"restart\", identity.systemdUnitName],\n          \"systemd restart\",\n        );\n      } else if (previous.state !== \"active\") {\n        await runRequired(options.runner, systemctl, [\"--user\", \"start\", identity.systemdUnitName], \"systemd start\");\n      }\n      const linger = await options.runner.run(\"loginctl\", [\"enable-linger\", username], {\n        timeoutMs: SYSTEMD_TIMEOUT_MS,\n      });\n      const current = await status();\n      if (current.state !== \"active\") {\n        throw new DaemonServiceError(\n          \"OPERATION_FAILED\",\n          \"systemd reported that the OpenTag service did not become active\",\n        );\n      }\n      return linger.code === 0\n        ? current\n        : {\n            ...current,\n            detail: `Service is active; enable lingering manually with: loginctl enable-linger ${username}`,\n          };\n    },\n    async start() {\n      await preflight();\n      if ((await readRegularFile(unitPath)) === undefined) {\n        throw new DaemonServiceError(\"NOT_INSTALLED\", \"The daemon service is not installed; run daemon install\");\n      }\n      const current = await status();\n      if (current.state !== \"active\") {\n        await runRequired(options.runner, systemctl, [\"--user\", \"start\", identity.systemdUnitName], \"systemd start\");\n      }\n      return status();\n    },\n    async refreshDefinition() {\n      await preflight();\n      const current = await readRegularFile(unitPath);\n      if (current === undefined) {\n        throw new DaemonServiceError(\"NOT_INSTALLED\", \"The daemon service is not installed; run daemon install\");\n      }\n      if (current !== expected) {\n        await writeFileAtomically(unitPath, expected, 0o644, 0o700);\n        await runRequired(options.runner, systemctl, [\"--user\", \"daemon-reload\"], \"systemd daemon-reload\");\n      }\n      return status();\n    },\n    async stop() {\n      if ((await readRegularFile(unitPath)) === undefined) return info(\"not-installed\", { drifted: true });\n      const current = await status();\n      if (current.state === \"active\" || current.state === \"unknown\") {\n        await runRequired(options.runner, systemctl, [\"--user\", \"stop\", identity.systemdUnitName], \"systemd stop\");\n      }\n      return status();\n    },\n    async restart() {\n      await preflight();\n      if ((await readRegularFile(unitPath)) === undefined) {\n        throw new DaemonServiceError(\"NOT_INSTALLED\", \"The daemon service is not installed; run daemon install\");\n      }\n      await runRequired(options.runner, systemctl, [\"--user\", \"restart\", identity.systemdUnitName], \"systemd restart\");\n      return status();\n    },\n    status,\n    async uninstall() {\n      const definition = await readRegularFile(unitPath);\n      if (definition === undefined) return info(\"not-installed\", { drifted: true });\n      await runRequired(\n        options.runner,\n        systemctl,\n        [\"--user\", \"disable\", \"--now\", identity.systemdUnitName],\n        \"systemd disable\",\n      );\n      const afterStop = await options.runner.run(systemctl, [\"--user\", \"is-active\", identity.systemdUnitName], {\n        timeoutMs: SYSTEMD_TIMEOUT_MS,\n      });\n      if (afterStop.timedOut || afterStop.code === 0 || ![\"inactive\", \"failed\"].includes(afterStop.stdout.trim())) {\n        throw new DaemonServiceError(\"OPERATION_FAILED\", \"systemd did not confirm that the service stopped\");\n      }\n      await rm(unitPath);\n      await runRequired(options.runner, systemctl, [\"--user\", \"daemon-reload\"], \"systemd daemon-reload\");\n      return info(\"not-installed\", { drifted: true });\n    },\n  };\n\n  function info(\n    state: DaemonServiceInfo[\"state\"],\n    extra: Partial<\n      Omit<DaemonServiceInfo, \"currentHome\" | \"definitionPath\" | \"logHint\" | \"platform\" | \"serviceId\" | \"state\">\n    > = {},\n  ): DaemonServiceInfo {\n    return {\n      currentHome: options.home,\n      definitionPath: unitPath,\n      logHint: `${paths.clientLog} (fallback: journalctl --user -u ${identity.systemdUnitName} -f)`,\n      platform: \"systemd\",\n      serviceId: options.serviceId,\n      state,\n      ...extra,\n    };\n  }\n}\n\nexport function extractSystemdHome(definition: string): string | undefined {\n  const match = definition.match(/^Environment=\"OPENTAG_HOME=(.*)\"$/mu);\n  if (!match?.[1]) return undefined;\n  return match[1].replace(/%%/g, \"%\").replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n}\n","import { userInfo } from \"node:os\";\nimport { resolve } from \"node:path\";\nimport { readMachineCredentials, resolveBoundAccountComputer, resolveOpenTagHome } from \"@opentag/client\";\nimport { getChannelConfig } from \"@opentag/shared\";\nimport { CHANNEL } from \"../../../build-info.js\";\nimport { channelConfig } from \"../../channel/config.js\";\nimport { resolveChannelEnvironment } from \"../../channel/environment.js\";\nimport { inspectDaemonOwner } from \"../ownership.js\";\nimport { createLaunchdBackend } from \"./launchd.js\";\nimport {\n  acquireServiceOperationLease,\n  acquireServiceTargetLease,\n  canonicalizeServiceHome,\n  defaultServiceRunner,\n  preflightHomeDirectory,\n  resolveCliInvocation,\n} from \"./shared.js\";\nimport { createSystemdBackend } from \"./systemd.js\";\nimport type {\n  DaemonServiceBackend,\n  DaemonServiceInfo,\n  DaemonServicePlatform,\n  ResolvedCliInvocation,\n  RuntimeOwnerInfo,\n  ServiceRunner,\n} from \"./types.js\";\nimport { DaemonServiceError } from \"./types.js\";\n\nexport interface DaemonServiceManager {\n  installAndStart(): Promise<DaemonServiceInfo>;\n  preflight(): Promise<void>;\n  refreshDefinition(): Promise<DaemonServiceInfo>;\n  restart(): Promise<DaemonServiceInfo>;\n  start(): Promise<DaemonServiceInfo>;\n  status(): Promise<DaemonServiceInfo>;\n  stop(): Promise<DaemonServiceInfo>;\n  uninstall(): Promise<DaemonServiceInfo>;\n}\n\nexport interface CreateDaemonServiceManagerOptions {\n  env?: NodeJS.ProcessEnv;\n  home?: string;\n  invocation?: ResolvedCliInvocation;\n  platform?: NodeJS.Platform;\n  runner?: ServiceRunner;\n  uid?: number;\n  userHome?: string;\n  username?: string;\n}\n\ntype DaemonServiceMutation = \"install\" | \"refresh\" | \"restart\" | \"start\" | \"stop\" | \"uninstall\";\n\nexport async function createDaemonServiceManager(\n  options: CreateDaemonServiceManagerOptions = {},\n): Promise<DaemonServiceManager> {\n  const environment = resolveChannelEnvironment(options.env ?? process.env);\n  const platform = options.platform ?? process.platform;\n  const account = userInfo();\n  const home = await canonicalizeServiceHome(resolve(options.home ?? resolveOpenTagHome(environment)));\n  const runner = options.runner ?? defaultServiceRunner;\n  const userHome = await canonicalizeServiceHome(resolve(options.userHome ?? account.homedir));\n  const channelDefaultHome = await canonicalizeServiceHome(getChannelConfig(CHANNEL, userHome).defaultHome);\n  const invocation =\n    options.invocation ??\n    (platform === \"darwin\" || platform === \"linux\"\n      ? await resolveCliInvocation({ binName: channelConfig.binName, env: options.env })\n      : { args: [], program: process.execPath });\n  const uid = options.uid ?? account.uid;\n  const backend = createBackend({\n    home,\n    invocation,\n    platform,\n    runner,\n    sourcePath: environment.PATH,\n    uid,\n    userHome,\n    username: options.username ?? account.username,\n  });\n\n  const status = async (): Promise<DaemonServiceInfo> => attachOwner(await backend.status(), home);\n  const preflight = async (): Promise<void> => {\n    await preflightHomeDirectory(home);\n    await backend.preflight();\n  };\n  const mutate = async (\n    mutation: DaemonServiceMutation,\n    operation: () => Promise<DaemonServiceInfo>,\n  ): Promise<DaemonServiceInfo> => {\n    const targetLease = await acquireServiceTargetLease(channelDefaultHome, channelConfig.serviceId);\n    let lease: Awaited<ReturnType<typeof acquireServiceOperationLease>> | undefined;\n    try {\n      lease = await acquireServiceOperationLease(home);\n      const before = await backend.status();\n      await assertConfiguredHome(before, home);\n      await assertOwnerConsistency(before, home, mutation);\n      const current = await attachOwner(await operation(), home);\n      await assertMutationHomePostcondition(mutation, current, home);\n      if (mutation === \"stop\") assertStopPostcondition(current);\n      return current;\n    } finally {\n      try {\n        await lease?.release();\n      } finally {\n        await targetLease.release();\n      }\n    }\n  };\n\n  return {\n    preflight,\n    async installAndStart() {\n      await preflight();\n      let credentials: Awaited<ReturnType<typeof readMachineCredentials>>;\n      try {\n        credentials = await readMachineCredentials(home);\n      } catch (error) {\n        throw new DaemonServiceError(\n          \"CONFIGURATION\",\n          \"OpenTag Computer credentials are invalid; run opentag connect again\",\n          { cause: error },\n        );\n      }\n      const bound = resolveBoundAccountComputer(credentials);\n      if (bound.status === \"disconnected\") {\n        throw new DaemonServiceError(\"CONFIGURATION\", \"This Computer is not connected; run opentag connect first\");\n      }\n      return mutate(\"install\", () => backend.installAndStart());\n    },\n    start: () => mutate(\"start\", () => backend.start()),\n    stop: () => mutate(\"stop\", () => backend.stop()),\n    refreshDefinition: () => mutate(\"refresh\", () => backend.refreshDefinition()),\n    restart: () => mutate(\"restart\", () => backend.restart()),\n    status,\n    uninstall: () => mutate(\"uninstall\", () => backend.uninstall()),\n  };\n}\n\nasync function assertMutationHomePostcondition(\n  mutation: DaemonServiceMutation,\n  info: DaemonServiceInfo,\n  requestedHome: string,\n): Promise<void> {\n  if (mutation === \"uninstall\" && info.state === \"not-installed\") return;\n  await assertConfiguredHome(info, requestedHome);\n}\n\nasync function assertConfiguredHome(info: DaemonServiceInfo, requestedHome: string): Promise<void> {\n  if (info.state === \"not-installed\") return;\n  if (!info.configuredHome) {\n    throw new DaemonServiceError(\n      \"CONFIGURATION\",\n      `The installed ${info.platform} service does not expose a verifiable OPENTAG_HOME; refusing mutation`,\n    );\n  }\n  const configuredHome = await canonicalizeServiceHome(info.configuredHome);\n  if (configuredHome !== requestedHome) {\n    throw new DaemonServiceError(\n      \"CONFIGURATION\",\n      `The installed ${info.platform} service belongs to a different OpenTag home (${configuredHome}); use that OPENTAG_HOME`,\n    );\n  }\n}\n\nexport function formatDaemonServiceInfo(info: DaemonServiceInfo): string {\n  const lines = [\n    `Service: ${info.serviceId}`,\n    `Platform: ${info.platform}`,\n    `State: ${info.state}`,\n    ...(info.pid ? [`PID: ${info.pid}`] : []),\n    ...(info.configuredHome ? [`Home: ${info.configuredHome}`] : []),\n    `Current home: ${info.currentHome}`,\n    `Definition: ${info.definitionPath}`,\n    `Logs: ${info.logHint}`,\n    `Configuration: ${info.drifted ? \"drifted\" : \"current\"}`,\n    `Runtime owner: ${formatRuntimeOwner(info.runtimeOwner)}`,\n    ...(info.detail ? [`Detail: ${info.detail}`] : []),\n  ];\n  return lines.join(\"\\n\");\n}\n\nfunction createBackend(options: {\n  home: string;\n  invocation: ResolvedCliInvocation;\n  platform: NodeJS.Platform;\n  runner: ServiceRunner;\n  sourcePath?: string;\n  uid: number;\n  userHome: string;\n  username?: string;\n}): DaemonServiceBackend {\n  if (options.platform === \"linux\") {\n    return createSystemdBackend({\n      home: options.home,\n      invocation: options.invocation,\n      runner: options.runner,\n      serviceId: channelConfig.serviceId,\n      ...(options.sourcePath ? { sourcePath: options.sourcePath } : {}),\n      uid: options.uid,\n      userHome: options.userHome,\n      ...(options.username ? { username: options.username } : {}),\n    });\n  }\n  if (options.platform === \"darwin\") {\n    return createLaunchdBackend({\n      home: options.home,\n      invocation: options.invocation,\n      runner: options.runner,\n      serviceId: channelConfig.serviceId,\n      ...(options.sourcePath ? { sourcePath: options.sourcePath } : {}),\n      uid: options.uid,\n      userHome: options.userHome,\n    });\n  }\n  return unsupportedBackend(options.platform, options.home, channelConfig.serviceId);\n}\n\nfunction unsupportedBackend(platform: NodeJS.Platform, home: string, serviceId: string): DaemonServiceBackend {\n  const unsupported = async (): Promise<never> => {\n    throw new DaemonServiceError(\n      \"UNSUPPORTED_PLATFORM\",\n      `OpenTag v0.1 daemon service supports Linux and macOS only (current platform: ${platform})`,\n    );\n  };\n  return {\n    platform: \"unsupported\",\n    preflight: unsupported,\n    installAndStart: unsupported,\n    refreshDefinition: unsupported,\n    start: unsupported,\n    stop: unsupported,\n    restart: unsupported,\n    uninstall: unsupported,\n    async status() {\n      return {\n        currentHome: home,\n        definitionPath: \"<unsupported>\",\n        detail: `Daemon service is unsupported on ${platform}`,\n        drifted: true,\n        logHint: \"<unsupported>\",\n        platform: \"unsupported\",\n        serviceId,\n        state: \"unknown\",\n      };\n    },\n  };\n}\n\nasync function attachOwner(info: DaemonServiceInfo, home: string): Promise<DaemonServiceInfo> {\n  const runtimeOwner = await ownerInfo(info, home);\n  return { ...info, runtimeOwner };\n}\n\nasync function assertOwnerConsistency(\n  info: DaemonServiceInfo,\n  home: string,\n  mutation: DaemonServiceMutation,\n): Promise<void> {\n  const owner = await ownerInfo(info, home);\n  if (owner.consistency === \"malformed\") {\n    throw new DaemonServiceError(\"CONFIGURATION\", \"The daemon owner record is malformed; refusing service mutation\");\n  }\n  if (owner.consistency === \"unmanaged\") {\n    throw new DaemonServiceError(\n      \"CONFIGURATION\",\n      `A daemon process exists outside the expected ${info.platform} service state (pid ${owner.pid})`,\n    );\n  }\n  if (owner.consistency === \"unverified\" && mutation !== \"stop\") {\n    throw new DaemonServiceError(\n      \"CONFIGURATION\",\n      `The ${info.platform} service PID could not be verified while a live daemon owns this home; run daemon stop before ${mutation}`,\n    );\n  }\n}\n\nfunction assertStopPostcondition(info: DaemonServiceInfo): void {\n  if (info.state !== \"inactive\" && info.state !== \"not-installed\") {\n    throw new DaemonServiceError(\"OPERATION_FAILED\", `The ${info.platform} service did not reach a stopped state`);\n  }\n  if (!info.runtimeOwner || ![\"missing\", \"stale\"].includes(info.runtimeOwner.consistency)) {\n    const ownerDetail = info.runtimeOwner?.pid ? ` (pid ${info.runtimeOwner.pid})` : \"\";\n    throw new DaemonServiceError(\n      \"OPERATION_FAILED\",\n      `The ${info.platform} service stopped but a live or unverifiable daemon still owns this home${ownerDetail}`,\n    );\n  }\n}\n\nasync function ownerInfo(info: DaemonServiceInfo, home: string): Promise<RuntimeOwnerInfo> {\n  let inspection: Awaited<ReturnType<typeof inspectDaemonOwner>>;\n  try {\n    inspection = await inspectDaemonOwner(home);\n  } catch {\n    return { consistency: \"malformed\" };\n  }\n  if (inspection.state === \"missing\") return { consistency: \"missing\" };\n  if (inspection.state === \"stale\") return { consistency: \"stale\", pid: inspection.record.pid };\n  if (info.state === \"unknown\") return { consistency: \"unverified\", pid: inspection.record.pid };\n  if (info.state === \"active\" && info.pid === inspection.record.pid) {\n    return { consistency: \"consistent\", pid: inspection.record.pid };\n  }\n  return { consistency: \"unmanaged\", pid: inspection.record.pid };\n}\n\nfunction formatRuntimeOwner(owner: RuntimeOwnerInfo | undefined): string {\n  if (!owner) return \"missing\";\n  return owner.pid ? `${owner.pid}/${owner.consistency}` : owner.consistency;\n}\n\nexport { DaemonServiceError } from \"./types.js\";\nexport type { DaemonServiceInfo, DaemonServicePlatform };\n","import { arch, hostname, platform } from \"node:os\";\nimport {\n  allocateComputerIdentity,\n  machineCredentialsPath,\n  normalizeServerUrl,\n  type OpenTagApi,\n  resolveOpenTagHome,\n  storeBoundAccountComputer,\n  writeComputerIdentityAtomically,\n} from \"@opentag/client\";\nimport { type AgentRuntimeProvider, withComputerRuntimeProviderSupport } from \"@opentag/shared\";\nimport { CLI_VERSION } from \"../../build-info.js\";\nimport { resolveCommandContext } from \"../command/context.js\";\nimport { redactSecrets } from \"../command/policy.js\";\nimport {\n  createDaemonServiceManager,\n  type DaemonServiceInfo,\n  type DaemonServiceManager,\n} from \"../daemon/service/index.js\";\n\nexport interface ComputerConnectOptions {\n  api?: Pick<OpenTagApi, \"exchangeComputerConnectCode\">;\n  code: string;\n  home?: string;\n  manager?: DaemonServiceManager;\n  noStart?: boolean;\n  serverUrl: string;\n}\n\nexport interface ComputerConnectResult {\n  agentId?: string;\n  /**\n   * The exact Runtime of the bound Agent, present only when the Server answered a Client marked\n   * with {@link withComputerRuntimeProviderSupport}. Never persisted: the machine credential\n   * format is unchanged, and a later exchange re-answers it.\n   */\n  runtimeProvider?: AgentRuntimeProvider;\n  computerId: string;\n  credentialsPath: string;\n  message: string;\n  service?: DaemonServiceInfo;\n  /**\n   * Redacted daemon service failure after the machine credential was stored. The connection is\n   * preserved; the caller must keep reporting `connected` and offer idempotent daemon repair\n   * instead of a raw throw that could read as \"retry the one-time code\".\n   */\n  serviceError?: string;\n  /** Server exchange committed, but local files must be recovered before starting the daemon. */\n  persistenceError?: {\n    stage: \"credentials\" | \"identity\";\n    installationId: string;\n    message: string;\n  };\n}\n\nexport async function runComputerConnect(options: ComputerConnectOptions): Promise<ComputerConnectResult> {\n  // Validate and mark the Client version before anything consumes the one-time code.\n  const clientVersion = withComputerRuntimeProviderSupport(CLI_VERSION);\n  const home = options.home ?? resolveOpenTagHome();\n  const serverUrl = normalizeServerUrl(options.serverUrl);\n  const currentPlatform = platform();\n  if (currentPlatform !== \"darwin\" && currentPlatform !== \"linux\" && currentPlatform !== \"win32\") {\n    throw new Error(`Unsupported Computer platform: ${currentPlatform}`);\n  }\n  const manager = options.noStart ? undefined : (options.manager ?? (await createDaemonServiceManager({ home })));\n  await manager?.preflight();\n  const serviceBefore = await manager?.status();\n  const identity = await allocateComputerIdentity(home, serverUrl);\n  const api = options.api ?? (await resolveCommandContext({ home, serverUrl })).api;\n  if (!api) throw new Error(\"Command context did not resolve an API\");\n  const exchange = await api.exchangeComputerConnectCode({\n    code: options.code,\n    installationId: identity.computerId,\n    displayName: hostname(),\n    platform: currentPlatform,\n    arch: arch(),\n    clientVersion,\n  });\n  const result: ComputerConnectResult = {\n    agentId: exchange.agentId,\n    runtimeProvider: exchange.runtimeProvider,\n    computerId: exchange.computerId,\n    credentialsPath: machineCredentialsPath(home),\n    message: exchange.agentId\n      ? `Connected Computer ${exchange.computerId} and bound Agent ${exchange.agentId}`\n      : `Connected Computer ${exchange.computerId}`,\n  };\n  let stage: \"credentials\" | \"identity\" = \"credentials\";\n  try {\n    // Save the non-reconstructable token first. Identity is derivable from this credential, so\n    // repair-local can finish a partial write (including a crash or an error after rename).\n    // These are two durable file writes, not an atomic transaction; never roll back to a token\n    // that the committed exchange may already have revoked.\n    await storeBoundAccountComputer({ ...exchange, serverUrl }, home);\n    stage = \"identity\";\n    await writeComputerIdentityAtomically(home, identity);\n  } catch (error) {\n    return {\n      ...result,\n      message: `${result.message} on the Server; local persistence is incomplete`,\n      persistenceError: {\n        stage,\n        installationId: identity.computerId,\n        message: safeFailureMessage(error, \"Local write failed\", exchange.machineToken),\n      },\n    };\n  }\n  if (!manager) return result;\n\n  try {\n    const shouldReload = serviceBefore?.state === \"active\" || serviceBefore?.state === \"unknown\";\n    const service = shouldReload ? await manager.restart() : await manager.installAndStart();\n    return { ...result, service };\n  } catch (error) {\n    return {\n      ...result,\n      serviceError: safeFailureMessage(error, \"Daemon service failed\", exchange.machineToken),\n    };\n  }\n}\n\nfunction safeFailureMessage(error: unknown, fallback: string, machineToken: string): string {\n  let message = error instanceof Error ? error.message : String(error);\n  if (machineToken) message = message.replaceAll(machineToken, \"[REDACTED]\");\n  return redactSecrets(message).trim().slice(0, 512) || fallback;\n}\n","import type {\n  ListAccountComputersResponse,\n  LocalComputerPreparationResult,\n  LocalPreparationAction,\n  LocalPreparationCheck,\n  LocalPreparationComponent,\n} from \"@opentag/shared\";\n\nexport function formatComputerList(response: ListAccountComputersResponse): string {\n  if (response.computers.length === 0) return \"No Computers registered\";\n  return response.computers\n    .map((computer) =>\n      [\n        computer.displayName,\n        computer.computerId,\n        computer.connectionStatus,\n        computer.platform,\n        computer.lastSeenAt,\n      ].join(\"\\t\"),\n    )\n    .join(\"\\n\");\n}\n\nfunction actionText(action: LocalPreparationAction): string {\n  return action.command ?? action.instruction ?? \"\";\n}\n\n/**\n * One-line row summary shared by the connect preparation output and `computer runtime-inspect`.\n * `(blocking)` marks every non-ready row that gates the local-ready verdict, and the inline message\n * or version keeps the row self-contained.\n */\nexport function formatPreparationCheckLine(check: LocalPreparationCheck): string {\n  const blocking = check.blocking ? \" (blocking)\" : \"\";\n  const detail = [check.version, check.message].filter((value) => value !== undefined).join(\" — \");\n  return `[${check.id}] ${check.status}${blocking}${detail ? ` — ${detail}` : \"\"}`;\n}\n\nfunction formatActionLines(check: LocalPreparationCheck, indent: string): string[] {\n  const lines: string[] = [];\n  for (const warning of check.warnings ?? []) {\n    lines.push(`${indent}warning (non-blocking): ${warning.code}${warning.message ? ` — ${warning.message}` : \"\"}`);\n  }\n  if (check.nextAction) lines.push(`${indent}next: ${actionText(check.nextAction)}`);\n  if (check.verifyAction) lines.push(`${indent}verify: ${actionText(check.verifyAction)}`);\n  return lines;\n}\n\n/** Human projection of one Component: summary, child Checks, warnings, and repair/verify actions. */\nexport function formatPreparationComponentLines(component: LocalPreparationComponent): string[] {\n  const lines = [formatPreparationCheckLine(component)];\n  for (const child of component.checks ?? []) {\n    lines.push(`  ${formatPreparationCheckLine(child)}`);\n    lines.push(...formatActionLines(child, \"    \"));\n  }\n  lines.push(...formatActionLines(component, \"  \"));\n  return lines;\n}\n\n/**\n * The shared human verdict for one local computer preparation result. The human summary and the\n * JSON envelope both project this same value, so they cannot disagree on blockers or next actions.\n */\nexport function formatPreparationResultLines(result: LocalComputerPreparationResult): string[] {\n  const lines = [\n    `Local computer preparation: ${result.status === \"ready\" ? \"READY\" : \"NEEDS_ATTENTION\"}`,\n    `${result.readyCount} / ${result.requiredCount} ready`,\n  ];\n  for (const component of result.components) {\n    lines.push(...formatPreparationComponentLines(component));\n  }\n  return lines;\n}\n","import {\n  type ProviderCliCandidate,\n  type ProviderCliCatalogEntry,\n  type ProviderCliExecFile,\n  type ProviderCliFetcher,\n  ProviderCliManager,\n  type ProviderCliProvider,\n  resolveAccountHome,\n} from \"@opentag/client\";\nimport { providerCliArtifactFailureIsManual } from \"@opentag/shared\";\nimport { channelConfig } from \"../channel/config.js\";\n\n/**\n * Shared plumbing for the `opentag provider-cli` commands: provider flag parsing,\n * display labels, and injectable dependencies. The CLI flag accepts `lark` for the\n * Feishu/Lark provider to match the native `lark-cli` command name.\n */\n\nexport class ProviderCliUsageError extends Error {\n  override readonly name = \"ProviderCliUsageError\";\n}\n\n/** Canonical provider order for multi-provider runs. */\nconst PROVIDER_FLAG_ORDER: readonly ProviderCliProvider[] = [\"feishu\", \"slack\"];\n\nexport function parseProviderCliProviderFlag(value: string): ProviderCliProvider[] {\n  switch (value) {\n    case \"lark\":\n      return [\"feishu\"];\n    case \"slack\":\n      return [\"slack\"];\n    case \"all\":\n      return [...PROVIDER_FLAG_ORDER];\n    default:\n      throw new ProviderCliUsageError(`Unknown provider \"${value}\"; expected lark, slack, or all`);\n  }\n}\n\n/** Short label used in human phase lines, matching the native command name. */\nexport function providerCliLabel(provider: ProviderCliProvider): \"lark\" | \"slack\" {\n  return provider === \"feishu\" ? \"lark\" : \"slack\";\n}\n\n/** Stable, current-shell-safe repair command for Agent and human output. */\nexport function providerCliRepairCommand(provider: ProviderCliProvider | \"all\"): string {\n  const flag = provider === \"all\" ? \"all\" : providerCliLabel(provider);\n  return `\"$HOME/.local/bin/${channelConfig.binName}\" provider-cli ensure --provider ${flag}`;\n}\n\n/** False when repeating ensure cannot change the local fact without a user or release change. */\nexport function providerCliCanAutoRepair(reason: string, stage: \"inspect\" | \"ensure\" = \"ensure\"): boolean {\n  return !providerCliArtifactFailureIsManual({ reason, stage });\n}\n\n/**\n * Failures that describe another OpenTag process holding the provider lock: transient, safe to\n * retry with bounded backoff once that operation finishes.\n */\nconst PROVIDER_CLI_TRANSIENT_REASONS = new Set([\"operation_in_progress\"]);\n\nfunction isTransientProviderCliReason(reason: string | undefined): boolean {\n  return reason !== undefined && PROVIDER_CLI_TRANSIENT_REASONS.has(reason);\n}\n\nexport interface ProviderCliAggregateFailure {\n  readonly category: \"unavailable\" | \"dependency\";\n  readonly retryability: \"backoff\" | \"immediate\" | \"never\";\n}\n\n/**\n * One aggregate posture for a multi-provider run, classified from each failure's diagnostic so\n * the envelope never contradicts the nextActions: lock contention is transient and retried with\n * backoff; a failure a nextAction repairs by rerunning ensure is safe to retry immediately; a\n * manual or unrepairable failure must change before a retry can succeed, so it is never retried\n * blindly. The most conservative failure wins the aggregate. The exit code is not part of this\n * verdict: it is derived from the category through the shared command policy.\n */\nexport function providerCliAggregateFailure(\n  failures: readonly { readonly diagnostic?: { readonly code: string } }[],\n): ProviderCliAggregateFailure {\n  const codes = failures.map((failure) => failure.diagnostic?.code);\n  if (codes.length > 0 && codes.every(isTransientProviderCliReason)) {\n    return { category: \"unavailable\", retryability: \"backoff\" };\n  }\n  const manual = codes.some(\n    (code) => !isTransientProviderCliReason(code) && (code === undefined || !providerCliCanAutoRepair(code)),\n  );\n  if (codes.length === 0 || manual) return { category: \"dependency\", retryability: \"never\" };\n  if (codes.some(isTransientProviderCliReason)) return { category: \"dependency\", retryability: \"backoff\" };\n  return { category: \"dependency\", retryability: \"immediate\" };\n}\n\nexport interface ProviderCliNextAction {\n  readonly provider: ProviderCliProvider | \"all\";\n  readonly command: string;\n  readonly reason: string;\n}\n\nexport interface ProviderCliCommandDeps {\n  /** OS account home override; tests inject an isolated account root. */\n  readonly accountHome?: string;\n  /** Invoking-process environment override (PATH authority for detection). */\n  readonly env?: NodeJS.ProcessEnv;\n  readonly platform?: NodeJS.Platform;\n  readonly arch?: string;\n  readonly catalog?: readonly ProviderCliCatalogEntry[];\n  readonly fetcher?: ProviderCliFetcher;\n  readonly execFile?: ProviderCliExecFile;\n  /** Test-only hook: runs inside the provider lock before the winner is persisted. */\n  readonly beforeWinnerReverify?: (winner: ProviderCliCandidate) => Promise<void>;\n  /** Test-only hook: replaces the cross-process lock retry wait. */\n  readonly sleep?: (ms: number) => Promise<void>;\n  readonly stdout?: (chunk: string) => void;\n  readonly stderr?: (chunk: string) => void;\n}\n\nexport function writeStdout(deps: ProviderCliCommandDeps, chunk: string): void {\n  if (deps.stdout) {\n    deps.stdout(chunk);\n    return;\n  }\n  process.stdout.write(chunk);\n}\n\nexport function writeStderr(deps: ProviderCliCommandDeps, chunk: string): void {\n  if (deps.stderr) {\n    deps.stderr(chunk);\n    return;\n  }\n  process.stderr.write(chunk);\n}\n\n/** Keep human diagnostics single-line and immune to terminal control injection. */\nexport function renderProviderCliHumanValue(value: string, maxLength = 1024): string {\n  let escaped = \"\";\n  for (const character of value) {\n    const code = character.codePointAt(0) ?? 0;\n    escaped += code <= 0x1f || (code >= 0x7f && code <= 0x9f) ? `\\\\u${code.toString(16).padStart(4, \"0\")}` : character;\n  }\n  return escaped.length <= maxLength ? escaped : `${escaped.slice(0, maxLength)}…`;\n}\n\n/** Parse the `--provider` flag; on a usage error, report to stderr and return undefined. */\nexport function parseProviderCliProvidersOrReport(\n  value: string,\n  stderr: (chunk: string) => void,\n): ProviderCliProvider[] | undefined {\n  try {\n    return parseProviderCliProviderFlag(value);\n  } catch (error) {\n    if (error instanceof ProviderCliUsageError) {\n      stderr(`${error.message}\\n`);\n      return undefined;\n    }\n    throw error;\n  }\n}\n\n/** Build the manager with the command's injectable dependencies. */\nexport function createProviderCliManager(options: ProviderCliCommandDeps): ProviderCliManager {\n  return new ProviderCliManager({\n    accountHome: options.accountHome ?? resolveAccountHome(),\n    ...(options.env ? { env: options.env } : {}),\n    ...(options.platform ? { platform: options.platform } : {}),\n    ...(options.arch ? { arch: options.arch } : {}),\n    ...(options.catalog ? { catalog: options.catalog } : {}),\n    ...(options.fetcher ? { fetcher: options.fetcher } : {}),\n    ...(options.execFile ? { execFile: options.execFile } : {}),\n    ...(options.beforeWinnerReverify ? { beforeWinnerReverify: options.beforeWinnerReverify } : {}),\n    ...(options.sleep ? { sleep: options.sleep } : {}),\n  });\n}\n","import {\n  PROVIDER_CLI_LOCK_BUSY_MAX_ATTEMPTS,\n  PROVIDER_CLI_LOCK_BUSY_RETRY_DELAY_MS,\n  type ProviderCliEnsureResult,\n  type ProviderCliManager,\n  type ProviderCliPhaseEvent,\n} from \"@opentag/client\";\nimport { CommandError, type CommandExitCode, commandExitCode, presentCommand } from \"../command/policy.js\";\nimport {\n  createProviderCliManager,\n  type ProviderCliCommandDeps,\n  type ProviderCliNextAction,\n  parseProviderCliProvidersOrReport,\n  providerCliAggregateFailure,\n  providerCliCanAutoRepair,\n  providerCliLabel,\n  providerCliRepairCommand,\n  renderProviderCliHumanValue,\n  writeStderr,\n  writeStdout,\n} from \"./shared.js\";\n\n/**\n * Reusable orchestration for `opentag provider-cli ensure`.\n *\n * Human mode prints bounded single-line phase updates and never prompts, with or\n * without a TTY. `--json` mode writes one common command envelope and suppresses phase lines.\n */\n\nexport interface ProviderCliEnsureCommandOptions extends ProviderCliCommandDeps {\n  readonly provider: string;\n  /** Observe real foreground phases when a parent command owns final presentation. */\n  readonly onPhase?: (event: ProviderCliPhaseEvent) => void;\n  readonly managedOnly?: boolean;\n  /** `--no-path-update` passes false. */\n  readonly pathUpdate?: boolean;\n  readonly dryRun?: boolean;\n  readonly json?: boolean;\n}\n\nexport interface ProviderCliEnsureCommandResult {\n  readonly exitCode: CommandExitCode;\n  readonly results: readonly ProviderCliEnsureResult[];\n  readonly nextActions: readonly ProviderCliNextAction[];\n}\n\nfunction renderPhaseLine(event: ProviderCliPhaseEvent): string | undefined {\n  const label = providerCliLabel(event.provider);\n  const detail = event.detail ? renderProviderCliHumanValue(event.detail) : undefined;\n  if (event.status === \"started\") {\n    // Keep started lines quiet for instant phases; the completed line carries detail.\n    if (event.phase === \"managed-install\") return `[${label}] managed-install: ${detail ?? \"started\"}`;\n    return undefined;\n  }\n  if (event.status === \"failed\") return `[${label}] ${event.phase}: failed${detail ? ` (${detail})` : \"\"}`;\n  return `[${label}] ${event.phase}: ${detail ?? \"completed\"}`;\n}\n\nfunction renderResultLines(result: ProviderCliEnsureResult, nextAction: ProviderCliNextAction | undefined): string[] {\n  const label = providerCliLabel(result.provider);\n  const lines = [\n    selectedLine(result, label),\n    ...ignoredCandidateLines(result, label),\n    ...warningLines(result, label),\n  ].filter((line): line is string => line !== undefined);\n  if (result.ok) {\n    const selected = result.selected;\n    const readySelection = selected\n      ? ` — ${selected.version} ${renderProviderCliHumanValue(selected.path)} (${selected.trust})`\n      : \"\";\n    lines.push(`[${label}] ready: ${result.action}${readySelection}`);\n  } else {\n    const code = result.diagnostic?.code ?? \"unavailable\";\n    const remediation = result.diagnostic?.remediation;\n    lines.push(`[${label}] failed: ${code}${remediation ? ` — ${remediation}` : \"\"}`);\n    if (nextAction) lines.push(`[${label}] next: ${nextAction.command}`);\n  }\n  return lines;\n}\n\nfunction selectedLine(result: ProviderCliEnsureResult, label: string): string | undefined {\n  if (!result.selected) return undefined;\n  const source = renderProviderCliHumanValue(result.selected.source);\n  const path = renderProviderCliHumanValue(result.selected.path);\n  return `[${label}] selected: ${result.selected.version} ${source} ${path} (${result.selected.trust})`;\n}\n\nfunction ignoredCandidateLines(result: ProviderCliEnsureResult, label: string): string[] {\n  return result.candidates\n    .filter((candidate) => candidate.disposition === \"ignored\")\n    .map(\n      (candidate) =>\n        `[${label}] ignored: ${renderProviderCliHumanValue(candidate.path)} (${renderProviderCliHumanValue(candidate.reason)})`,\n    );\n}\n\nfunction warningLines(result: ProviderCliEnsureResult, label: string): string[] {\n  return result.warnings.map(\n    (warningEntry) =>\n      `[${label}] warning: ${warningEntry.code}${warningEntry.remediation ? ` — ${warningEntry.remediation}` : \"\"}`,\n  );\n}\n\nfunction nextActionFor(result: ProviderCliEnsureResult): ProviderCliNextAction | undefined {\n  if (result.ok) return undefined;\n  const reason = result.diagnostic?.code ?? \"unavailable\";\n  if (!providerCliCanAutoRepair(reason)) return undefined;\n  return {\n    provider: result.provider,\n    command: providerCliRepairCommand(result.provider),\n    reason,\n  };\n}\n\nconst defaultSleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nasync function ensureOneProvider(\n  manager: ProviderCliManager,\n  provider: ProviderCliEnsureResult[\"provider\"],\n  options: ProviderCliEnsureCommandOptions,\n): Promise<ProviderCliEnsureResult> {\n  const ensure = (emitPhases: boolean): Promise<ProviderCliEnsureResult> =>\n    manager.ensure(provider, {\n      mode: options.managedOnly ? \"managed-only\" : \"auto\",\n      pathUpdate: options.pathUpdate ?? true,\n      dryRun: options.dryRun ?? false,\n      onPhase:\n        (options.json && !options.onPhase) || !emitPhases\n          ? undefined\n          : (event) => {\n              options.onPhase?.(event);\n              if (options.json) return;\n              const line = renderPhaseLine(event);\n              if (line !== undefined) writeStdout(options, `${line}\\n`);\n            },\n    });\n\n  let result = await ensure(true);\n  const sleep = options.sleep ?? defaultSleep;\n  for (let attempt = 0; result.diagnostic?.code === \"operation_in_progress\"; attempt += 1) {\n    if (attempt >= PROVIDER_CLI_LOCK_BUSY_MAX_ATTEMPTS) break;\n    await sleep(PROVIDER_CLI_LOCK_BUSY_RETRY_DELAY_MS);\n    // A daemon that acquired the cross-process lock first may have completed the same install.\n    // Re-enter ensure so the foreground Agent observes that terminal fact instead of reporting\n    // the transient lock owner as a Provider failure.\n    result = await ensure(false);\n  }\n  return result;\n}\n\nexport async function runProviderCliEnsure(\n  options: ProviderCliEnsureCommandOptions,\n): Promise<ProviderCliEnsureCommandResult> {\n  let usageMessage = \"\";\n  const providers = parseProviderCliProvidersOrReport(options.provider, (chunk) => {\n    usageMessage += chunk;\n  });\n  if (!providers) {\n    presentCommand(\n      {\n        ok: false,\n        error: new CommandError(\n          { code: \"INVALID_PROVIDER\", category: \"validation\", retryability: \"never\", phase: \"validation\" },\n          usageMessage.trim(),\n        ),\n        exitCode: 2,\n        value: { results: [], nextActions: [] },\n      },\n      { json: options.json, stdout: options.stdout, stderr: options.stderr },\n    );\n    return { exitCode: 2, results: [], nextActions: [] };\n  }\n  const manager = createProviderCliManager(options);\n\n  const results = await Promise.all(providers.map((provider) => ensureOneProvider(manager, provider, options)));\n  const nextActions = results.flatMap((result) => {\n    const action = nextActionFor(result);\n    return action ? [action] : [];\n  });\n  const ready = results.every((result) => result.ok);\n  const failure = ready ? undefined : providerCliSetupIncomplete(results);\n  const value = { results, nextActions };\n  if (!options.json) {\n    const write = ready ? writeStdout : writeStderr;\n    if (!ready) write(options, \"PROVIDER_CLI_SETUP_INCOMPLETE: One or more Provider CLIs need attention.\\n\");\n    for (const result of results) {\n      const nextAction = nextActions.find((action) => action.provider === result.provider);\n      for (const line of renderResultLines(result, nextAction)) {\n        write(options, `${line}\\n`);\n      }\n    }\n  } else if (ready) {\n    presentCommand({ ok: true, value, exitCode: 0 }, { json: true, stdout: options.stdout, stderr: options.stderr });\n  } else if (failure) {\n    presentCommand(\n      {\n        ok: false,\n        error: failure.error,\n        exitCode: failure.exitCode,\n        value,\n      },\n      { json: true, stdout: options.stdout, stderr: options.stderr },\n    );\n  }\n\n  return { exitCode: failure ? failure.exitCode : 0, results, nextActions };\n}\n\n/** The aggregate failure contract for a run where at least one provider did not become ready. */\nfunction providerCliSetupIncomplete(results: readonly ProviderCliEnsureResult[]): {\n  readonly error: CommandError;\n  readonly exitCode: ReturnType<typeof commandExitCode>;\n} {\n  const aggregate = providerCliAggregateFailure(results.filter((result) => !result.ok));\n  const error = new CommandError(\n    {\n      code: \"PROVIDER_CLI_SETUP_INCOMPLETE\",\n      category: aggregate.category,\n      retryability: aggregate.retryability,\n      phase: \"provider\",\n    },\n    \"One or more Provider CLIs need attention.\",\n  );\n  return { error, exitCode: commandExitCode(error) };\n}\n","import { realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport {\n  type AgentRuntimeFactory,\n  type AgentRuntimeProbeResult,\n  claudeCodeProcessEnvironment,\n  codexAgentRuntimeEnvironment,\n  piAgentRuntimeEnvironment,\n  resolveCodexHome,\n  resolvedClaudeCodeFactory,\n  resolvedCodexFactory,\n  resolvedPiFactory,\n  resolvePiHome,\n} from \"@opentag/client\";\nimport type { AgentRuntimeProvider, LocalPreparationComponent } from \"@opentag/shared\";\nimport { CLI_VERSION } from \"../../build-info.js\";\nimport { channelConfig } from \"../channel/config.js\";\nimport { redactSecrets } from \"../command/policy.js\";\n\n/**\n * Probe of one Agent Runtime CLI for targeted Computer preparation. It reuses the same\n * resolved factories and environment filters the daemon runs. This is point-in-time local proof,\n * not daemon readiness: OpenTag does not create Runtime homes here and uses fresh executable discovery,\n * whereas daemon startup creates homes and shares a login-shell discovery cache. No model is ever\n * invoked and OpenTag never installs a Runtime CLI: the operator supplies it. Provider commands\n * may maintain their own configuration (for example, Pi can migrate its config during a probe).\n */\n\n/** Bounded probe budget; matches the daemon's default provider probe deadline. */\nexport const RUNTIME_PROBE_TIMEOUT_MS = 10_000;\n\nexport interface ResolvedRuntimeProbeEnvironment {\n  readonly home: string;\n  readonly environment: NodeJS.ProcessEnv;\n  readonly sourceEnvironment: NodeJS.ProcessEnv;\n}\n\n/**\n * Reuse the daemon's selected Runtime home rules and environment filter without creating homes:\n * Codex under `CODEX_HOME` (default `~/.codex`), Claude Code under `CLAUDE_CONFIG_DIR`\n * (default `~/.claude`), and Pi under `PI_CODING_AGENT_DIR` (default `~/.pi/agent`).\n * `CLAUDE_CONFIG_DIR` is omitted when it resolves to Claude's own default,\n * because setting it explicitly would change the credential record the daemon later reads.\n */\nexport async function resolveRuntimeProbeEnvironment(\n  provider: AgentRuntimeProvider,\n  sourceEnvironment: NodeJS.ProcessEnv = process.env,\n): Promise<ResolvedRuntimeProbeEnvironment> {\n  if (provider === \"codex\") {\n    const home = await canonicalizeProviderHome(resolveCodexHome(sourceEnvironment));\n    return {\n      home,\n      sourceEnvironment,\n      environment: codexAgentRuntimeEnvironment({ ...sourceEnvironment, CODEX_HOME: home }),\n    };\n  }\n  if (provider === \"pi\") {\n    const home = await canonicalizeProviderHome(resolvePiHome(sourceEnvironment));\n    return {\n      home,\n      sourceEnvironment,\n      environment: piAgentRuntimeEnvironment({ ...sourceEnvironment, PI_CODING_AGENT_DIR: home }),\n    };\n  }\n  const configuredHome = resolve(\n    sourceEnvironment.CLAUDE_CONFIG_DIR ?? join(sourceEnvironment.HOME ?? homedir(), \".claude\"),\n  );\n  const claudeCodeHome = await canonicalizeProviderHome(configuredHome);\n  const defaultClaudeCodeHome = resolve(join(sourceEnvironment.HOME ?? homedir(), \".claude\"));\n  const canonicalDefaultHome = await realpath(defaultClaudeCodeHome).catch(() => defaultClaudeCodeHome);\n  return {\n    home: claudeCodeHome,\n    sourceEnvironment,\n    environment: claudeCodeProcessEnvironment(sourceEnvironment, claudeCodeHome, canonicalDefaultHome),\n  };\n}\n\nasync function canonicalizeProviderHome(configured: string): Promise<string> {\n  // Inspection does not create a Runtime home or install anything. An absent home is passed to\n  // the existing probe, which owns the credential/capability diagnosis.\n  return realpath(configured).catch((error: NodeJS.ErrnoException) => {\n    if (error.code === \"ENOENT\") return configured;\n    throw error;\n  });\n}\n\nfunction resolvedFactoryFor(\n  provider: AgentRuntimeProvider,\n  environment: ResolvedRuntimeProbeEnvironment,\n  clientVersion: string,\n): AgentRuntimeFactory {\n  if (provider === \"codex\") {\n    return resolvedCodexFactory({\n      clientVersion,\n      codexHome: environment.home,\n      command: \"codex\",\n      environment: environment.environment,\n      sourceEnvironment: environment.sourceEnvironment,\n    });\n  }\n  if (provider === \"pi\") {\n    return resolvedPiFactory({\n      command: \"pi\",\n      environment: environment.environment,\n      piHome: environment.home,\n      sessionDirectory: resolve(environment.home, \"sessions\"),\n      sourceEnvironment: environment.sourceEnvironment,\n    });\n  }\n  return resolvedClaudeCodeFactory({\n    claudeCodeHome: environment.home,\n    command: \"claude\",\n    environment: environment.environment,\n    sourceEnvironment: environment.sourceEnvironment,\n  });\n}\n\nexport interface RuntimeProbeOptions {\n  readonly provider: AgentRuntimeProvider;\n  /** Source environment; defaults to `process.env`. */\n  readonly environment?: NodeJS.ProcessEnv;\n  /** Overrides the channel Client version for factory tests only. */\n  readonly clientVersion?: string;\n  readonly signal?: AbortSignal;\n  readonly timeoutMs?: number;\n  readonly now?: () => Date;\n}\n\n/**\n * Probe one Runtime CLI and fold the outcome into the shared local preparation vocabulary. The\n * returned Component never carries an OpenTag install command: recovery is the operator's manual\n * install/login/config step followed by an idempotent read-only `runtime-inspect` verify.\n */\nexport async function probeRuntimeComponent(options: RuntimeProbeOptions): Promise<LocalPreparationComponent> {\n  const provider = options.provider;\n  const timeoutMs = options.timeoutMs ?? RUNTIME_PROBE_TIMEOUT_MS;\n  const controller = new AbortController();\n  const bounded = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;\n  const timer = setTimeout(() => controller.abort(new Error(\"Runtime probe timed out\")), timeoutMs);\n  let abortListener: (() => void) | undefined;\n  try {\n    bounded.throwIfAborted();\n    const aborted = new Promise<never>((_, reject) => {\n      abortListener = () => reject(bounded.reason);\n      bounded.addEventListener(\"abort\", abortListener, { once: true });\n    });\n    const result = await Promise.race([probeSelectedRuntime(options, bounded), aborted]);\n    return runtimeComponentFromProbeResult(provider, result, (options.now ?? (() => new Date()))().toISOString());\n  } catch (error) {\n    if (options.signal?.aborted) throw error;\n    return runtimeComponentFromProbeFailure(provider, error, (options.now ?? (() => new Date()))().toISOString());\n  } finally {\n    clearTimeout(timer);\n    if (abortListener) bounded.removeEventListener(\"abort\", abortListener);\n  }\n}\n\nasync function probeSelectedRuntime(\n  options: RuntimeProbeOptions,\n  signal: AbortSignal,\n): Promise<AgentRuntimeProbeResult> {\n  const environment = await resolveRuntimeProbeEnvironment(options.provider, options.environment);\n  signal.throwIfAborted();\n  return resolvedFactoryFor(options.provider, environment, options.clientVersion ?? CLI_VERSION).probe({ signal });\n}\n\nexport function runtimeComponentLabel(provider: AgentRuntimeProvider): string {\n  if (provider === \"codex\") return \"Codex CLI\";\n  if (provider === \"claude-code\") return \"Claude Code CLI\";\n  return \"Pi CLI\";\n}\n\nexport function runtimeComponentId(provider: AgentRuntimeProvider): `runtime:${AgentRuntimeProvider}` {\n  return `runtime:${provider}`;\n}\n\n/** The exact idempotent read-only verify command for a known Runtime provider. */\nexport function runtimeInspectCommand(provider: AgentRuntimeProvider): string {\n  return `\"$HOME/.local/bin/${channelConfig.binName}\" computer runtime-inspect --provider ${provider}`;\n}\n\nexport function runtimeComponentFromProbeResult(\n  provider: AgentRuntimeProvider,\n  result: AgentRuntimeProbeResult,\n  observedAt: string,\n): LocalPreparationComponent {\n  const label = runtimeComponentLabel(provider);\n  const base = {\n    id: runtimeComponentId(provider),\n    label,\n    required: true as const,\n    ...(result.version ? { version: redactSecrets(result.version).slice(0, 64) } : {}),\n    observedAt,\n  };\n  if (result.ready) {\n    return { ...base, status: \"ready\" as const, blocking: false };\n  }\n  const issue = result.issues[0];\n  const verifyAction = { command: runtimeInspectCommand(provider) };\n  if (!issue) {\n    return {\n      ...base,\n      status: \"unavailable\" as const,\n      blocking: true,\n      diagnosticCode: \"runtime_probe_failed\",\n      message: `${label} readiness could not be established.`,\n      nextAction: { instruction: \"Wait briefly, then run the verify command again.\" },\n      verifyAction,\n    };\n  }\n  switch (issue.code) {\n    case \"artifact_missing\":\n      return {\n        ...base,\n        status: \"install_required\" as const,\n        blocking: true,\n        diagnosticCode: issue.code,\n        message: `${label} is not installed or could not run.`,\n        nextAction: {\n          instruction: `Install and sign in to the ${label} yourself (OpenTag never installs Runtime CLIs), then run the verify command.`,\n        },\n        verifyAction,\n      };\n    case \"credential_missing\":\n      return {\n        ...base,\n        status: \"needs_attention\" as const,\n        blocking: true,\n        diagnosticCode: issue.code,\n        message: `${label} credentials were not found.`,\n        nextAction: { instruction: `Sign in to the ${label} with its own login command, then run the verify command.` },\n        verifyAction,\n      };\n    case \"version_incompatible\":\n      return {\n        ...base,\n        status: \"needs_attention\" as const,\n        blocking: true,\n        diagnosticCode: issue.code,\n        message: `${label} does not provide the required version or capabilities.`,\n        nextAction: { instruction: `Update the ${label} to a supported version, then run the verify command.` },\n        verifyAction,\n      };\n    case \"configuration_invalid\":\n      return {\n        ...base,\n        status: \"needs_attention\" as const,\n        blocking: true,\n        diagnosticCode: issue.code,\n        message: `${label} configuration is invalid.`,\n        nextAction: { instruction: `Fix the ${label} configuration, then run the verify command.` },\n        verifyAction,\n      };\n    default:\n      return {\n        ...base,\n        status: \"unavailable\" as const,\n        blocking: true,\n        diagnosticCode: issue.code,\n        message: `${label} could not be checked right now.`,\n        nextAction: { instruction: \"Wait briefly, then run the verify command again.\" },\n        verifyAction,\n      };\n  }\n}\n\nexport function runtimeComponentFromProbeFailure(\n  provider: AgentRuntimeProvider,\n  error: unknown,\n  observedAt: string,\n): LocalPreparationComponent {\n  const label = runtimeComponentLabel(provider);\n  const detail = redactSecrets(error instanceof Error ? error.message : String(error)).slice(0, 480);\n  return {\n    id: runtimeComponentId(provider),\n    label,\n    required: true,\n    status: \"unavailable\",\n    blocking: true,\n    diagnosticCode: \"runtime_probe_failed\",\n    message: detail.length > 0 ? `${label} check failed: ${detail}` : `${label} check failed.`,\n    nextAction: { instruction: \"Wait briefly, then run the verify command again.\" },\n    verifyAction: { command: runtimeInspectCommand(provider) },\n    observedAt,\n  };\n}\n\n/**\n * The fail-closed row for a marked Client talking to an older Server that answered `agentId`\n * without a `runtimeProvider`. The exact provider is unknown, so no probe runs, no default\n * Runtime is assumed, and the recovery is a Server upgrade plus a Web recheck — never a made-up\n * provider command.\n */\nexport function unconfirmedRuntimeComponent(): LocalPreparationComponent {\n  return {\n    id: \"runtime:unconfirmed\",\n    label: \"Runtime CLI (unconfirmed)\",\n    required: true,\n    status: \"needs_attention\",\n    blocking: true,\n    diagnosticCode: \"RUNTIME_UNCONFIRMED\",\n    message: \"The connected Server did not report which Runtime CLI this Agent uses.\",\n    nextAction: {\n      instruction: \"Upgrade the OpenTag Server (and this CLI), then recheck this Computer in the OpenTag Web app.\",\n    },\n  };\n}\n","import type { ProviderCliEnsureResult, ProviderCliPhaseEvent, ProviderCliProvider } from \"@opentag/client\";\nimport {\n  type AgentRuntimeProvider,\n  type LocalComputerPreparationResult,\n  LocalComputerPreparationResultSchema,\n  type LocalPreparationCheck,\n  type LocalPreparationComponent,\n} from \"@opentag/shared\";\nimport { channelConfig } from \"../channel/config.js\";\nimport { OPEN_TAG_HOME_ENVIRONMENT_VARIABLE } from \"../channel/environment.js\";\nimport { redactSecrets } from \"../command/policy.js\";\nimport type { DaemonServiceInfo } from \"../daemon/service/index.js\";\nimport { quotePosix } from \"../daemon/service/shared.js\";\nimport { runProviderCliEnsure } from \"../provider-cli/ensure.js\";\nimport { providerCliCanAutoRepair, providerCliRepairCommand } from \"../provider-cli/shared.js\";\nimport {\n  probeRuntimeComponent,\n  type RuntimeProbeOptions,\n  runtimeComponentFromProbeFailure,\n  unconfirmedRuntimeComponent,\n} from \"./runtime-probe.js\";\n\n/**\n * One-shot local computer preparation for a targeted connect. It renders exactly four required\n * top-level Components — `computer` (with connection/daemon child Checks), the selected Runtime\n * (`runtime:<provider>` or `runtime:unconfirmed`), and the two Provider CLIs — and derives every\n * count from the completed Checks, never from an ensure exit code alone.\n */\n\nexport const LOCAL_COMPUTER_PREPARATION_INCOMPLETE = \"LOCAL_COMPUTER_PREPARATION_INCOMPLETE\";\n\nexport const SERVER_CONFIRMATION_GUIDANCE = \"Server/Web confirmation still requires fresh daemon observations.\";\nexport const NO_CODE_REUSE_GUIDANCE = \"Connection preserved. Do not reuse the one-time connect code.\";\n\nconst PROVIDER_COMPONENTS: Record<ProviderCliProvider, { id: \"im-cli:lark\" | \"im-cli:slack\"; label: string }> = {\n  feishu: { id: \"im-cli:lark\", label: \"Lark CLI\" },\n  slack: { id: \"im-cli:slack\", label: \"Slack CLI\" },\n};\n\nexport interface LocalComputerPreparationOptions {\n  readonly runtimeProvider?: AgentRuntimeProvider;\n  readonly service?: DaemonServiceInfo;\n  readonly serviceError?: string;\n  readonly noStart: boolean;\n  readonly prepareProviderClis: boolean;\n  readonly home: string;\n  readonly now?: () => Date;\n  readonly env?: NodeJS.ProcessEnv;\n  readonly onPhase?: (event: ProviderCliPhaseEvent) => void;\n  readonly probeRuntime?: (options: RuntimeProbeOptions) => Promise<LocalPreparationComponent>;\n}\n\n/** Idempotent daemon commands that reach the exact connected `--home` through the channel variable. */\nexport function daemonServiceCommand(action: \"install\" | \"status\", home: string): string {\n  return `${OPEN_TAG_HOME_ENVIRONMENT_VARIABLE}=${quotePosix(home)} \"$HOME/.local/bin/${channelConfig.binName}\" daemon ${action}`;\n}\n\nfunction observedAt(now: () => Date): string {\n  return now().toISOString();\n}\n\n/**\n * The daemon child Check: ready only when the service actually reports `active`. Unknown, inactive,\n * missing, failed, or deliberately skipped (`--no-start`) states are all blocking, and the repair is\n * the idempotent `daemon install` (install/update/start) followed by a `daemon status` verify.\n */\nexport function daemonChildCheck(input: {\n  service?: DaemonServiceInfo;\n  serviceError?: string;\n  noStart: boolean;\n  home: string;\n  now: () => Date;\n}): LocalPreparationCheck {\n  const verifyAction = { command: daemonServiceCommand(\"status\", input.home) };\n  if (input.noStart) {\n    return {\n      id: \"computer:daemon\",\n      label: \"Daemon service\",\n      required: true,\n      status: \"skipped\",\n      blocking: true,\n      message: \"Daemon service was not started (--no-start).\",\n      nextAction: { command: daemonServiceCommand(\"install\", input.home) },\n      verifyAction,\n    };\n  }\n  if (input.serviceError) {\n    return {\n      id: \"computer:daemon\",\n      label: \"Daemon service\",\n      required: true,\n      status: \"needs_attention\",\n      blocking: true,\n      diagnosticCode: \"DAEMON_SERVICE_FAILED\",\n      message: redactSecrets(input.serviceError).trim().slice(0, 512) || \"Daemon service failed.\",\n      nextAction: { command: daemonServiceCommand(\"install\", input.home) },\n      verifyAction,\n    };\n  }\n  const service = input.service;\n  if (!service) {\n    return {\n      id: \"computer:daemon\",\n      label: \"Daemon service\",\n      required: true,\n      status: \"needs_attention\",\n      blocking: true,\n      diagnosticCode: \"DAEMON_SERVICE_UNAVAILABLE\",\n      message: \"Daemon service did not report a state.\",\n      nextAction: { command: daemonServiceCommand(\"install\", input.home) },\n      verifyAction,\n    };\n  }\n  const terminal = {\n    id: \"computer:daemon\" as const,\n    label: \"Daemon service\",\n    required: true as const,\n    observedAt: observedAt(input.now),\n  };\n  if (service.state === \"active\") {\n    return { ...terminal, status: \"ready\" as const, blocking: false };\n  }\n  if (service.state === \"not-installed\") {\n    return {\n      ...terminal,\n      status: \"install_required\" as const,\n      blocking: true,\n      diagnosticCode: \"DAEMON_SERVICE_NOT_INSTALLED\",\n      message: \"Daemon service is not installed.\",\n      nextAction: { command: daemonServiceCommand(\"install\", input.home) },\n      verifyAction,\n    };\n  }\n  return {\n    ...terminal,\n    status: \"needs_attention\" as const,\n    blocking: true,\n    diagnosticCode: service.state === \"inactive\" ? \"DAEMON_SERVICE_INACTIVE\" : \"DAEMON_SERVICE_UNKNOWN\",\n    message: service.state === \"inactive\" ? \"Daemon service is inactive.\" : \"Daemon service state is unknown.\",\n    nextAction: { command: daemonServiceCommand(\"install\", input.home) },\n    verifyAction,\n  };\n}\n\nexport function computerComponent(input: {\n  service?: DaemonServiceInfo;\n  serviceError?: string;\n  noStart: boolean;\n  home: string;\n  now: () => Date;\n}): LocalPreparationComponent {\n  const daemon = daemonChildCheck(input);\n  const daemonReady = daemon.status === \"ready\";\n  return {\n    id: \"computer\",\n    label: \"Computer\",\n    required: true,\n    status: daemonReady ? \"ready\" : \"needs_attention\",\n    blocking: !daemonReady,\n    checks: [\n      {\n        id: \"computer:connection\",\n        label: \"Computer connection\",\n        required: true,\n        status: \"ready\",\n        blocking: false,\n        observedAt: observedAt(input.now),\n      },\n      daemon,\n    ],\n  };\n}\n\nfunction safeRemediation(remediation: string | undefined): string | undefined {\n  return remediation ? redactSecrets(remediation).slice(0, 512) : undefined;\n}\n\nfunction warningsFromProvider(result: ProviderCliEnsureResult): LocalPreparationComponent[\"warnings\"] {\n  if (result.warnings.length === 0) return undefined;\n  return result.warnings.map((warning) => ({\n    code: warning.code.slice(0, 64),\n    ...(warning.remediation ? { message: redactSecrets(warning.remediation).slice(0, 512) } : {}),\n    blocking: false,\n  }));\n}\n\nfunction providerRepairCommand(provider: ProviderCliProvider): string {\n  return providerCliRepairCommand(provider);\n}\n\nfunction providerInspectCommand(provider: ProviderCliProvider): string {\n  return `\"$HOME/.local/bin/${channelConfig.binName}\" provider-cli inspect --provider ${provider === \"feishu\" ? \"lark\" : \"slack\"}`;\n}\n\n/**\n * Map one Provider CLI ensure outcome into its Component. Non-ready rows keep the exact provider\n * diagnostic code, block the verdict, and point at the existing idempotent ensure repair — except\n * manual failures, which get a safe instruction plus a read-only provider-cli inspect verify.\n */\nexport function providerComponentFromEnsureResult(\n  provider: ProviderCliProvider,\n  result: ProviderCliEnsureResult | undefined,\n  now: () => Date,\n  skipped = false,\n): LocalPreparationComponent {\n  const { id, label } = PROVIDER_COMPONENTS[provider];\n  if (skipped) {\n    return {\n      id,\n      label,\n      required: true,\n      status: \"skipped\",\n      blocking: true,\n      message: `${label} preparation was skipped (--no-prepare-provider-clis).`,\n      nextAction: { command: providerRepairCommand(provider) },\n      verifyAction: { command: providerInspectCommand(provider) },\n    };\n  }\n  if (!result) {\n    return {\n      id,\n      label,\n      required: true,\n      status: \"unavailable\",\n      blocking: true,\n      diagnosticCode: \"provider_result_missing\",\n      message: `${label} preparation produced no result.`,\n      nextAction: { command: providerRepairCommand(provider) },\n      verifyAction: { command: providerInspectCommand(provider) },\n    };\n  }\n  const observed = observedAt(now);\n  if (result.ok && result.readiness === \"ready\" && result.selected) {\n    const warnings = warningsFromProvider(result);\n    return {\n      id,\n      label,\n      required: true,\n      status: \"ready\",\n      blocking: false,\n      version: redactSecrets(result.selected.version).slice(0, 64),\n      observedAt: observed,\n      ...(warnings ? { warnings } : {}),\n    };\n  }\n  const code = result.diagnostic?.code ?? \"unavailable\";\n  const remediation = safeRemediation(result.diagnostic?.remediation);\n  const manual = !providerCliCanAutoRepair(code);\n  const base = {\n    id,\n    label,\n    required: true,\n    observedAt: observed,\n    diagnosticCode: code,\n    verifyAction: { command: providerInspectCommand(provider) },\n  };\n  if (code === \"operation_in_progress\") {\n    return {\n      ...base,\n      status: \"checking\" as const,\n      blocking: true,\n      message: `${label} preparation is owned by another OpenTag process.`,\n      nextAction: { command: providerRepairCommand(provider) },\n    };\n  }\n  if (code === \"not_installed\" || code === \"install_incomplete\" || code === \"artifact_drifted\") {\n    return {\n      ...base,\n      status: \"install_required\" as const,\n      blocking: true,\n      message: remediation ?? `${label} must be installed or repaired.`,\n      nextAction: { command: providerRepairCommand(provider) },\n    };\n  }\n  if (manual) {\n    return {\n      ...base,\n      status: \"needs_attention\" as const,\n      blocking: true,\n      message: remediation ?? `${label} needs manual attention.`,\n      nextAction: { instruction: remediation ?? `Fix the ${label} manually, then run the verify command.` },\n    };\n  }\n  return {\n    ...base,\n    status: \"needs_attention\" as const,\n    blocking: true,\n    message: remediation ?? `${label} preparation needs attention.`,\n    nextAction: { command: providerRepairCommand(provider) },\n  };\n}\n\n/** Fail-closed Provider rows when ensure itself threw or reported no results at all. */\nfunction failedClosedProviderComponent(\n  provider: ProviderCliProvider,\n  error: unknown,\n  now: () => Date,\n): LocalPreparationComponent {\n  const { id, label } = PROVIDER_COMPONENTS[provider];\n  const detail = redactSecrets(error instanceof Error ? error.message : String(error)).slice(0, 480);\n  return {\n    id,\n    label,\n    required: true,\n    status: \"unavailable\",\n    blocking: true,\n    diagnosticCode: \"provider_prepare_failed\",\n    message: detail.length > 0 ? `${label} preparation failed: ${detail}` : `${label} preparation failed.`,\n    nextAction: { command: providerRepairCommand(provider) },\n    verifyAction: { command: providerInspectCommand(provider) },\n    observedAt: observedAt(now),\n  };\n}\n\nexport async function runLocalComputerPreparation(\n  options: LocalComputerPreparationOptions,\n): Promise<LocalComputerPreparationResult> {\n  const now = options.now ?? (() => new Date());\n  const probe = options.probeRuntime ?? probeRuntimeComponent;\n  const computer = computerComponent({\n    service: options.service,\n    serviceError: options.serviceError,\n    noStart: options.noStart,\n    home: options.home,\n    now,\n  });\n  const runtime = await probeRuntimeSafely(options, probe, now);\n  let lark: LocalPreparationComponent;\n  let slack: LocalPreparationComponent;\n  if (!options.prepareProviderClis) {\n    lark = providerComponentFromEnsureResult(\"feishu\", undefined, now, true);\n    slack = providerComponentFromEnsureResult(\"slack\", undefined, now, true);\n  } else {\n    try {\n      const ensured = await runProviderCliEnsure({\n        provider: \"all\",\n        json: true,\n        stdout: () => undefined,\n        stderr: () => undefined,\n        onPhase: options.onPhase,\n        ...(options.env ? { env: options.env } : {}),\n      });\n      const byProvider = new Map(ensured.results.map((result) => [result.provider, result]));\n      lark = providerComponentFromEnsureResult(\"feishu\", byProvider.get(\"feishu\"), now);\n      slack = providerComponentFromEnsureResult(\"slack\", byProvider.get(\"slack\"), now);\n    } catch (error) {\n      // An unexpected ensure failure must not lose the complete picture: both Provider rows fail\n      // closed and the connection/runtime verdicts still render.\n      lark = failedClosedProviderComponent(\"feishu\", error, now);\n      slack = failedClosedProviderComponent(\"slack\", error, now);\n    }\n  }\n  return projectPreparation([computer, runtime, lark, slack]);\n}\n\n/** Derive counts from required rows and validate both normal and fail-closed projections. */\nexport function projectPreparation(components: LocalPreparationComponent[]): LocalComputerPreparationResult {\n  const required = components.filter((component) => component.required);\n  const ready = required.filter(\n    (component) =>\n      component.status === \"ready\" &&\n      !component.blocking &&\n      !(component.checks ?? []).some((check) => check.blocking || (check.required && check.status !== \"ready\")),\n  ).length;\n  return LocalComputerPreparationResultSchema.parse({\n    status: ready === required.length ? \"ready\" : \"needs_attention\",\n    localReady: ready === required.length,\n    readyCount: ready,\n    requiredCount: required.length,\n    components,\n  });\n}\n\n/** Preserve all four rows after an unexpected post-connection orchestration/projection error. */\nexport function failedLocalComputerPreparation(\n  options: LocalComputerPreparationOptions,\n  error: unknown,\n): LocalComputerPreparationResult {\n  const now = options.now ?? (() => new Date());\n  const computer = computerComponent({ ...options, now });\n  const runtime = options.runtimeProvider\n    ? runtimeComponentFromProbeFailure(options.runtimeProvider, error, observedAt(now))\n    : unconfirmedRuntimeComponent();\n  return projectPreparation([\n    computer,\n    runtime,\n    failedClosedProviderComponent(\"feishu\", error, now),\n    failedClosedProviderComponent(\"slack\", error, now),\n  ]);\n}\n\nasync function probeRuntimeSafely(\n  options: LocalComputerPreparationOptions,\n  probe: NonNullable<LocalComputerPreparationOptions[\"probeRuntime\"]>,\n  now: () => Date,\n): Promise<LocalPreparationComponent> {\n  if (options.runtimeProvider === undefined) return unconfirmedRuntimeComponent();\n  try {\n    return await probe({ provider: options.runtimeProvider, environment: options.env, now });\n  } catch (error) {\n    // Provider preparation still runs after an unexpected Runtime failure.\n    return runtimeComponentFromProbeFailure(options.runtimeProvider, error, observedAt(now));\n  }\n}\n\n/** Diagnostic codes of the blocking rows that keep this result from being ready. */\nexport function preparationBlockerCodes(result: LocalComputerPreparationResult): string[] {\n  const codes: string[] = [];\n  for (const component of result.components) {\n    if (component.status === \"ready\") continue;\n    if (component.diagnosticCode) codes.push(component.diagnosticCode);\n    for (const check of component.checks ?? []) {\n      if ((check.blocking || (check.required && check.status !== \"ready\")) && check.diagnosticCode) {\n        codes.push(check.diagnosticCode);\n      }\n    }\n  }\n  return codes;\n}\n\n/** Guidance lines shared verbatim by the human and JSON projections of one result. */\nexport function preparationGuidance(result: LocalComputerPreparationResult): string[] {\n  if (result.status === \"ready\") return [SERVER_CONFIRMATION_GUIDANCE];\n  const codes = preparationBlockerCodes(result);\n  return [\n    ...(codes.length ? [`Blocked by: ${codes.join(\", \")}`] : []),\n    NO_CODE_REUSE_GUIDANCE,\n    SERVER_CONFIRMATION_GUIDANCE,\n  ];\n}\n","import { resolve } from \"node:path\";\nimport { resolveOpenTagHome } from \"@opentag/client\";\nimport type { LocalComputerPreparationResult } from \"@opentag/shared\";\nimport type { Command } from \"commander\";\nimport { channelConfig } from \"../../core/channel/config.js\";\nimport { resolveChannelEnvironment } from \"../../core/channel/environment.js\";\nimport * as commandPolicy from \"../../core/command/policy.js\";\nimport { type ComputerConnectResult, runComputerConnect } from \"../../core/computer/connect.js\";\nimport { formatPreparationResultLines } from \"../../core/computer/formatting.js\";\nimport {\n  daemonServiceCommand,\n  failedLocalComputerPreparation,\n  LOCAL_COMPUTER_PREPARATION_INCOMPLETE,\n  NO_CODE_REUSE_GUIDANCE,\n  preparationGuidance,\n  runLocalComputerPreparation,\n} from \"../../core/computer/preparation.js\";\nimport { quotePosix } from \"../../core/daemon/service/shared.js\";\nimport { renderProviderCliHumanValue } from \"../../core/provider-cli/shared.js\";\n\ntype ComputerConnectCommandOptions = {\n  home?: string;\n  server?: string;\n  start?: boolean;\n  prepareProviderClis?: boolean;\n  json?: boolean;\n};\n\nexport function registerComputerConnectCommand(computer: Command): void {\n  computer\n    .command(\"connect\")\n    .description(\"Connect this Computer, check the selected Runtime, and prepare Lark and Slack CLIs\")\n    .argument(\"<code>\", \"one-time Computer connect code\")\n    .option(\"--server <url>\", \"OpenTag server URL\")\n    .option(\"--home <path>\", \"OpenTag home directory\")\n    .option(\"--no-start\", \"skip only daemon service installation/start\")\n    .option(\"--no-prepare-provider-clis\", \"skip Lark and Slack CLI preparation\")\n    .option(\"--json\", \"print JSON\")\n    .action(executeComputerConnectCommand);\n}\n\nasync function executeComputerConnectCommand(code: string, options: ComputerConnectCommandOptions): Promise<void> {\n  const environment = resolveChannelEnvironment(process.env);\n  const home = resolve(options.home ?? resolveOpenTagHome(environment));\n  const connection = await connectOrPresentFailure(code, home, environment, options);\n  if (!connection) return;\n  if (connection.persistenceError) {\n    presentPersistenceFailure(connection, home, options.json === true);\n    return;\n  }\n  if (!connection.agentId) {\n    presentOrdinaryConnection(connection, home, options.json === true);\n    return;\n  }\n  const preparationOptions = {\n    runtimeProvider: connection.runtimeProvider,\n    service: connection.service,\n    serviceError: connection.serviceError,\n    home,\n    env: environment,\n    noStart: options.start === false,\n    prepareProviderClis: options.prepareProviderClis !== false,\n  };\n  let preparation: LocalComputerPreparationResult;\n  try {\n    preparation = await runLocalComputerPreparation({\n      ...preparationOptions,\n      onPhase: options.json\n        ? undefined\n        : (event) => {\n            const provider = event.provider === \"feishu\" ? \"lark\" : \"slack\";\n            const detail = event.detail ? ` — ${event.detail}` : \"\";\n            process.stdout.write(`${safeLine(`[im-cli:${provider}] ${event.phase}: ${event.status}${detail}`)}\\n`);\n          },\n    });\n  } catch (error) {\n    // Preserve the already-saved connection even after a projection failure. Neither exchange\n    // nor ensure is repeated here: the one-time code cannot be reused.\n    preparation = failedLocalComputerPreparation(preparationOptions, error);\n  }\n  presentPreparation(connection, preparation, options.json === true);\n}\n\nasync function connectOrPresentFailure(\n  code: string,\n  home: string,\n  environment: NodeJS.ProcessEnv,\n  options: ComputerConnectCommandOptions,\n): Promise<ComputerConnectResult | undefined> {\n  try {\n    const serverUrl = options.server ?? environment.OPENTAG_SERVER_URL ?? channelConfig.defaultServerUrl;\n    if (!serverUrl) throw new Error(`The ${channelConfig.channel} channel requires --server for Computer connect`);\n    return await runComputerConnect({ code, home, noStart: options.start === false, serverUrl });\n  } catch (error) {\n    const commandError = commandPolicy.toCommandError(error, \"request\");\n    process.exitCode = commandPolicy.presentCommand(\n      { ok: false, error: commandError, exitCode: commandPolicy.commandExitCode(commandError) },\n      { json: options.json },\n    );\n    return undefined;\n  }\n}\n\nfunction preparationError(\n  code: string,\n  message: string,\n  phase: commandPolicy.CommandPhase = \"provider\",\n): commandPolicy.CommandError {\n  return new commandPolicy.CommandError(\n    // Retryability applies to connect, not to the separate, idempotent repair commands.\n    { code, category: \"dependency\", retryability: \"never\", phase },\n    message,\n  );\n}\n\nfunction safeLine(line: string): string {\n  return renderProviderCliHumanValue(commandPolicy.redactSecrets(line), 16384);\n}\n\nfunction presentPersistenceFailure(connection: ComputerConnectResult, home: string, json: boolean): void {\n  const failure = connection.persistenceError;\n  if (!failure) return;\n  const guidance = [\n    \"Server exchange committed; the one-time connect code was consumed. Do not reuse it.\",\n    \"Local credentials/identity may be incomplete; previous credentials may no longer work. No daemon was started or restarted.\",\n    \"Fix local storage permissions/free space, then run the local repair below. It accepts only a saved credential for this exact installation.\",\n    `Repair: \"$HOME/.local/bin/${channelConfig.binName}\" computer repair-local --installation-id ${failure.installationId} --home ${quotePosix(home)}`,\n    \"If repair reports COMPUTER_CREDENTIAL_UNAVAILABLE, request a NEW connect/repair code in OpenTag Web after fixing storage. The consumed code cannot be recovered.\",\n  ];\n  const error = preparationError(\n    \"COMPUTER_LOCAL_PERSISTENCE_FAILED\",\n    guidance[0] ?? \"Do not reuse the connect code.\",\n    \"startup\",\n  );\n  // `connected` records the committed Server exchange, not locally usable credentials or readiness.\n  const value = { connected: true, codeConsumed: true, localPersistenceReady: false, connection, guidance };\n  const exitCode = commandPolicy.commandExitCode(error);\n  process.exitCode = exitCode;\n  if (json) {\n    commandPolicy.presentCommand({ ok: false, value, error, exitCode }, { json: true });\n  } else {\n    process.stderr.write(\n      `${[connection.message, `${failure.stage}: ${failure.message}`, ...guidance].map(safeLine).join(\"\\n\")}\\n`,\n    );\n  }\n}\n\nfunction presentPreparation(\n  connection: ComputerConnectResult,\n  preparation: LocalComputerPreparationResult,\n  json: boolean,\n): void {\n  const guidance = preparationGuidance(preparation);\n  const value = { connected: true, connection, preparation, guidance };\n  const error = preparationError(LOCAL_COMPUTER_PREPARATION_INCOMPLETE, NO_CODE_REUSE_GUIDANCE);\n  process.exitCode = preparation.localReady ? 0 : commandPolicy.commandExitCode(error);\n  if (json) {\n    commandPolicy.presentCommand(\n      preparation.localReady\n        ? { ok: true, value, exitCode: 0 }\n        : { ok: false, value, error, exitCode: commandPolicy.commandExitCode(error) },\n      { json: true },\n    );\n    return;\n  }\n  const lines = [connection.message, ...formatPreparationResultLines(preparation), ...guidance];\n  const output = `${lines.map(safeLine).join(\"\\n\")}\\n`;\n  if (preparation.localReady) process.stdout.write(output);\n  else process.stderr.write(output);\n}\n\nfunction presentOrdinaryConnection(connection: ComputerConnectResult, home: string, json: boolean): void {\n  const guidance = connection.serviceError\n    ? [\n        NO_CODE_REUSE_GUIDANCE,\n        `Repair: ${daemonServiceCommand(\"install\", home)}`,\n        `Verify: ${daemonServiceCommand(\"status\", home)}`,\n      ]\n    : [];\n  const value = { connected: true, connection, guidance };\n  const error = preparationError(\n    \"DAEMON_SERVICE_FAILED\",\n    `Daemon service failed; machine credentials were preserved. ${NO_CODE_REUSE_GUIDANCE}`,\n    \"startup\",\n  );\n  if (json) {\n    process.exitCode = commandPolicy.presentCommand(\n      connection.serviceError\n        ? { ok: false, value, error, exitCode: commandPolicy.commandExitCode(error) }\n        : { ok: true, value, exitCode: 0 },\n      { json: true },\n    );\n    return;\n  }\n  process.stdout.write(`${safeLine(connection.message)}\\n`);\n  if (connection.service)\n    process.stdout.write(\n      `${safeLine(`Daemon service ${connection.service.serviceId} is ${connection.service.state}`)}\\n`,\n    );\n  for (const line of guidance) process.stderr.write(`${safeLine(line)}\\n`);\n  process.exitCode = connection.serviceError ? commandPolicy.commandExitCode(error) : 0;\n}\n","import type { ListAccountComputersResponse } from \"@opentag/shared\";\nimport { resolveCommandContext } from \"../command/context.js\";\n\nexport async function listComputers(home?: string): Promise<ListAccountComputersResponse> {\n  const context = await resolveCommandContext({ home, requireAuth: true });\n  if (!context.api || !context.accessToken) throw new Error(\"Command context did not resolve an authenticated API\");\n  return context.api.listAccountComputers(context.accessToken);\n}\n","import type { Command } from \"commander\";\nimport { executeCommand } from \"../../core/command/policy.js\";\nimport { formatComputerList } from \"../../core/computer/formatting.js\";\nimport { listComputers } from \"../../core/computer/queries.js\";\n\nexport function registerComputerListCommand(computer: Command): void {\n  computer\n    .command(\"list\")\n    .description(\"List Computers\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { json?: boolean }) => {\n      process.exitCode = await executeCommand(() => listComputers(), {\n        json: options.json === true,\n        formatValue: formatComputerList,\n        phase: \"request\",\n      });\n    });\n}\n","import {\n  machineCredentialsPath,\n  readMachineCredentialsStrict,\n  storeBoundAccountComputer,\n  writeComputerIdentityAtomically,\n} from \"@opentag/client\";\nimport { CommandError } from \"../command/policy.js\";\n\n/**\n * Recover only the local files of an already-consumed exchange, never exchange a code or start a\n * daemon. The expected installation prevents accidentally reviving an older, revoked credential.\n * Rewriting the credential also retries durability/permissions after a post-rename write error.\n */\nexport async function repairLocalComputerConnection(options: { home: string; installationId: string }) {\n  const credential = (\n    await readMachineCredentialsStrict(options.home).catch((error: unknown) => {\n      throw unavailableCredential(error);\n    })\n  )?.computer;\n  if (!credential || credential.installationId !== options.installationId) {\n    throw unavailableCredential();\n  }\n  try {\n    await storeBoundAccountComputer(credential, options.home);\n    await writeComputerIdentityAtomically(options.home, {\n      version: 2,\n      computerId: credential.installationId,\n      serverUrl: credential.serverUrl,\n    });\n  } catch (error) {\n    throw new CommandError(\n      { code: \"COMPUTER_LOCAL_PERSISTENCE_FAILED\", category: \"dependency\", retryability: \"never\", phase: \"startup\" },\n      \"Local repair could not persist the Computer files. Fix storage permissions/free space, then retry repair-local. Do not reuse the consumed connect code.\",\n      { cause: error },\n    );\n  }\n  return {\n    computerId: credential.computerId,\n    installationId: credential.installationId,\n    credentialsPath: machineCredentialsPath(options.home),\n    localPersistenceReady: true,\n  };\n}\n\nfunction unavailableCredential(cause?: unknown): CommandError {\n  return new CommandError(\n    { code: \"COMPUTER_CREDENTIAL_UNAVAILABLE\", category: \"dependency\", retryability: \"never\", phase: \"validation\" },\n    \"The credential for this exchange is missing, unreadable, or belongs to another installation. Fix local storage and retry repair-local; if unavailable, request a NEW connect/repair code in OpenTag Web. Do not reuse the consumed code or assume previous credentials still work.\",\n    { cause },\n  );\n}\n","import { resolve } from \"node:path\";\nimport { resolveOpenTagHome } from \"@opentag/client\";\nimport { ComputerConnectCodeExchangeRequestSchema } from \"@opentag/shared\";\nimport type { Command } from \"commander\";\nimport { resolveChannelEnvironment } from \"../../core/channel/environment.js\";\nimport { commandExitCode, presentCommand, toCommandError } from \"../../core/command/policy.js\";\nimport { daemonServiceCommand, SERVER_CONFIRMATION_GUIDANCE } from \"../../core/computer/preparation.js\";\nimport { repairLocalComputerConnection } from \"../../core/computer/repair-local.js\";\n\nexport function registerComputerRepairLocalCommand(computer: Command): void {\n  computer\n    .command(\"repair-local\")\n    .description(\"Recover saved Computer credentials and identity without reusing a connect code\")\n    .requiredOption(\"--installation-id <id>\", \"installation ID reported by the failed connect\")\n    .option(\"--home <path>\", \"OpenTag home directory\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { installationId: string; home?: string; json?: boolean }) => {\n      try {\n        const installationId = ComputerConnectCodeExchangeRequestSchema.shape.installationId.parse(\n          options.installationId,\n        );\n        const home = resolve(options.home ?? resolveOpenTagHome(resolveChannelEnvironment(process.env)));\n        const connection = await repairLocalComputerConnection({ home, installationId });\n        const guidance = [\n          \"Local Computer files repaired. No daemon was started and no Runtime or Provider readiness was asserted.\",\n          `Resume: ${daemonServiceCommand(\"install\", home)}`,\n          `Verify: ${daemonServiceCommand(\"status\", home)}`,\n          SERVER_CONFIRMATION_GUIDANCE,\n        ];\n        process.exitCode = presentCommand(\n          { ok: true, value: { ...connection, guidance }, exitCode: 0 },\n          { json: options.json, formatValue: () => guidance.join(\"\\n\") },\n        );\n      } catch (error) {\n        const commandError = toCommandError(error, \"startup\");\n        process.exitCode = presentCommand(\n          { ok: false, error: commandError, exitCode: commandExitCode(commandError) },\n          { json: options.json },\n        );\n      }\n    });\n}\n","import { AgentRuntimeProviderSchema, type LocalPreparationComponent } from \"@opentag/shared\";\nimport type { Command } from \"commander\";\nimport { CommandError, commandExitCode, presentCommand, toCommandError } from \"../../core/command/policy.js\";\nimport { formatPreparationComponentLines } from \"../../core/computer/formatting.js\";\nimport { probeRuntimeComponent } from \"../../core/computer/runtime-probe.js\";\nimport { renderProviderCliHumanValue } from \"../../core/provider-cli/shared.js\";\n\n/** Idempotent inspection only: no connect code, daemon change, Runtime installation, or model turn. */\nexport function registerRuntimeInspectCommand(computer: Command): void {\n  computer\n    .command(\"runtime-inspect\")\n    .description(\"Check one preinstalled Runtime CLI, its required capabilities and credentials\")\n    .requiredOption(\"--provider <provider>\", \"codex, claude-code, or pi (no default)\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { provider: string; json?: boolean }) => {\n      try {\n        const provider = AgentRuntimeProviderSchema.parse(options.provider);\n        const component = await probeRuntimeComponent({ provider });\n        const error = runtimeInspectionError(component);\n        const ready = component.status === \"ready\" && !component.blocking;\n        process.exitCode = ready ? 0 : commandExitCode(error);\n        if (options.json) {\n          presentCommand(\n            ready\n              ? { ok: true, value: component, exitCode: 0 }\n              : { ok: false, value: component, error, exitCode: commandExitCode(error) },\n            { json: true },\n          );\n        } else {\n          const output = `${formatPreparationComponentLines(component)\n            .map((line) => renderProviderCliHumanValue(line, 16384))\n            .join(\"\\n\")}\\n`;\n          if (ready) process.stdout.write(output);\n          else process.stderr.write(output);\n        }\n      } catch (error) {\n        const commandError = toCommandError(error, \"validation\");\n        process.exitCode = presentCommand(\n          { ok: false, error: commandError, exitCode: commandExitCode(commandError) },\n          { json: options.json },\n        );\n      }\n    });\n}\n\nfunction runtimeInspectionError(component: LocalPreparationComponent): CommandError {\n  const transient =\n    component.diagnosticCode === \"temporarily_unavailable\" || component.diagnosticCode === \"runtime_probe_failed\";\n  return new CommandError(\n    {\n      code: \"RUNTIME_CHECK_INCOMPLETE\",\n      category: \"dependency\",\n      retryability: transient ? \"backoff\" : \"never\",\n      phase: \"provider\",\n    },\n    \"The selected Runtime needs attention. Follow its repair and verify actions.\",\n  );\n}\n","import type { Command } from \"commander\";\nimport { registerComputerConnectCommand } from \"./connect.js\";\nimport { registerComputerListCommand } from \"./list.js\";\nimport { registerComputerRepairLocalCommand } from \"./repair-local.js\";\nimport { registerRuntimeInspectCommand } from \"./runtime-inspect.js\";\n\nexport function registerComputerCommand(program: Command): void {\n  const computer = program\n    .command(\"computer\")\n    .description(\"Connect and inspect Computers available to the current Account\");\n  registerComputerConnectCommand(computer);\n  registerComputerListCommand(computer);\n  registerComputerRepairLocalCommand(computer);\n  registerRuntimeInspectCommand(computer);\n}\n","import { resolve } from \"node:path\";\nimport { readMachineCredentials, resolveBoundAccountComputer, resolveOpenTagHome } from \"@opentag/client\";\nimport { resolveChannelEnvironment } from \"../channel/environment.js\";\nimport { createDaemonServiceManager, type DaemonServiceInfo, type DaemonServiceManager } from \"./service/index.js\";\nimport { DaemonServiceError } from \"./service/types.js\";\n\nexport type DaemonServiceReconcileResult =\n  | {\n      action: \"installed-or-repaired\" | \"restarted\";\n      service: DaemonServiceInfo;\n      status: \"ready\";\n    }\n  | {\n      reason: \"credentials-missing\" | \"unsupported-platform\";\n      service: DaemonServiceInfo;\n      status: \"deferred\";\n    };\n\nexport async function reconcileDaemonService(\n  options: { createManager?: () => Promise<DaemonServiceManager>; hasCredentials?: () => Promise<boolean> } = {},\n): Promise<DaemonServiceReconcileResult> {\n  const manager = await (options.createManager ?? createDaemonServiceManager)();\n  const current = await manager.status();\n  if (current.platform === \"unsupported\") {\n    return { reason: \"unsupported-platform\", service: current, status: \"deferred\" };\n  }\n\n  const hasCredentials =\n    options.hasCredentials ??\n    (async () =>\n      resolveBoundAccountComputer(\n        await readMachineCredentials(resolve(resolveOpenTagHome(resolveChannelEnvironment(process.env)))),\n      ).status === \"bound\");\n  if (!(await hasCredentials())) {\n    return { reason: \"credentials-missing\", service: current, status: \"deferred\" };\n  }\n\n  const shouldRestart = current.state === \"active\" && current.drifted === false;\n  const service = shouldRestart ? await manager.restart() : await manager.installAndStart();\n  if (service.state !== \"active\") {\n    throw new DaemonServiceError(\n      \"OPERATION_FAILED\",\n      `Daemon service ${service.serviceId} was reconciled but is ${service.state}`,\n    );\n  }\n  return { action: shouldRestart ? \"restarted\" : \"installed-or-repaired\", service, status: \"ready\" };\n}\n","import type { Command } from \"commander\";\nimport * as commandPolicy from \"../../core/command/policy.js\";\nimport { type DaemonServiceReconcileResult, reconcileDaemonService } from \"../../core/daemon/reconcile-service.js\";\n\nexport const ENSURE_SERVICE_DEFERRED_EXIT_CODE = 3;\ntype EnsureErrorOption = { writeError?: (message: string) => void };\ntype EnsureOutputOption = { writeOutput?: (message: string) => void };\ntype EnsureJsonOption = { json?: boolean };\ntype EnsureServiceCallbacks = EnsureErrorOption & EnsureOutputOption & EnsureJsonOption;\ntype EnsureServiceOptions = { reconcileService?: () => Promise<DaemonServiceReconcileResult> } & EnsureServiceCallbacks;\ntype EnsureServiceResult = Promise<commandPolicy.CommandExitCode>;\n\nexport async function executeDaemonEnsureService(options: EnsureServiceOptions = {}): EnsureServiceResult {\n  const writeOutput = options.writeOutput ?? ((message: string) => process.stdout.write(`${message}\\n`));\n  const writeError = options.writeError ?? ((message: string) => process.stderr.write(message));\n  try {\n    const result = await (options.reconcileService ?? reconcileDaemonService)();\n    if (result.status === \"deferred\") {\n      writeOutput(renderEnsureResult(result, options.json === true));\n      return ENSURE_SERVICE_DEFERRED_EXIT_CODE;\n    }\n    writeOutput(renderEnsureResult(result, options.json === true));\n    return 0;\n  } catch (error) {\n    const commandError = commandPolicy.toCommandError(error, \"request\");\n    return commandPolicy.presentCommand(\n      { ok: false, error: commandError, exitCode: commandPolicy.commandExitCode(commandError) },\n      { json: options.json === true, stderr: writeError },\n    );\n  }\n}\n\nfunction renderEnsureResult(result: DaemonServiceReconcileResult, json: boolean): string {\n  const message =\n    result.status === \"deferred\"\n      ? result.reason === \"credentials-missing\"\n        ? \"No credentials found; daemon service setup is deferred until login.\"\n        : `Daemon service control is not supported on ${process.platform}; setup is deferred.`\n      : result.action === \"restarted\"\n        ? `Daemon service ${result.service.serviceId} was restarted and is active.`\n        : `Daemon service ${result.service.serviceId} was installed or repaired and is active.`;\n  return json ? JSON.stringify({ ok: true, result: { ...result, message } }) : message;\n}\n\nexport function registerDaemonEnsureServiceCommand(daemon: Command): void {\n  daemon\n    .command(\"ensure-service\", { hidden: true })\n    .description(\"Ensure the daemon service is installed and active when credentials already exist\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { json?: boolean }) => {\n      process.exitCode = await executeDaemonEnsureService({ json: options.json === true });\n    });\n}\n","import { basename, dirname, isAbsolute } from \"node:path\";\n\n/**\n * How this OpenTag CLI was installed. The portable shim exports `OPENTAG_INSTALL_MODE=portable`\n * with the install root and shim directory; anything else is an npm-global install. Detection is\n * fail-closed: a malformed portable environment disables automatic upgrades rather than upgrading\n * an install whose layout is unknown.\n */\nexport type InstallMode = { mode: \"portable\"; root: string; binDir: string } | { mode: \"npm-global\" };\n\nexport function detectInstallMode(environment: NodeJS.ProcessEnv = process.env): InstallMode {\n  if (environment.OPENTAG_INSTALL_MODE === \"portable\") {\n    const root = environment.OPENTAG_PORTABLE_ROOT;\n    const binDir = environment.OPENTAG_PORTABLE_BIN_DIR;\n    if (root && isAbsolute(root) && binDir && isAbsolute(binDir)) {\n      // The managed installer shim historically exports its stable `<prefix>/current` path. Keep\n      // that environment contract while normalizing the updater's layout root to `<prefix>`.\n      return { mode: \"portable\", root: basename(root) === \"current\" ? dirname(root) : root, binDir };\n    }\n  }\n  return { mode: \"npm-global\" };\n}\n","import {\n  readPrivateJson,\n  type UpdaterAttempt,\n  type UpdaterStateName,\n  type UpdaterStateSnapshot,\n  writePrivateJson,\n} from \"@opentag/client\";\nimport { isSemVer } from \"@opentag/shared\";\nimport { resolveDaemonPaths } from \"../daemon/paths.js\";\n\nconst UPDATER_STATE_FILE = \"updater.json\";\n\nexport type UpdaterStateLoad =\n  | { status: \"ok\"; state: UpdaterStateSnapshot }\n  | { status: \"missing\" }\n  | { status: \"invalid\" };\n\nexport class UpdaterStateInvalidError extends Error {\n  constructor() {\n    super(\"The daemon updater state is invalid; run the CLI upgrade command to repair it manually\");\n    this.name = \"UpdaterStateInvalidError\";\n  }\n}\n\nfunction updaterStateRelativePath(home: string): string {\n  const paths = resolveDaemonPaths(home);\n  return `${paths.daemonState.slice(paths.home.length + 1)}/${UPDATER_STATE_FILE}`;\n}\n\n/** Read the durable updater state. Missing is normal; malformed is never silently rewritten. */\nexport async function readUpdaterState(home: string): Promise<UpdaterStateLoad> {\n  let parsed: unknown;\n  try {\n    parsed = await readPrivateJson(home, updaterStateRelativePath(home), (value) => value);\n  } catch {\n    return { status: \"invalid\" };\n  }\n  if (parsed === undefined) return { status: \"missing\" };\n  try {\n    return { status: \"ok\", state: parseUpdaterState(parsed) };\n  } catch {\n    return { status: \"invalid\" };\n  }\n}\n\nexport async function writeUpdaterState(home: string, state: UpdaterStateSnapshot): Promise<void> {\n  await writePrivateJson(home, updaterStateRelativePath(home), state);\n}\n\n/**\n * State store for the daemon UpdateManager. An invalid state file fails closed: the manager refuses\n * to auto-install rather than guess at attempt history and risk a retry storm.\n */\nexport function createUpdaterStateStore(home: string): {\n  loadState(): Promise<UpdaterStateSnapshot | undefined>;\n  saveState(state: UpdaterStateSnapshot): Promise<void>;\n} {\n  return {\n    async loadState() {\n      const loaded = await readUpdaterState(home);\n      if (loaded.status === \"missing\") return undefined;\n      if (loaded.status === \"invalid\") throw new UpdaterStateInvalidError();\n      return loaded.state;\n    },\n    saveState: (state) => writeUpdaterState(home, state),\n  };\n}\n\nconst STATE_NAMES: readonly UpdaterStateName[] = [\n  \"idle\",\n  \"awaiting_protected_work\",\n  \"installing\",\n  \"blocked\",\n  \"installed\",\n];\n\nfunction stateRecord(value: unknown, label = \"state\"): Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(`malformed updater ${label}`);\n  return value as Record<string, unknown>;\n}\n\nfunction semVerString(value: unknown, label = \"state\"): string {\n  if (typeof value !== \"string\" || !isSemVer(value)) throw new Error(`malformed updater ${label}`);\n  return value;\n}\n\nfunction optionalString(value: unknown, label = \"attempt\"): string | undefined {\n  if (value === undefined) return undefined;\n  if (typeof value !== \"string\") throw new Error(`malformed updater ${label}`);\n  return value;\n}\n\nfunction parseStateName(value: unknown): UpdaterStateName {\n  if (typeof value !== \"string\" || !STATE_NAMES.includes(value as UpdaterStateName)) {\n    throw new Error(\"malformed updater state\");\n  }\n  return value as UpdaterStateName;\n}\n\nfunction parseAttempts(value: unknown): Record<string, UpdaterAttempt> {\n  const record = stateRecord(value, \"state\");\n  const attempts: Record<string, UpdaterAttempt> = {};\n  for (const [version, candidate] of Object.entries(record)) {\n    semVerString(version);\n    const attempt = parseUpdaterAttempt(candidate);\n    if (attempt.target !== version) throw new Error(\"malformed updater state\");\n    attempts[version] = attempt;\n  }\n  return attempts;\n}\n\nfunction parseUpdaterState(value: unknown): UpdaterStateSnapshot {\n  const record = stateRecord(value);\n  if (record.schemaVersion !== 1) throw new Error(\"malformed updater state\");\n  const currentVersion = semVerString(record.currentVersion);\n  const state = parseStateName(record.state);\n  const target = record.target === undefined ? undefined : semVerString(record.target);\n  const attempts = parseAttempts(record.attempts);\n  const lastAttempt = record.lastAttempt === undefined ? undefined : parseUpdaterAttempt(record.lastAttempt);\n  return {\n    schemaVersion: 1,\n    currentVersion,\n    state,\n    ...(target ? { target } : {}),\n    ...(lastAttempt ? { lastAttempt } : {}),\n    attempts,\n  };\n}\n\nfunction parseUpdaterAttempt(value: unknown): UpdaterAttempt {\n  const record = stateRecord(value, \"attempt\");\n  const target = semVerString(record.target, \"attempt\");\n  if (typeof record.startedAt !== \"string\" || record.startedAt.length === 0) {\n    throw new Error(\"malformed updater attempt\");\n  }\n  const finishedAt = optionalString(record.finishedAt);\n  if (record.result !== undefined && record.result !== \"installed\" && record.result !== \"failed\") {\n    throw new Error(\"malformed updater attempt\");\n  }\n  const failureReason = optionalString(record.failureReason);\n  return {\n    target,\n    startedAt: record.startedAt,\n    ...(finishedAt !== undefined ? { finishedAt } : {}),\n    ...(record.result !== undefined ? { result: record.result as \"installed\" | \"failed\" } : {}),\n    ...(failureReason !== undefined ? { failureReason } : {}),\n  };\n}\n","import { resolveOpenTagHome } from \"@opentag/client\";\nimport { CLI_VERSION } from \"../../build-info.js\";\nimport { resolveChannelEnvironment } from \"../../core/channel/environment.js\";\nimport * as commandPolicy from \"../../core/command/policy.js\";\nimport type { DaemonServiceManager } from \"../../core/daemon/service/index.js\";\nimport { createDaemonServiceManager, formatDaemonServiceInfo } from \"../../core/daemon/service/index.js\";\nimport { detectInstallMode, type InstallMode } from \"../../core/update/install-mode.js\";\nimport { readUpdaterState } from \"../../core/update/updater-state.js\";\n\nexport type DaemonServiceAction = \"installAndStart\" | \"restart\" | \"start\" | \"status\" | \"stop\" | \"uninstall\";\ntype DaemonErrorOption = { writeError?: (message: string) => void };\ntype DaemonOutputOption = { writeOutput?: (message: string) => void };\ntype DaemonJsonOption = { json?: boolean };\ntype DaemonServiceCallbacks = DaemonErrorOption & DaemonOutputOption & DaemonJsonOption;\ntype DaemonServiceCommandOptions = { manager?: DaemonServiceManager } & DaemonServiceCallbacks;\ntype DaemonServiceResult = Awaited<ReturnType<DaemonServiceManager[DaemonServiceAction]>>;\n\nexport interface DaemonUpdateStatus {\n  currentVersion: string;\n  installMode?: InstallMode[\"mode\"];\n  state: string;\n  target?: string;\n  lastAttempt?: { target: string; startedAt: string; finishedAt?: string; result?: string; failureReason?: string };\n  historyStatus?: \"invalid\";\n}\n\n/** Update-state lines for `daemon status`; running identity does not depend on durable history. */\nexport function formatUpdateStatus(state: DaemonUpdateStatus): string {\n  const lines = [`Update current: ${state.currentVersion}`];\n  if (state.installMode) lines.push(`Update install mode: ${state.installMode}`);\n  lines.push(\n    state.historyStatus === \"invalid\"\n      ? \"Update state: unknown (the updater state record is invalid; run the upgrade command)\"\n      : `Update state: ${state.state}`,\n  );\n  if (state.target) lines.push(`Update target: ${state.target}`);\n  const attempt = state.lastAttempt;\n  if (attempt) {\n    const outcome = attempt.result ?? \"interrupted\";\n    const when = attempt.finishedAt ?? attempt.startedAt;\n    lines.push(\n      `Update last attempt: ${attempt.target} ${outcome} at ${when}${attempt.failureReason ? ` (${attempt.failureReason})` : \"\"}`,\n    );\n  }\n  return lines.join(\"\\n\");\n}\n\nexport async function executeDaemonServiceCommand(\n  action: DaemonServiceAction,\n  options: DaemonServiceCommandOptions = {},\n): Promise<commandPolicy.CommandExitCode> {\n  try {\n    const manager = options.manager ?? (await createDaemonServiceManager());\n    const info = await manager[action]();\n    const update = action === \"status\" ? await resolveDaemonUpdateStatus() : undefined;\n    const output = renderDaemonServiceOutput(info, options.json === true, update);\n    (options.writeOutput ?? ((message) => process.stdout.write(`${message}\\n`)))(output);\n    return daemonServiceExitCode(action, info.state);\n  } catch (error) {\n    const commandError = commandPolicy.toCommandError(error, \"request\");\n    return commandPolicy.presentCommand(\n      { ok: false, error: commandError, exitCode: commandPolicy.commandExitCode(commandError) },\n      {\n        json: options.json === true,\n        ...(options.writeError ? { stderr: options.writeError } : {}),\n      },\n    );\n  }\n}\n\nasync function resolveDaemonUpdateStatus(): Promise<DaemonUpdateStatus> {\n  const environment = resolveChannelEnvironment(process.env);\n  const installMode = detectInstallMode(environment).mode;\n  const loaded = await readUpdaterState(resolveOpenTagHome(environment));\n  if (loaded.status === \"ok\") {\n    return {\n      ...loaded.state,\n      currentVersion: CLI_VERSION,\n      installMode,\n    };\n  }\n  return {\n    currentVersion: CLI_VERSION,\n    installMode,\n    state: installMode === \"npm-global\" ? \"manual\" : \"idle\",\n    ...(loaded.status === \"invalid\" ? { historyStatus: \"invalid\" as const } : {}),\n  };\n}\n\nfunction renderDaemonServiceOutput(info: DaemonServiceResult, json: boolean, update?: DaemonUpdateStatus): string {\n  if (json) return JSON.stringify({ ok: true, result: update ? { ...info, update } : info });\n  return update ? `${formatDaemonServiceInfo(info)}\\n${formatUpdateStatus(update)}` : formatDaemonServiceInfo(info);\n}\n\nfunction daemonServiceExitCode(action: DaemonServiceAction, state: DaemonServiceResult[\"state\"]): 0 | 1 {\n  if (action === \"stop\") return [\"inactive\", \"not-installed\"].includes(state) ? 0 : 1;\n  if (action === \"uninstall\") return state === \"not-installed\" ? 0 : 1;\n  return state === \"active\" ? 0 : 1;\n}\n","import type { Command } from \"commander\";\nimport { executeDaemonServiceCommand } from \"./shared.js\";\n\nexport function registerDaemonInstallCommand(daemon: Command): void {\n  daemon\n    .command(\"install\")\n    .description(\"Install or update and start the daemon service\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { json?: boolean }) => {\n      process.exitCode = options.json\n        ? await executeDaemonServiceCommand(\"installAndStart\", { json: true })\n        : await executeDaemonServiceCommand(\"installAndStart\");\n    });\n}\n","import type { Command } from \"commander\";\nimport { type CommandExitCode, commandExitCode, presentCommand, toCommandError } from \"../../core/command/policy.js\";\nimport {\n  createDaemonServiceManager,\n  type DaemonServiceManager,\n  formatDaemonServiceInfo,\n} from \"../../core/daemon/service/index.js\";\n\n/**\n * `daemon refresh-service` (hidden) — rewrite the platform supervisor definition using the current\n * binary's templates without restarting the daemon.\n *\n * This is the portable upgrade's service-refresh step: after the new version is live behind the\n * stable shim, the running daemon invokes this command through the shim, so the definition the\n * supervisor reloads comes from the newly installed binary. The reserved exit-code handoff owns the\n * actual restart; this command must never trigger one itself.\n */\nexport async function executeDaemonRefreshService(\n  options: {\n    manager?: Pick<DaemonServiceManager, \"refreshDefinition\">;\n    writeError?: (message: string) => void;\n    writeOutput?: (message: string) => void;\n  } = {},\n): Promise<CommandExitCode> {\n  const writeOutput = options.writeOutput ?? ((message: string) => process.stdout.write(`${message}\\n`));\n  const writeError = options.writeError ?? ((message: string) => process.stderr.write(message));\n  try {\n    const manager = options.manager ?? (await createDaemonServiceManager());\n    const info = await manager.refreshDefinition();\n    writeOutput(formatDaemonServiceInfo(info));\n    return 0;\n  } catch (error) {\n    const commandError = toCommandError(error, \"request\");\n    return presentCommand(\n      { ok: false, error: commandError, exitCode: commandExitCode(commandError) },\n      { stderr: writeError },\n    );\n  }\n}\n\nexport function registerDaemonRefreshServiceCommand(daemon: Command): void {\n  daemon\n    .command(\"refresh-service\", { hidden: true })\n    .description(\"Rewrite the daemon service definition from the current binary without restarting (internal)\")\n    .action(async () => {\n      process.exitCode = await executeDaemonRefreshService();\n    });\n}\n","import type { Command } from \"commander\";\nimport { executeDaemonServiceCommand } from \"./shared.js\";\n\nexport function registerDaemonRestartCommand(daemon: Command): void {\n  daemon\n    .command(\"restart\")\n    .description(\"Restart the installed daemon service\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { json?: boolean }) => {\n      process.exitCode = options.json\n        ? await executeDaemonServiceCommand(\"restart\", { json: true })\n        : await executeDaemonServiceCommand(\"restart\");\n    });\n}\n","import { randomUUID } from \"node:crypto\";\nimport * as client from \"@opentag/client\";\nimport type { Command } from \"commander\";\nimport { CHANNEL, CLI_VERSION } from \"../../build-info.js\";\nimport { resolveChannelEnvironment } from \"../channel/environment.js\";\nimport type { CommandError } from \"../command/policy.js\";\n\n/**\n * Categories that describe the program rather than the caller's input, credentials, or environment.\n * Everything else is an answer the CLI gave on purpose and is not a defect worth a tracker entry.\n */\nconst REPORTED_CATEGORIES: ReadonlySet<CommandError[\"category\"]> = new Set([\"internal\", \"dependency\", \"protocol\"]);\n\nexport function shouldReportCommandError(error: CommandError): boolean {\n  return REPORTED_CATEGORIES.has(error.category);\n}\n\nconst reportedFailures = new WeakSet<object>();\n\n/**\n * Relay one command failure at most once. The same thrown value can be handled by `executeCommand`\n * and still surface at the entry point, so the original error object is the identity that is tracked.\n */\nexport async function reportCommandFailure(\n  error: unknown,\n  commandError: CommandError,\n  options: CliErrorReportOptions = {},\n): Promise<{ ok: boolean }> {\n  if (!shouldReportCommandError(commandError)) return { ok: false };\n  const identity = typeof error === \"object\" && error !== null ? error : commandError;\n  if (reportedFailures.has(identity)) return { ok: false };\n  reportedFailures.add(identity);\n  return reportCliError(error, options);\n}\n\n/**\n * The subcommand path Commander would dispatch to, such as `agent create`, from the raw arguments.\n * Options are skipped and the walk stops at the first token that is not a registered subcommand,\n * so a user-supplied value never becomes part of the result.\n */\nexport function resolveCommandPath(program: Command, argv: readonly string[]): string | undefined {\n  const path: string[] = [];\n  let current = program;\n  for (const token of argv) {\n    if (token.startsWith(\"-\")) continue;\n    if (!Array.isArray(current.commands)) break;\n    const next = current.commands.find(\n      (candidate) => candidate.name() === token || candidate.aliases().includes(token),\n    );\n    if (!next) break;\n    path.push(next.name());\n    current = next;\n  }\n  return path.length > 0 ? path.join(\" \") : undefined;\n}\n\n/** Where a report goes and who it is from, as far as this OpenTag home knows either. */\nexport interface ErrorReportTarget {\n  /** `undefined` when this home has never signed in or connected; there is then nowhere to report. */\n  serverUrl?: string | undefined;\n  userId?: string | undefined;\n  /** The Account Computer this home is connected as; the identifier the Server and the Web App know. */\n  computerId?: string | undefined;\n  /** This installation's own locally generated identity, which several Computers over time can share. */\n  installationId?: string | undefined;\n}\n\n/**\n * Read one optional identity file, treating a missing or malformed file alike as \"nothing known\".\n *\n * Each file is read on its own rather than under one shared `catch`: the readers throw on a\n * malformed file, and a corrupt `computer.json` must not silence a report that valid Account\n * credentials alone could still address. What is unreadable simply goes unreported.\n */\nasync function readOptionalIdentity<T>(read: () => Promise<T | undefined>): Promise<T | undefined> {\n  try {\n    return await read();\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Read the identity this OpenTag home reports under, from whichever credential files exist.\n *\n * All three are read rather than stopping at the first server URL: an installation that has both an\n * Account and a Computer can say so, and the two answer different questions — who hit this, and\n * which machine it was. A home that has neither reports nothing at all, which is the point of\n * returning the whole thing rather than throwing.\n *\n * The two machine identifiers come from different records on purpose. `computer.json` holds the\n * installation's locally generated uuid, which the daemon logs as `installationId`; the Account's\n * Computer uuid — the one a reader can look up — exists only in the machine credential, which is\n * what a connected Computer received from the Server.\n *\n * The Account comes from its own file rather than from the credentials, because the credentials\n * file is read strictly by every CLI version and an older one must keep reading it after a\n * rollback.\n *\n * Every identifier is attached only from a record that names the server the report goes to. The\n * destination is chosen first — the Account's server when signed in, else the Computer's — and each\n * record contributes only if its server is that one. The mismatch is a supported state, not a\n * corrupt one: a `login --server A` followed by `computer connect --server B` leaves an Account for\n * A beside a Computer for B, and a report to A that named B's Computer would hand A's operator an\n * identifier they cannot resolve, and carry B's identifiers across a deployment boundary. The two\n * machine identifiers also stay a pair: a Computer uuid never travels with an installation uuid\n * from another server.\n */\nexport async function resolveErrorReportTarget(home: string): Promise<ErrorReportTarget> {\n  const [credentials, account, identity, machine] = await Promise.all([\n    readOptionalIdentity(() => client.readCredentials(home)),\n    readOptionalIdentity(() => client.readAccountIdentity(home)),\n    readOptionalIdentity(() => client.readComputerIdentity(home)),\n    readOptionalIdentity(() => client.readMachineCredentials(home)),\n  ]);\n  // Each candidate is normalized on its own, so a record with an unusable server yields to the\n  // next rather than ending the chain: a malformed computer.json costs only what it names.\n  const serverUrl =\n    normalizedServerUrl(credentials?.serverUrl) ??\n    normalizedServerUrl(identity?.serverUrl) ??\n    normalizedServerUrl(machine?.computer.serverUrl);\n  const machineOnServer = sameServer(machine?.computer.serverUrl, serverUrl) ? machine?.computer : undefined;\n  const identityOnServer = sameServer(identity?.serverUrl, serverUrl) ? identity : undefined;\n  /*\n   * The Account counts only when its file names the destination and was provably written beside\n   * the credentials read here. Rollback is supported, and an older CLI signing in as another\n   * Account rewrites only `credentials.json`; without the fingerprint check the previous Account\n   * would be attributed to the new tokens. Omission is the safe direction, never misattribution.\n   */\n  const accountIsBound =\n    account !== undefined &&\n    credentials !== undefined &&\n    sameServer(account.serverUrl, serverUrl) &&\n    client.accountIdentityMatchesCredentials(account, credentials);\n  return {\n    serverUrl,\n    userId: accountIsBound ? account.userId : undefined,\n    computerId: machineOnServer?.computerId,\n    installationId: identityOnServer?.computerId ?? machineOnServer?.installationId,\n  };\n}\n\n/**\n * A record's server in the form the destination is compared in, or nothing when the record names\n * no server or one that is not an OpenTag server URL at all. `credentials.json` and the Account\n * identity are normalized on read; `computer.json` and the machine credential are stored as they\n * were given, so a trailing slash or a capitalised host must not read as a different server.\n */\nfunction normalizedServerUrl(serverUrl: string | undefined): string | undefined {\n  if (!serverUrl) return undefined;\n  try {\n    return client.normalizeServerUrl(serverUrl);\n  } catch {\n    return undefined;\n  }\n}\n\n/** Whether a record names the server the report is going to. */\nfunction sameServer(recordServerUrl: string | undefined, destination: string | undefined): boolean {\n  return destination !== undefined && normalizedServerUrl(recordServerUrl) === destination;\n}\n\n/** The Agent a failure belongs to, when it happened inside a turn rather than inside a command. */\nexport interface CliErrorReportAgent {\n  agentId?: string | undefined;\n  sessionId?: string | undefined;\n  turnId?: string | undefined;\n  provider?: string | undefined;\n}\n\nexport interface CliErrorReportOptions {\n  command?: string | undefined;\n  environment?: NodeJS.ProcessEnv;\n  home?: string;\n  fetchImpl?: typeof fetch;\n  agent?: CliErrorReportAgent | undefined;\n}\n\n/**\n * Relay a CLI failure through the server this installation is connected to. Silent when no server is\n * known: a CLI that was never logged in or connected has nowhere to send a report, and nothing to\n * gain from complaining about it.\n */\nexport async function reportCliError(error: unknown, options: CliErrorReportOptions = {}): Promise<{ ok: boolean }> {\n  try {\n    const environment = resolveChannelEnvironment(options.environment ?? process.env);\n    const home = options.home ?? client.resolveOpenTagHome(environment);\n    const { serverUrl, ...identity } = await resolveErrorReportTarget(home);\n    if (!serverUrl) return { ok: false };\n    return await client.reportClientError({\n      serverUrl,\n      error,\n      version: CLI_VERSION,\n      channel: CHANNEL,\n      command: options.command,\n      platform: client.describePlatform(),\n      reportId: randomUUID(),\n      ...identity,\n      ...options.agent,\n      fetchImpl: options.fetchImpl,\n    });\n  } catch {\n    return { ok: false };\n  }\n}\n\n/** Report and exit on an uncaught exception or unhandled rejection anywhere in this CLI process. */\nexport function installCliProcessErrorReporting(options: CliErrorReportOptions = {}): () => void {\n  return client.installProcessErrorReporting({\n    logger: client.createLogger(\"cli\"),\n    report: (error) => reportCliError(error, options),\n  });\n}\n","import type { AgentTurnErrorReporter, AgentTurnFailure } from \"@opentag/client\";\nimport type { TurnFailureReason } from \"@opentag/shared\";\nimport type { CliErrorReportOptions } from \"./error-reporting.js\";\nimport { reportCliError } from \"./error-reporting.js\";\n\n/**\n * Turn failures that describe OpenTag rather than the machine, the provider, or the caller.\n *\n * The same judgement `shouldReportCommandError` makes for commands, applied to the other way a\n * failure reaches a reader. Everything left out is an answer the runtime gave on purpose: a provider\n * that is not installed or refused the prompt, a credential the Account has not supplied, a sandbox\n * this machine cannot open, a budget that ran out, a shutdown. Those are worth a log line and a\n * message to the person, not a tracker entry that no release can ever fix.\n *\n * Only what the runner can actually emit is listed. `provider_protocol_error` is a provider that\n * answered in a shape the runtime could not read, whether it threw or returned it.\n * `turn_state_unknown` is the important one: it is the catch-all for a throw nothing classified,\n * which is exactly the shape of a defect nobody has seen yet. `provider_teardown_failed` and\n * `session_resume_failed` exist in the shared taxonomy but nothing in the Client produces them\n * yet; they join this set when a producer does, not before.\n */\nconst REPORTED_TURN_FAILURES: ReadonlySet<TurnFailureReason> = new Set([\n  \"provider_protocol_error\",\n  \"turn_state_unknown\",\n]);\n\nexport function shouldReportTurnFailure(failure: Pick<AgentTurnFailure, \"errorReason\">): boolean {\n  return failure.errorReason !== undefined && REPORTED_TURN_FAILURES.has(failure.errorReason);\n}\n\n/** How long one Session's repeat of the same failure stays unreported after a relay. */\nexport const AGENT_ERROR_REPORT_COOLDOWN_MS = 30_000;\n/** Distinct failures remembered for the cooldown; beyond this the oldest is forgotten first. */\nconst MAX_TRACKED_FAILURES = 200;\n\nexport interface AgentErrorReporterOptions extends Pick<CliErrorReportOptions, \"environment\" | \"home\" | \"fetchImpl\"> {\n  /** Which provider ran the Session, when the runtime can still say; it often cannot after a failure. */\n  resolveProvider?: (sessionId: string) => string | undefined;\n  /** Injected so a test can await the relay the runner deliberately does not wait for. */\n  onReported?: (result: Promise<{ ok: boolean }>) => void;\n  /** Overrides the cooldown; `0` relays every reportable failure. */\n  cooldownMs?: number;\n  now?: () => number;\n}\n\n/**\n * Relay Agent turn failures from the daemon.\n *\n * Returns synchronously and swallows everything: the runner calls this on the path that is already\n * failing a turn, and a tracker that is slow, unreachable, or broken must not add to that.\n *\n * One failure per Session and reason per cooldown, the same shape the Web App sink applies: the\n * daemon is long-lived, and a Session whose every turn fails the same way would otherwise post one\n * report per turn for as long as it is written to, saying nothing the first one did not.\n */\nexport function createAgentErrorReporter(options: AgentErrorReporterOptions = {}): AgentTurnErrorReporter {\n  const { resolveProvider, onReported, cooldownMs, now, ...reportOptions } = options;\n  const cooldown = new FailureCooldown(Math.max(0, cooldownMs ?? AGENT_ERROR_REPORT_COOLDOWN_MS), now ?? Date.now);\n  return (failure) => {\n    if (!shouldReportTurnFailure(failure)) return;\n    if (!cooldown.admit(`${failure.errorReason}\\u0000${failure.sessionId}`)) return;\n    const relay = reportCliError(failure.error, {\n      ...reportOptions,\n      command: \"daemon service-run\",\n      agent: {\n        agentId: failure.agentId,\n        sessionId: failure.sessionId,\n        turnId: failure.turnId,\n        provider: resolveProvider?.(failure.sessionId),\n      },\n    }).catch(() => ({ ok: false }));\n    onReported?.(relay);\n  };\n}\n\n/**\n * Remembers when each failure key was last relayed. Bounded: expired entries go first, then the\n * oldest, because Map insertion order is age order and every key is re-inserted when it is relayed.\n */\nclass FailureCooldown {\n  readonly #lastSentAt = new Map<string, number>();\n\n  constructor(\n    readonly cooldownMs: number,\n    readonly now: () => number,\n  ) {}\n\n  /** Records the key as relayed now and says whether it is due, or refuses it inside its cooldown. */\n  admit(key: string): boolean {\n    const at = this.now();\n    const previous = this.#lastSentAt.get(key);\n    if (previous !== undefined && at >= previous && at - previous < this.cooldownMs) return false;\n    for (const [trackedKey, sentAt] of this.#lastSentAt) {\n      if (at - sentAt >= this.cooldownMs) this.#lastSentAt.delete(trackedKey);\n    }\n    this.#lastSentAt.delete(key);\n    this.#lastSentAt.set(key, at);\n    while (this.#lastSentAt.size > MAX_TRACKED_FAILURES) {\n      const oldest = this.#lastSentAt.keys().next();\n      if (oldest.done) break;\n      this.#lastSentAt.delete(oldest.value);\n    }\n    return true;\n  }\n}\n","import { execFile } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport { access, lstat, mkdir, readFile, rename, rm, symlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type { ChannelName } from \"@opentag/shared\";\n\n/**\n * Portable installer for daemon-driven automatic upgrades and the manual upgrade command. Mirrors\n * scripts/portable/install.sh semantics exactly: channel metadata and SHA-256 verification from the\n * immutable version manifest (never the mutable channel pointer), immutable version directories, a\n * stable shim that resolves through `current`, and a single atomic `current` symlink switch as the\n * commit point. A version directory is never rewritten in place.\n */\n\nexport const DEFAULT_DOWNLOAD_BASE_URL = \"https://dl.opentag.build/releases\";\nconst PORTABLE_APP_ENTRY = \"app/cli/index.mjs\";\nconst MANIFEST_SCHEMA_VERSION = 1;\n\nexport class PortableInstallError extends Error {\n  override readonly name = \"PortableInstallError\";\n}\n\nexport interface PortableManifestAsset {\n  platform: string;\n  fileName: string;\n  url: string;\n  sha256: string;\n  size: number;\n}\n\ninterface PortableManifest {\n  channel: ChannelName;\n  version: string;\n  packageName: string;\n  binName: string;\n  assets: PortableManifestAsset[];\n}\n\nexport interface PortableInstallOptions {\n  channel: ChannelName;\n  targetVersion: string;\n  /** Portable install root (`OPENTAG_PORTABLE_ROOT`). */\n  root: string;\n  /** Stable shim directory (`OPENTAG_PORTABLE_BIN_DIR`). */\n  binDir: string;\n  binName: string;\n  packageName: string;\n  downloadBaseUrl?: string;\n  /** Defaults to the detected `<os>-<arch>` portable platform. */\n  platform?: string;\n  fetchFn?: typeof fetch;\n  /** Extraction hook; defaults to `tar -xzf`, the same tool the shell installer requires. */\n  extractTarball?: (tarball: string, destination: string) => Promise<void>;\n  /** Pre-commit payload smoke check; defaults to running the payload's embedded runtime. */\n  runSmokeCheck?: (payloadDir: string, appEntry: string) => Promise<void>;\n}\n\nexport interface PortableInstallResult {\n  /** True when the target already was the live install and nothing was downloaded. */\n  alreadyCurrent: boolean;\n  versionDir: string;\n  /** Cleanup failed after the atomic activation commit; the target is live and must not be retried. */\n  cleanupFailure?: string;\n}\n\nconst execFileAsync = promisify(execFile);\n\nexport function detectPortablePlatform(platform = process.platform, arch = process.arch): string {\n  const os = platform === \"darwin\" ? \"darwin\" : platform === \"linux\" ? \"linux\" : undefined;\n  const architecture = arch === \"arm64\" ? \"arm64\" : arch === \"x64\" ? \"x64\" : undefined;\n  if (!os || !architecture) {\n    throw new PortableInstallError(`Portable upgrades are unsupported on ${platform}-${arch}`);\n  }\n  return `${os}-${architecture}`;\n}\n\nasync function defaultExtractTarball(tarball: string, destination: string): Promise<void> {\n  try {\n    await execFileAsync(\"tar\", [\"-xzf\", tarball, \"-C\", destination]);\n  } catch (error) {\n    throw new PortableInstallError(\n      `Portable payload extraction failed: ${error instanceof Error ? error.message : String(error)}`,\n    );\n  }\n}\n\nasync function defaultRunSmokeCheck(payloadDir: string, appEntry: string): Promise<void> {\n  try {\n    await execFileAsync(join(payloadDir, \"node\", \"bin\", \"node\"), [join(payloadDir, appEntry), \"--version\"]);\n  } catch (error) {\n    throw new PortableInstallError(\n      `Portable payload failed the pre-commit runtime smoke check: ${error instanceof Error ? error.message : String(error)}`,\n    );\n  }\n}\n\nexport function renderPortableShim(currentLink: string, binDir: string): string {\n  return `#!/bin/sh\nset -eu\nroot=${shellSingleQuote(currentLink)}\nbin_dir=${shellSingleQuote(binDir)}\nexport OPENTAG_INSTALL_MODE=portable\nexport OPENTAG_PORTABLE_ROOT=\"$root\"\nexport OPENTAG_PORTABLE_BIN_DIR=\"$bin_dir\"\nexec \"$root/node/bin/node\" \"$root/app/cli/index.mjs\" \"$@\"\n`;\n}\n\nfunction shellSingleQuote(value: string): string {\n  return `'${value.replace(/'/g, `'\"'\"'`)}'`;\n}\n\ninterface InstallLayout {\n  install: Record<string, unknown> | undefined;\n  nodeExecutable: boolean;\n  appEntryPresent: boolean;\n  shimTargetsCurrent: boolean;\n}\n\nasync function inspectCurrentInstall(\n  root: string,\n  binDir: string,\n  binName: string,\n): Promise<InstallLayout | undefined> {\n  const currentLink = join(root, \"current\");\n  let installRaw: string;\n  try {\n    if (!(await lstat(currentLink)).isSymbolicLink()) return undefined;\n    installRaw = await readFile(join(currentLink, \"INSTALL.json\"), \"utf8\");\n  } catch {\n    return undefined;\n  }\n  let install: Record<string, unknown> | undefined;\n  try {\n    const parsed: unknown = JSON.parse(installRaw);\n    if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) install = parsed as Record<string, unknown>;\n  } catch {\n    install = undefined;\n  }\n  const nodeExecutable = await isExecutable(join(currentLink, \"node\", \"bin\", \"node\"));\n  const appEntry = typeof install?.appEntry === \"string\" ? install.appEntry : PORTABLE_APP_ENTRY;\n  const appEntryPresent = await exists(join(currentLink, appEntry));\n  let shimTargetsCurrent = false;\n  try {\n    const shim = await readFile(join(binDir, binName), \"utf8\");\n    await access(join(binDir, binName), constants.X_OK);\n    shimTargetsCurrent = shim.split(\"\\n\").includes(`root=${shellSingleQuote(currentLink)}`);\n  } catch {\n    shimTargetsCurrent = false;\n  }\n  return { install, nodeExecutable, appEntryPresent, shimTargetsCurrent };\n}\n\n/** Mirror of install.sh's portable_install_is_current: strict enough that yes means nothing to do. */\nexport async function portableInstallIsCurrent(\n  root: string,\n  binDir: string,\n  binName: string,\n  targetVersion: string,\n  platform: string,\n): Promise<boolean> {\n  const current = await inspectCurrentInstall(root, binDir, binName);\n  if (!current?.install) return false;\n  const { install } = current;\n  return (\n    install.version === targetVersion &&\n    install.platform === platform &&\n    install.installMode === \"portable\" &&\n    install.binName === binName &&\n    current.nodeExecutable &&\n    current.appEntryPresent &&\n    current.shimTargetsCurrent\n  );\n}\n\ninterface PortableStagingLayout {\n  currentLink: string;\n  canonicalVersionDir: string;\n  tempVersionDir: string;\n  tarball: string;\n  newLink: string;\n  cleanup(): Promise<void>;\n}\n\nfunction selectPortableAsset(manifest: PortableManifest, platform: string): PortableManifestAsset {\n  const asset = manifest.assets.find((candidate) => candidate.platform === platform);\n  if (!asset) throw new PortableInstallError(`The portable release has no asset for ${platform}`);\n  if (!/^https?:\\/\\//u.test(asset.url)) throw new PortableInstallError(\"The portable asset URL is not HTTP(S)\");\n  return asset;\n}\n\nasync function prepareStagingLayout(options: PortableInstallOptions): Promise<PortableStagingLayout> {\n  const currentLink = join(options.root, \"current\");\n  const canonicalVersionDir = join(options.root, \"versions\", options.targetVersion);\n  const tempRoot = join(options.root, \".tmp\");\n  await mkdir(join(options.root, \"versions\"), { recursive: true });\n  await mkdir(tempRoot, { recursive: true });\n  await mkdir(options.binDir, { recursive: true });\n\n  const workId = `${options.targetVersion}.${process.pid}`;\n  const tempVersionDir = join(tempRoot, workId);\n  const tarball = join(tempRoot, `payload.${process.pid}.tar.gz`);\n  const newLink = join(options.root, `.current.${process.pid}`);\n  return {\n    currentLink,\n    canonicalVersionDir,\n    tempVersionDir,\n    tarball,\n    newLink,\n    cleanup: async () => {\n      const results = await Promise.allSettled([\n        rm(tempVersionDir, { recursive: true, force: true }),\n        rm(tarball, { force: true }),\n        rm(newLink, { force: true }),\n      ]);\n      const failures = results.flatMap((result) => (result.status === \"rejected\" ? [result.reason] : []));\n      if (failures.length > 0) throw new AggregateError(failures, \"Portable staging cleanup failed\");\n    },\n  };\n}\n\nasync function runWithStagingCleanup(\n  layout: PortableStagingLayout,\n  operation: () => Promise<void>,\n): Promise<string | undefined> {\n  let operationFailed = false;\n  let operationError: unknown;\n  try {\n    await operation();\n  } catch (error) {\n    operationFailed = true;\n    operationError = error;\n  }\n  try {\n    await layout.cleanup();\n  } catch (cleanupError) {\n    if (operationFailed) {\n      throw new AggregateError(\n        [operationError, cleanupError],\n        \"Portable installation failed and staging cleanup also failed\",\n        { cause: operationError },\n      );\n    }\n    return cleanupError instanceof Error ? cleanupError.message : String(cleanupError);\n  }\n  if (operationFailed) throw operationError;\n  return undefined;\n}\n\nasync function downloadVerifiedPayload(fetchFn: typeof fetch, asset: PortableManifestAsset): Promise<Buffer> {\n  const payload = await download(fetchFn, asset.url);\n  if (payload.byteLength !== asset.size) {\n    throw new PortableInstallError(\n      `Portable payload size mismatch: expected ${asset.size}, received ${payload.byteLength}`,\n    );\n  }\n  const digest = createHash(\"sha256\").update(payload).digest(\"hex\");\n  if (digest !== asset.sha256) {\n    throw new PortableInstallError(`Portable payload checksum mismatch: expected ${asset.sha256}, received ${digest}`);\n  }\n  return payload;\n}\n\nasync function stagePortableVersion(options: {\n  layout: PortableStagingLayout;\n  manifest: PortableManifest;\n  asset: PortableManifestAsset;\n  platform: string;\n  fetchFn: typeof fetch;\n  extract(tarball: string, destination: string): Promise<void>;\n  smoke(payloadDir: string, appEntry: string): Promise<void>;\n}): Promise<void> {\n  const { layout } = options;\n  const payload = await downloadVerifiedPayload(options.fetchFn, options.asset);\n  await writeFile(layout.tarball, payload);\n  await rm(layout.tempVersionDir, { recursive: true, force: true });\n  await mkdir(layout.tempVersionDir, { recursive: true });\n  await options.extract(layout.tarball, layout.tempVersionDir);\n\n  // Never write a version directory in place: `current` may resolve through it. When the target's\n  // canonical directory already exists it is reused as-is, exactly like the shell installer.\n  const existsCanonical = await exists(layout.canonicalVersionDir);\n  const validationDir = existsCanonical ? layout.canonicalVersionDir : layout.tempVersionDir;\n  await validateInstallMetadata(validationDir, options.manifest, options.platform);\n  await options.smoke(validationDir, PORTABLE_APP_ENTRY);\n  if (existsCanonical) return;\n\n  try {\n    await rename(layout.tempVersionDir, layout.canonicalVersionDir);\n  } catch (error) {\n    throw new PortableInstallError(\n      `Could not move the portable payload into place: ${error instanceof Error ? error.message : String(error)}`,\n    );\n  }\n}\n\nasync function activatePortableVersion(options: PortableInstallOptions, layout: PortableStagingLayout): Promise<void> {\n  // Prepare the stable shim while `current` still names the old version; the symlink switch below\n  // is the single commit point, so a shim failure never reports success after activation.\n  const shimPath = join(options.binDir, options.binName);\n  const shimTemp = `${shimPath}.${process.pid}`;\n  await writeFile(shimTemp, renderPortableShim(layout.currentLink, options.binDir), { mode: 0o755 });\n  await rename(shimTemp, shimPath);\n\n  await rm(layout.newLink, { force: true });\n  await symlink(layout.canonicalVersionDir, layout.newLink);\n  try {\n    // rename(2) replaces the existing `current` symlink atomically; this is the commit point.\n    await rename(layout.newLink, layout.currentLink);\n  } catch (error) {\n    throw new PortableInstallError(\n      `Could not atomically switch the current portable version: ${error instanceof Error ? error.message : String(error)}`,\n    );\n  }\n}\n\nexport async function installPortableTarget(options: PortableInstallOptions): Promise<PortableInstallResult> {\n  const base = (options.downloadBaseUrl ?? DEFAULT_DOWNLOAD_BASE_URL).replace(/\\/+$/, \"\");\n  const platform = options.platform ?? detectPortablePlatform();\n  const fetchFn = options.fetchFn ?? fetch;\n  const extract = options.extractTarball ?? defaultExtractTarball;\n  const smoke = options.runSmokeCheck ?? defaultRunSmokeCheck;\n  const canonicalVersionDir = join(options.root, \"versions\", options.targetVersion);\n\n  if (await portableInstallIsCurrent(options.root, options.binDir, options.binName, options.targetVersion, platform)) {\n    return { alreadyCurrent: true, versionDir: canonicalVersionDir };\n  }\n\n  const manifest = await fetchManifest(fetchFn, `${base}/${options.channel}/${options.targetVersion}/manifest.json`);\n  assertManifest(manifest, options, platform);\n  const asset = selectPortableAsset(manifest, platform);\n  const layout = await prepareStagingLayout(options);\n\n  const cleanupFailure = await runWithStagingCleanup(layout, async () => {\n    await stagePortableVersion({ layout, manifest, asset, platform, fetchFn, extract, smoke });\n    await activatePortableVersion(options, layout);\n  });\n  return {\n    alreadyCurrent: false,\n    versionDir: canonicalVersionDir,\n    ...(cleanupFailure ? { cleanupFailure } : {}),\n  };\n}\n\nasync function fetchManifest(fetchFn: typeof fetch, url: string): Promise<PortableManifest> {\n  let response: Response;\n  try {\n    response = await fetchFn(url, { headers: { accept: \"application/json\" }, signal: AbortSignal.timeout(30_000) });\n  } catch (error) {\n    throw new PortableInstallError(\n      `Portable release metadata could not be downloaded: ${error instanceof Error ? error.message : String(error)}`,\n    );\n  }\n  if (!response.ok) {\n    throw new PortableInstallError(`Portable release metadata could not be downloaded (HTTP ${response.status})`);\n  }\n  let body: unknown;\n  try {\n    body = await response.json();\n  } catch {\n    throw new PortableInstallError(\"Portable release metadata is not valid JSON\");\n  }\n  return parseManifest(body);\n}\n\nasync function download(fetchFn: typeof fetch, url: string): Promise<Buffer> {\n  let response: Response;\n  try {\n    response = await fetchFn(url, { signal: AbortSignal.timeout(300_000) });\n  } catch (error) {\n    throw new PortableInstallError(\n      `Portable payload could not be downloaded: ${error instanceof Error ? error.message : String(error)}`,\n    );\n  }\n  if (!response.ok) {\n    throw new PortableInstallError(`Portable payload could not be downloaded (HTTP ${response.status})`);\n  }\n  return Buffer.from(await response.arrayBuffer());\n}\n\nfunction parseManifest(body: unknown): PortableManifest {\n  if (!body || typeof body !== \"object\" || Array.isArray(body)) {\n    throw new PortableInstallError(\"Portable release metadata is malformed\");\n  }\n  const record = body as Record<string, unknown>;\n  const assetsValue = record.assets;\n  if (!Array.isArray(assetsValue)) throw new PortableInstallError(\"Portable release metadata has no assets\");\n  const assets: PortableManifestAsset[] = assetsValue.map((entry) => {\n    if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n      throw new PortableInstallError(\"Portable release metadata has a malformed asset\");\n    }\n    const asset = entry as Record<string, unknown>;\n    if (\n      typeof asset.platform !== \"string\" ||\n      typeof asset.fileName !== \"string\" ||\n      typeof asset.url !== \"string\" ||\n      typeof asset.sha256 !== \"string\" ||\n      !/^[0-9a-f]{64}$/u.test(asset.sha256) ||\n      typeof asset.size !== \"number\" ||\n      !Number.isSafeInteger(asset.size) ||\n      asset.size < 1\n    ) {\n      throw new PortableInstallError(\"Portable release metadata has a malformed asset\");\n    }\n    return {\n      platform: asset.platform,\n      fileName: asset.fileName,\n      url: asset.url,\n      sha256: asset.sha256,\n      size: asset.size,\n    };\n  });\n  if (\n    record.schemaVersion !== MANIFEST_SCHEMA_VERSION ||\n    typeof record.channel !== \"string\" ||\n    typeof record.version !== \"string\" ||\n    typeof record.packageName !== \"string\" ||\n    typeof record.binName !== \"string\"\n  ) {\n    throw new PortableInstallError(\"Portable release metadata is malformed\");\n  }\n  return {\n    channel: record.channel as ChannelName,\n    version: record.version,\n    packageName: record.packageName,\n    binName: record.binName,\n    assets,\n  };\n}\n\nfunction assertManifest(manifest: PortableManifest, options: PortableInstallOptions, platform: string): void {\n  if (manifest.version !== options.targetVersion) {\n    throw new PortableInstallError(\"Portable release metadata version does not match the upgrade target\");\n  }\n  if (manifest.channel !== options.channel) {\n    throw new PortableInstallError(\"Portable release metadata belongs to another channel\");\n  }\n  if (manifest.packageName !== options.packageName || manifest.binName !== options.binName) {\n    throw new PortableInstallError(\"Portable release metadata identity does not match this channel\");\n  }\n  if (!platform) throw new PortableInstallError(\"The portable platform could not be determined\");\n}\n\nasync function validateInstallMetadata(\n  payloadDir: string,\n  manifest: PortableManifest,\n  platform: string,\n): Promise<void> {\n  let raw: string;\n  try {\n    raw = await readFile(join(payloadDir, \"INSTALL.json\"), \"utf8\");\n  } catch {\n    throw new PortableInstallError(\"The portable payload is missing INSTALL.json\");\n  }\n  let install: Record<string, unknown>;\n  try {\n    const parsed: unknown = JSON.parse(raw);\n    if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new Error(\"malformed\");\n    install = parsed as Record<string, unknown>;\n  } catch {\n    throw new PortableInstallError(\"The portable payload INSTALL.json is malformed\");\n  }\n  if (install.version !== manifest.version) {\n    throw new PortableInstallError(\"INSTALL.json version does not match the downloaded metadata\");\n  }\n  if (install.packageName !== manifest.packageName || install.binName !== manifest.binName) {\n    throw new PortableInstallError(\"INSTALL.json identity does not match the downloaded metadata\");\n  }\n  if (install.platform !== platform) {\n    throw new PortableInstallError(\"INSTALL.json platform does not match the current platform\");\n  }\n  if (install.installMode !== \"portable\") {\n    throw new PortableInstallError(\"INSTALL.json does not describe a portable install\");\n  }\n  if (install.appEntry !== PORTABLE_APP_ENTRY) {\n    throw new PortableInstallError(\"INSTALL.json appEntry is unsupported\");\n  }\n}\n\nasync function exists(path: string): Promise<boolean> {\n  try {\n    await access(path);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nasync function isExecutable(path: string): Promise<boolean> {\n  try {\n    await access(path, constants.X_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport {\n  type ClientLogger,\n  createLogger,\n  type ProtectedWorkCount,\n  UpdateManager,\n  type UpdateManagerOptions,\n  type UpdaterStateSnapshot,\n} from \"@opentag/client\";\nimport { CHANNEL, CLI_VERSION } from \"../../build-info.js\";\nimport { channelConfig } from \"../channel/config.js\";\nimport type { InstallMode } from \"./install-mode.js\";\nimport { DEFAULT_DOWNLOAD_BASE_URL, installPortableTarget, PortableInstallError } from \"./portable-installer.js\";\nimport { createUpdaterStateStore } from \"./updater-state.js\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface PortableAutoUpdateOptions {\n  home: string;\n  installMode: Extract<InstallMode, { mode: \"portable\" }>;\n  protectedWork(): ProtectedWorkCount;\n  quiesce(): () => void;\n  /** Called after a successful install so the daemon can stop and exit with the reserved code. */\n  onHandoff(): void | Promise<void>;\n  logger?: ClientLogger;\n  environment?: NodeJS.ProcessEnv;\n  /** Injectable install step (tests). Defaults to the real portable installer. */\n  installTarget?: (target: string) => Promise<void>;\n  /** Injectable service refresh (tests). Defaults to running the newly installed binary. */\n  refreshService?: () => Promise<void>;\n  stateStore?: {\n    loadState(): Promise<UpdaterStateSnapshot | undefined>;\n    saveState(state: UpdaterStateSnapshot): Promise<void>;\n  };\n  checkIntervalMs?: UpdateManagerOptions[\"checkIntervalMs\"];\n}\n\n/**\n * Runs `daemon refresh-service` through the stable shim — which now resolves to the newly installed\n * binary — so the supervisor definition is rewritten by the version that will run next, without\n * restarting the service (the reserved exit code handoff owns the restart).\n */\nasync function refreshServiceThroughShim(binDir: string, binName: string): Promise<void> {\n  try {\n    await execFileAsync(`${binDir}/${binName}`, [\"daemon\", \"refresh-service\"]);\n  } catch (error) {\n    const detail =\n      error && typeof error === \"object\" && \"code\" in error && typeof error.code === \"number\"\n        ? `exit code ${error.code}`\n        : error instanceof Error\n          ? error.message\n          : String(error);\n    throw new PortableInstallError(`The daemon service refresh through the new version failed (${detail})`);\n  }\n}\n\n/**\n * Attach the automatic-upgrade manager for a portable install. npm-global installs never attach one:\n * they upgrade only through the manual `upgrade` command.\n */\nexport function createPortableAutoUpdater(options: PortableAutoUpdateOptions): UpdateManager {\n  const environment = options.environment ?? process.env;\n  const logger = options.logger ?? createLogger(\"updater\");\n  const installTarget =\n    options.installTarget ??\n    (async (target: string) => {\n      const result = await installPortableTarget({\n        channel: CHANNEL,\n        targetVersion: target,\n        root: options.installMode.root,\n        binDir: options.installMode.binDir,\n        binName: channelConfig.binName,\n        packageName: channelConfig.packageName,\n        ...(environment.OPENTAG_PORTABLE_DOWNLOAD_BASE_URL\n          ? { downloadBaseUrl: environment.OPENTAG_PORTABLE_DOWNLOAD_BASE_URL }\n          : {}),\n      });\n      if (result.cleanupFailure) {\n        logger.warn(\n          { target, cleanupFailure: result.cleanupFailure },\n          \"Portable update activated but staging cleanup failed\",\n        );\n      }\n    });\n  const refreshService =\n    options.refreshService ?? (() => refreshServiceThroughShim(options.installMode.binDir, channelConfig.binName));\n  const stateStore = options.stateStore ?? createUpdaterStateStore(options.home);\n  return new UpdateManager({\n    channel: CHANNEL,\n    currentVersion: CLI_VERSION,\n    logger,\n    protectedWork: options.protectedWork,\n    quiesce: options.quiesce,\n    executeUpdate: async (target) => {\n      await installTarget(target);\n      await refreshService();\n    },\n    onHandoff: options.onHandoff,\n    loadState: stateStore.loadState,\n    saveState: stateStore.saveState,\n    ...(options.checkIntervalMs ? { checkIntervalMs: options.checkIntervalMs } : {}),\n  });\n}\n\nexport { DEFAULT_DOWNLOAD_BASE_URL };\n","/** Local proxy mode is explicit; an invalid value never silently falls back to raw credential grants. */\nexport function resolveRuntimeCredentialMode(environment: NodeJS.ProcessEnv): \"legacy\" | \"proxy\" {\n  const mode = environment.OPENTAG_RUNTIME_CREDENTIAL_MODE;\n  if (mode === undefined || mode === \"legacy\") return \"legacy\";\n  if (mode === \"proxy\") return \"proxy\";\n  throw new Error(\"OPENTAG_RUNTIME_CREDENTIAL_MODE must be legacy or proxy\");\n}\n","import { lstat, readFile } from \"node:fs/promises\";\nimport { validatePrivateDirectory } from \"@opentag/client\";\nimport { buildChildEnvironment } from \"../command/environment.js\";\nimport { resolveDaemonPaths } from \"./paths.js\";\nimport { DaemonServiceError } from \"./service/types.js\";\n\nexport interface DaemonEnvironmentResult {\n  appliedKeys: string[];\n  diagnostics: string[];\n  env: NodeJS.ProcessEnv;\n  malformedLineNumbers: number[];\n}\n\nexport async function loadDaemonEnvironment(\n  home: string,\n  baseEnvironment: NodeJS.ProcessEnv = process.env,\n): Promise<DaemonEnvironmentResult> {\n  const paths = resolveDaemonPaths(home);\n  if (!(await validatePrivateDirectory(paths.home, paths.config))) {\n    return { appliedKeys: [], diagnostics: [], env: { ...baseEnvironment }, malformedLineNumbers: [] };\n  }\n  const path = paths.daemonEnvironment;\n  let content: string;\n  try {\n    const status = await lstat(path);\n    if (!status.isFile() || status.isSymbolicLink()) {\n      throw new DaemonServiceError(\"CONFIGURATION\", \"daemon.env must be a real regular file\");\n    }\n    if ((status.mode & 0o077) !== 0) {\n      throw new DaemonServiceError(\"CONFIGURATION\", \"daemon.env permissions must not allow group or other access\");\n    }\n    content = await readFile(path, \"utf8\");\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n      return { appliedKeys: [], diagnostics: [], env: { ...baseEnvironment }, malformedLineNumbers: [] };\n    }\n    throw error;\n  }\n\n  const env = { ...baseEnvironment };\n  const appliedKeys: string[] = [];\n  const diagnostics: string[] = [];\n  const malformedLineNumbers: number[] = [];\n  const lines = content.split(/\\r?\\n/u);\n  for (const [index, line] of lines.entries()) {\n    const trimmed = line.trim();\n    if (!trimmed || trimmed.startsWith(\"#\")) continue;\n    const match = trimmed.match(/^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/u);\n    if (!match) {\n      diagnostics.push(`Ignored malformed daemon.env line ${index + 1}`);\n      malformedLineNumbers.push(index + 1);\n      continue;\n    }\n    const key = match[1];\n    if (!key) {\n      diagnostics.push(`Ignored malformed daemon.env line ${index + 1}`);\n      malformedLineNumbers.push(index + 1);\n      continue;\n    }\n    const parsed = parseEnvironmentValue(match[2] ?? \"\");\n    if (parsed === undefined) {\n      diagnostics.push(`Ignored malformed daemon.env line ${index + 1}`);\n      malformedLineNumbers.push(index + 1);\n      continue;\n    }\n    if (env[key]) continue;\n    env[key] = parsed;\n    appliedKeys.push(key);\n  }\n  return { appliedKeys, diagnostics, env, malformedLineNumbers };\n}\n\nexport async function applyDaemonEnvironment(\n  home: string,\n  environment: NodeJS.ProcessEnv = process.env,\n): Promise<DaemonEnvironmentResult> {\n  return loadDaemonEnvironment(home, environment);\n}\n\n/** Build the daemon child environment as a detached object. */\nexport function buildDaemonChildEnvironment(result: DaemonEnvironmentResult): NodeJS.ProcessEnv {\n  return buildChildEnvironment(result.env);\n}\n\nfunction parseEnvironmentValue(rawValue: string): string | undefined {\n  const value = rawValue.trim();\n  if (value.startsWith(\"'\")) {\n    if (value.length < 2 || !value.endsWith(\"'\")) return undefined;\n    return value.slice(1, -1);\n  }\n  if (value.startsWith('\"')) {\n    if (value.length < 2 || !value.endsWith('\"')) return undefined;\n    return value.slice(1, -1).replace(/\\\\([\\\\\"nrt])/gu, (_, escaped: string) => {\n      if (escaped === \"n\") return \"\\n\";\n      if (escaped === \"r\") return \"\\r\";\n      if (escaped === \"t\") return \"\\t\";\n      return escaped;\n    });\n  }\n  if (value.includes(\"'\") || value.includes('\"')) return undefined;\n  return value;\n}\n","/**\n * Web tools daemon opt-in. Off by default; effective only together with\n * OPENTAG_RUNTIME_CREDENTIAL_MODE=proxy, a negotiated webTools capability, and a Server-granted\n * web execution scope — the flag alone never enables anything.\n */\nexport function resolveWebToolsOptIn(environment: NodeJS.ProcessEnv): { enabled: boolean } {\n  const value = environment.OPENTAG_WEB_TOOLS_ENABLED;\n  if (value === undefined || value === \"false\") return { enabled: false };\n  if (value === \"true\") return { enabled: true };\n  throw new Error(\"OPENTAG_WEB_TOOLS_ENABLED must be true or false\");\n}\n","import { randomUUID } from \"node:crypto\";\nimport { arch, hostname, platform } from \"node:os\";\nimport {\n  type ClientLogger,\n  type ComposedClientRuntime,\n  configureClientLoggerForService,\n  createClientRuntime,\n  createLogger,\n  RuntimeConnection,\n  RuntimeConnectionError,\n  readMachineCredentials,\n  resolveBoundAccountComputer,\n  resolveComputerIdentity,\n  resolveOpenTagHome,\n  type UpdateManager,\n  type UpdaterStateSnapshot,\n} from \"@opentag/client\";\nimport type { RuntimeChannelTarget } from \"@opentag/shared\";\nimport { CHANNEL, CLI_VERSION } from \"../../build-info.js\";\nimport { channelConfig } from \"../channel/config.js\";\nimport { resolveChannelEnvironment } from \"../channel/environment.js\";\nimport { resolveCommandContext } from \"../command/context.js\";\nimport { createAgentErrorReporter } from \"../diagnostics/agent-error-reporting.js\";\nimport { createPortableAutoUpdater } from \"../update/auto-update.js\";\nimport { detectInstallMode, type InstallMode } from \"../update/install-mode.js\";\nimport { resolveRuntimeCredentialMode } from \"./credential-mode.js\";\nimport { applyDaemonEnvironment, buildDaemonChildEnvironment } from \"./environment.js\";\nimport { SUPERVISOR_RESTART_EXIT_CODE } from \"./handoff.js\";\nimport { acquireDaemonOwner, DaemonOwnerStartupError } from \"./ownership.js\";\nimport { resolveDaemonPaths } from \"./paths.js\";\nimport { DaemonServiceError } from \"./service/types.js\";\nimport { resolveWebToolsOptIn } from \"./web-tools.js\";\n\nexport interface DaemonAutoUpdateOverrides {\n  /** Force attaching or skipping the updater; defaults to portable installs on non-dev channels. */\n  attach?: boolean;\n  installMode?: InstallMode;\n  installTarget?: (target: string) => Promise<void>;\n  refreshService?: () => Promise<void>;\n  stateStore?: {\n    loadState(): Promise<UpdaterStateSnapshot | undefined>;\n    saveState(state: UpdaterStateSnapshot): Promise<void>;\n  };\n  checkIntervalMs?: number;\n  /** Observe a target immediately after startup (deterministic tests). */\n  initialTarget?: RuntimeChannelTarget;\n}\n\nexport interface DaemonServiceRunResult {\n  /** True when the daemon stopped to let the supervisor restart it onto a newly installed version. */\n  supervisorRestartRequested: boolean;\n}\n\nexport interface DaemonRuntimeOptions {\n  home?: string;\n  logger?: ClientLogger;\n  signals?: NodeJS.Process;\n  /** Automatic-upgrade control: `false` disables it; overrides exist for deterministic tests. */\n  autoUpdate?: false | DaemonAutoUpdateOverrides;\n  /** Relays an unexpected terminal failure before the entry point turns it into exit code 1. */\n  reportFailure?: (error: unknown) => Promise<unknown>;\n}\n\ninterface DaemonRuntime {\n  run(): Promise<void>;\n  stop(): void;\n}\n\ninterface DaemonSignals {\n  off(event: \"SIGINT\" | \"SIGTERM\", listener: () => void): unknown;\n  once(event: \"SIGINT\" | \"SIGTERM\", listener: () => void): unknown;\n}\n\ninterface ClientLoggerGate {\n  disable(): void;\n  logger: ClientLogger;\n}\n\ninterface DaemonMutableState {\n  channelTargetObserver?: (target: RuntimeChannelTarget) => void;\n  handoffRequested: boolean;\n  terminalLogger?: ClientLogger;\n  updater?: UpdateManager;\n}\n\ninterface DaemonLifecycleContext {\n  currentPlatform: NodeJS.Platform;\n  daemonEnvironment: NodeJS.ProcessEnv;\n  gatedRuntimeLogger: ClientLoggerGate;\n  home: string;\n  logger: ClientLogger;\n  options: DaemonRuntimeOptions;\n  state: DaemonMutableState;\n}\n\nexport async function runDaemonLifecycle(\n  createRuntime: (signal: AbortSignal) => Promise<DaemonRuntime>,\n  signals: DaemonSignals,\n): Promise<void> {\n  const startupAbort = new AbortController();\n  let runtime: DaemonRuntime | undefined;\n  let stopRequested = false;\n  const stop = () => {\n    stopRequested = true;\n    startupAbort.abort();\n    runtime?.stop();\n  };\n  signals.once(\"SIGINT\", stop);\n  signals.once(\"SIGTERM\", stop);\n  try {\n    runtime = await createRuntime(startupAbort.signal);\n    if (stopRequested) {\n      runtime.stop();\n      return;\n    }\n    await runtime.run();\n  } catch (error) {\n    if (!stopRequested) throw error;\n  } finally {\n    signals.off(\"SIGINT\", stop);\n    signals.off(\"SIGTERM\", stop);\n  }\n}\n\nexport class DaemonRuntimeConfigurationError extends Error {\n  override readonly name = \"DaemonRuntimeConfigurationError\";\n}\n\nexport async function runDaemonService(options: DaemonRuntimeOptions = {}): Promise<DaemonServiceRunResult> {\n  const environment = resolveChannelEnvironment(process.env);\n  const home = options.home ?? resolveOpenTagHome(environment);\n  const paths = resolveDaemonPaths(home);\n  const signals = options.signals ?? process;\n  const instanceId = randomUUID();\n  const currentPlatform = platform();\n  const baseBindings = {\n    clientVersion: CLI_VERSION,\n    instanceId,\n    platform: currentPlatform,\n  };\n\n  let lifecycleLogger: ClientLogger | undefined;\n  let runtimeLoggerGate: ClientLoggerGate | undefined;\n  const state: DaemonMutableState = { handoffRequested: false };\n  let ownership: Awaited<ReturnType<typeof acquireOwnership>> | undefined;\n  let failure: unknown;\n  let failed = false;\n  try {\n    const environmentResult = await applyDaemonEnvironment(home, environment);\n    const daemonEnvironment = buildDaemonChildEnvironment(environmentResult);\n    if (daemonEnvironment.OPENTAG_SERVICE_MODE === \"1\") configureClientLoggerForService(paths.logs);\n    ownership = await acquireOwnership(home, instanceId);\n\n    const logger = (options.logger ?? createLogger(\"daemon\")).child(baseBindings);\n    lifecycleLogger = logger;\n    state.terminalLogger = logger;\n    const gatedRuntimeLogger = createClientLoggerGate(logger);\n    runtimeLoggerGate = gatedRuntimeLogger;\n    const environmentLogger = logger.child({ module: \"environment\" });\n    environmentLogger.debug({ appliedCount: environmentResult.appliedKeys.length }, \"Daemon environment loaded\");\n    for (const lineNumber of environmentResult.malformedLineNumbers) {\n      environmentLogger.warn({ lineNumber }, \"Malformed daemon environment line ignored\");\n    }\n    logger.info({}, \"Daemon startup started\");\n    const context = { currentPlatform, daemonEnvironment, gatedRuntimeLogger, home, logger, options, state };\n    await runDaemonLifecycle((signal) => createDaemonRuntime(context, signal), signals);\n  } catch (error) {\n    const logger =\n      state.terminalLogger ?? (options.logger ?? createLogger(\"daemon\", { destination: \"dual\" })).child(baseBindings);\n    logTerminalFailure(logger, error);\n    failure = error;\n    failed = true;\n  }\n\n  lifecycleLogger?.info({}, \"Daemon stopping\");\n  state.updater?.stop();\n  lifecycleLogger?.info({}, \"Daemon runtime stopped\");\n  runtimeLoggerGate?.disable();\n  try {\n    await ownership?.release();\n  } catch (error) {\n    const logger =\n      state.terminalLogger ?? (options.logger ?? createLogger(\"daemon\", { destination: \"dual\" })).child(baseBindings);\n    logger.error({ category: \"ownership_release\" }, \"Daemon ownership release failed\");\n    if (!failed) {\n      failure = error;\n      failed = true;\n    }\n  }\n  if (failed) throw failure;\n  return { supervisorRestartRequested: state.handoffRequested };\n}\n\nasync function acquireOwnership(\n  home: string,\n  instanceId: string,\n): Promise<Awaited<ReturnType<typeof acquireDaemonOwner>>> {\n  return acquireDaemonOwner(home, instanceId);\n}\n\nasync function createDaemonRuntime(context: DaemonLifecycleContext, signal: AbortSignal): Promise<DaemonRuntime> {\n  const { credential, identity, supportedPlatform } = await readDaemonIdentity(\n    context.home,\n    context.currentPlatform,\n    signal,\n  );\n  context.state.terminalLogger = context.logger.child({\n    computerId: credential.computerId,\n    installationId: identity.computerId,\n  });\n  const connectionInstanceId = randomUUID();\n  const runtimeLogger = context.gatedRuntimeLogger.logger.child({\n    computerId: credential.computerId,\n    installationId: identity.computerId,\n    instanceId: connectionInstanceId,\n  });\n  const apiContext = await resolveCommandContext({ home: context.home, serverUrl: credential.serverUrl });\n  if (!apiContext.api) throw new Error(\"Command context did not resolve an API\");\n  const connection = new RuntimeConnection({\n    arch: arch(),\n    clientVersion: CLI_VERSION,\n    computer: identity,\n    displayName: hostname(),\n    instanceId: connectionInstanceId,\n    logger: runtimeLogger.child({ module: \"connection\" }),\n    machineToken: credential.machineToken,\n    onChannelTarget: (target) => context.state.channelTargetObserver?.(target),\n    platform: supportedPlatform,\n  });\n  /*\n   * The provider a Session ran on is known only to the composed runtime, and the reporter has to\n   * exist before the runtime does because the composition takes it as an option. The holder closes\n   * that loop: filled in once the runtime exists, empty — and answering no provider — for any\n   * failure filed before then.\n   */\n  const composed: { runtime?: Pick<ComposedClientRuntime, \"runtimeManager\"> } = {};\n  const runtime = await createClientRuntime(connection, {\n    home: context.home,\n    environment: context.daemonEnvironment,\n    credentialMode: resolveRuntimeCredentialMode(context.daemonEnvironment),\n    clientVersion: CLI_VERSION,\n    cliCommand: channelConfig.binName,\n    logger: runtimeLogger,\n    signal,\n    api: apiContext.api,\n    machineToken: credential.machineToken,\n    webTools: resolveWebToolsOptIn(context.daemonEnvironment),\n    // A turn that fails inside the daemon never reaches a terminal, so the tracker is the only place\n    // it can be seen. The reporter decides which failures are defects; the runner reports them all.\n    agentErrorReporter: createAgentErrorReporter({\n      home: context.home,\n      environment: context.daemonEnvironment,\n      resolveProvider: (sessionId) => composed.runtime?.runtimeManager.providerId(sessionId),\n    }),\n  });\n  composed.runtime = runtime;\n  context.state.updater = await attachAutoUpdater(context, runtime, runtimeLogger);\n  void connection.whenRegistered(signal).then(\n    () => runtimeLogger.info({}, \"Computer runtime is ready\"),\n    () => undefined,\n  );\n  return { run: () => runtime.run(), stop: () => runtime.stop() };\n}\n\nasync function readDaemonIdentity(home: string, currentPlatform: NodeJS.Platform, signal: AbortSignal) {\n  let credentials: Awaited<ReturnType<typeof readMachineCredentials>>;\n  try {\n    credentials = await readMachineCredentials(home);\n  } catch (error) {\n    throw new DaemonRuntimeConfigurationError(\"OpenTag Computer credentials are invalid; run opentag connect again\", {\n      cause: error,\n    });\n  }\n  signal.throwIfAborted();\n  const bound = resolveBoundAccountComputer(credentials);\n  if (bound.status === \"disconnected\") {\n    throw new DaemonRuntimeConfigurationError(\"This Computer is not connected; run opentag connect first\");\n  }\n  let identity: Awaited<ReturnType<typeof resolveComputerIdentity>>;\n  try {\n    identity = await resolveComputerIdentity(home, bound.credential.serverUrl);\n  } catch (error) {\n    throw new DaemonRuntimeConfigurationError(\"The local Computer identity is invalid\", { cause: error });\n  }\n  signal.throwIfAborted();\n  if (currentPlatform !== \"darwin\" && currentPlatform !== \"linux\") {\n    throw new DaemonRuntimeConfigurationError(`Unsupported daemon service platform: ${currentPlatform}`);\n  }\n  if (bound.credential.installationId !== identity.computerId) {\n    throw new DaemonRuntimeConfigurationError(\"A machine credential belongs to another Computer\");\n  }\n  return { credential: bound.credential, identity, supportedPlatform: currentPlatform };\n}\n\nasync function attachAutoUpdater(\n  context: DaemonLifecycleContext,\n  runtime: Awaited<ReturnType<typeof createClientRuntime>>,\n  runtimeLogger: ClientLogger,\n): Promise<UpdateManager | undefined> {\n  const autoUpdate = context.options.autoUpdate === false ? undefined : (context.options.autoUpdate ?? {});\n  const installMode = autoUpdate?.installMode ?? detectInstallMode(process.env);\n  const shouldAttach =\n    autoUpdate !== undefined && installMode.mode === \"portable\" && (autoUpdate.attach ?? CHANNEL !== \"dev\");\n  if (!shouldAttach || installMode.mode !== \"portable\") return undefined;\n  const updater = createPortableAutoUpdater({\n    home: context.home,\n    installMode,\n    protectedWork: () => runtime.protectedWork(),\n    quiesce: () => runtime.quiesceForUpdate(),\n    onHandoff: () => {\n      context.state.handoffRequested = true;\n      runtime.stop();\n    },\n    logger: runtimeLogger.child({ module: \"updater\" }),\n    ...(autoUpdate.installTarget ? { installTarget: autoUpdate.installTarget } : {}),\n    ...(autoUpdate.refreshService ? { refreshService: autoUpdate.refreshService } : {}),\n    ...(autoUpdate.stateStore ? { stateStore: autoUpdate.stateStore } : {}),\n    ...(autoUpdate.checkIntervalMs ? { checkIntervalMs: autoUpdate.checkIntervalMs } : {}),\n  });\n  await updater.syncRunningVersion();\n  context.state.channelTargetObserver = (target) => updater.observe(target);\n  if (autoUpdate.initialTarget) updater.observe(autoUpdate.initialTarget);\n  return updater;\n}\n\nexport async function runDaemonServiceEntry(options: DaemonRuntimeOptions = {}): Promise<0 | 1 | 75> {\n  try {\n    const result = await runDaemonService(options);\n    return result.supervisorRestartRequested ? SUPERVISOR_RESTART_EXIT_CODE : 0;\n  } catch (error) {\n    if (isExpectedDaemonStop(error)) return 0;\n    if (options.reportFailure) await options.reportFailure(error).catch(() => undefined);\n    return 1;\n  }\n}\n\nfunction isExpectedDaemonStop(error: unknown): boolean {\n  return (\n    error instanceof DaemonRuntimeConfigurationError ||\n    error instanceof DaemonOwnerStartupError ||\n    (error instanceof RuntimeConnectionError && error.fatal) ||\n    (error instanceof DaemonServiceError && [\"CONFIGURATION\", \"UNSUPPORTED_PLATFORM\"].includes(error.code))\n  );\n}\n\nfunction daemonOperatorMessage(error: unknown): string {\n  if (error instanceof DaemonRuntimeConfigurationError) {\n    return \"Daemon configuration is invalid; run opentag connect or inspect daemon status\";\n  }\n  if (error instanceof DaemonOwnerStartupError) {\n    return error.code === \"BUSY\"\n      ? \"Daemon is already running; inspect daemon status\"\n      : \"Daemon ownership prevented startup; inspect daemon status\";\n  }\n  if (error instanceof RuntimeConnectionError) return \"Daemon connection was rejected; run opentag connect again\";\n  return \"Daemon service configuration prevented startup; inspect daemon status\";\n}\n\nfunction daemonFailureCategory(error: unknown): string {\n  if (error instanceof DaemonRuntimeConfigurationError) return \"configuration\";\n  if (error instanceof DaemonOwnerStartupError) return \"ownership\";\n  if (error instanceof RuntimeConnectionError) return error.fatal ? \"connection_fatal\" : \"connection\";\n  if (error instanceof DaemonServiceError) return error.code.toLowerCase();\n  return \"unexpected\";\n}\n\nfunction logTerminalFailure(logger: ClientLogger, error: unknown): void {\n  if (isExpectedDaemonStop(error)) {\n    logger.warn({ category: daemonFailureCategory(error) }, daemonOperatorMessage(error));\n    return;\n  }\n  logger.error({ category: daemonFailureCategory(error) }, \"Daemon stopped because of an unexpected internal failure\");\n}\n\nfunction createClientLoggerGate(logger: ClientLogger): ClientLoggerGate {\n  const state = { enabled: true };\n  const wrap = (target: ClientLogger): ClientLogger => ({\n    child: (bindings) => wrap(target.child(bindings)),\n    debug: (fields, message) => {\n      if (state.enabled) target.debug(fields, message);\n    },\n    error: (fields, message) => {\n      if (state.enabled) target.error(fields, message);\n    },\n    info: (fields, message) => {\n      if (state.enabled) target.info(fields, message);\n    },\n    warn: (fields, message) => {\n      if (state.enabled) target.warn(fields, message);\n    },\n  });\n  return {\n    disable: () => {\n      state.enabled = false;\n    },\n    logger: wrap(logger),\n  };\n}\n","import type { Command } from \"commander\";\nimport { runDaemonServiceEntry } from \"../../core/daemon/runtime.js\";\nimport { reportCliError } from \"../../core/diagnostics/error-reporting.js\";\n\nexport function registerDaemonServiceRunCommand(daemon: Command): void {\n  daemon\n    .command(\"service-run\", { hidden: true })\n    .description(\"Internal daemon service entrypoint\")\n    .action(async () => {\n      process.exitCode = await runDaemonServiceEntry({\n        reportFailure: (error) => reportCliError(error, { command: \"daemon service-run\" }),\n      });\n    });\n}\n","import type { Command } from \"commander\";\nimport { executeDaemonServiceCommand } from \"./shared.js\";\n\nexport function registerDaemonStartCommand(daemon: Command): void {\n  daemon\n    .command(\"start\")\n    .description(\"Start the installed daemon service\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { json?: boolean }) => {\n      process.exitCode = options.json\n        ? await executeDaemonServiceCommand(\"start\", { json: true })\n        : await executeDaemonServiceCommand(\"start\");\n    });\n}\n","import type { Command } from \"commander\";\nimport { executeDaemonServiceCommand } from \"./shared.js\";\n\nexport function registerDaemonStatusCommand(daemon: Command): void {\n  daemon\n    .command(\"status\")\n    .description(\"Show daemon service status\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { json?: boolean }) => {\n      process.exitCode = options.json\n        ? await executeDaemonServiceCommand(\"status\", { json: true })\n        : await executeDaemonServiceCommand(\"status\");\n    });\n}\n","import type { Command } from \"commander\";\nimport { executeDaemonServiceCommand } from \"./shared.js\";\n\nexport function registerDaemonStopCommand(daemon: Command): void {\n  daemon\n    .command(\"stop\")\n    .description(\"Stop the daemon service\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { json?: boolean }) => {\n      process.exitCode = options.json\n        ? await executeDaemonServiceCommand(\"stop\", { json: true })\n        : await executeDaemonServiceCommand(\"stop\");\n    });\n}\n","import type { Command } from \"commander\";\nimport { executeDaemonServiceCommand } from \"./shared.js\";\n\nexport function registerDaemonUninstallCommand(daemon: Command): void {\n  daemon\n    .command(\"uninstall\")\n    .description(\"Remove the daemon service while preserving local data\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { json?: boolean }) => {\n      process.exitCode = options.json\n        ? await executeDaemonServiceCommand(\"uninstall\", { json: true })\n        : await executeDaemonServiceCommand(\"uninstall\");\n    });\n}\n","import type { Command } from \"commander\";\nimport { registerDaemonEnsureServiceCommand } from \"./ensure-service.js\";\nimport { registerDaemonInstallCommand } from \"./install.js\";\nimport { registerDaemonRefreshServiceCommand } from \"./refresh-service.js\";\nimport { registerDaemonRestartCommand } from \"./restart.js\";\nimport { registerDaemonServiceRunCommand } from \"./service-run.js\";\nimport { registerDaemonStartCommand } from \"./start.js\";\nimport { registerDaemonStatusCommand } from \"./status.js\";\nimport { registerDaemonStopCommand } from \"./stop.js\";\nimport { registerDaemonUninstallCommand } from \"./uninstall.js\";\n\nexport function registerDaemonCommand(program: Command): void {\n  const daemon = program.command(\"daemon\").description(\"Manage the OpenTag daemon service\");\n  registerDaemonEnsureServiceCommand(daemon);\n  registerDaemonInstallCommand(daemon);\n  registerDaemonRefreshServiceCommand(daemon);\n  registerDaemonStartCommand(daemon);\n  registerDaemonStopCommand(daemon);\n  registerDaemonRestartCommand(daemon);\n  registerDaemonStatusCommand(daemon);\n  registerDaemonUninstallCommand(daemon);\n  registerDaemonServiceRunCommand(daemon);\n}\n","import { resolve } from \"node:path\";\nimport {\n  type AgentRuntimeCliInstallation,\n  checkServerHealth,\n  type IntegrationCliInstallation,\n  inspectLocalComputerConfiguration,\n  type LocalComputerConfigurationInspection,\n  probeAgentRuntimeCliInstallations,\n  probeIntegrationCliInstallations,\n  ServerHealthConfigurationError,\n  ServerHealthHttpError,\n  ServerHealthNetworkError,\n  ServerHealthResponseError,\n  ServerHealthTimeoutError,\n} from \"@opentag/client\";\nimport { AGENT_RUNTIME_PROVIDERS, type AgentRuntimeProvider, type ServerHealth } from \"@opentag/shared\";\nimport { CHANNEL, CLI_VERSION } from \"../../build-info.js\";\nimport { channelConfig } from \"../channel/config.js\";\nimport { wasChannelDefaultHomeApplied } from \"../channel/home-source.js\";\nimport { createDaemonServiceManager } from \"../daemon/service/index.js\";\nimport { canonicalizeServiceHome } from \"../daemon/service/shared.js\";\nimport type { DaemonServiceInfo } from \"../daemon/service/types.js\";\nimport { providerCliRepairCommand } from \"../provider-cli/shared.js\";\n\nexport type DoctorCheckStatus = \"pass\" | \"fail\" | \"unknown\" | \"info\" | \"skipped\";\nexport type DoctorCheckScope =\n  | \"target\"\n  | \"local-configuration\"\n  | \"daemon-service\"\n  | \"server\"\n  | \"agent-runtime\"\n  | \"provider-cli\";\n\nexport interface DoctorCheck {\n  code: string;\n  scope: DoctorCheckScope;\n  status: DoctorCheckStatus;\n  blocking: boolean;\n  label: string;\n  detail: string;\n  observedFrom?: string;\n  path?: string;\n  remediation?: string;\n  command?: string;\n}\n\nexport interface DoctorNextAction {\n  checkCode: string;\n  command: string;\n  reason: string;\n}\n\nexport interface DoctorTarget {\n  home: string;\n  homeSource: \"environment\" | \"channel-default\";\n  cliVersion: string;\n  channel: string;\n  platform: NodeJS.Platform;\n  arch: string;\n  nodeVersion: string;\n}\n\nexport interface DoctorReport {\n  target: DoctorTarget;\n  checks: DoctorCheck[];\n  nextActions: DoctorNextAction[];\n  providerCliSetup: \"ready\" | \"needs_attention\" | \"unknown\";\n  notEvaluated: readonly string[];\n  exitCode: 0 | 1;\n}\n\nexport interface DoctorResult extends DoctorReport {\n  message: string;\n}\n\nexport type HealthChecker = (serverUrl: string) => Promise<ServerHealth>;\nexport type LocalConfigurationInspector = (home: string) => Promise<LocalComputerConfigurationInspection>;\nexport type DaemonServiceInspector = (home: string) => Promise<DaemonServiceInfo>;\nexport type RuntimeDetector = (options: {\n  environment: NodeJS.ProcessEnv;\n  platform: NodeJS.Platform;\n}) => Promise<AgentRuntimeCliInstallation[]>;\nexport type IntegrationCliDetector = (options: {\n  environment: NodeJS.ProcessEnv;\n  platform: NodeJS.Platform;\n}) => Promise<IntegrationCliInstallation[]>;\n\nexport interface DoctorOptions {\n  env?: NodeJS.ProcessEnv;\n  platform?: NodeJS.Platform;\n  arch?: string;\n  nodeVersion?: string;\n  cliVersion?: string;\n  channel?: string;\n  healthChecker?: HealthChecker;\n  inspectLocalConfiguration?: LocalConfigurationInspector;\n  inspectDaemonService?: DaemonServiceInspector;\n  runtimeDetector?: RuntimeDetector;\n  integrationCliDetector?: IntegrationCliDetector;\n}\n\nexport const DOCTOR_NOT_EVALUATED = [\n  \"Agent Runtime authentication\",\n  \"Agent Runtime version or protocol compatibility\",\n  \"Agent Runtime visibility from the installed daemon environment\",\n  \"machine-token authentication or WebSocket registration\",\n  \"Integration CLI version compatibility, authentication, credentials, installation configuration, or network availability\",\n  \"Integration CLI visibility from the installed daemon environment\",\n  \"end-to-end Turn or handoff delivery\",\n] as const;\n\nexport async function runDoctor(options: DoctorOptions = {}): Promise<DoctorResult> {\n  const environment = options.env ?? process.env;\n  const platform = options.platform ?? process.platform;\n  const selectedTarget = resolveDoctorTarget({\n    environment,\n    platform,\n    arch: options.arch ?? process.arch,\n    nodeVersion: options.nodeVersion ?? process.version,\n    cliVersion: options.cliVersion ?? CLI_VERSION,\n    channel: options.channel ?? CHANNEL,\n    channelDefaultHomeApplied: environment === process.env && wasChannelDefaultHomeApplied(),\n  });\n  const target = {\n    ...selectedTarget,\n    home: await canonicalizeServiceHome(selectedTarget.home).catch(() => selectedTarget.home),\n  };\n  const localInspector = options.inspectLocalConfiguration ?? inspectLocalComputerConfiguration;\n  const daemonInspector =\n    options.inspectDaemonService ??\n    (async (home: string) => (await createDaemonServiceManager({ env: environment, home, platform })).status());\n  const runtimeDetector =\n    options.runtimeDetector ??\n    ((request) =>\n      probeAgentRuntimeCliInstallations({\n        environment: request.environment,\n        platform: request.platform,\n      }));\n  const integrationCliDetector =\n    options.integrationCliDetector ??\n    ((request) =>\n      probeIntegrationCliInstallations({\n        environment: request.environment,\n        platform: request.platform,\n      }));\n  const healthChecker = options.healthChecker ?? checkServerHealth;\n\n  const localPromise = settle(localInspector(target.home));\n  const daemonPromise = settle(daemonInspector(target.home));\n  const runtimePromise = settle(runtimeDetector({ environment, platform }));\n  const providerCliPromise = settle(integrationCliDetector({ environment, platform }));\n  const healthPromise = localPromise.then(async (localResult) => {\n    if (localResult.status === \"rejected\") return { status: \"skipped\" as const };\n    const serverUrl = localResult.value.binding.serverUrl;\n    if (!serverUrl || localResult.value.binding.status !== \"valid\") return { status: \"skipped\" as const };\n    return settle(healthChecker(serverUrl));\n  });\n\n  const [localResult, daemonResult, healthResult, runtimeResult, providerCliResult] = await Promise.all([\n    localPromise,\n    daemonPromise,\n    healthPromise,\n    runtimePromise,\n    providerCliPromise,\n  ]);\n  const checks: DoctorCheck[] = [\n    targetCheck(target),\n    ...localChecks(localResult),\n    daemonCheck(daemonResult, target.home),\n    serverCheck(healthResult, localResult),\n    ...runtimeChecks(runtimeResult),\n    ...providerCliChecks(providerCliResult),\n  ];\n  const exitCode: 0 | 1 = checks.some(\n    (check) => check.blocking && (check.status === \"fail\" || check.status === \"unknown\"),\n  )\n    ? 1\n    : 0;\n  const nextActions = checks.flatMap((check) =>\n    check.command ? [{ checkCode: check.code, command: check.command, reason: check.code }] : [],\n  );\n  const providerCliSetup = providerCliSetupStatus(checks);\n  const report: DoctorReport = {\n    target,\n    checks,\n    nextActions,\n    providerCliSetup,\n    notEvaluated: DOCTOR_NOT_EVALUATED,\n    exitCode,\n  };\n  return { ...report, message: renderDoctorReport(report) };\n}\n\nexport function resolveDoctorTarget(options: {\n  environment: NodeJS.ProcessEnv;\n  platform: NodeJS.Platform;\n  arch: string;\n  nodeVersion: string;\n  cliVersion: string;\n  channel: string;\n  channelDefaultHomeApplied?: boolean;\n}): DoctorTarget {\n  const selected = options.environment.OPENTAG_HOME?.trim();\n  const homeSource = selected && !options.channelDefaultHomeApplied ? \"environment\" : \"channel-default\";\n  return {\n    home: resolve(selected || channelConfig.defaultHome),\n    homeSource,\n    cliVersion: options.cliVersion,\n    channel: options.channel,\n    platform: options.platform,\n    arch: options.arch,\n    nodeVersion: options.nodeVersion,\n  };\n}\n\nexport function renderDoctorReport(report: DoctorReport): string {\n  const blockingFailures = report.checks.filter(\n    (check) => check.blocking && (check.status === \"fail\" || check.status === \"unknown\"),\n  ).length;\n  const baselineSummary =\n    blockingFailures === 0\n      ? \"Baseline checks passed for this OpenTag Home.\"\n      : `${blockingFailures} blocking baseline check(s) failed for this OpenTag Home.`;\n  const providerSummary =\n    report.providerCliSetup === \"ready\"\n      ? \"Lark and Slack CLIs are ready.\"\n      : report.providerCliSetup === \"unknown\"\n        ? \"Lark and Slack CLI readiness could not be fully inspected.\"\n        : \"At least one messaging CLI still needs attention.\";\n  const lines = [\n    \"OpenTag Doctor\",\n    \"\",\n    \"Target\",\n    `  - OpenTag Home: ${report.target.home} (${report.target.homeSource === \"environment\" ? \"environment\" : \"channel default\"})`,\n    `  - CLI: ${report.target.cliVersion}, ${report.target.channel}, ${report.target.platform} ${report.target.arch}, Node.js ${report.target.nodeVersion}`,\n  ];\n  for (const [heading, scope] of [\n    [\"Local configuration\", \"local-configuration\"],\n    [\"Daemon service\", \"daemon-service\"],\n    [\"Server\", \"server\"],\n    [\"Agent Runtime CLIs\", \"agent-runtime\"],\n    [\"IM Provider CLIs\", \"provider-cli\"],\n  ] as const) {\n    lines.push(\"\", heading);\n    for (const check of report.checks.filter((candidate) => candidate.scope === scope)) {\n      lines.push(`  ${statusMarker(check.status)} ${check.label}: ${check.detail}`);\n      if (check.remediation) lines.push(`    Next: ${check.remediation}`);\n      if (check.command) lines.push(`    Command: ${check.command}`);\n    }\n  }\n  lines.push(\"\", \"Summary\", `  ${baselineSummary}`, `  ${providerSummary}`, \"\", \"Not evaluated\");\n  for (const item of report.notEvaluated) lines.push(`  - ${item}`);\n  return lines.join(\"\\n\");\n}\n\nfunction providerCliSetupStatus(checks: readonly DoctorCheck[]): DoctorReport[\"providerCliSetup\"] {\n  const providerChecks = checks.filter((check) => check.scope === \"provider-cli\");\n  if (providerChecks.length === 0 || providerChecks.some((check) => check.status === \"unknown\")) return \"unknown\";\n  return providerChecks.every((check) => check.status === \"pass\") ? \"ready\" : \"needs_attention\";\n}\n\nfunction targetCheck(target: DoctorTarget): DoctorCheck {\n  return {\n    code: \"target.home\",\n    scope: \"target\",\n    status: \"info\",\n    blocking: false,\n    label: \"OpenTag Home\",\n    detail: target.home,\n    path: target.home,\n    observedFrom: target.homeSource,\n  };\n}\n\nfunction localChecks(result: PromiseSettledResult<LocalComputerConfigurationInspection>): DoctorCheck[] {\n  if (result.status === \"rejected\") {\n    const detail = safeErrorDetail(result.reason, \"Local Computer configuration could not be inspected\");\n    return [\n      localCheck(\"local.identity\", \"Computer identity\", \"unknown\", detail),\n      localCheck(\"local.credentials\", \"Computer credentials\", \"unknown\", detail),\n      localCheck(\"local.binding\", \"Local Computer binding\", \"unknown\", \"Local binding could not be verified\"),\n    ];\n  }\n  const { identity, credentials, binding } = result.value;\n  return [\n    localCheck(\n      \"local.identity\",\n      \"Computer identity\",\n      localStatus(identity.status),\n      identity.status === \"valid\" ? \"valid for one Computer and one Server\" : (identity.detail ?? \"invalid\"),\n    ),\n    localCheck(\n      \"local.credentials\",\n      \"Computer credentials\",\n      localStatus(credentials.status),\n      credentials.status === \"valid\" ? \"1 valid Computer credential\" : (credentials.detail ?? \"invalid\"),\n    ),\n    localCheck(\n      \"local.binding\",\n      \"Local Computer configuration\",\n      localStatus(binding.status),\n      binding.status === \"valid\"\n        ? `${binding.credentialCount} credential(s), one Computer, one Server`\n        : (binding.detail ?? \"invalid\"),\n    ),\n  ];\n}\n\nfunction localCheck(code: string, label: string, status: \"pass\" | \"fail\" | \"unknown\", detail: string): DoctorCheck {\n  return {\n    code,\n    scope: \"local-configuration\",\n    status,\n    blocking: true,\n    label,\n    detail,\n    ...(status === \"fail\"\n      ? {\n          remediation: `Review this OpenTag Home and run '${channelConfig.binName} connect' with a valid connect code`,\n        }\n      : {}),\n  };\n}\n\nfunction localStatus(status: LocalComputerConfigurationInspection[\"identity\"][\"status\"]): \"pass\" | \"fail\" {\n  return status === \"valid\" ? \"pass\" : \"fail\";\n}\n\nfunction daemonCheck(result: PromiseSettledResult<DaemonServiceInfo>, home: string): DoctorCheck {\n  if (result.status === \"rejected\") {\n    return {\n      code: \"daemon.service\",\n      scope: \"daemon-service\",\n      status: \"unknown\",\n      blocking: true,\n      label: \"Daemon service\",\n      detail: safeErrorDetail(result.reason, \"Daemon service status could not be determined\"),\n    };\n  }\n  const info = result.value;\n  const sameHome = info.configuredHome !== undefined && resolve(info.configuredHome) === home;\n  const passed =\n    info.platform !== \"unsupported\" &&\n    info.state === \"active\" &&\n    sameHome &&\n    info.drifted === false &&\n    info.runtimeOwner?.consistency === \"consistent\";\n  const detail = passed\n    ? `active for this OpenTag Home; logs: ${info.logHint}`\n    : `${daemonFailureDetail(info, sameHome)}; logs: ${info.logHint}`;\n  return {\n    code: \"daemon.service\",\n    scope: \"daemon-service\",\n    status: passed ? \"pass\" : info.state === \"unknown\" ? \"unknown\" : \"fail\",\n    blocking: true,\n    label: \"Daemon service\",\n    detail,\n    ...(passed\n      ? {}\n      : { remediation: `Inspect with '${channelConfig.binName} daemon status' before changing the service` }),\n  };\n}\n\nfunction daemonFailureDetail(info: DaemonServiceInfo, sameHome: boolean): string {\n  if (info.platform === \"unsupported\") return \"unsupported on this platform\";\n  if (info.state !== \"active\") return info.detail ? `${info.state} (${truncate(info.detail)})` : info.state;\n  if (!sameHome) return \"active for a different or unverifiable OpenTag Home\";\n  if (info.drifted !== false) return \"service definition is drifted or unverifiable\";\n  if (info.runtimeOwner?.consistency !== \"consistent\") {\n    return `runtime owner is ${info.runtimeOwner?.consistency ?? \"unverified\"}`;\n  }\n  return \"status could not be verified\";\n}\n\nfunction serverCheck(\n  result: { status: \"skipped\" } | PromiseSettledResult<ServerHealth>,\n  localResult: PromiseSettledResult<LocalComputerConfigurationInspection>,\n): DoctorCheck {\n  const serverUrl = localResult.status === \"fulfilled\" ? localResult.value.binding.serverUrl : undefined;\n  if (result.status === \"skipped\" || !serverUrl) {\n    return {\n      code: \"server.health\",\n      scope: \"server\",\n      status: \"skipped\",\n      blocking: true,\n      label: \"Server health endpoint\",\n      detail: \"not checked because there is no connected Server\",\n    };\n  }\n  if (result.status === \"fulfilled\") {\n    return {\n      code: \"server.health\",\n      scope: \"server\",\n      status: \"pass\",\n      blocking: true,\n      label: \"Server health endpoint\",\n      detail: `reachable at ${serverUrl}`,\n    };\n  }\n  return {\n    code: \"server.health\",\n    scope: \"server\",\n    status: \"fail\",\n    blocking: true,\n    label: \"Server health endpoint\",\n    detail: formatHealthFailure(result.reason, serverUrl),\n    remediation: \"Check network access and the connected Server health endpoint\",\n  };\n}\n\nconst RUNTIME_CLI_LABELS = {\n  codex: \"Codex CLI\",\n  \"claude-code\": \"Claude Code CLI\",\n  pi: \"Pi CLI\",\n} as const satisfies Record<AgentRuntimeProvider, string>;\n\nfunction runtimeChecks(result: PromiseSettledResult<AgentRuntimeCliInstallation[]>): DoctorCheck[] {\n  if (result.status === \"rejected\") {\n    return [\n      {\n        code: \"runtime.any-installed\",\n        scope: \"agent-runtime\",\n        status: \"unknown\",\n        blocking: true,\n        label: \"Agent Runtime CLI\",\n        detail: safeErrorDetail(result.reason, \"Runtime installation could not be determined\"),\n        observedFrom: \"current CLI process environment\",\n      },\n      ...AGENT_RUNTIME_PROVIDERS.map((provider) => runtimeProviderUnknown(provider, RUNTIME_CLI_LABELS[provider])),\n    ];\n  }\n  const byProvider = new Map(result.value.map((entry) => [entry.provider, entry]));\n  const runtimes = AGENT_RUNTIME_PROVIDERS.map(\n    (provider) => byProvider.get(provider) ?? unknownRuntime(provider, RUNTIME_CLI_LABELS[provider]),\n  );\n  const installed = runtimes.filter((entry) => entry.status === \"installed\");\n  const hasUnknown = runtimes.some((entry) => entry.status === \"unknown\");\n  return [\n    {\n      code: \"runtime.any-installed\",\n      scope: \"agent-runtime\",\n      status: installed.length > 0 ? \"pass\" : hasUnknown ? \"unknown\" : \"fail\",\n      blocking: true,\n      label: \"Agent Runtime CLI\",\n      detail:\n        installed.length > 0\n          ? \"at least one supported Runtime is installed\"\n          : hasUnknown\n            ? \"no supported Runtime was found and at least one result is unknown\"\n            : \"no supported Runtime is installed\",\n      observedFrom: \"current CLI process environment\",\n      ...(installed.length > 0 ? {} : { remediation: \"Install Codex CLI, Claude Code CLI, or Pi CLI\" }),\n    },\n    ...runtimes.map((entry) => cliInstallationCheck(`runtime.${entry.provider}.installation`, \"agent-runtime\", entry)),\n  ];\n}\n\nfunction providerCliChecks(result: PromiseSettledResult<IntegrationCliInstallation[]>): DoctorCheck[] {\n  if (result.status === \"rejected\") {\n    const detail = safeErrorDetail(result.reason, \"Integration CLI installation could not be determined\");\n    return [\n      cliInstallationCheck(\"provider-cli.feishu.installation\", \"provider-cli\", {\n        detail,\n        displayName: \"Lark CLI\",\n        status: \"unknown\",\n      }),\n      cliInstallationCheck(\"provider-cli.slack.installation\", \"provider-cli\", {\n        detail,\n        displayName: \"Slack CLI\",\n        status: \"unknown\",\n      }),\n    ];\n  }\n  const byCli = new Map(result.value.map((entry) => [entry.cli, entry]));\n  return [\n    cliInstallationCheck(\n      \"provider-cli.feishu.installation\",\n      \"provider-cli\",\n      byCli.get(\"feishu\") ?? {\n        displayName: \"Lark CLI\",\n        status: \"unknown\",\n        detail: \"Detector did not return a result\",\n      },\n    ),\n    cliInstallationCheck(\n      \"provider-cli.slack.installation\",\n      \"provider-cli\",\n      byCli.get(\"slack\") ?? {\n        displayName: \"Slack CLI\",\n        status: \"unknown\",\n        detail: \"Detector did not return a result\",\n      },\n    ),\n  ];\n}\n\nfunction cliInstallationCheck(\n  code: string,\n  scope: Extract<DoctorCheckScope, \"agent-runtime\" | \"provider-cli\">,\n  entry: {\n    displayName: string;\n    status: \"installed\" | \"not-installed\" | \"unknown\";\n    path?: string;\n    source?: string;\n    detail?: string;\n  },\n): DoctorCheck {\n  const observedFrom =\n    scope === \"provider-cli\"\n      ? \"current CLI process environment and operating-system account locations\"\n      : \"current CLI process environment\";\n  if (entry.status === \"installed\") {\n    return {\n      code,\n      scope,\n      status: \"pass\",\n      blocking: false,\n      label: entry.displayName,\n      detail: `installed at ${entry.path} (${entry.source})`,\n      path: entry.path,\n      observedFrom,\n    };\n  }\n  if (entry.status === \"unknown\") {\n    return {\n      code,\n      scope,\n      status: \"unknown\",\n      blocking: false,\n      label: entry.displayName,\n      detail: truncate(entry.detail ?? \"installation could not be determined\"),\n      observedFrom,\n      ...(scope === \"provider-cli\" ? { command: providerCliRepairCommand(providerFromCheckCode(code)) } : {}),\n    };\n  }\n  return {\n    code,\n    scope,\n    status: \"info\",\n    blocking: false,\n    label: entry.displayName,\n    detail: \"not installed\",\n    observedFrom,\n    ...(scope === \"provider-cli\"\n      ? {\n          remediation: \"Prepare this CLI before choosing the messaging app, or let an Agent run the command\",\n          command: providerCliRepairCommand(providerFromCheckCode(code)),\n        }\n      : {}),\n  };\n}\n\nfunction providerFromCheckCode(code: string): \"feishu\" | \"slack\" {\n  switch (code) {\n    case \"provider-cli.feishu.installation\":\n      return \"feishu\";\n    case \"provider-cli.slack.installation\":\n      return \"slack\";\n    default:\n      throw new Error(`Unsupported Provider CLI check code: ${code}`);\n  }\n}\n\nfunction runtimeProviderUnknown(provider: AgentRuntimeProvider, label: string, detail?: string): DoctorCheck {\n  return cliInstallationCheck(`runtime.${provider}.installation`, \"agent-runtime\", {\n    detail,\n    displayName: label,\n    status: \"unknown\",\n  });\n}\n\nfunction unknownRuntime(provider: AgentRuntimeProvider, displayName: string): AgentRuntimeCliInstallation {\n  return { provider, displayName, status: \"unknown\", detail: \"Detector did not return a result\" };\n}\n\nfunction formatHealthFailure(error: unknown, serverUrl: string): string {\n  if (error instanceof ServerHealthConfigurationError) return `invalid connected Server URL ${serverUrl}`;\n  if (error instanceof ServerHealthTimeoutError) return `timed out while reaching ${serverUrl}`;\n  if (error instanceof ServerHealthNetworkError) return `could not reach ${serverUrl}`;\n  if (error instanceof ServerHealthHttpError) return `${serverUrl} returned HTTP ${error.status}`;\n  if (error instanceof ServerHealthResponseError) return `${serverUrl} returned an invalid health response`;\n  return `health status could not be determined for ${serverUrl}`;\n}\n\nfunction statusMarker(status: DoctorCheckStatus): string {\n  if (status === \"pass\") return \"✓\";\n  if (status === \"fail\") return \"✗\";\n  if (status === \"unknown\") return \"?\";\n  return \"-\";\n}\n\nfunction settle<T>(promise: Promise<T>): Promise<PromiseSettledResult<T>> {\n  return promise.then(\n    (value) => ({ status: \"fulfilled\", value }),\n    (reason: unknown) => ({ status: \"rejected\", reason }),\n  );\n}\n\nfunction safeErrorDetail(error: unknown, fallback: string): string {\n  if (!(error instanceof Error) || error.message.length === 0) return fallback;\n  return truncate(error.message);\n}\n\nfunction truncate(value: string): string {\n  const redacted = value.replace(/otmc_[^\\s]+/giu, \"[redacted]\");\n  return [...redacted]\n    .map((character) => {\n      const code = character.codePointAt(0) ?? 0;\n      return code < 32 || code === 127 ? \" \" : character;\n    })\n    .join(\"\")\n    .slice(0, 300);\n}\n","import type { Command } from \"commander\";\nimport * as commandPolicy from \"../core/command/policy.js\";\nimport { type DoctorResult, runDoctor } from \"../core/diagnostics/doctor.js\";\n\nexport function registerDoctorCommand(program: Command): void {\n  program\n    .command(\"doctor\")\n    .description(\"Run read-only baseline diagnostics for the selected OpenTag Home\")\n    .option(\"--json\", \"print JSON with machine-readable checks and next actions\")\n    .action(async (options: { json?: boolean }) => {\n      try {\n        const result = await runDoctor();\n        if (!options.json) {\n          process.exitCode = result.exitCode;\n          process.stdout.write(`${result.message}\\n`);\n          return;\n        }\n        process.exitCode =\n          result.exitCode === 0\n            ? commandPolicy.presentCommand({ ok: true, value: result, exitCode: 0 }, { json: true })\n            : commandPolicy.presentCommand(doctorFailure(result), { json: true });\n      } catch (error) {\n        const commandError = commandPolicy.toCommandError(error, \"request\");\n        process.exitCode = commandPolicy.presentCommand(\n          { ok: false, error: commandError, exitCode: commandPolicy.commandExitCode(commandError) },\n          { json: options.json === true },\n        );\n      }\n    });\n}\n\n/**\n * An unhealthy report is a failure document with the report attached: the reader gets the same\n * envelope shape as every other command and still receives the checks and next actions. The\n * verdict is about this machine's setup being missing or inconsistent — a configuration failure,\n * so the shared policy maps it to the operational-failure exit rather than service-unavailable.\n */\nfunction doctorFailure(result: DoctorResult): commandPolicy.CommandResult<DoctorResult> {\n  const blocking = result.checks.filter(\n    (check) => check.blocking && (check.status === \"fail\" || check.status === \"unknown\"),\n  ).length;\n  const error = new commandPolicy.CommandError(\n    {\n      code: \"DOCTOR_UNHEALTHY\",\n      category: \"configuration\",\n      retryability: \"never\",\n      phase: \"unknown\",\n    },\n    `${blocking} blocking baseline check(s) failed for this OpenTag Home.`,\n  );\n  return { ok: false, error, exitCode: commandPolicy.commandExitCode(error), value: result };\n}\n","import {\n  type ClientLogger,\n  createLogger,\n  credentialsFingerprint,\n  credentialsPath,\n  normalizeServerUrl,\n  type OpenTagApi,\n  readComputerIdentity,\n  removeAccountIdentity,\n  resolveOpenTagHome,\n  type StoredCredentials,\n  writeAccountIdentityAtomically,\n  writeCredentialsAtomically,\n} from \"@opentag/client\";\nimport { resolveCommandContext } from \"../command/context.js\";\n\n/** Reading the Account back is best effort, so a caller may hand in an API that cannot do it. */\ntype LoginApi = Pick<OpenTagApi, \"exchangeConnectCode\"> & Partial<Pick<OpenTagApi, \"me\">>;\n\nexport interface LoginOptions {\n  api?: LoginApi;\n  code: string;\n  home?: string;\n  now?: () => Date;\n  serverUrl: string;\n  /** Where a best-effort step that did not change the outcome is noted. */\n  logger?: Pick<ClientLogger, \"warn\">;\n}\n\nexport interface LoginResult {\n  credentialsPath: string;\n  message: string;\n}\n\nexport async function runLogin(options: LoginOptions): Promise<LoginResult> {\n  const home = options.home ?? resolveOpenTagHome();\n  const now = options.now ?? (() => new Date());\n  const serverUrl = normalizeServerUrl(options.serverUrl);\n  const computer = await readComputerIdentity(home);\n  if (computer && computer.serverUrl !== serverUrl) {\n    throw new Error(\"This OpenTag home is bound to another server; choose a different OPENTAG_HOME\");\n  }\n  const api = options.api ?? (await resolveCommandContext({ home, serverUrl })).api;\n  if (!api) throw new Error(\"Command context did not resolve an API\");\n  const response = await api.exchangeConnectCode(options.code);\n  const userId = await resolveUserId(api, response.accessToken);\n  const credentials: StoredCredentials = {\n    accessToken: response.accessToken,\n    accessTokenExpiresAt: new Date(now().getTime() + response.expiresIn * 1000).toISOString(),\n    refreshToken: response.refreshToken,\n    serverUrl,\n  };\n  await writeCredentialsAtomically(credentials, home);\n  await recordAccountIdentity(home, credentials, userId, options.logger ?? createLogger(\"login\"));\n  return {\n    credentialsPath: credentialsPath(home),\n    message: `Logged in to OpenTag at ${serverUrl}`,\n  };\n}\n\n/**\n * Which Account these tokens belong to, recorded so a later diagnostic report can name them without\n * a round trip on a path that is already failing.\n *\n * Best effort on purpose: the sign-in has already succeeded by the time this runs, and refusing it\n * over a diagnostic detail would turn a working login into a failed one. An installation that signs\n * in while the Server cannot answer simply reports no Account until it signs in again.\n */\nasync function resolveUserId(api: LoginApi, accessToken: string): Promise<string | undefined> {\n  try {\n    return (await api.me?.(accessToken))?.user.id;\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * Record the Account beside the credentials, in its own file, or forget the one that was there.\n *\n * Beside rather than inside: `credentials.json` is read strictly by every CLI already installed,\n * and a key an older reader does not know would break the documented rollback. Best effort on\n * purpose, for the same reason `resolveUserId` is: the credentials are already written, and a\n * diagnostic detail must not turn a working login into a failed one. A sign-in that could not name\n * its Account removes any identity a previous sign-in left, so a report never names an Account the\n * current tokens may not belong to. The identity carries a fingerprint of the credentials it is\n * written beside, so a later sign-in by an older CLI — which rewrites only the credentials — leaves\n * a file the report path can tell is no longer about the tokens it holds.\n */\nasync function recordAccountIdentity(\n  home: string,\n  credentials: StoredCredentials,\n  userId: string | undefined,\n  logger: Pick<ClientLogger, \"warn\">,\n): Promise<void> {\n  try {\n    if (userId) {\n      await writeAccountIdentityAtomically(\n        { userId, serverUrl: credentials.serverUrl, credentialsFingerprint: credentialsFingerprint(credentials) },\n        home,\n      );\n    } else await removeAccountIdentity(home);\n  } catch (error) {\n    logger.warn(\n      { code: \"account_identity_write_failed\", reason: error instanceof Error ? error.message : String(error) },\n      \"Signed in, but the Account could not be recorded for diagnostics\",\n    );\n  }\n}\n","import { resolve } from \"node:path\";\nimport { readComputerIdentity, resolveOpenTagHome } from \"@opentag/client\";\nimport type { ChannelConfig } from \"@opentag/shared\";\nimport type { Command } from \"commander\";\nimport { runLogin } from \"../core/auth/login.js\";\nimport { channelConfig as defaultChannelConfig } from \"../core/channel/config.js\";\nimport { resolveChannelEnvironment } from \"../core/channel/environment.js\";\nimport { executeCommand } from \"../core/command/policy.js\";\n\ntype LoginCommandOptions = { home?: string; server?: string; json?: boolean };\n\ninterface LoginCommandDependencies {\n  channelConfig?: ChannelConfig;\n  environment?: NodeJS.ProcessEnv;\n  login?: typeof runLogin;\n  writeError?: (message: string) => void;\n  writeOutput?: (message: string) => void;\n}\n\nexport async function executeLoginCommand(\n  code: string,\n  options: LoginCommandOptions,\n  dependencies: LoginCommandDependencies = {},\n): Promise<0 | 1> {\n  const environment = resolveChannelEnvironment(dependencies.environment ?? process.env);\n  const home = resolve(options.home ?? resolveOpenTagHome(environment));\n  const computer = await readComputerIdentity(home);\n  const activeChannelConfig = dependencies.channelConfig ?? defaultChannelConfig;\n  const serverUrl =\n    options.server ?? computer?.serverUrl ?? environment.OPENTAG_SERVER_URL ?? activeChannelConfig.defaultServerUrl;\n  if (!serverUrl) {\n    throw new Error(\n      `The ${activeChannelConfig.channel} channel has no server URL; pass --server <url> to ${activeChannelConfig.binName} login`,\n    );\n  }\n  const writeOutput = dependencies.writeOutput ?? ((message: string) => process.stdout.write(`${message}\\n`));\n  const result = await (dependencies.login ?? runLogin)({\n    code,\n    home,\n    serverUrl,\n  });\n  writeOutput(result.message);\n  return 0;\n}\n\nexport function registerLoginCommand(program: Command, dependencies: LoginCommandDependencies = {}): void {\n  program\n    .command(\"login\")\n    .description(\"Exchange a one-time Account login code and store Account credentials\")\n    .argument(\"<code>\", \"one-time Account login code\")\n    .option(\"--server <url>\", \"OpenTag server URL\")\n    .option(\"--home <path>\", \"OpenTag home directory\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (code: string, options: LoginCommandOptions) => {\n      process.exitCode = await executeCommand(\n        async () => {\n          const output: string[] = [];\n          await executeLoginCommand(code, options, { ...dependencies, writeOutput: (message) => output.push(message) });\n          return output.join(\"\\n\");\n        },\n        { json: options.json === true, phase: \"authentication\" },\n      );\n    });\n}\n","import { readdir, readFile } from \"node:fs/promises\";\nimport { arch, platform, release } from \"node:os\";\nimport { resolveOpenTagHome, resolveOpenTagHomeLayout } from \"@opentag/client\";\nimport { redactForLog } from \"@opentag/shared\";\nimport { CHANNEL, CLI_VERSION } from \"../../build-info.js\";\n\nexport interface LogsOptions {\n  environment?: NodeJS.ProcessEnv;\n  home?: string;\n}\n\nexport interface LogBundleFile {\n  content: string;\n  name: string;\n}\n\nexport interface LogsResult {\n  environment: {\n    arch: string;\n    channel: string;\n    cliVersion: string;\n    homeConfigured: boolean;\n    logLevel: string;\n    nodeEnv: string;\n    nodeVersion: string;\n    osRelease: string;\n    platform: string;\n    serverConfigured: boolean;\n    serviceMode: boolean;\n  };\n  files: LogBundleFile[];\n}\n\nconst CLIENT_LOG_NAME = \"client.log\";\nconst CLIENT_LOG_PATTERN = /^client\\.log(?:\\.\\d+)?$/u;\nconst MAX_EXPORTED_LOG_FILE_BYTES = 1024 * 1024;\n\n/** Read the local client log set and safe runtime metadata for support diagnostics. */\nexport async function runLogs(options: LogsOptions = {}): Promise<LogsResult> {\n  const environment = options.environment ?? process.env;\n  const home = options.home ?? resolveOpenTagHome(environment);\n  const layout = resolveOpenTagHomeLayout(home);\n  const files = await readClientLogs(layout.logs);\n  return {\n    environment: redactForLog({\n      arch: arch(),\n      channel: CHANNEL,\n      cliVersion: CLI_VERSION,\n      homeConfigured: Boolean(environment.OPENTAG_HOME),\n      logLevel: environment.OPENTAG_LOG_LEVEL ?? \"default\",\n      nodeEnv: environment.NODE_ENV ?? \"unset\",\n      nodeVersion: process.version,\n      osRelease: release(),\n      platform: platform(),\n      serverConfigured: Boolean(environment.OPENTAG_SERVER_URL),\n      serviceMode: environment.OPENTAG_SERVICE_MODE === \"1\",\n    }),\n    files,\n  };\n}\n\nexport function formatLogs(result: LogsResult): string {\n  const safeEnvironment = redactForLog(result.environment);\n  const lines = [\"OpenTag logs\", \"Environment:\", JSON.stringify(safeEnvironment) ?? \"{}\", \"\", \"Client log files:\"];\n  if (result.files.length === 0) {\n    lines.push(\"(no client log files found)\");\n    return lines.join(\"\\n\");\n  }\n  for (const file of result.files) {\n    lines.push(`--- ${file.name} ---`, file.content.replace(/\\s+$/u, \"\"));\n  }\n  return lines.join(\"\\n\");\n}\n\nasync function readClientLogs(directory: string): Promise<LogBundleFile[]> {\n  let entries: import(\"node:fs\").Dirent[];\n  try {\n    entries = await readdir(directory, { withFileTypes: true });\n  } catch (error) {\n    if (isMissingPath(error)) return [];\n    throw error;\n  }\n  const names = entries\n    .filter((entry) => entry.isFile() && CLIENT_LOG_PATTERN.test(entry.name))\n    .map((entry) => entry.name)\n    .sort(compareLogNames);\n  const files: LogBundleFile[] = [];\n  for (const name of names) {\n    try {\n      const redacted = redactLogContent(await readFile(`${directory}/${name}`, \"utf8\"));\n      files.push({ content: boundLogContent(redacted), name });\n    } catch (error) {\n      if (!isMissingPath(error)) throw error;\n    }\n  }\n  return files;\n}\n\nfunction boundLogContent(content: string): string {\n  const totalBytes = Buffer.byteLength(content, \"utf8\");\n  if (totalBytes <= MAX_EXPORTED_LOG_FILE_BYTES) return content;\n\n  const lines = content.match(/.*(?:\\n|$)/gu)?.filter((line) => line.length > 0) ?? [];\n  let retainedLines = 0;\n  let retainedBytes = 0;\n  for (let index = lines.length - 1; index >= 0; index -= 1) {\n    const line = lines[index];\n    if (line === undefined) continue;\n    const candidateBytes = retainedBytes + Buffer.byteLength(line, \"utf8\");\n    const omittedBytes = totalBytes - candidateBytes;\n    const marker = formatOmissionMarker(omittedBytes);\n    if (Buffer.byteLength(marker, \"utf8\") + candidateBytes > MAX_EXPORTED_LOG_FILE_BYTES) break;\n    retainedLines += 1;\n    retainedBytes = candidateBytes;\n  }\n\n  const omittedBytes = totalBytes - retainedBytes;\n  const marker = formatOmissionMarker(omittedBytes);\n  return `${marker}${lines.slice(lines.length - retainedLines).join(\"\")}`;\n}\n\nfunction formatOmissionMarker(omittedBytes: number): string {\n  return `[... ${omittedBytes} earlier bytes omitted ...]\\n`;\n}\n\nfunction redactLogContent(content: string): string {\n  return content\n    .split(/(?<=\\n)/u)\n    .map((line) => {\n      const trimmed = line.endsWith(\"\\n\") ? line.slice(0, -1) : line;\n      try {\n        return `${JSON.stringify(redactForLog(JSON.parse(trimmed)))}${line.endsWith(\"\\n\") ? \"\\n\" : \"\"}`;\n      } catch {\n        return redactForLog(line);\n      }\n    })\n    .join(\"\");\n}\n\nfunction compareLogNames(left: string, right: string): number {\n  if (left === CLIENT_LOG_NAME) return -1;\n  if (right === CLIENT_LOG_NAME) return 1;\n  return Number(left.slice(CLIENT_LOG_NAME.length + 1)) - Number(right.slice(CLIENT_LOG_NAME.length + 1));\n}\n\nfunction isMissingPath(error: unknown): boolean {\n  return error !== null && typeof error === \"object\" && (error as NodeJS.ErrnoException).code === \"ENOENT\";\n}\n","import type { Command } from \"commander\";\nimport { executeCommand } from \"../core/command/policy.js\";\nimport { formatLogs, runLogs } from \"../core/diagnostics/logs.js\";\n\nexport function registerLogsCommand(program: Command): void {\n  program\n    .command(\"logs\")\n    .description(\"Bundle local Client logs and a safe environment summary\")\n    .option(\"--home <path>\", \"OpenTag home directory\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { home?: string; json?: boolean }) => {\n      process.exitCode = await executeCommand(() => runLogs({ home: options.home }), {\n        json: options.json === true,\n        formatValue: formatLogs,\n        phase: \"request\",\n      });\n    });\n}\n","import type { ProviderCliInspection } from \"@opentag/client\";\nimport { CommandError, type CommandExitCode, commandExitCode, presentCommand } from \"../command/policy.js\";\nimport {\n  createProviderCliManager,\n  type ProviderCliCommandDeps,\n  type ProviderCliNextAction,\n  parseProviderCliProvidersOrReport,\n  providerCliAggregateFailure,\n  providerCliCanAutoRepair,\n  providerCliLabel,\n  providerCliRepairCommand,\n  renderProviderCliHumanValue,\n  writeStderr,\n  writeStdout,\n} from \"./shared.js\";\n\n/**\n * Reusable orchestration for `opentag provider-cli inspect`: read-only diagnostics for\n * the selected Provider CLI. `--json` emits one common command envelope.\n */\n\nexport interface ProviderCliInspectCommandOptions extends ProviderCliCommandDeps {\n  readonly provider: string;\n  readonly json?: boolean;\n}\n\nexport interface ProviderCliInspectCommandResult {\n  readonly exitCode: CommandExitCode;\n  readonly results: readonly ProviderCliInspection[];\n  readonly nextActions: readonly ProviderCliNextAction[];\n}\n\nfunction renderInspectionLines(\n  inspection: ProviderCliInspection,\n  nextAction: ProviderCliNextAction | undefined,\n): string[] {\n  const label = providerCliLabel(inspection.provider);\n  const lines = [`[${label}] state: ${inspection.state}`];\n  if (inspection.selection) {\n    lines.push(\n      `[${label}] selection: ${inspection.selection.kind} ${inspection.selection.version} ${renderProviderCliHumanValue(inspection.selection.path)} (${inspection.selection.trust})`,\n    );\n  }\n  lines.push(\n    `[${label}] launcher: ${inspection.launcher.status} ${renderProviderCliHumanValue(inspection.launcher.path)}`,\n  );\n  const globalCommand = inspection.globalCommand;\n  if (globalCommand.active) {\n    lines.push(\n      `[${label}] global-command: active ${renderProviderCliHumanValue(globalCommand.resolvedPath ?? globalCommand.path ?? \"\")}`.trimEnd(),\n    );\n  } else if (globalCommand.resolvedPath) {\n    lines.push(`[${label}] global-command: shadowed by ${renderProviderCliHumanValue(globalCommand.resolvedPath)}`);\n  } else {\n    lines.push(`[${label}] global-command: inactive`);\n  }\n  for (const warningEntry of inspection.warnings) {\n    lines.push(\n      `[${label}] warning: ${warningEntry.code}${warningEntry.remediation ? ` — ${warningEntry.remediation}` : \"\"}`,\n    );\n  }\n  if (inspection.diagnostic) {\n    lines.push(\n      `[${label}] diagnostic: ${inspection.diagnostic.code}${inspection.diagnostic.remediation ? ` — ${inspection.diagnostic.remediation}` : \"\"}`,\n    );\n  }\n  if (nextAction) lines.push(`[${label}] next: ${nextAction.command}`);\n  return lines;\n}\n\nfunction nextActionFor(inspection: ProviderCliInspection): ProviderCliNextAction | undefined {\n  if (inspection.state === \"ready\") return undefined;\n  const reason = inspection.diagnostic?.code ?? (inspection.readiness === \"install\" ? \"not_installed\" : \"unavailable\");\n  if (!providerCliCanAutoRepair(reason, \"inspect\")) return undefined;\n  return {\n    provider: inspection.provider,\n    command: providerCliRepairCommand(inspection.provider),\n    reason,\n  };\n}\n\nexport async function runProviderCliInspect(\n  options: ProviderCliInspectCommandOptions,\n): Promise<ProviderCliInspectCommandResult> {\n  let usageMessage = \"\";\n  const providers = parseProviderCliProvidersOrReport(options.provider, (chunk) => {\n    usageMessage += chunk;\n  });\n  if (!providers) {\n    presentCommand(\n      {\n        ok: false,\n        error: new CommandError(\n          { code: \"INVALID_PROVIDER\", category: \"validation\", retryability: \"never\", phase: \"validation\" },\n          usageMessage.trim(),\n        ),\n        exitCode: 2,\n        value: { results: [], nextActions: [] },\n      },\n      { json: options.json, stdout: options.stdout, stderr: options.stderr },\n    );\n    return { exitCode: 2, results: [], nextActions: [] };\n  }\n  const manager = createProviderCliManager(options);\n\n  const results = await Promise.all(providers.map((provider) => manager.inspect(provider)));\n  const nextActions = results.flatMap((inspection) => {\n    const action = nextActionFor(inspection);\n    return action ? [action] : [];\n  });\n  const ready = results.every((result) => result.state === \"ready\");\n  const failure = ready ? undefined : providerCliNotReady(results);\n  const value = { results, nextActions };\n  if (!options.json) {\n    const write = ready ? writeStdout : writeStderr;\n    if (!ready) write(options, \"PROVIDER_CLI_NOT_READY: One or more Provider CLIs need attention.\\n\");\n    for (const inspection of results) {\n      const nextAction = nextActions.find((action) => action.provider === inspection.provider);\n      for (const line of renderInspectionLines(inspection, nextAction)) {\n        write(options, `${line}\\n`);\n      }\n    }\n  } else if (ready) {\n    presentCommand({ ok: true, value, exitCode: 0 }, { json: true, stdout: options.stdout, stderr: options.stderr });\n  } else if (failure) {\n    presentCommand(\n      {\n        ok: false,\n        error: failure.error,\n        exitCode: failure.exitCode,\n        value,\n      },\n      { json: true, stdout: options.stdout, stderr: options.stderr },\n    );\n  }\n\n  return { exitCode: failure ? failure.exitCode : 0, results, nextActions };\n}\n\n/**\n * The aggregate failure contract for a read-only inspection that found a provider not ready.\n * The posture comes from the same classifier as ensure, so inspect never contradicts the repair\n * path its nextActions point at.\n */\nfunction providerCliNotReady(results: readonly ProviderCliInspection[]): {\n  readonly error: CommandError;\n  readonly exitCode: ReturnType<typeof commandExitCode>;\n} {\n  const aggregate = providerCliAggregateFailure(results.filter((result) => result.state !== \"ready\"));\n  const error = new CommandError(\n    {\n      code: \"PROVIDER_CLI_NOT_READY\",\n      category: aggregate.category,\n      retryability: aggregate.retryability,\n      phase: \"provider\",\n    },\n    \"One or more Provider CLIs need attention.\",\n  );\n  return { error, exitCode: commandExitCode(error) };\n}\n","import { type Command, CommanderError } from \"commander\";\nimport * as commandPolicy from \"../core/command/policy.js\";\nimport { runProviderCliEnsure } from \"../core/provider-cli/ensure.js\";\nimport { runProviderCliInspect } from \"../core/provider-cli/inspect.js\";\nimport type { ProviderCliCommandDeps } from \"../core/provider-cli/shared.js\";\n\n/**\n * Thin Commander surface for Provider CLI management. All behavior lives in\n * `core/provider-cli`; this file only wires flags and exit codes.\n *\n * Usage errors (unknown flags, bad `--provider` values) exit 2; operational results\n * exit 0 when every requested provider is ready and 1 otherwise.\n */\n\n// Commander writes the message/help first, then calls this instead of exiting.\nfunction usageErrorsExit2(error: CommanderError): never {\n  if (error.exitCode === 0) throw error;\n  throw new CommanderError(2, error.code, error.message);\n}\n\nexport function registerProviderCliCommand(program: Command, deps: ProviderCliCommandDeps = {}): void {\n  const providerCli = program\n    .command(\"provider-cli\")\n    .description(\"Manage the account-global Feishu/Lark and Slack provider CLIs\")\n    .exitOverride(usageErrorsExit2);\n\n  providerCli\n    .command(\"inspect\")\n    .description(\"Read-only Provider CLI diagnostics for this account\")\n    .requiredOption(\"--provider <name>\", \"Provider CLI to inspect: lark, slack, or all\")\n    .option(\"--json\", \"Emit one JSON document with machine-readable next actions\")\n    .action(async (options: { provider: string; json?: boolean }) => {\n      try {\n        const result = await runProviderCliInspect({\n          ...deps,\n          provider: options.provider,\n          json: options.json === true,\n        });\n        process.exitCode = result.exitCode;\n      } catch (error) {\n        process.exitCode = presentProviderCliFailure(error, options.json === true, deps);\n      }\n    });\n\n  providerCli\n    .command(\"ensure\")\n    .description(\"Select the newest compatible Provider CLI or install the reviewed managed artifact\")\n    .requiredOption(\"--provider <name>\", \"Provider CLI to ensure: lark, slack, or all\")\n    .option(\"--managed-only\", \"Only use reviewed managed artifacts; never select a detected external CLI\")\n    .option(\"--no-path-update\", \"Do not create or refresh the public shim in the account's ~/.local/bin\")\n    .option(\"--dry-run\", \"Detect, rank, and report without selecting or installing\")\n    .option(\"--json\", \"Emit one JSON document with machine-readable next actions\")\n    .action(\n      async (options: {\n        provider: string;\n        managedOnly?: boolean;\n        pathUpdate?: boolean;\n        dryRun?: boolean;\n        json?: boolean;\n      }) => {\n        try {\n          const result = await runProviderCliEnsure({\n            ...deps,\n            provider: options.provider,\n            managedOnly: options.managedOnly === true,\n            pathUpdate: options.pathUpdate !== false,\n            dryRun: options.dryRun === true,\n            json: options.json === true,\n          });\n          process.exitCode = result.exitCode;\n        } catch (error) {\n          process.exitCode = presentProviderCliFailure(error, options.json === true, deps);\n        }\n      },\n    );\n}\n\nfunction presentProviderCliFailure(\n  error: unknown,\n  json: boolean,\n  deps: ProviderCliCommandDeps,\n): commandPolicy.CommandExitCode {\n  const commandError = commandPolicy.toCommandError(error, \"provider\");\n  return commandPolicy.presentCommand(\n    { ok: false, error: commandError, exitCode: commandPolicy.commandExitCode(commandError) },\n    { json, stdout: deps.stdout, stderr: deps.stderr },\n  );\n}\n","import type { Command } from \"commander\";\nimport { commandExitCode, presentCommand, toCommandError } from \"../../core/command/policy.js\";\nimport {\n  formatSessionCommandError,\n  formatSessionCommandResult,\n  formatSessionList,\n  runSessionCreate,\n  runSessionList,\n  runSessionSend,\n  SessionCommandRequestError,\n} from \"../../core/session/index.js\";\n\ninterface OutputOptions {\n  json?: boolean;\n}\n\nexport function registerSessionCommand(program: Command): void {\n  const session = program\n    .command(\"session\")\n    .description(\"Create, message, and list internal Sessions using the implicit managed source Session\");\n\n  session\n    .command(\"create\")\n    .description(\"Create an internal child Session and atomically submit its first message\")\n    .option(\"--message <text>\", \"initial task text\")\n    .option(\"--message-file <path>\", \"read the initial task from a file, or - for stdin\")\n    .option(\"--message-id <uuid>\", \"idempotency key for an explicit retry\")\n    .option(\"--model <model>\", \"override the internal Session model\")\n    .option(\"--reasoning-effort <effort>\", \"override the internal Session reasoning effort\")\n    .option(\"--max-duration-ms <milliseconds>\", \"override the maximum Run duration\", parsePositiveInteger)\n    .option(\"--json\", \"print JSON\")\n    .action(async (options) => runCommand(() => runSessionCreate(options), options));\n\n  session\n    .command(\"send\")\n    .description(\"Send a message to an existing Session in the same collaboration scope\")\n    .argument(\"<target-session-id>\", \"target Session ID\")\n    .option(\"--message <text>\", \"message text\")\n    .option(\"--message-file <path>\", \"read the message from a file, or - for stdin\")\n    .option(\"--message-id <uuid>\", \"idempotency key for an explicit retry\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (targetSessionId, options) => runCommand(() => runSessionSend(targetSessionId, options), options));\n\n  session\n    .command(\"list\")\n    .description(\"List internal Sessions created by the implicit managed source Session\")\n    .option(\"--recursive\", \"include all descendant internal Sessions\")\n    .option(\"--limit <count>\", \"page size (maximum 100)\", parsePositiveInteger)\n    .option(\"--cursor <cursor>\", \"opaque cursor returned by the previous page\")\n    .option(\"--since <timestamp>\", \"include Sessions active since this ISO-8601 timestamp\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options) => {\n      try {\n        const result = await runSessionList(options);\n        if (options.json) {\n          process.stdout.write(`${JSON.stringify({ ok: true, result })}\\n`);\n        } else {\n          process.stdout.write(`${formatSessionList(result)}\\n`);\n        }\n      } catch (error) {\n        const commandError = toCommandError(error, \"request\");\n        process.exitCode = presentCommand(\n          { ok: false, error: commandError, exitCode: commandExitCode(commandError) },\n          { json: options.json === true },\n        );\n      }\n    });\n}\n\nfunction writeCommandResult(result: Awaited<ReturnType<typeof runSessionCreate>>, options: OutputOptions): void {\n  process.stdout.write(`${options.json ? JSON.stringify(result) : formatSessionCommandResult(result)}\\n`);\n  if (result.status !== \"accepted\") process.exitCode = 1;\n}\n\nasync function runCommand(\n  operation: () => Promise<Awaited<ReturnType<typeof runSessionCreate>>>,\n  options: OutputOptions,\n): Promise<void> {\n  try {\n    writeCommandResult(await operation(), options);\n  } catch (error) {\n    if (error instanceof SessionCommandRequestError) {\n      process.stderr.write(`${formatSessionCommandError(error, options.json ?? false)}\\n`);\n      const commandError = toCommandError(error.cause, \"request\");\n      process.exitCode = commandExitCode(commandError);\n      return;\n    }\n    const commandError = toCommandError(error, \"request\");\n    process.exitCode = presentCommand(\n      { ok: false, error: commandError, exitCode: commandExitCode(commandError) },\n      { json: options.json === true },\n    );\n  }\n}\n\nfunction parsePositiveInteger(value: string): number {\n  const parsed = Number(value);\n  if (!Number.isSafeInteger(parsed) || parsed < 1) throw new Error(\"Expected a positive integer\");\n  return parsed;\n}\n","import type { OpenTagApi } from \"@opentag/client\";\nimport { resolveCommandContext } from \"../command/context.js\";\nimport { CommandError } from \"../command/policy.js\";\nimport { resolveSessionProofContext } from \"../session/index.js\";\nimport type { SkillApiClient, SkillCommandDependencies } from \"./shared.js\";\n\n/**\n * Decide whether a `skill` command runs as the Agent (Session proof) or as an Account operator.\n *\n * In a managed Session the Agent may push, list, and pull its own Skills but may not name another\n * Agent and may not run the Account lifecycle commands: disabling or deleting a Skill is a human's\n * decision, not the Agent's.\n */\n\nexport type SkillOperation = \"push\" | \"list\" | \"pull\" | \"remove\" | \"enable\" | \"disable\";\n\nconst ACCOUNT_ONLY_OPERATIONS: ReadonlySet<SkillOperation> = new Set([\"remove\", \"enable\", \"disable\"]);\n\nexport type SkillAuthority =\n  | { readonly mode: \"agent\"; readonly api: SkillApiClient; readonly proof: string }\n  | {\n      readonly mode: \"account\";\n      readonly api: SkillApiClient;\n      readonly accessToken: string;\n      readonly agentId: string;\n    };\n\nfunction validationError(code: string, message: string): CommandError {\n  return new CommandError({ code, category: \"validation\", retryability: \"never\", phase: \"validation\" }, message);\n}\n\nasync function agentAuthority(dependencies: SkillCommandDependencies): Promise<SkillAuthority> {\n  if (dependencies.api && dependencies.proof) {\n    return { mode: \"agent\", api: dependencies.api, proof: dependencies.proof };\n  }\n  const { api, proof } = await resolveSessionProofContext(dependencies.environment ?? process.env);\n  return { mode: \"agent\", api: api as SkillApiClient, proof };\n}\n\nasync function accountAuthority(agentId: string, dependencies: SkillCommandDependencies): Promise<SkillAuthority> {\n  const context = await resolveCommandContext({\n    accessToken: dependencies.accessToken,\n    api: dependencies.api as OpenTagApi | undefined,\n    environment: dependencies.environment,\n    home: dependencies.home,\n    requireAuth: true,\n  });\n  if (!context.api || !context.accessToken) {\n    throw new Error(\"Command context did not resolve an authenticated API\");\n  }\n  return {\n    mode: \"account\",\n    api: context.api as SkillApiClient,\n    accessToken: context.accessToken,\n    agentId,\n  };\n}\n\nexport async function resolveSkillCommandContext(\n  operation: SkillOperation,\n  dependencies: SkillCommandDependencies & { agentId?: string } = {},\n): Promise<SkillAuthority> {\n  const environment = dependencies.environment ?? process.env;\n  const agentMode = Boolean(environment.OPENTAG_SESSION_PROOF_FILE) || dependencies.proof !== undefined;\n  if (agentMode) {\n    if (dependencies.agentId !== undefined) {\n      throw validationError(\n        \"SKILL_AGENT_FLAG_FORBIDDEN\",\n        \"--agent is not accepted inside a managed Session; the Skill always belongs to the Session's Agent\",\n      );\n    }\n    if (ACCOUNT_ONLY_OPERATIONS.has(operation)) {\n      throw validationError(\n        \"SKILL_LIFECYCLE_ACCOUNT_ONLY\",\n        `skill ${operation} is an Account action; the Agent manages its Skills by pushing, and lifecycle is a human decision`,\n      );\n    }\n    return agentAuthority(dependencies);\n  }\n  if (dependencies.agentId === undefined) {\n    throw validationError(\"SKILL_AGENT_REQUIRED\", \"--agent <agent-id> is required when not running inside a Session\");\n  }\n  return accountAuthority(dependencies.agentId, dependencies);\n}\n","import { mkdir, readdir, stat } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport {\n  extractSkillArchive,\n  isSkillMaterializationTarget,\n  isSyncedWorkspace,\n  markSkillDirectoryManaged,\n  OpenTagApiError,\n  packSkillDirectory,\n  readBundleBody,\n  resolveMaterializationWorkspace,\n  SKILL_PULL_BUNDLE_TIMEOUT_MS,\n  SkillArchiveError,\n  verifySkillBundle,\n} from \"@opentag/client\";\nimport { type ListAgentSkillsResponse, SKILL_ERROR_CODES, type Skill } from \"@opentag/shared\";\nimport { CommandError } from \"../command/policy.js\";\nimport { resolveSkillCommandContext, type SkillAuthority } from \"./context.js\";\nimport type { SkillCommandDependencies } from \"./shared.js\";\n\n/**\n * The Skill operations the CLI performs.\n *\n * `push` packs the local directory client-side so the user sees manifest and limit errors before a\n * byte is uploaded, and adopts the directory as platform-managed when it is the Skill's own\n * materialization target. `pull` refuses a non-empty destination rather than overwriting an\n * Agent's authored work.\n */\n\nfunction conflictError(name: string, cause: { requestId?: string }): CommandError {\n  return new CommandError(\n    {\n      code: SKILL_ERROR_CODES.NAME_CONFLICT,\n      category: \"conflict\",\n      retryability: \"never\",\n      phase: \"request\",\n      ...(cause.requestId ? { requestId: cause.requestId } : {}),\n    },\n    `A Skill named \"${name}\" already exists; pass --replace to replace it`,\n    { cause },\n  );\n}\n\n/**\n * A name conflict is reported by the server as `SKILL_NAME_CONFLICT`; the shared error envelope\n * admits that code, so the CLI can act on it directly.\n */\nfunction isUploadConflict(error: unknown): error is OpenTagApiError {\n  return error instanceof OpenTagApiError && error.code === SKILL_ERROR_CODES.NAME_CONFLICT;\n}\n\nasync function resolveSkill(nameOrId: string, authority: SkillAuthority): Promise<Skill> {\n  const listing: ListAgentSkillsResponse =\n    authority.mode === \"account\"\n      ? await authority.api.listAgentSkills(authority.accessToken, authority.agentId)\n      : await authority.api.listRuntimeSkills(authority.proof);\n  const match = listing.skills.find((skill) => skill.name === nameOrId || skill.id === nameOrId);\n  if (!match) throw new Error(`No Skill named or identified by \"${nameOrId}\"`);\n  return match;\n}\n\nexport interface SkillPushOptions {\n  agentId?: string;\n  replace?: boolean;\n}\n\nexport interface SkillPushResult {\n  readonly skill: Skill;\n  readonly adopted: boolean;\n  /** Present exactly when `adopted` is false, so the CLI can always explain the outcome. */\n  readonly adoptionReason?: string;\n}\n\n/**\n * Adopt the uploaded directory as platform-managed, and say whether it happened.\n *\n * Adoption is Agent-only: a human pushing from their own checkout must never have a marker written\n * into their repository. Inside a Session the workspace is derived from the directory's own path\n * shape, so `cd`-ing into the skill directory does not change the outcome. A Skill the server\n * reports as disabled is not adopted, because the next sync would remove the authored directory.\n */\nasync function adoptPushedDirectory(\n  directory: string,\n  name: string,\n  authority: SkillAuthority,\n  uploaded: Skill,\n): Promise<{ adopted: boolean; adoptionReason?: string }> {\n  if (authority.mode !== \"agent\") {\n    return { adopted: false, adoptionReason: \"adoption applies only inside an Agent Session\" };\n  }\n  if (!isSkillMaterializationTarget(directory, name)) {\n    return { adopted: false, adoptionReason: \"the directory is not a Skill materialization target\" };\n  }\n  const workspace = resolveMaterializationWorkspace(directory, name);\n  if (workspace === undefined || !(await isSyncedWorkspace(workspace))) {\n    return { adopted: false, adoptionReason: \"the directory is not inside this Agent's synced workspace\" };\n  }\n  if (uploaded.enabled === false) {\n    return { adopted: false, adoptionReason: \"the Skill is disabled on the platform; the next sync would remove it\" };\n  }\n  await markSkillDirectoryManaged(resolve(directory), {\n    skillId: uploaded.id,\n    archiveSha256: uploaded.archiveSha256,\n  });\n  return { adopted: true };\n}\n\nexport async function runSkillPush(\n  directory: string,\n  options: SkillPushOptions,\n  dependencies: SkillCommandDependencies = {},\n): Promise<SkillPushResult> {\n  const packed = await packSkillDirectory(directory);\n  const authority = await resolveSkillCommandContext(\"push\", { ...dependencies, agentId: options.agentId });\n  const input = {\n    archive: packed.archive,\n    sha256: packed.sha256,\n    format: \"tar.gz\" as const,\n    ...(options.replace === true ? { replace: true } : {}),\n  };\n  let uploaded: Skill;\n  try {\n    uploaded =\n      authority.mode === \"account\"\n        ? await authority.api.uploadAgentSkill(authority.accessToken, authority.agentId, input)\n        : await authority.api.pushRuntimeSkill(authority.proof, input);\n  } catch (error) {\n    if (isUploadConflict(error)) throw conflictError(packed.name, error);\n    throw error;\n  }\n  const adoption = await adoptPushedDirectory(directory, packed.name, authority, uploaded);\n  return { skill: uploaded, ...adoption };\n}\n\nexport async function runSkillList(\n  options: { agentId?: string },\n  dependencies: SkillCommandDependencies = {},\n): Promise<ListAgentSkillsResponse> {\n  const authority = await resolveSkillCommandContext(\"list\", { ...dependencies, agentId: options.agentId });\n  return authority.mode === \"account\"\n    ? await authority.api.listAgentSkills(authority.accessToken, authority.agentId)\n    : await authority.api.listRuntimeSkills(authority.proof);\n}\n\nexport interface SkillPullOptions {\n  agentId?: string;\n  outDir?: string;\n}\n\nasync function assertEmptyDestination(directory: string): Promise<void> {\n  let present: boolean;\n  try {\n    present = (await stat(directory)).isDirectory();\n  } catch {\n    return;\n  }\n  if (!present) {\n    throw new CommandError(\n      { code: \"SKILL_PULL_DESTINATION_INVALID\", category: \"validation\", retryability: \"never\", phase: \"validation\" },\n      `Pull destination is not a directory: ${directory}`,\n    );\n  }\n  if ((await readdir(directory)).length > 0) {\n    throw new CommandError(\n      { code: \"SKILL_PULL_DESTINATION_NOT_EMPTY\", category: \"validation\", retryability: \"never\", phase: \"validation\" },\n      `Pull destination is not empty: ${directory}`,\n    );\n  }\n}\n\nexport async function runSkillPull(\n  nameOrId: string,\n  options: SkillPullOptions,\n  dependencies: SkillCommandDependencies = {},\n): Promise<{ skill: Skill; directory: string }> {\n  const authority = await resolveSkillCommandContext(\"pull\", { ...dependencies, agentId: options.agentId });\n  const skill = await resolveSkill(nameOrId, authority);\n  const directory = resolve(options.outDir ?? join(dependencies.cwd ?? process.cwd(), skill.name));\n  await assertEmptyDestination(directory);\n  const signal = AbortSignal.timeout(SKILL_PULL_BUNDLE_TIMEOUT_MS);\n  const response =\n    authority.mode === \"account\"\n      ? await authority.api.openAgentSkillBundle(authority.accessToken, authority.agentId, skill.id, { signal })\n      : await authority.api.openRuntimeSkillBundle(authority.proof, skill.name, { signal });\n  const bytes = await readBundleBody(response, { signal, maxBytes: skill.archiveBytes });\n  verifySkillBundle(bytes, {\n    archiveBytes: skill.archiveBytes,\n    archiveSha256: skill.archiveSha256,\n    name: skill.name,\n  });\n  await mkdir(resolve(directory, \"..\"), { recursive: true, mode: 0o700 });\n  try {\n    await extractSkillArchive(Readable.from(Buffer.from(bytes)), directory);\n  } catch (error) {\n    if (error instanceof SkillArchiveError && error.code === \"destination_not_empty\") {\n      throw new CommandError(\n        {\n          code: \"SKILL_PULL_DESTINATION_NOT_EMPTY\",\n          category: \"validation\",\n          retryability: \"never\",\n          phase: \"validation\",\n        },\n        `Pull destination is not empty: ${directory}`,\n        { cause: error },\n      );\n    }\n    throw error;\n  }\n  return { skill, directory };\n}\n\nexport async function runSkillRemove(\n  nameOrId: string,\n  options: { agentId?: string },\n  dependencies: SkillCommandDependencies = {},\n): Promise<Skill> {\n  const authority = await resolveSkillCommandContext(\"remove\", { ...dependencies, agentId: options.agentId });\n  const skill = await resolveSkill(nameOrId, authority);\n  /* The Session-proof path is rejected in `resolveSkillCommandContext`, so only an operator reaches here. */\n  if (authority.mode !== \"account\") throw new Error(\"Removing a Skill requires an Account operator\");\n  await authority.api.removeAgentSkill(authority.accessToken, authority.agentId, skill.id);\n  return skill;\n}\n\nexport async function runSkillSetEnabled(\n  nameOrId: string,\n  enabled: boolean,\n  options: { agentId?: string },\n  dependencies: SkillCommandDependencies = {},\n): Promise<Skill> {\n  const authority = await resolveSkillCommandContext(enabled ? \"enable\" : \"disable\", {\n    ...dependencies,\n    agentId: options.agentId,\n  });\n  const skill = await resolveSkill(nameOrId, authority);\n  if (authority.mode !== \"account\") throw new Error(\"Changing a Skill's state requires an Account operator\");\n  return await authority.api.updateAgentSkill(authority.accessToken, authority.agentId, skill.id, { enabled });\n}\n","import type { OpenTagApi } from \"@opentag/client\";\nimport type { ListAgentSkillsResponse, Skill } from \"@opentag/shared\";\nimport type { SkillPushResult } from \"./operations.js\";\n\n/**\n * Shared plumbing for the `skill` commands.\n *\n * A Skill is owned by exactly one Agent, so every command either names its Agent (an Account\n * operator) or is scoped by the Session proof (the Agent itself). `context.ts` decides which, and\n * these helpers only format what the operations return.\n */\n\nexport interface SkillApiClient\n  extends Pick<\n    OpenTagApi,\n    | \"listAgentSkills\"\n    | \"uploadAgentSkill\"\n    | \"updateAgentSkill\"\n    | \"removeAgentSkill\"\n    | \"openAgentSkillBundle\"\n    | \"listRuntimeSkills\"\n    | \"pushRuntimeSkill\"\n    | \"openRuntimeSkillBundle\"\n  > {}\n\nexport interface SkillCommandDependencies {\n  accessToken?: string;\n  api?: SkillApiClient;\n  home?: string;\n  environment?: NodeJS.ProcessEnv;\n  proof?: string;\n  cwd?: string;\n}\n\nexport function formatSkill(skill: Skill): string {\n  return [\n    `id\\t${skill.id}`,\n    `name\\t${skill.name}`,\n    `description\\t${skill.description}`,\n    `enabled\\t${skill.enabled}`,\n    `source\\t${skill.source}`,\n    `revision\\t${skill.revision}`,\n    `bytes\\t${skill.archiveBytes}`,\n    `files\\t${skill.fileCount}`,\n    `sha256\\t${skill.archiveSha256}`,\n    `updatedAt\\t${skill.updatedAt}`,\n  ].join(\"\\n\");\n}\n\nexport function formatSkillPush(result: SkillPushResult): string {\n  return [\n    formatSkill(result.skill),\n    `adopted\\t${result.adopted}`,\n    ...(result.adoptionReason === undefined ? [] : [`adoptionReason\\t${result.adoptionReason}`]),\n  ].join(\"\\n\");\n}\n\nexport function formatSkillList(result: ListAgentSkillsResponse): string {\n  if (result.skills.length === 0) return `No Skills configured (storage: ${result.storage})`;\n  return [\n    [\"NAME\", \"ENABLED\", \"SOURCE\", \"FILES\", \"REVISION\", \"UPDATED\"].join(\"\\t\"),\n    ...result.skills.map((skill) =>\n      [\n        skill.name,\n        skill.enabled ? \"enabled\" : \"disabled\",\n        skill.source,\n        String(skill.fileCount),\n        String(skill.revision),\n        skill.updatedAt,\n      ].join(\"\\t\"),\n    ),\n    `storage\\t${result.storage}`,\n  ].join(\"\\n\");\n}\n\nexport function formatSkillPull(result: { skill: Skill; directory: string }): string {\n  return [`name\\t${result.skill.name}`, `directory\\t${result.directory}`].join(\"\\n\");\n}\n\nexport function formatSkillRemoval(skill: Skill): string {\n  return `Removed Skill ${skill.name}`;\n}\n\nexport function formatSkillEnabled(skill: Skill): string {\n  return `${skill.enabled ? \"Enabled\" : \"Disabled\"} Skill ${skill.name}`;\n}\n","import type { Command } from \"commander\";\nimport { executeCommand } from \"../../core/command/policy.js\";\nimport {\n  runSkillList,\n  runSkillPull,\n  runSkillPush,\n  runSkillRemove,\n  runSkillSetEnabled,\n} from \"../../core/skill/operations.js\";\nimport {\n  formatSkillEnabled,\n  formatSkillList,\n  formatSkillPull,\n  formatSkillPush,\n  formatSkillRemoval,\n} from \"../../core/skill/shared.js\";\n\n/**\n * `skill` — the Agent's own Skills.\n *\n * Inside a managed Session the Agent may push, list, and pull its own Skills; outside one an\n * operator names an Agent with `--agent`. `context.ts` enforces both, so `--agent` is optional here\n * and rejected only when a Session proof is present.\n */\nexport function registerSkillCommand(program: Command): void {\n  const skill = program.command(\"skill\").description(\"Manage an Agent's Agent Skills\");\n\n  skill\n    .command(\"push <dir>\")\n    .description(\"Upload a local skill directory (requires SKILL.md); adopts it if it is the Skill's target\")\n    .option(\"--agent <agent-id>\", \"the Agent that owns the Skill, as an Account operator\")\n    .option(\"--replace\", \"replace an existing Skill with the same name\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (dir: string, options: { agent?: string; replace?: boolean; json?: boolean }) => {\n      process.exitCode = await executeCommand(\n        () =>\n          runSkillPush(dir, {\n            ...(options.agent === undefined ? {} : { agentId: options.agent }),\n            ...(options.replace === true ? { replace: true } : {}),\n          }),\n        { json: options.json === true, formatValue: formatSkillPush, phase: \"request\" },\n      );\n    });\n\n  skill\n    .command(\"list\")\n    .description(\"List the Agent's Skills\")\n    .option(\"--agent <agent-id>\", \"the Agent whose Skills to list, as an Account operator\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (options: { agent?: string; json?: boolean }) => {\n      process.exitCode = await executeCommand(\n        () => runSkillList(options.agent === undefined ? {} : { agentId: options.agent }),\n        { json: options.json === true, formatValue: formatSkillList, phase: \"request\" },\n      );\n    });\n\n  skill\n    .command(\"pull <name>\")\n    .description(\"Download a Skill into an empty directory\")\n    .option(\"--agent <agent-id>\", \"the Agent that owns the Skill, as an Account operator\")\n    .option(\"--out <dir>\", \"destination directory; defaults to <name> under the current directory\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (name: string, options: { agent?: string; out?: string; json?: boolean }) => {\n      process.exitCode = await executeCommand(\n        () =>\n          runSkillPull(name, {\n            ...(options.agent === undefined ? {} : { agentId: options.agent }),\n            ...(options.out === undefined ? {} : { outDir: options.out }),\n          }),\n        { json: options.json === true, formatValue: formatSkillPull, phase: \"request\" },\n      );\n    });\n\n  skill\n    .command(\"remove <name>\")\n    .description(\"Delete a Skill; an Account operator may do this, an Agent may not\")\n    .option(\"--agent <agent-id>\", \"the Agent that owns the Skill, as an Account operator\")\n    .option(\"--json\", \"print JSON\")\n    .action(async (name: string, options: { agent?: string; json?: boolean }) => {\n      process.exitCode = await executeCommand(\n        () => runSkillRemove(name, options.agent === undefined ? {} : { agentId: options.agent }),\n        { json: options.json === true, formatValue: formatSkillRemoval, phase: \"request\" },\n      );\n    });\n\n  for (const [name, enabled] of [\n    [\"enable\", true],\n    [\"disable\", false],\n  ] as const) {\n    skill\n      .command(`${name} <name>`)\n      .description(enabled ? \"Enable a Skill for its Agent\" : \"Disable a Skill, keeping it stored\")\n      .option(\"--agent <agent-id>\", \"the Agent that owns the Skill, as an Account operator\")\n      .option(\"--json\", \"print JSON\")\n      .action(async (skillName: string, options: { agent?: string; json?: boolean }) => {\n        process.exitCode = await executeCommand(\n          () => runSkillSetEnabled(skillName, enabled, options.agent === undefined ? {} : { agentId: options.agent }),\n          { json: options.json === true, formatValue: formatSkillEnabled, phase: \"request\" },\n        );\n      });\n  }\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { resolveOpenTagHome, type UpdaterStateSnapshot } from \"@opentag/client\";\nimport { type ChannelName, compareSemVer, getChannelConfig, parseSemVer } from \"@opentag/shared\";\nimport { CHANNEL, CLI_VERSION } from \"../../build-info.js\";\nimport { type DaemonServiceReconcileResult, reconcileDaemonService } from \"../daemon/reconcile-service.js\";\nimport { detectInstallMode, type InstallMode } from \"./install-mode.js\";\nimport { DEFAULT_DOWNLOAD_BASE_URL, installPortableTarget } from \"./portable-installer.js\";\nimport { readUpdaterState, writeUpdaterState } from \"./updater-state.js\";\n\nconst execFileAsync = promisify(execFile);\nconst DEFAULT_NPM_REGISTRY_URL = \"https://registry.npmjs.org\";\n\nexport class UpgradeError extends Error {\n  override readonly name = \"UpgradeError\";\n}\n\nexport interface UpgradeOptions {\n  /** Report the target without installing anything. */\n  check?: boolean;\n  /** Release channel override (tests); defaults to this build's channel. */\n  channel?: ChannelName;\n  /** Running CLI version override for deterministic exact-target tests. */\n  currentVersion?: string;\n  home?: string;\n  environment?: NodeJS.ProcessEnv;\n  installMode?: InstallMode;\n  fetchFn?: typeof fetch;\n  /** Injectable npm runner (tests); defaults to executing `npm` on PATH. */\n  runNpm?: (args: readonly string[]) => Promise<void>;\n  /** Injectable portable install step (tests). */\n  installPortable?: (target: string) => Promise<void> | Promise<{ cleanupFailure?: string }>;\n  /** Injectable service reconciliation (tests). */\n  reconcileService?: () => Promise<DaemonServiceReconcileResult>;\n  /** Injectable durable-state writer (tests). */\n  writeState?: typeof writeUpdaterState;\n  now?: () => number;\n}\n\nexport interface UpgradeResult {\n  exitCode: 0 | 1;\n  currentVersion: string;\n  targetVersion?: string;\n  status: \"error\" | \"up-to-date\" | \"ahead\" | \"available\" | \"installed\";\n  installMode: InstallMode[\"mode\"];\n  serviceRefresh?: \"ready\" | \"deferred\" | \"failed\";\n  message: string;\n}\n\ninterface ResolvedTarget {\n  version: string;\n}\n\nasync function resolveChannelTarget(\n  mode: InstallMode,\n  channel: ChannelName,\n  packageName: string,\n  fetchFn: typeof fetch,\n  environment: NodeJS.ProcessEnv,\n): Promise<ResolvedTarget> {\n  if (mode.mode === \"portable\") {\n    const base = (environment.OPENTAG_PORTABLE_DOWNLOAD_BASE_URL ?? DEFAULT_DOWNLOAD_BASE_URL).replace(/\\/+$/, \"\");\n    const url = `${base}/${channel}/latest.json`;\n    const body = await fetchJson(fetchFn, url, \"the channel release pointer\");\n    const pointer = body as Record<string, unknown>;\n    if (pointer.channel !== channel) {\n      throw new UpgradeError(\"The channel release pointer belongs to another channel\");\n    }\n    return { version: requireSemVer(pointer.version, \"the channel release pointer\") };\n  }\n  const registry = (environment.OPENTAG_NPM_REGISTRY_URL ?? DEFAULT_NPM_REGISTRY_URL).replace(/\\/+$/, \"\");\n  const url = `${registry}/${packageName}`;\n  const body = await fetchJson(fetchFn, url, \"the npm registry metadata\", {\n    accept: \"application/vnd.npm.install-v1+json\",\n  });\n  const packument = body as Record<string, unknown>;\n  const distTags = packument[\"dist-tags\"];\n  const latest =\n    distTags && typeof distTags === \"object\" && !Array.isArray(distTags)\n      ? (distTags as Record<string, unknown>).latest\n      : undefined;\n  return { version: requireSemVer(latest, \"the npm registry metadata\") };\n}\n\nfunction requireSemVer(value: unknown, source: string): string {\n  if (typeof value !== \"string\" || !parseSemVer(value)) {\n    throw new UpgradeError(`The exact channel target is missing or invalid in ${source}`);\n  }\n  return value;\n}\n\nasync function fetchJson(\n  fetchFn: typeof fetch,\n  url: string,\n  label: string,\n  headers: Record<string, string> = { accept: \"application/json\" },\n): Promise<unknown> {\n  let response: Response;\n  try {\n    response = await fetchFn(url, { headers, signal: AbortSignal.timeout(30_000) });\n  } catch (error) {\n    throw new UpgradeError(`Could not read ${label}: ${error instanceof Error ? error.message : String(error)}`);\n  }\n  if (!response.ok) throw new UpgradeError(`Could not read ${label} (HTTP ${response.status})`);\n  try {\n    return await response.json();\n  } catch {\n    throw new UpgradeError(`The response from ${label} is not valid JSON`);\n  }\n}\n\nasync function defaultRunNpm(args: readonly string[]): Promise<void> {\n  try {\n    await execFileAsync(\"npm\", [...args]);\n  } catch (error) {\n    throw new UpgradeError(`npm ${args.join(\" \")} failed: ${error instanceof Error ? error.message : String(error)}`);\n  }\n}\n\ninterface UpgradeContext {\n  currentVersion: string;\n  channel: ChannelName;\n  channelConfig: ReturnType<typeof getChannelConfig>;\n  environment: NodeJS.ProcessEnv;\n  installMode: InstallMode;\n  home: string;\n}\n\ninterface ServiceRefreshResult {\n  serviceRefresh: NonNullable<UpgradeResult[\"serviceRefresh\"]>;\n  serviceMessage: string;\n}\n\nfunction createUpgradeContext(options: UpgradeOptions): UpgradeContext {\n  const channel = options.channel ?? CHANNEL;\n  const environment = options.environment ?? process.env;\n  return {\n    currentVersion: options.currentVersion ?? CLI_VERSION,\n    channel,\n    channelConfig: getChannelConfig(channel),\n    environment,\n    installMode: options.installMode ?? detectInstallMode(environment),\n    home: options.home ?? resolveOpenTagHome(environment),\n  };\n}\n\nfunction finishUpgrade(\n  context: UpgradeContext,\n  result: Omit<UpgradeResult, \"currentVersion\" | \"installMode\">,\n): UpgradeResult {\n  return { currentVersion: context.currentVersion, installMode: context.installMode.mode, ...result };\n}\n\nfunction errorMessage(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n\nasync function currentTargetNeedsRepair(home: string, target: string): Promise<boolean> {\n  const loaded = await readUpdaterState(home);\n  if (loaded.status !== \"ok\") return true;\n  return (\n    loaded.state.target !== target ||\n    loaded.state.state !== \"installed\" ||\n    loaded.state.attempts[target]?.result !== \"installed\"\n  );\n}\n\nasync function noInstallResult(\n  context: UpgradeContext,\n  target: ResolvedTarget,\n  comparison: -1 | 0 | 1,\n  check: boolean,\n): Promise<UpgradeResult | undefined> {\n  const exactCurrent = target.version === context.currentVersion;\n  if (exactCurrent && (check || !(await currentTargetNeedsRepair(context.home, target.version)))) {\n    return finishUpgrade(context, {\n      exitCode: 0,\n      status: \"up-to-date\",\n      targetVersion: target.version,\n      message: `OpenTag ${context.currentVersion} is already the exact ${context.channel} channel target`,\n    });\n  }\n  if (comparison < 0) {\n    return finishUpgrade(context, {\n      exitCode: 0,\n      status: \"ahead\",\n      targetVersion: target.version,\n      message: `OpenTag ${context.currentVersion} is ahead of the ${context.channel} channel target ${target.version}; nothing to do`,\n    });\n  }\n  if (comparison >= 0 && check) {\n    return finishUpgrade(context, {\n      exitCode: 0,\n      status: \"available\",\n      targetVersion: target.version,\n      message: `OpenTag ${target.version} is available on the ${context.channel} channel (running ${context.currentVersion})`,\n    });\n  }\n  return undefined;\n}\n\nasync function installResolvedTarget(\n  context: UpgradeContext,\n  target: string,\n  options: UpgradeOptions,\n): Promise<string | undefined> {\n  // The exact target is already running. Manual upgrade repairs durable state and the supervisor\n  // definition without reinstalling identical bytes.\n  if (target === context.currentVersion) return undefined;\n  if (context.installMode.mode === \"npm-global\") {\n    await (options.runNpm ?? defaultRunNpm)([\"install\", \"-g\", `${context.channelConfig.packageName}@${target}`]);\n    return undefined;\n  }\n  if (options.installPortable) {\n    const result = await options.installPortable(target);\n    return result && typeof result === \"object\" ? result.cleanupFailure : undefined;\n  }\n  const result = await installPortableTarget({\n    channel: context.channel,\n    targetVersion: target,\n    root: context.installMode.root,\n    binDir: context.installMode.binDir,\n    binName: context.channelConfig.binName,\n    packageName: context.channelConfig.packageName,\n    ...(context.environment.OPENTAG_PORTABLE_DOWNLOAD_BASE_URL\n      ? { downloadBaseUrl: context.environment.OPENTAG_PORTABLE_DOWNLOAD_BASE_URL }\n      : {}),\n  });\n  return result.cleanupFailure;\n}\n\nasync function prepareUpgradeState(home: string, target: string, now: number): Promise<UpdaterStateSnapshot> {\n  const loaded = await readUpdaterState(home);\n  const state: UpdaterStateSnapshot =\n    loaded.status === \"ok\" ? loaded.state : { schemaVersion: 1, currentVersion: target, state: \"idle\", attempts: {} };\n  const attempt = {\n    target,\n    startedAt: new Date(now).toISOString(),\n  };\n  state.currentVersion = target;\n  state.state = \"installing\";\n  state.target = target;\n  state.attempts[target] = attempt;\n  state.lastAttempt = attempt;\n  return state;\n}\n\nasync function recordInstalledUpgrade(\n  home: string,\n  target: string,\n  now: number,\n  state: UpdaterStateSnapshot,\n  writeState: typeof writeUpdaterState,\n): Promise<string | undefined> {\n  const attempt = state.attempts[target];\n  if (!attempt) throw new UpgradeError(\"The updater attempt disappeared before it could be recorded\");\n  attempt.finishedAt = new Date(now).toISOString();\n  attempt.result = \"installed\";\n  delete attempt.failureReason;\n  state.currentVersion = target;\n  state.state = \"installed\";\n  state.target = target;\n  state.lastAttempt = attempt;\n  try {\n    await writeState(home, state);\n    return undefined;\n  } catch (error) {\n    return errorMessage(error);\n  }\n}\n\nasync function refreshDaemonService(\n  home: string,\n  target: string,\n  state: UpdaterStateSnapshot,\n  reconcile: () => Promise<DaemonServiceReconcileResult>,\n  writeState: typeof writeUpdaterState,\n): Promise<ServiceRefreshResult> {\n  try {\n    const reconciled = await reconcile();\n    const deferred = reconciled.status === \"deferred\";\n    return {\n      serviceRefresh: deferred ? \"deferred\" : \"ready\",\n      serviceMessage:\n        deferred && reconciled.reason === \"credentials-missing\" ? \" (service setup deferred until login)\" : \"\",\n    };\n  } catch (error) {\n    const failureReason = errorMessage(error);\n    const attempt = state.attempts[target];\n    state.state = \"blocked\";\n    if (attempt) {\n      attempt.result = \"failed\";\n      attempt.failureReason = failureReason;\n      state.lastAttempt = attempt;\n    }\n    try {\n      await writeState(home, state);\n      return { serviceRefresh: \"failed\", serviceMessage: `; the daemon service refresh failed: ${failureReason}` };\n    } catch (stateError) {\n      return {\n        serviceRefresh: \"failed\",\n        serviceMessage: `; the daemon service refresh failed: ${failureReason}; recording the blocked updater state also failed: ${errorMessage(stateError)}`,\n      };\n    }\n  }\n}\n\n/**\n * Manual upgrade for both install modes. This is the only upgrade path for npm-global installs\n * (they never auto-install), and the operator-driven repair path for a blocked portable target.\n * Both modes install the exact channel target, refresh the daemon service, and record the outcome\n * so the daemon's automatic updater never re-attempts it.\n */\nexport async function runUpgrade(options: UpgradeOptions = {}): Promise<UpgradeResult> {\n  const context = createUpgradeContext(options);\n  if (context.channel === \"dev\") {\n    return finishUpgrade(context, {\n      exitCode: 1,\n      status: \"error\",\n      message: \"Upgrades are available on the staging and production channels only\",\n    });\n  }\n\n  let target: ResolvedTarget;\n  try {\n    target = await resolveChannelTarget(\n      context.installMode,\n      context.channel,\n      context.channelConfig.packageName,\n      options.fetchFn ?? fetch,\n      context.environment,\n    );\n  } catch (error) {\n    return finishUpgrade(context, { exitCode: 1, status: \"error\", message: errorMessage(error) });\n  }\n\n  const comparison = compareSemVer(target.version, context.currentVersion);\n  const noInstall = await noInstallResult(context, target, comparison, options.check ?? false);\n  if (noInstall) return noInstall;\n\n  let installWarning: string | undefined;\n  try {\n    installWarning = await installResolvedTarget(context, target.version, options);\n  } catch (error) {\n    return finishUpgrade(context, {\n      exitCode: 1,\n      status: \"error\",\n      targetVersion: target.version,\n      message: errorMessage(error),\n    });\n  }\n\n  const now = (options.now ?? Date.now)();\n  const state = await prepareUpgradeState(context.home, target.version, now);\n\n  const { serviceRefresh, serviceMessage } = await refreshDaemonService(\n    context.home,\n    target.version,\n    state,\n    options.reconcileService ?? reconcileDaemonService,\n    options.writeState ?? writeUpdaterState,\n  );\n  const persistenceFailure =\n    serviceRefresh === \"failed\"\n      ? undefined\n      : await recordInstalledUpgrade(context.home, target.version, now, state, options.writeState ?? writeUpdaterState);\n\n  return finishUpgrade(context, {\n    exitCode: serviceRefresh === \"failed\" || persistenceFailure ? 1 : 0,\n    status: \"installed\",\n    targetVersion: target.version,\n    serviceRefresh,\n    message: `OpenTag ${target.version} installed (${context.installMode.mode})${serviceMessage}${persistenceFailure ? `; recording the installed updater state failed: ${persistenceFailure}` : \"\"}${installWarning ? `; warning: ${installWarning}` : \"\"}`,\n  });\n}\n","import type { Command } from \"commander\";\nimport { runUpgrade } from \"../core/update/manual-upgrade.js\";\n\nexport function registerUpgradeCommand(program: Command): void {\n  program\n    .command(\"upgrade\")\n    .description(\"Upgrade OpenTag to the exact channel target (manual path; portable daemons upgrade automatically)\")\n    .option(\"--check\", \"Report the channel target without installing anything\")\n    .action(async (options: { check?: boolean }) => {\n      const result = await runUpgrade({ check: options.check === true });\n      const write = result.exitCode === 0 ? process.stdout : process.stderr;\n      write.write(`${result.message}\\n`);\n      process.exitCode = result.exitCode;\n    });\n}\n","import { Command } from \"commander\";\nimport { CLI_VERSION } from \"../build-info.js\";\nimport { registerAgentCommand } from \"../commands/agent/index.js\";\nimport { registerComputerConnectCommand } from \"../commands/computer/connect.js\";\nimport { registerComputerCommand } from \"../commands/computer/index.js\";\nimport { registerDaemonCommand } from \"../commands/daemon/index.js\";\nimport { registerDoctorCommand } from \"../commands/doctor.js\";\nimport { registerLoginCommand } from \"../commands/login.js\";\nimport { registerLogsCommand } from \"../commands/logs.js\";\nimport { registerMcpCommand } from \"../commands/mcp/index.js\";\nimport { registerProviderCliCommand } from \"../commands/provider-cli.js\";\nimport { registerSessionCommand } from \"../commands/session/index.js\";\nimport { registerSkillCommand } from \"../commands/skill/index.js\";\nimport { registerUpgradeCommand } from \"../commands/upgrade.js\";\nimport { channelConfig } from \"../core/channel/config.js\";\n\nexport function createProgram(options: { json?: boolean } = {}): Command {\n  const program = new Command();\n  program\n    .name(channelConfig.binName)\n    .description(\"OpenTag command-line interface\")\n    .version(CLI_VERSION)\n    .showHelpAfterError()\n    // Throw rather than exit inside Commander so the process entrypoint owns the failure\n    // envelope and the usage exit code for every command, not just the ones that override.\n    .exitOverride();\n  if (options.json) {\n    // A --json caller reads exactly one failure document from the entrypoint; Commander's own\n    // human error and help-after-error text would corrupt that stream, so it is suppressed.\n    program.configureOutput({ writeErr: () => undefined });\n  }\n  // The onboarding command is top-level so an Agent can run the copied setup command without\n  // needing to know the CLI's resource hierarchy. Keep `computer connect` as a compatible alias.\n  registerComputerConnectCommand(program);\n  registerComputerCommand(program);\n  registerAgentCommand(program);\n  registerDaemonCommand(program);\n  registerDoctorCommand(program);\n  registerLoginCommand(program);\n  registerLogsCommand(program);\n  registerMcpCommand(program);\n  registerProviderCliCommand(program);\n  registerSessionCommand(program);\n  registerSkillCommand(program);\n  registerUpgradeCommand(program);\n  return program;\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,129,130,131,132,133,134,135],"mappings":";;;;;;;;;;;;;;;;;;;AAgBA,SAAgB,cAAc,SAAS;CACnC,MAAM,gBAAgB,OAAO,OAAO,OAAO,CAAC,CAAC,QAAQ,MAAM,OAAO,MAAM,QAAQ;CAIhF,OAHe,OAAO,QAAQ,OAAO,CAAC,CACjC,QAAQ,CAAC,GAAG,OAAO,cAAc,QAAQ,CAAC,CAAC,MAAM,EAAE,CAAC,CACpD,KAAK,CAAC,GAAG,OAAO,CACT;AAChB;AACA,SAAgB,WAAW,OAAO,YAAY,KAAK;CAC/C,OAAO,MAAM,KAAK,QAAQ,mBAAmB,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AClC,MAAM,oBAAoB;CACzB,WAAW;CACX,eAAe;CACf,mBAAmB;CACnB,eAAe;CACf,eAAe;CACf,kBAAkB;CAClB,iBAAiB;CACjB,eAAe;CACf,mBAAmB;CACnB,qBAAqB;AACtB;AAEE,kBAAkB,WAIlB,kBAAkB,eAIlB,kBAAkB,mBAIlB,kBAAkB,eAIlB,kBAAkB,eAIlB,kBAAkB,kBAIlB,kBAAkB,iBAIlB,kBAAkB,eAIlB,kBAAkB,mBAIlB,kBAAkB;AAOpB,MAAM,sBAAsBG,MAAO;CAClC;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,kBAAkBA,MAAO;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG,OAAO,OAAO,eAAe;CAChC,GAAG,OAAO,OAAO,iBAAiB;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,wBAAwBH,OAAS;CACtC,MAAMC,MAAQI,MAAQ,CAACN,OAAS,GAAGG,SAAS,CAAC,CAAC,CAAC;CAC/C,MAAMH,OAAS,CAAC,CAAC,IAAI,CAAC;CACtB,SAASA,OAAS,CAAC,CAAC,IAAI,CAAC;AAC1B,CAAC,CAAC,CAAC,OAAO;AAgBV,MAAM,sBAAsBC,OAAS,EAAE,OAfbA,OAAS;CAClC,MAAM;CACN,UAAU;CACV,SAASD,OAAS,CAAC,CAAC,IAAI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