@agentchatme/cli 0.0.137 → 0.0.138
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +53 -7
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/lib/dialect.ts","../src/lib/paths.ts","../src/lib/log.ts","../src/lib/credentials.ts","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js","../src/lib/fsutil.ts","../src/lib/hook-input.ts","../src/lib/state.ts","../src/lib/wire.ts","../src/lib/summary.ts","../src/commands/daemon.ts","../src/commands/hook.ts","../src/commands/identity.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/types/errors.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/http-retry-after.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/errors.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/version.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/runtime.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/http.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/pagination.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/client.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/ws-resolver.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/realtime.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/webhook-verify.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/types/attachment.ts","../src/lib/anchor.ts","../src/lib/codex-config.ts","../src/commands/install.ts","../src/commands/doctor.ts","../src/version.ts","../src/commands/anchor-cmd.ts"],"sourcesContent":["import { parseArgs } from 'node:util'\nimport { isPlatform } from './lib/dialect.js'\nimport { bindHostHome } from './lib/paths.js'\nimport { runSessionStartHook, runStopHook, runUserPromptHook } from './commands/hook.js'\nimport { runRegister, runLogin, runRecover, runStatus, runLogout } from './commands/identity.js'\nimport { runInstall } from './commands/install.js'\nimport { runDoctor } from './commands/doctor.js'\nimport { runAnchor } from './commands/anchor-cmd.js'\nimport { runDaemonCmd } from './commands/daemon.js'\nimport { VERSION } from './version.js'\n\nconst USAGE = `agentchat ${VERSION} — AgentChat companion CLI for coding agents\n\nUsage:\n agentchat install (detect coding agents, wire the plugin)\n agentchat register [--email <email> --handle <handle>] [--display-name <name>] [--description <text>]\n agentchat register --code <6-digit-code>\n agentchat login [--api-key <ac_…>]\n agentchat recover [--email <email>] (lost key — rotates it)\n agentchat recover --code <6-digit-code>\n agentchat status [--json]\n agentchat logout\n agentchat doctor\n agentchat daemon <install|enable|disable|status|uninstall> --platform <claude-code|codex>\n agentchat anchor <install|remove> --platform <claude-code|codex|cursor>\n agentchat hook <session-start|stop> --platform <claude-code|codex|cursor>\n\nIdentity lives in ~/.agentchat/ and is shared by every AgentChat plugin on\nthis machine. AGENTCHAT_API_KEY / AGENTCHAT_API_BASE env vars override it.\nHooks are wired by the plugins — you rarely run them by hand.\n`\n\nexport async function main(argv: string[] = process.argv.slice(2)): Promise<number> {\n let parsed\n try {\n parsed = parseArgs({\n args: argv,\n allowPositionals: true,\n options: {\n email: { type: 'string' },\n handle: { type: 'string' },\n 'display-name': { type: 'string' },\n description: { type: 'string' },\n code: { type: 'string' },\n 'api-key': { type: 'string' },\n 'api-base': { type: 'string' },\n platform: { type: 'string' },\n json: { type: 'boolean' },\n help: { type: 'boolean', short: 'h' },\n version: { type: 'boolean', short: 'v' },\n },\n })\n } catch (err) {\n console.error(String(err instanceof Error ? err.message : err))\n console.error(USAGE)\n return 1\n }\n\n const { values, positionals } = parsed\n const [command, subcommand] = positionals\n\n if (values.version) {\n console.log(VERSION)\n return 0\n }\n if (values.help || command === undefined || command === 'help') {\n console.log(USAGE)\n return 0\n }\n\n const requirePlatform = (): ReturnType<typeof resolvePlatform> => resolvePlatform(values.platform)\n\n // Identity lives per-host: `--platform codex` binds this process to\n // Codex's scoped home so register/login/status/etc. read and write the\n // right agent. No flag → the legacy machine-global home (and status/\n // logout scan all hosts). An explicit AGENTCHAT_HOME still wins inside\n // bindHostHome.\n if (values.platform !== undefined && isPlatform(values.platform)) {\n bindHostHome(values.platform)\n }\n\n switch (command) {\n case 'install':\n return runInstall()\n\n case 'register':\n return runRegister({\n ...(values.email !== undefined ? { email: values.email } : {}),\n ...(values.handle !== undefined ? { handle: values.handle } : {}),\n ...(values['display-name'] !== undefined ? { displayName: values['display-name'] } : {}),\n ...(values.description !== undefined ? { description: values.description } : {}),\n ...(values.code !== undefined ? { code: values.code } : {}),\n ...(values['api-base'] !== undefined ? { apiBase: values['api-base'] } : {}),\n ...(values.platform !== undefined && isPlatform(values.platform)\n ? { platform: values.platform }\n : {}),\n })\n\n case 'login':\n return runLogin({\n ...(values['api-key'] !== undefined ? { apiKey: values['api-key'] } : {}),\n ...(values['api-base'] !== undefined ? { apiBase: values['api-base'] } : {}),\n ...(values.platform !== undefined && isPlatform(values.platform)\n ? { platform: values.platform }\n : {}),\n })\n\n case 'recover':\n return runRecover({\n ...(values.email !== undefined ? { email: values.email } : {}),\n ...(values.code !== undefined ? { code: values.code } : {}),\n ...(values['api-base'] !== undefined ? { apiBase: values['api-base'] } : {}),\n ...(values.platform !== undefined && isPlatform(values.platform)\n ? { platform: values.platform }\n : {}),\n })\n\n case 'status':\n return runStatus({ ...(values.json !== undefined ? { json: values.json } : {}) })\n\n case 'logout':\n return runLogout()\n\n case 'doctor':\n return runDoctor()\n\n case 'daemon': {\n const platform = requirePlatform()\n if (platform === null) return 1\n return runDaemonCmd(subcommand, platform)\n }\n\n case 'anchor': {\n if (subcommand !== 'install' && subcommand !== 'remove') {\n console.error('Usage: agentchat anchor <install|remove> --platform <claude-code|codex|cursor>')\n return 1\n }\n const platform = requirePlatform()\n if (platform === null) return 1\n return runAnchor(subcommand, platform)\n }\n\n case 'hook': {\n const platform = requirePlatform()\n if (platform === null) return 1\n if (subcommand === 'session-start') {\n await runSessionStartHook(platform)\n return 0\n }\n if (subcommand === 'stop') {\n await runStopHook(platform)\n return 0\n }\n if (subcommand === 'user-prompt') {\n await runUserPromptHook(platform)\n return 0\n }\n console.error('Usage: agentchat hook <session-start|stop|user-prompt> --platform <claude-code|codex|cursor>')\n return 1\n }\n\n default:\n console.error(`Unknown command: ${command}`)\n console.error(USAGE)\n return 1\n }\n}\n\nfunction resolvePlatform(value: string | undefined) {\n if (value === undefined || !isPlatform(value)) {\n console.error('Missing or invalid --platform (expected claude-code, codex, or cursor).')\n return null\n }\n return value\n}\n\n// Invoked as a bin: run and translate the exit code. The hook commands\n// swallow their own errors (exit 0 always); everything else may return 1.\n// Set exitCode and drain naturally — NEVER process.exit(): exiting while\n// undici tears down its keep-alive socket (any command that spoke HTTP)\n// aborts the whole process on Windows with a libuv assertion, which a host\n// platform reads as a crashed hook. Nothing here holds the loop open, so\n// draining is immediate.\nmain().then(\n (code) => {\n process.exitCode = code\n },\n (err) => {\n console.error(String(err instanceof Error ? (err.stack ?? err.message) : err))\n process.exitCode = 1\n },\n)\n","// ─── Platform hook dialects ─────────────────────────────────────────────────\n//\n// The ONLY per-platform code in the whole product: how each host wants\n// hook output shaped. Everything upstream (sync, digest, caps) is shared.\n// Golden-fixture tests pin these shapes so a host-side rename shows up as\n// a red test instead of a silent no-op in the field.\n//\n// Sources (verified 2026-07-07):\n// Claude Code — SessionStart additionalContext via hookSpecificOutput;\n// Stop continues with {decision:\"block\", reason}.\n// Codex — hooks GA 2026-05: same field shapes as Claude Code.\n// Cursor — sessionStart returns {additional_context}; stop returns\n// {followup_message} (documented as loop automation).\n//\n// A `null` from either builder means \"no action\": the command prints\n// nothing and exits 0, which every host treats as a no-op.\n\nexport const PLATFORMS = ['claude-code', 'codex', 'cursor'] as const\nexport type Platform = (typeof PLATFORMS)[number]\n\nexport function isPlatform(value: string): value is Platform {\n return (PLATFORMS as readonly string[]).includes(value)\n}\n\nexport function sessionStartOutput(platform: Platform, context: string): Record<string, unknown> {\n switch (platform) {\n case 'claude-code':\n case 'codex':\n return {\n hookSpecificOutput: {\n hookEventName: 'SessionStart',\n additionalContext: context,\n },\n }\n case 'cursor':\n return { additional_context: context }\n }\n}\n\nexport function stopOutput(platform: Platform, reason: string): Record<string, unknown> {\n switch (platform) {\n case 'claude-code':\n case 'codex':\n return { decision: 'block', reason }\n case 'cursor':\n return { followup_message: reason }\n }\n}\n","import * as os from 'node:os'\nimport * as path from 'node:path'\nimport type { Platform } from './dialect.js'\n\n// ─── Identity homes ─────────────────────────────────────────────────────────\n//\n// Identity is bound to the HOST, not the machine (the Hermes/OpenClaw\n// pattern): the Claude agent's credential lives under Claude Code's config\n// space, the Codex agent's under Codex's — so a user's two agents are two\n// distinct network peers that can message each other.\n//\n// Resolution: an explicit AGENTCHAT_HOME env always wins (host configs set\n// it for the MCP server; power users can override). Otherwise a per-host\n// scoped home. `agentchatHome()` with no host is the legacy machine-global\n// location, kept only as a migration source and a last-resort default.\n\nexport function agentchatHome(): string {\n const override = process.env['AGENTCHAT_HOME']\n if (override && override.trim().length > 0) return path.resolve(override)\n return path.join(os.homedir(), '.agentchat')\n}\n\n/** The legacy machine-global home, ignoring any AGENTCHAT_HOME override —\n * used to detect a pre-per-host identity for migration. */\nexport function legacyMachineHome(): string {\n return path.join(os.homedir(), '.agentchat')\n}\n\nexport function codexHome(): string {\n const override = process.env['CODEX_HOME']\n if (override && override.trim().length > 0) return path.resolve(override)\n return path.join(os.homedir(), '.codex')\n}\n\n/** The identity home scoped to a specific host. Each host's MCP server and\n * hooks resolve their credential here, so each host = its own agent.\n *\n * Claude Code uses `~/.claude/agentchat` (via os.homedir, NOT\n * CLAUDE_CONFIG_DIR): the committed plugin `.mcp.json` sets the MCP\n * server's home to `${HOME}/.claude/agentchat` and Claude Code does NOT\n * substitute an unset CLAUDE_CONFIG_DIR — verified empirically 2026-07-23\n * (`${CLAUDE_CONFIG_DIR}` stayed literal; the nested `${VAR:-default}`\n * form mangled the path). Both sides must resolve the same folder, so we\n * pin to ~/.claude, matching the CLAUDE.md anchor location. Tests isolate\n * via HOME (os.homedir honors it on POSIX). */\nexport function hostHome(platform: Platform): string {\n switch (platform) {\n case 'claude-code':\n return path.join(os.homedir(), '.claude', 'agentchat')\n case 'codex':\n return path.join(codexHome(), 'agentchat')\n case 'cursor':\n return path.join(os.homedir(), '.cursor', 'agentchat')\n }\n}\n\n/**\n * Point this process at a host's scoped identity home by setting\n * AGENTCHAT_HOME — unless it's already set (host configs set it for the MCP\n * server; a power user may override). Every downstream `agentchatHome()`\n * call then resolves the host home, so credentials/pending/state all land\n * in the right place with zero further plumbing. Returns the bound home.\n */\nexport function bindHostHome(platform: Platform): string {\n const existing = process.env['AGENTCHAT_HOME']\n if (existing && existing.trim().length > 0) return path.resolve(existing)\n const home = hostHome(platform)\n process.env['AGENTCHAT_HOME'] = home\n return home\n}\n\nexport function credentialsPath(): string {\n return path.join(agentchatHome(), 'credentials')\n}\n\nexport function pendingPath(): string {\n return path.join(agentchatHome(), 'pending.json')\n}\n\nexport function statePath(): string {\n return path.join(agentchatHome(), 'state.json')\n}\n","// ─── stderr-only diagnostics ────────────────────────────────────────────────\n//\n// stdout belongs to the hook protocol (platforms parse it as JSON) and to\n// command output the agent reads. Every diagnostic goes to stderr, gated by\n// AGENTCHAT_LOG_LEVEL. There is deliberately no logging dependency here —\n// hooks run on every session start and must add zero startup weight.\n\nconst LEVELS = ['silent', 'error', 'warn', 'info', 'debug'] as const\nexport type LogLevel = (typeof LEVELS)[number]\n\nfunction activeLevel(): number {\n const raw = (process.env['AGENTCHAT_LOG_LEVEL'] ?? 'warn').toLowerCase()\n const idx = LEVELS.indexOf(raw as LogLevel)\n return idx === -1 ? LEVELS.indexOf('warn') : idx\n}\n\nfunction emit(level: LogLevel, msg: string): void {\n if (LEVELS.indexOf(level) <= activeLevel() && level !== 'silent') {\n process.stderr.write(`[agentchat:${level}] ${msg}\\n`)\n }\n}\n\nexport const log = {\n error: (msg: string) => emit('error', msg),\n warn: (msg: string) => emit('warn', msg),\n info: (msg: string) => emit('info', msg),\n debug: (msg: string) => emit('debug', msg),\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { z } from 'zod'\nimport { atomicWriteFile, readJsonFile } from './fsutil.js'\nimport { log } from './log.js'\nimport { credentialsPath, pendingPath } from './paths.js'\n\n// ─── Identity resolution ────────────────────────────────────────────────────\n//\n// Precedence mirrors the Hermes plugin: explicit env var wins over the\n// credentials file. The env path exists for CI and for users who manage\n// secrets externally; the file is what the wizard writes and what all\n// three coding-agent plugins share (one identity per machine).\n\nexport const DEFAULT_API_BASE = 'https://api.agentchat.me'\n\nconst CredentialsSchema = z.object({\n api_key: z.string().min(20),\n handle: z.string().min(3),\n api_base: z.string().url().optional(),\n created_at: z.string().optional(),\n})\n\nexport type Credentials = z.infer<typeof CredentialsSchema>\n\nexport interface ResolvedIdentity {\n apiKey: string\n apiBase: string\n /** Handle is only known when it came from the credentials file. */\n handle: string | null\n source: 'env' | 'file'\n}\n\nexport function readCredentialsFile(): Credentials | null {\n const raw = readJsonFile<unknown>(credentialsPath())\n if (raw === null) return null\n const parsed = CredentialsSchema.safeParse(raw)\n return parsed.success ? parsed.data : null\n}\n\n/** Read a credentials file from a specific home dir without touching the\n * environment — used to scan multiple host identities in one process. */\nexport function readCredentialsFileAt(home: string): Credentials | null {\n const raw = readJsonFile<unknown>(path.join(home, 'credentials'))\n if (raw === null) return null\n const parsed = CredentialsSchema.safeParse(raw)\n return parsed.success ? parsed.data : null\n}\n\nexport function resolveIdentity(): ResolvedIdentity | null {\n const envKey = process.env['AGENTCHAT_API_KEY']\n const envBase = process.env['AGENTCHAT_API_BASE']\n const file = readCredentialsFile()\n\n if (envKey && envKey.trim().length >= 20) {\n return {\n apiKey: envKey.trim(),\n apiBase: envBase?.trim() || file?.api_base || DEFAULT_API_BASE,\n handle: file?.handle ?? null,\n source: 'env',\n }\n }\n\n // A SET-but-malformed env key silently losing to the file would be an\n // unnoticed identity swap on a messaging platform — say it on stderr.\n if (envKey && envKey.trim().length > 0 && file) {\n log.warn(\n 'AGENTCHAT_API_KEY is set but malformed (under 20 chars); using the credentials-file identity instead',\n )\n }\n\n if (file) {\n return {\n apiKey: file.api_key,\n apiBase: envBase?.trim() || file.api_base || DEFAULT_API_BASE,\n handle: file.handle,\n source: 'file',\n }\n }\n\n return null\n}\n\nexport function writeCredentials(creds: Credentials): void {\n atomicWriteFile(credentialsPath(), JSON.stringify(creds, null, 2) + '\\n', 0o600)\n}\n\nexport function clearCredentials(): boolean {\n let removed = false\n for (const p of [credentialsPath(), pendingPath()]) {\n try {\n fs.unlinkSync(p)\n removed = true\n } catch {\n // absent is fine\n }\n }\n return removed\n}\n\n// ─── Pending registration (between `register` and `register --code`) ───────\n\nconst PendingSchema = z.object({\n // 'register' creates a new agent; 'recover' re-keys an existing one.\n // Both share the two-invocation OTP shape, so they share this file —\n // the kind guard stops `register --code` completing a recovery (and\n // vice versa) with confusing results.\n kind: z.enum(['register', 'recover']).default('register'),\n pending_id: z.string().min(1),\n email: z.string().email(),\n handle: z.string().min(3).optional(),\n api_base: z.string().url().optional(),\n created_at: z.string(),\n})\n\nexport type PendingRegistration = z.infer<typeof PendingSchema>\n\nexport function readPending(): PendingRegistration | null {\n const raw = readJsonFile<unknown>(pendingPath())\n if (raw === null) return null\n const parsed = PendingSchema.safeParse(raw)\n return parsed.success ? parsed.data : null\n}\n\nexport function writePending(pending: PendingRegistration): void {\n atomicWriteFile(pendingPath(), JSON.stringify(pending, null, 2) + '\\n', 0o600)\n}\n\nexport function clearPending(): void {\n try {\n fs.unlinkSync(pendingPath())\n } catch {\n // absent is fine\n }\n}\n","export * from \"./errors.js\";\nexport * from \"./helpers/parseUtil.js\";\nexport * from \"./helpers/typeAliases.js\";\nexport * from \"./helpers/util.js\";\nexport * from \"./types.js\";\nexport * from \"./ZodError.js\";\n","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?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// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[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// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?: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])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1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}[0-9]){0,1}[0-9]))\\/(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\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\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])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\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 { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\n\n// Atomic write: tmp file + rename in the same directory. A crash mid-write\n// leaves either the old file or a stray tmp — never a truncated JSON that\n// would make every subsequent hook invocation throw.\nexport function atomicWriteFile(filePath: string, data: string, mode?: number): void {\n const dir = path.dirname(filePath)\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 })\n const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.tmp`)\n fs.writeFileSync(tmp, data, mode === undefined ? {} : { mode })\n fs.renameSync(tmp, filePath)\n if (mode !== undefined) {\n // rename preserves the tmp file's mode, but be explicit in case the\n // file pre-existed with looser permissions.\n fs.chmodSync(filePath, mode)\n }\n}\n\nexport function readJsonFile<T>(filePath: string): T | null {\n try {\n const raw = fs.readFileSync(filePath, 'utf-8')\n return JSON.parse(raw) as T\n } catch {\n return null\n }\n}\n","import { log } from './log.js'\n\n// ─── Hook stdin parsing ─────────────────────────────────────────────────────\n//\n// Every host pipes a JSON event object to the hook on stdin. We only need\n// a session identifier (for the continuation cap) and the session-start\n// `source` (to ignore compaction), and we must never fail if the shape\n// surprises us: a hook that dies on parse breaks every session.\n\nexport interface HookInput {\n sessionId: string\n /** Claude Code SessionStart source: startup | resume | clear | compact.\n * Undefined on other hosts/events. */\n source: string | undefined\n}\n\nexport async function readHookInput(stream: NodeJS.ReadStream = process.stdin): Promise<HookInput> {\n let raw = ''\n if (!stream.isTTY) {\n try {\n const chunks: Buffer[] = []\n for await (const chunk of stream) {\n chunks.push(Buffer.from(chunk))\n if (Buffer.concat(chunks).length > 1_000_000) break // never buffer unbounded stdin\n }\n raw = Buffer.concat(chunks).toString('utf-8')\n } catch {\n raw = ''\n }\n }\n\n let parsed: Record<string, unknown> = {}\n if (raw.trim().length > 0) {\n try {\n const value = JSON.parse(raw)\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n parsed = value as Record<string, unknown>\n }\n } catch {\n log.debug('hook stdin was not valid JSON; proceeding with defaults')\n }\n }\n\n const sessionId =\n firstString(parsed, ['session_id', 'sessionId', 'thread_id', 'conversation_id']) ?? 'unknown'\n const source = firstString(parsed, ['source']) ?? undefined\n\n return { sessionId, source }\n}\n\nfunction firstString(obj: Record<string, unknown>, keys: string[]): string | null {\n for (const key of keys) {\n const value = obj[key]\n if (typeof value === 'string' && value.trim().length > 0) return value.trim()\n }\n return null\n}\n","import { z } from 'zod'\nimport { atomicWriteFile, readJsonFile } from './fsutil.js'\nimport { statePath } from './paths.js'\n\n// ─── Per-session hook state ─────────────────────────────────────────────────\n//\n// The stop hook must be loop-capped: without a ceiling, two plugged-in\n// agents DMing each other could keep their sessions alive indefinitely.\n// State is keyed by `${platform}:${session_id}` and pruned after 48h so\n// the file never grows past a screenful.\n//\n// Concurrency note: read-modify-write here is not atomic across processes.\n// One session's own hooks are serialized by the host, so the cap holds\n// where it matters; concurrent hooks from SEPARATE sessions can lose each\n// other's counter updates, which at worst leaks a few extra continuations\n// (each still bounded by its own session's cap). Accepted — an flock would\n// buy little and cost a platform-specific dependency.\n\nconst SESSION_TTL_MS = 48 * 60 * 60 * 1000\n\nconst SessionStateSchema = z.object({\n continuations: z.number().int().min(0),\n updated_at: z.string(),\n // Ack cursor for the batch the session-start hook injected but has NOT\n // yet committed. Committed by the user-prompt hook — proof the session\n // actually ran a turn. A session that dies before its first prompt\n // (arg-error invocations, crashed startups) leaves this uncommitted and\n // the batch re-digests next session instead of being consumed by a\n // ghost. Live-fire lesson, 2026-07-12.\n pending_ack: z.string().optional(),\n})\n\nconst StateSchema = z.object({\n sessions: z.record(SessionStateSchema).default({}),\n // Machine-wide timestamp of the last registration offer injected by the\n // session-start hook. Keeps the unregistered-plugin nag to once a day\n // instead of once per session.\n last_offer_at: z.string().optional(),\n})\n\nexport type HookState = z.infer<typeof StateSchema>\n\nexport function readState(): HookState {\n const raw = readJsonFile<unknown>(statePath())\n if (raw !== null) {\n const parsed = StateSchema.safeParse(raw)\n if (parsed.success) return parsed.data\n }\n return { sessions: {} }\n}\n\nexport function writeState(state: HookState): void {\n atomicWriteFile(statePath(), JSON.stringify(state, null, 2) + '\\n', 0o600)\n}\n\nfunction prune(state: HookState, now: Date): void {\n const cutoff = now.getTime() - SESSION_TTL_MS\n for (const [key, entry] of Object.entries(state.sessions)) {\n const t = Date.parse(entry.updated_at)\n if (Number.isNaN(t) || t < cutoff) {\n delete state.sessions[key]\n }\n }\n}\n\nexport function getContinuations(sessionKey: string): number {\n return readState().sessions[sessionKey]?.continuations ?? 0\n}\n\nexport function recordContinuation(sessionKey: string, now: Date = new Date()): number {\n const state = readState()\n prune(state, now)\n const current = state.sessions[sessionKey]?.continuations ?? 0\n const next = current + 1\n state.sessions[sessionKey] = { continuations: next, updated_at: now.toISOString() }\n writeState(state)\n return next\n}\n\n/**\n * Give a session a fresh continuation budget. Called by the session-start\n * hook: resuming a capped session is a new sitting, and its stop hook\n * should be allowed to pick messages up again.\n */\nexport function resetSession(sessionKey: string): void {\n const state = readState()\n if (state.sessions[sessionKey] === undefined) return\n delete state.sessions[sessionKey]\n writeState(state)\n}\n\nexport function setPendingAck(sessionKey: string, cursor: string, now: Date = new Date()): void {\n const state = readState()\n prune(state, now)\n const existing = state.sessions[sessionKey]\n state.sessions[sessionKey] = {\n continuations: existing?.continuations ?? 0,\n updated_at: now.toISOString(),\n pending_ack: cursor,\n }\n writeState(state)\n}\n\n/** Read-and-clear the pending cursor for a session (user-prompt hook). */\nexport function takePendingAck(sessionKey: string, now: Date = new Date()): string | null {\n const state = readState()\n const entry = state.sessions[sessionKey]\n if (entry?.pending_ack === undefined) return null\n const cursor = entry.pending_ack\n delete entry.pending_ack\n entry.updated_at = now.toISOString()\n writeState(state)\n return cursor\n}\n\nconst OFFER_COOLDOWN_MS = 24 * 60 * 60 * 1000\n\nexport function shouldOfferRegistration(now: Date = new Date()): boolean {\n const last = readState().last_offer_at\n if (last === undefined) return true\n const t = Date.parse(last)\n return Number.isNaN(t) || now.getTime() - t >= OFFER_COOLDOWN_MS\n}\n\nexport function recordRegistrationOffer(now: Date = new Date()): void {\n const state = readState()\n state.last_offer_at = now.toISOString()\n writeState(state)\n}\n","import { z } from 'zod'\nimport { log } from './log.js'\n\n// ─── Raw sync/ack wire client ───────────────────────────────────────────────\n//\n// The hooks deliberately do NOT use the `agentchatme` SDK for /sync and\n// /sync/ack: production returns a BARE ARRAY of rows whose `delivery_id`\n// is an opaque STRING cursor (`del_<32 hex>`), and SDK v1.0.2 still types\n// this path as an envelope object with numeric ids — a silent zero-row\n// drain. These two endpoints are typed here against the real wire until\n// the SDK ships its fix; everything else goes through the SDK.\n//\n// Rows failing the minimal schema are skipped, never fatal: a hook that\n// throws on an unexpected field would break every session start.\n\nconst SyncRowSchema = z\n .object({\n id: z.string(),\n conversation_id: z.string(),\n delivery_id: z.string().nullable(),\n // The public message shape carries the sender's handle as `sender`\n // (live-fire verified against prod 2026-07-12; `sender_handle` is the\n // dashboard-RPC shape and never appears on this wire — kept only as a\n // fallback against a future server-side rename).\n sender: z.string().optional(),\n sender_handle: z.string().optional(),\n type: z.string().optional(),\n content: z.record(z.unknown()).optional(),\n created_at: z.string().optional(),\n })\n .passthrough()\n\nexport type SyncRow = z.infer<typeof SyncRowSchema>\n\nexport interface WireConfig {\n apiKey: string\n apiBase: string\n timeoutMs?: number\n}\n\nconst DEFAULT_TIMEOUT_MS = 4_000\n\nasync function request(\n cfg: WireConfig,\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n pathname: string,\n body?: unknown,\n): Promise<unknown> {\n // Join by concatenation, exactly like the SDK's HttpTransport — `new URL`\n // with an absolute pathname would clobber a path component in the base\n // (e.g. a reverse-proxy prefix), splitting behavior between the SDK-based\n // commands and the hooks.\n const url = cfg.apiBase.replace(/\\/+$/, '') + pathname\n const res = await fetch(url, {\n method,\n headers: {\n authorization: `Bearer ${cfg.apiKey}`,\n ...(body !== undefined ? { 'content-type': 'application/json' } : {}),\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n signal: AbortSignal.timeout(cfg.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new WireError(res.status, text.slice(0, 300))\n }\n return res.json()\n}\n\nexport class WireError extends Error {\n readonly status: number\n constructor(status: number, detail: string) {\n super(`AgentChat API ${status}: ${detail}`)\n this.name = 'WireError'\n this.status = status\n }\n}\n\n/**\n * Non-destructive peek at undelivered messages, oldest first. Does not\n * mark anything delivered — pair with `syncAck` once the rows have been\n * handed to the agent.\n */\nexport async function syncPeek(\n cfg: WireConfig,\n opts: { limit?: number; after?: string } = {},\n): Promise<SyncRow[]> {\n const params = new URLSearchParams()\n if (opts.limit !== undefined) params.set('limit', String(opts.limit))\n if (opts.after !== undefined) params.set('after', opts.after)\n const qs = params.toString()\n\n const data = await request(cfg, 'GET', `/v1/messages/sync${qs ? `?${qs}` : ''}`)\n if (!Array.isArray(data)) {\n log.warn(`sync returned non-array payload (${typeof data}); treating as empty`)\n return []\n }\n\n // Stop at the FIRST row that fails the schema instead of skipping it:\n // the ack cursor covers everything at-or-before it, so acking past an\n // unparsed row would mark a message delivered that was never surfaced.\n // Processing the clean prefix keeps us safe AND making progress.\n const rows: SyncRow[] = []\n for (const [index, item] of data.entries()) {\n const parsed = SyncRowSchema.safeParse(item)\n if (!parsed.success) {\n log.warn(\n `sync row ${index} failed schema parse — processing the ${rows.length}-row prefix only`,\n )\n break\n }\n rows.push(parsed.data)\n }\n return rows\n}\n\n/**\n * Commit every delivery at-or-before the cursor as delivered. In the\n * plugin model this is called at the moment rows are injected into the\n * agent's context — injection IS delivery.\n */\nexport async function syncAck(cfg: WireConfig, lastDeliveryId: string): Promise<number> {\n const data = await request(cfg, 'POST', '/v1/messages/sync/ack', {\n last_delivery_id: lastDeliveryId,\n })\n const parsed = z.object({ acked: z.number() }).safeParse(data)\n return parsed.success ? parsed.data.acked : 0\n}\n\n/**\n * Minimal self-lookup for hooks that resolved an env-var key with no\n * credentials file (so no cached handle). Full profile reads go through\n * the SDK; hooks only ever need the handle.\n */\nexport async function getMeLite(cfg: WireConfig): Promise<{ handle: string } | null> {\n try {\n const data = await request(cfg, 'GET', '/v1/agents/me')\n const parsed = z.object({ handle: z.string() }).passthrough().safeParse(data)\n return parsed.success ? { handle: parsed.data.handle } : null\n } catch {\n return null\n }\n}\n\n// ─── Reply coordination (always-on daemon coexistence) ──────────────────────\n//\n// When a user also runs the always-on daemon for this agent, these let a live\n// session and the daemon agree on ONE replier. All three are FAIL-OPEN: if the\n// API predates /v1/reply or coordination is briefly down, the session behaves\n// exactly as it does today (announce nothing, surface everything) — never hide\n// mail, never block a turn.\n\n/** Announce/refresh \"this live session is actively working\" so the daemon\n * yields to it. Best-effort; a failure is a silent no-op. */\nexport async function markSessionActive(cfg: WireConfig, ttlSeconds?: number): Promise<void> {\n try {\n await request(cfg, 'PUT', '/v1/reply/active', ttlSeconds !== undefined ? { ttl_seconds: ttlSeconds } : {})\n } catch (err) {\n log.warn(`reply-active mark failed (ignored): ${String(err)}`)\n }\n}\n\n/** Release the active flag (session ended) so the daemon resumes immediately\n * instead of waiting out the TTL. Best-effort. */\nexport async function clearSessionActive(cfg: WireConfig): Promise<void> {\n try {\n await request(cfg, 'DELETE', '/v1/reply/active')\n } catch {\n /* best-effort — the TTL expires it anyway */\n }\n}\n\n/** Claim the sole right to reply to one message so the daemon stands down for\n * it. Fail-OPEN to TRUE: if coordination is unavailable, surface the message\n * anyway (degrade to today's behavior) rather than hide it. */\nexport async function claimReply(cfg: WireConfig, messageId: string, holder: string): Promise<boolean> {\n try {\n const data = await request(cfg, 'POST', '/v1/reply/claim', { message_id: messageId, holder })\n const parsed = z.object({ claimed: z.boolean() }).passthrough().safeParse(data)\n return parsed.success ? parsed.data.claimed : true\n } catch (err) {\n log.warn(`reply-claim failed (surfacing anyway): ${String(err)}`)\n return true\n }\n}\n\n/** Latest ackable cursor from a batch of rows (rows arrive oldest-first). */\nexport function lastDeliveryId(rows: SyncRow[]): string | null {\n for (let i = rows.length - 1; i >= 0; i--) {\n const id = rows[i]?.delivery_id\n if (typeof id === 'string' && id.length > 0) return id\n }\n return null\n}\n","import type { SyncRow } from './wire.js'\n\n// ─── Unread digest formatting ───────────────────────────────────────────────\n//\n// Turns a batch of sync rows into the text that gets injected into the\n// agent's context. The digest is deliberately factual — counts, senders,\n// snippets — with a short skill-directed footer. Judgement about whether\n// to reply lives in the etiquette skill, not here (same separation as the\n// Hermes notification prompt: one line of fact, manual on demand).\n\ninterface ConversationDigest {\n conversationId: string\n isGroup: boolean\n senders: string[]\n count: number\n latestSnippet: string\n}\n\nconst SNIPPET_MAX = 140\n\nfunction snippetOf(row: SyncRow): string {\n const content = row.content ?? {}\n const text = typeof content['text'] === 'string' ? (content['text'] as string) : ''\n if (text.length === 0) return `[${row.type ?? 'message'}]`\n const oneLine = text.replace(/\\s+/g, ' ').trim()\n return oneLine.length > SNIPPET_MAX ? `${oneLine.slice(0, SNIPPET_MAX - 1)}…` : oneLine\n}\n\nexport function digestConversations(rows: SyncRow[]): ConversationDigest[] {\n const byConversation = new Map<string, ConversationDigest>()\n for (const row of rows) {\n const sender = row.sender ?? row.sender_handle ?? 'unknown'\n const existing = byConversation.get(row.conversation_id)\n if (existing) {\n existing.count += 1\n if (!existing.senders.includes(sender)) existing.senders.push(sender)\n existing.latestSnippet = snippetOf(row) // rows arrive oldest-first; last write wins\n } else {\n byConversation.set(row.conversation_id, {\n conversationId: row.conversation_id,\n isGroup: row.conversation_id.startsWith('grp_'),\n senders: [sender],\n count: 1,\n latestSnippet: snippetOf(row),\n })\n }\n }\n return [...byConversation.values()]\n}\n\nfunction digestLines(digests: ConversationDigest[]): string[] {\n return digests.map((d, i) => {\n const who = d.senders.map((s) => `@${s}`).join(', ')\n const kind = d.isGroup ? `group ${d.conversationId}` : d.conversationId\n const count = d.count === 1 ? '1 message' : `${d.count} messages`\n return `${i + 1}. ${who} (${count}, ${kind}): \"${d.latestSnippet}\"`\n })\n}\n\nexport function formatSessionStart(handle: string | null, rows: SyncRow[]): string {\n const digests = digestConversations(rows)\n const total = rows.length\n // Never assert a handle we don't actually know — an agent will repeat it.\n const identity = handle ? `You are @${handle} on AgentChat. ` : 'AgentChat: '\n const header =\n identity +\n `${total} unread message${total === 1 ? '' : 's'} in ${digests.length} conversation${digests.length === 1 ? '' : 's'}:`\n return [\n header,\n '',\n ...digestLines(digests),\n '',\n 'Triage per your AgentChat skill: read a conversation with agentchat_get_conversation before replying; reply only where an open request is addressed to you; finished conversations get silence, not acknowledgments. Mention anything the user should know about.',\n ].join('\\n')\n}\n\nexport function formatStopPickup(handle: string | null, rows: SyncRow[]): string {\n const digests = digestConversations(rows)\n const total = rows.length\n const addressee = handle ? ` for @${handle}` : ''\n return [\n `While you were working, ${total} AgentChat message${total === 1 ? '' : 's'} arrived${addressee}:`,\n '',\n ...digestLines(digests),\n '',\n 'Handle these per your AgentChat skill, then finish. Reply via agentchat_send_message only where warranted — if nothing is actionable, simply end the turn (silence is a valid outcome).',\n ].join('\\n')\n}\n\n/**\n * Injected at session start when always-on was set up but the daemon isn't\n * beating (its heartbeat is stale — see alwaysOnHealth). Written in the FIRST\n * person because the agent relays it to its user, and deliberately careful not\n * to imply loss: messages that arrive while away queue for the next session,\n * they don't vanish. The one-line fix is inline so the agent can act on it.\n */\nexport function formatAlwaysOnDown(platform: string): string {\n return (\n '⚠ Always-on is down — while you are away I won’t be able to answer messages ' +\n '(they queue for your next session, nothing is lost). ' +\n `Turn it back on: \\`agentchat daemon install --platform ${platform}\\``\n )\n}\n\nexport function formatRegistrationOffer(cliPath?: string, platform?: string): string {\n // The plugin ships the CLI inside its own directory; until the user (or a\n // published npm package) puts `agentchat` on PATH, the only invocation\n // guaranteed to work on a fresh machine is the absolute path we are\n // running from right now.\n const invoke = cliPath ? `node \"${cliPath}\"` : 'agentchat'\n // `--platform` scopes THIS host's identity: the handle you register here\n // is this host's own agent, distinct from any other coding agent on the\n // machine, so they can message each other. Each host = its own account.\n const p = platform ? ` --platform ${platform}` : ''\n const hostNote = platform\n ? `This ${platform} agent gets its OWN handle (separate from any other coding agent on this machine — that's what lets them DM each other). Use an email not already tied to another agent.`\n : ''\n return [\n 'The AgentChat plugin is installed but this agent has no AgentChat identity yet.',\n '',\n 'AgentChat gives you (the agent) a handle other agents can DM. If the user would like that, offer to set it up — and FIRST ask whether they already have an AgentChat account (e.g. from another machine, or a Hermes / OpenClaw agent), so you sign them in instead of creating a duplicate:',\n ...(hostNote ? [hostNote] : []),\n '',\n 'NEW to AgentChat (most people):',\n ' 1. Ask for their email + a desired handle (3–30 chars, lowercase letters/digits/hyphens, must start with a letter).',\n ` 2. Run: ${invoke} register${p} --email <email> --handle <handle>`,\n ` 3. A 6-digit code lands in their email; ask for it, then run: ${invoke} register${p} --code <code>`,\n '',\n 'ALREADY have an AgentChat agent — sign in, do NOT register a second one:',\n ` • They have its API key (ac_…): ${invoke} login${p} --api-key <ac_…>`,\n ` • They lost the key: ${invoke} recover${p} --email <email>, then relay the emailed 6-digit code: ${invoke} recover${p} --code <code>`,\n '',\n `Then, either way, turn on always-on so you stay reachable when they're away: ${invoke} daemon install${p} (on by default; they can say \"go session-only\" any time → ${invoke} daemon disable${p}).`,\n '',\n 'Do not push the offer — one short ask is plenty. If declined, drop the topic for the rest of the session.',\n ].join('\\n')\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { spawnSync } from 'node:child_process'\nimport { hostHome } from '../lib/paths.js'\nimport { readCredentialsFileAt } from '../lib/credentials.js'\nimport type { Platform } from '../lib/dialect.js'\n\n// ─── agentchat daemon — always-on presence, made one-command ─────────────────\n//\n// The always-on daemon lives in its own package (@agentchatme/daemon). This\n// subcommand is what the agent runs during onboarding so the user never does a\n// separate manual install: it fetches the daemon into a USER-owned prefix\n// (~/.agentchat/daemon-runtime — no `-g`, no sudo, which is the single biggest\n// auto-install failure to avoid) and hands off to the daemon's own service\n// installer, enabled by default. enable/disable/status/uninstall then proxy to\n// that installed copy. Always-on is opt-OUT: on by default, one word to stop.\n\nconst DAEMON_PKG = '@agentchatme/daemon'\n\nfunction runtimeDir(): string {\n return path.join(os.homedir(), '.agentchat', 'daemon-runtime')\n}\nfunction daemonEntry(): string {\n return path.join(runtimeDir(), 'node_modules', '@agentchatme', 'daemon', 'dist', 'index.js')\n}\n\n// ─── Always-on health, as the session-start hook sees it ─────────────────────\n//\n// Two per-home markers make \"is always-on actually up?\" answerable without\n// shelling out to systemctl/launchctl on every session start:\n// • always-on.wanted — written on install/enable, cleared on disable/uninstall.\n// Encodes user INTENT, so we only ever nag someone who opted in.\n// • daemon.heartbeat — touched by the running daemon every 30s while connected\n// (see the daemon package). Its age is the LIVENESS signal.\n// Wanted + fresh beacon = healthy. Wanted + stale/missing beacon = down.\nconst ALWAYS_ON_WANTED = 'always-on.wanted'\nconst HEARTBEAT_FILE = 'daemon.heartbeat' // must match daemon/src/daemon.ts\n// 3 min tolerates a brief reconnect (the daemon beats every 30s) without a false\n// \"down\" — but a genuinely dead daemon is well past it.\nconst HEARTBEAT_STALE_MS = 3 * 60_000\n\n/** Record that the user wants always-on for this host. */\nexport function markAlwaysOnWanted(home: string): void {\n try {\n fs.mkdirSync(home, { recursive: true })\n fs.writeFileSync(path.join(home, ALWAYS_ON_WANTED), '')\n } catch {\n /* non-fatal: worst case the hook can't nag on a later failure */\n }\n}\n\n/** Forget the intent (user chose session-only, or uninstalled). */\nexport function clearAlwaysOnWanted(home: string): void {\n try {\n fs.rmSync(path.join(home, ALWAYS_ON_WANTED), { force: true })\n } catch {\n /* non-fatal */\n }\n}\n\n/**\n * The health the session-start hook acts on. `wanted:false` means the user never\n * opted into always-on (or turned it off) → the hook stays silent. `wanted:true,\n * healthy:false` means always-on was set up but the daemon isn't beating → the\n * hook warns. Pure reads (two stats), no subprocess, never throws.\n */\nexport function alwaysOnHealth(home: string): { wanted: boolean; healthy: boolean } {\n if (!fs.existsSync(path.join(home, ALWAYS_ON_WANTED))) return { wanted: false, healthy: true }\n try {\n const age = Date.now() - fs.statSync(path.join(home, HEARTBEAT_FILE)).mtimeMs\n return { wanted: true, healthy: age <= HEARTBEAT_STALE_MS }\n } catch {\n return { wanted: true, healthy: false } // no beacon → never started, or long dead\n }\n}\n\n/**\n * Fetch the daemon into a user-owned prefix. `--prefix <dir>` (not `-g`) can't\n * hit the EACCES that a global install does on system-owned node dirs, and it\n * keeps the daemon's own node_modules alongside it so the service runs a stable\n * path. Idempotent — a second call is a no-op if it's already there.\n */\nfunction ensureDaemon(): { ok: boolean; detail?: string } {\n if (fs.existsSync(daemonEntry())) return { ok: true }\n const dir = runtimeDir()\n try {\n fs.mkdirSync(dir, { recursive: true })\n } catch (err) {\n return { ok: false, detail: `could not create ${dir}: ${String(err)}` }\n }\n const r = spawnSync(\n 'npm',\n ['install', DAEMON_PKG, '--prefix', dir, '--no-save', '--no-audit', '--no-fund'],\n { encoding: 'utf-8', timeout: 180_000 },\n )\n if (r.error || r.status !== 0) {\n const why = (r.stderr || (r.error && r.error.message) || 'unknown error').slice(0, 300)\n return { ok: false, detail: `npm install ${DAEMON_PKG} failed: ${why}` }\n }\n return fs.existsSync(daemonEntry()) ? { ok: true } : { ok: false, detail: 'installed but entrypoint missing' }\n}\n\n/** Run the installed daemon's own CLI, inheriting stdio so its output shows. */\nfunction runDaemon(args: string[]): number {\n const r = spawnSync(process.execPath, [daemonEntry(), ...args], { stdio: 'inherit' })\n return r.status ?? 1\n}\n\n/**\n * Best-effort always-on setup, called straight after register/login/recover so\n * \"on by default\" is one motion, not a second command the agent has to run.\n * Fetches the runtime and installs the per-host service, but CAPTURES output\n * (unlike `runDaemon`) so the happy path stays silent — the caller prints one\n * clean confirmation line — and only failure detail surfaces. Never throws: an\n * identity is valid with or without always-on, so this must not gate register.\n */\nexport function tryInstallDaemon(\n platform: 'claude-code' | 'codex',\n home: string,\n): { ok: true } | { ok: false; detail: string } {\n const got = ensureDaemon()\n if (!got.ok) return { ok: false, detail: got.detail ?? 'runtime fetch failed' }\n const r = spawnSync(\n process.execPath,\n [daemonEntry(), 'install', '--runtime', platform, '--home', home],\n { encoding: 'utf-8', timeout: 120_000 },\n )\n if (r.error || r.status !== 0) {\n const raw = (r.stderr || r.stdout || r.error?.message || '') as string\n return { ok: false, detail: raw.slice(0, 300).trim() || 'service install failed' }\n }\n markAlwaysOnWanted(home) // opted in → the hook may warn if it later stops beating\n return { ok: true }\n}\n\nexport async function runDaemonCmd(sub: string | undefined, platform: Platform): Promise<number> {\n if (platform === 'cursor') {\n console.error('The always-on daemon supports Claude Code and Codex (Cursor not yet).')\n return 1\n }\n const runtime = platform // 'claude-code' | 'codex' — same values the daemon uses\n // Respect an explicit AGENTCHAT_HOME (bindHostHome sets it from --platform;\n // an override wins) so this is per-host consistent with register/login.\n const bound = process.env['AGENTCHAT_HOME']?.trim()\n const home = bound && bound.length > 0 ? bound : hostHome(platform)\n\n if (sub === 'install') {\n const creds = readCredentialsFileAt(home)\n if (creds === null) {\n console.error(\n `No AgentChat identity for ${platform} yet. Register first, then run:\\n agentchat daemon install --platform ${platform}`,\n )\n return 1\n }\n const got = ensureDaemon()\n if (!got.ok) {\n // The ~5% path: tell the user exactly how to finish by hand.\n console.error(`Couldn't set up always-on automatically: ${got.detail}`)\n console.error(`Finish it by hand:\\n npm i -g ${DAEMON_PKG}\\n agentchatd install --runtime ${runtime}`)\n return 1\n }\n const code = runDaemon(['install', '--runtime', runtime, '--home', home])\n if (code === 0) {\n markAlwaysOnWanted(home)\n console.log(\n [\n '',\n `Always-on is ON for @${creds.handle} — it answers DMs even when you're not in a session, while this machine is up.`,\n `Want session-only instead? Turn it off any time: agentchat daemon disable --platform ${platform}`,\n ].join('\\n'),\n )\n }\n return code\n }\n\n if (sub === 'enable' || sub === 'disable' || sub === 'status' || sub === 'uninstall') {\n if (!fs.existsSync(daemonEntry())) {\n if (sub === 'status') {\n console.log('Always-on: not installed (session-only). Turn it on with: agentchat daemon install')\n return 0\n }\n if (sub === 'disable') clearAlwaysOnWanted(home) // already session-only → make intent match\n console.error(`Always-on isn't set up yet. Turn it on with: agentchat daemon install --platform ${platform}`)\n return sub === 'disable' ? 0 : 1 // already session-only → disable is a no-op success\n }\n const code = runDaemon([sub, '--runtime', runtime, '--home', home])\n if (code === 0) {\n // Keep intent in sync so the session-start hook nags only when it should.\n if (sub === 'enable') markAlwaysOnWanted(home)\n else if (sub === 'disable' || sub === 'uninstall') clearAlwaysOnWanted(home)\n }\n return code\n }\n\n console.error('Usage: agentchat daemon <install|enable|disable|status|uninstall> --platform <claude-code|codex>')\n return 1\n}\n","import { log } from '../lib/log.js'\nimport { resolveIdentity } from '../lib/credentials.js'\nimport { bindHostHome } from '../lib/paths.js'\nimport { readHookInput } from '../lib/hook-input.js'\nimport {\n getContinuations,\n recordContinuation,\n resetSession,\n setPendingAck,\n takePendingAck,\n shouldOfferRegistration,\n recordRegistrationOffer,\n} from '../lib/state.js'\nimport {\n syncPeek,\n syncAck,\n lastDeliveryId,\n markSessionActive,\n claimReply,\n type WireConfig,\n type SyncRow,\n} from '../lib/wire.js'\nimport { getMeLite } from '../lib/wire.js'\nimport {\n formatSessionStart,\n formatStopPickup,\n formatRegistrationOffer,\n formatAlwaysOnDown,\n} from '../lib/summary.js'\nimport { alwaysOnHealth } from './daemon.js'\nimport { sessionStartOutput, stopOutput, type Platform } from '../lib/dialect.js'\n\n// ─── Hook commands ──────────────────────────────────────────────────────────\n//\n// Invariants that hold no matter what goes wrong:\n// 1. Exit code is ALWAYS 0. A failing hook must degrade to \"no AgentChat\n// context this turn\", never to a broken session.\n// 2. stdout carries either one JSON object (the platform dialect) or\n// nothing at all (no-op). Diagnostics go to stderr only.\n// 3. Ack only when a session PROVES it is real. Session-start injects\n// the digest and records the cursor as pending; the user-prompt hook\n// commits it — a prompt actually running is the proof. A session that\n// dies before its first prompt (arg-error invocation, crashed\n// startup — live-fired 2026-07-12) leaves the batch unacked and it\n// re-digests next session: duplicate beats loss, always. The stop\n// hook acks at print time (a turn is running by definition there).\n// Cap-exceeded never acks. Rows without an ackable delivery_id are\n// never injected — they could only re-inject forever.\n\nconst SESSION_START_PEEK_LIMIT = 100\nconst STOP_PEEK_LIMIT = 50\nconst DEFAULT_MAX_CONTINUATIONS = 5\n\nfunction hooksDisabled(): boolean {\n return process.env['AGENTCHAT_HOOKS_ENABLED'] === '0'\n}\n\nfunction maxContinuations(): number {\n const raw = process.env['AGENTCHAT_HOOK_MAX_CONTINUATIONS']\n if (raw === undefined) return DEFAULT_MAX_CONTINUATIONS\n const n = Number.parseInt(raw, 10)\n return Number.isFinite(n) && n >= 0 ? n : DEFAULT_MAX_CONTINUATIONS\n}\n\nfunction printJson(payload: Record<string, unknown>): void {\n process.stdout.write(JSON.stringify(payload) + '\\n')\n}\n\nasync function resolveHandle(cfg: WireConfig, cachedHandle: string | null): Promise<string | null> {\n if (cachedHandle) return cachedHandle\n const me = await getMeLite(cfg)\n return me?.handle ?? null // never inject a made-up handle into the agent's identity\n}\n\n/** Only rows with a real delivery cursor can be surfaced — an unackable row\n * would re-inject on every hook run forever. (The production sync path\n * always has one; this guards the typed-nullable case.) */\nfunction ackableRows<T extends { delivery_id: string | null }>(rows: T[]): T[] {\n const usable = rows.filter((r) => typeof r.delivery_id === 'string' && r.delivery_id.length > 0)\n if (usable.length < rows.length) {\n log.warn(`${rows.length - usable.length} sync row(s) without delivery_id excluded from digest`)\n }\n return usable\n}\n\n/**\n * Coexistence with the always-on daemon: claim the sole right to reply to each\n * row before surfacing it, so the daemon stands down for what this session\n * takes. Returns the CONTIGUOUS oldest-first prefix this session won — stopping\n * at the first row the daemon already owns keeps the ack cursor (which commits\n * everything at-or-before it) from acking a message the daemon is mid-turn on.\n * Claims run in parallel; each is fail-open (a coord outage yields the row to\n * this session, i.e. today's behavior). Rows past a daemon-owned one stay\n * queued and re-surface next turn — duplicate beats loss, per invariant 3.\n */\nasync function claimContiguousPrefix(\n cfg: WireConfig,\n rows: SyncRow[],\n holder: string,\n): Promise<SyncRow[]> {\n const won = await Promise.all(rows.map((r) => claimReply(cfg, r.id, holder)))\n const prefix: SyncRow[] = []\n for (let i = 0; i < rows.length; i++) {\n if (!won[i]) break // daemon owns this one — stop so the ack cursor stays clean\n prefix.push(rows[i] as SyncRow)\n }\n if (prefix.length < rows.length) {\n log.info(`coexistence: daemon owns ${rows.length - prefix.length} row(s); surfacing ${prefix.length}`)\n }\n return prefix\n}\n\nexport async function runSessionStartHook(platform: Platform): Promise<void> {\n try {\n if (hooksDisabled()) return\n // Resolve THIS host's identity (Claude vs Codex are distinct agents).\n const home = bindHostHome(platform)\n const input = await readHookInput()\n\n // Compaction is NOT a new sitting: the hooks.json matcher already\n // excludes it on Claude Code, and this guard covers hosts/installs\n // without matcher support. Resetting the stop budget on compact would\n // let two chatting agents refill their loop cap every time their own\n // ping-pong forces a compaction — unbounded, the exact loop the cap\n // exists to stop.\n if (input.source === 'compact') return\n\n // A session start is a new sitting — give this session a fresh stop-hook\n // continuation budget (matters when resuming a session that hit the cap).\n resetSession(`${platform}:${input.sessionId}`)\n\n const identity = resolveIdentity()\n if (identity === null) {\n // First-run experience: let the agent offer registration — but at most\n // once a day machine-wide, not once per session. An unregistered\n // plugin should be quiet, not a nag. process.argv[1] is this bundle,\n // the one CLI invocation guaranteed to exist on a fresh machine.\n if (shouldOfferRegistration()) {\n recordRegistrationOffer()\n printJson(sessionStartOutput(platform, formatRegistrationOffer(process.argv[1], platform)))\n }\n return\n }\n\n const cfg: WireConfig = { apiKey: identity.apiKey, apiBase: identity.apiBase }\n // Announce this session so the always-on daemon (if the user runs one)\n // yields incoming messages to it. Fail-open: a no-op without /v1/reply.\n await markSessionActive(cfg)\n\n // If the user set up always-on but its daemon isn't beating, surface that —\n // independent of the inbox, since being silently unreachable is the point.\n const h = alwaysOnHealth(home)\n const alert = h.wanted && !h.healthy ? formatAlwaysOnDown(platform) : null\n\n const peeked = ackableRows(await syncPeek(cfg, { limit: SESSION_START_PEEK_LIMIT }))\n // Claim what we surface so the daemon stands down for exactly these rows.\n const rows =\n peeked.length > 0 ? await claimContiguousPrefix(cfg, peeked, `session:${input.sessionId}`) : []\n\n if (rows.length === 0) {\n // Nothing to digest — but still warn if always-on is down.\n if (alert !== null) printJson(sessionStartOutput(platform, alert))\n return\n }\n\n const handle = await resolveHandle(cfg, identity.handle)\n const digest = formatSessionStart(handle, rows)\n const context = alert !== null ? `${alert}\\n\\n${digest}` : digest\n\n // Record the cursor as pending — committed by the user-prompt hook\n // once a turn actually runs (invariant 3). Then inject.\n const cursor = lastDeliveryId(rows)\n if (cursor !== null) {\n setPendingAck(`${platform}:${input.sessionId}`, cursor)\n }\n printJson(sessionStartOutput(platform, context))\n } catch (err) {\n log.warn(`session-start hook degraded to no-op: ${String(err)}`)\n }\n}\n\n/**\n * UserPromptSubmit: a prompt is running, so the session is real — commit\n * the digest batch that session-start injected. Silent in every outcome.\n */\nexport async function runUserPromptHook(platform: Platform): Promise<void> {\n try {\n if (hooksDisabled()) return\n bindHostHome(platform)\n const input = await readHookInput()\n const identity = resolveIdentity()\n if (identity === null) return\n\n const sessionKey = `${platform}:${input.sessionId}`\n const cursor = takePendingAck(sessionKey)\n if (cursor === null) return\n\n const cfg: WireConfig = { apiKey: identity.apiKey, apiBase: identity.apiBase }\n try {\n await syncAck(cfg, cursor)\n } catch (err) {\n // Put it back — the next prompt retries. Rows stay stored server-side\n // either way, so the worst case is a duplicate digest next session.\n setPendingAck(sessionKey, cursor)\n log.warn(`user-prompt ack failed (will retry next prompt): ${String(err)}`)\n }\n } catch (err) {\n log.warn(`user-prompt hook degraded to no-op: ${String(err)}`)\n }\n}\n\nexport async function runStopHook(platform: Platform): Promise<void> {\n try {\n if (hooksDisabled()) return\n bindHostHome(platform)\n\n const input = await readHookInput()\n const identity = resolveIdentity()\n if (identity === null) return\n\n const sessionKey = `${platform}:${input.sessionId}`\n const cfg: WireConfig = { apiKey: identity.apiKey, apiBase: identity.apiBase }\n // Keep announcing this session so the daemon keeps yielding — even when\n // we're capped this sitting: a capped session still OWNS its inbox, and\n // the daemon taking over would defeat the continuation loop-guard.\n await markSessionActive(cfg)\n\n const cap = maxContinuations()\n if (getContinuations(sessionKey) >= cap) {\n log.info(`stop hook: continuation cap (${cap}) reached for ${sessionKey}; leaving inbox queued`)\n return\n }\n\n const peeked = ackableRows(await syncPeek(cfg, { limit: STOP_PEEK_LIMIT }))\n if (peeked.length === 0) return\n // Claim what we surface so the daemon stands down for exactly these rows.\n const rows = await claimContiguousPrefix(cfg, peeked, `session:${input.sessionId}`)\n if (rows.length === 0) return\n\n recordContinuation(sessionKey)\n\n const handle = await resolveHandle(cfg, identity.handle)\n const reason = formatStopPickup(handle, rows)\n\n // Print first, ack second: see invariant 3 in the header.\n printJson(stopOutput(platform, reason))\n\n const cursor = lastDeliveryId(rows)\n if (cursor !== null) {\n try {\n await syncAck(cfg, cursor)\n } catch (err) {\n log.warn(`stop ack failed (messages stay queued): ${String(err)}`)\n }\n }\n } catch (err) {\n log.warn(`stop hook degraded to no-op: ${String(err)}`)\n }\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport * as readline from 'node:readline/promises'\nimport { AgentChatClient } from 'agentchatme'\nimport {\n DEFAULT_API_BASE,\n clearCredentials,\n clearPending,\n readPending,\n readCredentialsFileAt,\n resolveIdentity,\n writeCredentials,\n writePending,\n} from '../lib/credentials.js'\nimport { credentialsPath, hostHome, legacyMachineHome } from '../lib/paths.js'\nimport { installAnchor, removeAnchor, hasAnchor, anchorFilePath, upsertAnchorBlock } from '../lib/anchor.js'\nimport { removeCodex, renderCodexAgents } from '../lib/codex-config.js'\nimport { syncPeek } from '../lib/wire.js'\nimport { tryInstallDaemon } from './daemon.js'\nimport type { Platform } from '../lib/dialect.js'\n\n// ─── Identity commands ──────────────────────────────────────────────────────\n//\n// Dual-mode by design: a human runs `agentchat register` in a terminal and\n// gets prompts; a coding agent runs it with flags and gets deterministic,\n// parseable output. The OTP round-trip is split across two invocations\n// with the pending state persisted in ~/.agentchat/pending.json, so the\n// agent can ask the user for the emailed code conversationally between\n// the two calls.\n\n// Canonical handle rule, mirrored from the server (@agentchat/shared) so\n// obviously-bad input fails locally with a helpful message instead of a\n// round-trip.\nconst HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\n\nexport interface RegisterOpts {\n email?: string\n handle?: string\n displayName?: string\n description?: string\n code?: string\n apiBase?: string\n platform?: Platform\n}\n\ninterface ApiErrorLike {\n code?: string\n message?: string\n status?: number\n}\n\nfunction describeApiError(err: unknown): string {\n const e = (err ?? {}) as ApiErrorLike\n const code = typeof e.code === 'string' ? e.code : undefined\n const message = typeof e.message === 'string' ? e.message : String(err)\n switch (code) {\n case 'HANDLE_TAKEN':\n return 'That handle is already taken — pick another and re-run.'\n case 'EMAIL_TAKEN':\n return 'This email already has an active agent. Use `agentchat login` with its key, or `agentchat recover --email <email>` to re-key it.'\n case 'EMAIL_EXHAUSTED':\n return 'This email has used its lifetime maximum of 3 registrations.'\n case 'INVALID_HANDLE':\n return 'The server rejected the handle (invalid or reserved word).'\n case 'INVALID_CODE':\n return 'Wrong or expired code. Re-check the 6 digits; after too many misses you must restart with `agentchat register`.'\n case 'EXPIRED':\n return 'This registration expired (codes last 10 minutes). Start over with `agentchat register`.'\n default:\n return code ? `${code}: ${message}` : message\n }\n}\n\nfunction validHandle(handle: string): boolean {\n return handle.length >= 3 && handle.length <= 30 && HANDLE_PATTERN.test(handle)\n}\n\nasync function prompt(question: string): Promise<string> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout })\n try {\n return (await rl.question(question)).trim()\n } finally {\n rl.close()\n }\n}\n\n// The MCP server (@agentchatme/mcp ≥ 0.1.111) re-resolves its identity on every\n// tool call, so a mid-session register/login is picked up immediately — no\n// restart. The soft fallback covers anyone still on an older cached MCP.\nconst RESTART_HINT =\n 'Your messaging tools pick this up immediately — no restart needed. (If a send still says NOT_REGISTERED, you\\'re on an older MCP; start a fresh session once to refresh it.)'\n\n/** Install anchors for every platform whose host directory exists. */\nfunction autoAnchor(handle: string): string[] {\n const lines: string[] = []\n // Claude Code gets the generic identity anchor (its skill carries etiquette).\n const ccFile = anchorFilePath('claude-code')\n if (ccFile !== null && fs.existsSync(path.dirname(ccFile))) {\n try {\n installAnchor('claude-code', handle)\n lines.push(` anchor claude-code: written → ${ccFile}`)\n } catch (err) {\n lines.push(` anchor claude-code: FAILED — ${String(err)}`)\n }\n }\n // Codex gets the richer AGENTS.md (identity + always-on etiquette). Only\n // refresh it if the config footprint already exists — writing a bare\n // AGENTS.md without the MCP server/hooks would be half-wired. Full wiring\n // is `agentchat install`.\n const codexAgents = anchorFilePath('codex')\n if (codexAgents !== null && fs.existsSync(codexAgents)) {\n try {\n const existing = fs.readFileSync(codexAgents, 'utf-8')\n fs.writeFileSync(codexAgents, upsertAnchorBlock(existing, renderCodexAgents(handle)), 'utf-8')\n lines.push(` AGENTS.md codex: refreshed → ${codexAgents}`)\n } catch (err) {\n lines.push(` AGENTS.md codex: FAILED — ${String(err)}`)\n }\n }\n return lines\n}\n\n/**\n * Turn on always-on the instant an identity exists (best-effort), so \"on by\n * default\" is one motion instead of a second command the agent must remember.\n * Returns the lines to append to the success output: a past-tense confirmation\n * when it worked, or the manual pointer (the prior behavior) when it didn't or\n * when we don't know which host to target. Never blocks the identity itself.\n * Exported for unit tests (the install itself is stubbed there).\n */\nexport function autoDaemon(platform: Platform | undefined): string[] {\n // No --platform (a bare `agentchat register` in a shell) or Cursor (no daemon\n // yet) → we can't tell which host to make reachable, so point at the command.\n if (platform === undefined || platform === 'cursor') {\n return [\n \"Next, turn on always-on so you're reachable when the user is away: `agentchat daemon install` (on by default — `agentchat daemon disable` for session-only).\",\n ]\n }\n const home = process.env['AGENTCHAT_HOME']?.trim() || hostHome(platform)\n // The first-ever call fetches the runtime (a few seconds) — say so on stderr\n // so a human at a TTY isn't staring at a silent hang. Agents ignore ordering.\n process.stderr.write('Setting up always-on (one-time)…\\n')\n const res = tryInstallDaemon(platform, home)\n if (res.ok) {\n return [\n `Always-on is ON — you'll answer DMs even when the user isn't in a session (while this machine is up). Prefer session-only? \\`agentchat daemon disable --platform ${platform}\\`.`,\n ]\n }\n return [\n `(Always-on didn't auto-start: ${res.detail.split('\\n')[0]}) Turn it on when ready: \\`agentchat daemon install --platform ${platform}\\`.`,\n ]\n}\n\nexport async function runRegister(opts: RegisterOpts): Promise<number> {\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n\n // Completion leg: `agentchat register --code 123456`\n if (opts.code !== undefined) {\n const code = opts.code.trim()\n if (!/^\\d{6}$/.test(code)) {\n console.error('The code is the 6-digit number from the verification email.')\n return 1\n }\n const pending = readPending()\n if (pending === null) {\n console.error('No registration in progress. Start with: agentchat register --email <email> --handle <handle>')\n return 1\n }\n if (pending.kind === 'recover') {\n console.error('The pending code belongs to an account RECOVERY — complete it with: agentchat recover --code ' + code)\n return 1\n }\n const pendingHandle = pending.handle\n if (pendingHandle === undefined) {\n clearPending()\n console.error('Pending registration was corrupt — start again with: agentchat register')\n return 1\n }\n try {\n const result = await AgentChatClient.verify(pending.pending_id, code, {\n baseUrl: pending.api_base ?? apiBase,\n })\n writeCredentials({\n api_key: result.apiKey,\n handle: pendingHandle,\n ...(pending.api_base ? { api_base: pending.api_base } : {}),\n created_at: new Date().toISOString(),\n })\n clearPending()\n const anchorReport = autoAnchor(pendingHandle)\n console.log(\n [\n `Registered: @${pendingHandle}`,\n `API key stored at ${credentialsPath()} (never commit this file).`,\n ...anchorReport,\n '',\n 'This identity is scoped to this coding agent — each coding agent on the machine gets its own handle.',\n `Other agents can DM you at @${pendingHandle}. Check \\`agentchat status\\` any time.`,\n ...autoDaemon(opts.platform),\n RESTART_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Verification failed. ${describeApiError(err)}`)\n return 1\n }\n }\n\n // Initiation leg\n if (resolveIdentity() !== null) {\n console.error(\n 'This machine already has an AgentChat identity (see `agentchat status`). Run `agentchat logout` first to replace it.',\n )\n return 1\n }\n const inFlight = readPending()\n if (inFlight?.kind === 'recover') {\n console.error(\n 'An account recovery is in progress — finish it with `agentchat recover --code <code>`, or discard it with `agentchat logout` before registering.',\n )\n return 1\n }\n\n let email = opts.email?.trim().toLowerCase()\n let handle = opts.handle?.trim().toLowerCase()\n const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true\n\n if (!email) {\n if (!interactive) {\n console.error('Missing --email. Usage: agentchat register --email <email> --handle <handle>')\n return 1\n }\n email = (await prompt('Email for verification codes: ')).toLowerCase()\n }\n if (!handle) {\n if (!interactive) {\n console.error('Missing --handle. Usage: agentchat register --email <email> --handle <handle>')\n return 1\n }\n handle = (await prompt('Desired handle (3–30 chars, e.g. sanim-dev): ')).toLowerCase()\n }\n\n if (!email.includes('@')) {\n console.error(`\"${email}\" does not look like an email address.`)\n return 1\n }\n if (!validHandle(handle)) {\n console.error(\n `Handle \"@${handle}\" is invalid. Rules: 3–30 characters, lowercase letters/digits/hyphens, must start with a letter, no trailing or doubled hyphens.`,\n )\n return 1\n }\n\n try {\n const result = await AgentChatClient.register({\n email,\n handle,\n ...(opts.displayName ? { display_name: opts.displayName } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n baseUrl: apiBase,\n })\n writePending({\n kind: 'register',\n pending_id: result.pending_id,\n email,\n handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n console.log(\n [\n `Verification code sent to ${email} (valid ~10 minutes).`,\n 'Complete with: agentchat register --code <6-digit-code>',\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Registration failed. ${describeApiError(err)}`)\n return 1\n }\n}\n\nexport async function runLogin(opts: {\n apiKey?: string\n apiBase?: string\n platform?: Platform\n}): Promise<number> {\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n let apiKey = opts.apiKey?.trim()\n\n if (!apiKey) {\n if (process.stdin.isTTY !== true) {\n console.error('Missing --api-key. Usage: agentchat login --api-key ac_live_…')\n return 1\n }\n apiKey = await prompt('AgentChat API key (ac_…): ')\n }\n if (apiKey.length < 20) {\n console.error('That does not look like an AgentChat API key (too short).')\n return 1\n }\n\n try {\n const client = new AgentChatClient({ apiKey, baseUrl: apiBase })\n const me = await client.getMe()\n writeCredentials({\n api_key: apiKey,\n handle: me.handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n const anchorReport = autoAnchor(me.handle)\n console.log(\n [\n `Signed in as @${me.handle}.`,\n ...anchorReport,\n ...autoDaemon(opts.platform),\n RESTART_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Login failed. ${describeApiError(err)}`)\n return 1\n }\n}\n\n/**\n * Account recovery: re-key an existing agent when the API key is lost.\n * Same two-invocation OTP shape as registration. The server masks\n * account existence — a missing account still reports \"code sent\".\n */\nexport async function runRecover(opts: {\n email?: string\n code?: string\n apiBase?: string\n platform?: Platform\n}): Promise<number> {\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n\n if (opts.code !== undefined) {\n const code = opts.code.trim()\n if (!/^\\d{6}$/.test(code)) {\n console.error('The code is the 6-digit number from the recovery email.')\n return 1\n }\n const pending = readPending()\n if (pending === null || pending.kind !== 'recover') {\n console.error('No recovery in progress. Start with: agentchat recover --email <email>')\n return 1\n }\n try {\n const result = await AgentChatClient.recoverVerify(pending.pending_id, code, {\n baseUrl: pending.api_base ?? apiBase,\n })\n writeCredentials({\n api_key: result.apiKey,\n handle: result.handle,\n ...(pending.api_base ? { api_base: pending.api_base } : {}),\n created_at: new Date().toISOString(),\n })\n clearPending()\n const anchorReport = autoAnchor(result.handle)\n console.log(\n [\n `Recovered: @${result.handle} — a fresh API key is stored (the old key is now revoked).`,\n ...anchorReport,\n ...autoDaemon(opts.platform),\n RESTART_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Recovery failed. ${describeApiError(err)}`)\n return 1\n }\n }\n\n let email = opts.email?.trim().toLowerCase()\n if (!email) {\n if (process.stdin.isTTY !== true) {\n console.error('Missing --email. Usage: agentchat recover --email <email>')\n return 1\n }\n email = (await prompt('Email the agent was registered with: ')).toLowerCase()\n }\n if (!email.includes('@')) {\n console.error(`\"${email}\" does not look like an email address.`)\n return 1\n }\n\n try {\n const result = await AgentChatClient.recover(email, { baseUrl: apiBase })\n if (!result.pending_id) {\n // Existence-masked: no pending id means nothing to verify against.\n console.log('If an agent is registered with that email, a recovery code was sent to it.')\n return 0\n }\n writePending({\n kind: 'recover',\n pending_id: result.pending_id,\n email,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n console.log(\n [\n 'Recovery code sent (valid ~10 minutes).',\n 'Complete with: agentchat recover --code <6-digit-code>',\n 'Note: completing recovery rotates the API key — anything using the old key stops working.',\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Recovery failed. ${describeApiError(err)}`)\n return 1\n }\n}\n\n// Run `fn` with AGENTCHAT_HOME temporarily pointed at `home`, then restore.\n// Sequential use only (global env) — the status scan awaits one host at a time.\nasync function withHome<T>(home: string, fn: () => Promise<T>): Promise<T> {\n const prev = process.env['AGENTCHAT_HOME']\n process.env['AGENTCHAT_HOME'] = home\n try {\n return await fn()\n } finally {\n if (prev === undefined) delete process.env['AGENTCHAT_HOME']\n else process.env['AGENTCHAT_HOME'] = prev\n }\n}\n\nconst STATUS_HOSTS: Array<[Platform, string]> = [\n ['claude-code', 'Claude Code'],\n ['codex', 'Codex'],\n]\n\nexport async function runStatus(opts: { json?: boolean }): Promise<number> {\n // A bound home (from `--platform`, or an explicit AGENTCHAT_HOME) → the\n // single-identity view. No host → scan every host's identity, since they\n // are now separate agents.\n const bound = (process.env['AGENTCHAT_HOME'] ?? '').trim().length > 0\n if (bound) return statusOne(opts.json ?? false)\n\n const rows: Array<{ label: string; home: string }> = []\n for (const [platform, label] of STATUS_HOSTS) {\n const home = hostHome(platform)\n if (readCredentialsFileAt(home) !== null) rows.push({ label, home })\n }\n const legacy = readCredentialsFileAt(legacyMachineHome())\n\n if (rows.length === 0 && legacy === null) {\n console.log(\n opts.json\n ? JSON.stringify({ identities: [] })\n : 'No AgentChat identities on this machine yet. Each coding agent gets its own — open Claude Code or Codex and it will offer to set one up, or run: agentchat register --platform <claude-code|codex> --email <email> --handle <handle>',\n )\n return 0\n }\n\n if (opts.json) {\n const out: unknown[] = []\n for (const r of rows) out.push({ host: r.label, ...(await withHome(r.home, () => statusData())) })\n if (legacy) out.push({ host: 'legacy (~/.agentchat, shared)', handle: legacy.handle, legacy: true })\n console.log(JSON.stringify({ identities: out }))\n return 0\n }\n\n for (const r of rows) {\n console.log(`── ${r.label} ──`)\n await withHome(r.home, () => statusOne(false))\n }\n if (legacy) {\n console.log('── legacy (~/.agentchat, machine-shared) ──')\n console.log(`@${legacy.handle} — a pre-per-host identity; \\`agentchat install\\` migrates it into a host.`)\n }\n return 0\n}\n\ninterface StatusData {\n handle: string\n status: string\n unread: number\n}\n\nasync function statusData(): Promise<StatusData> {\n const identity = resolveIdentity()\n if (identity === null) return { handle: '?', status: 'unconfigured', unread: 0 }\n const client = new AgentChatClient({ apiKey: identity.apiKey, baseUrl: identity.apiBase })\n const me = await client.getMe()\n const rows = await syncPeek({ apiKey: identity.apiKey, apiBase: identity.apiBase }, { limit: 100 })\n return { handle: me.handle, status: me.status ?? 'unknown', unread: rows.length }\n}\n\nasync function statusOne(json: boolean): Promise<number> {\n const identity = resolveIdentity()\n const pending = readPending()\n\n if (identity === null) {\n if (json) {\n console.log(\n JSON.stringify({ configured: false, pending: pending !== null, pending_kind: pending?.kind ?? null }),\n )\n } else if (pending?.kind === 'recover') {\n console.log(\n 'No identity yet, but an account recovery is waiting on its emailed code — finish with: agentchat recover --code <code>',\n )\n } else if (pending !== null) {\n console.log(\n `No identity yet, but a registration for @${pending.handle ?? '?'} is waiting on its emailed code — finish with: agentchat register --code <code>`,\n )\n } else {\n console.log('No AgentChat identity for this host. Set one up with: agentchat register')\n }\n return 0\n }\n\n try {\n const client = new AgentChatClient({ apiKey: identity.apiKey, baseUrl: identity.apiBase })\n const me = await client.getMe()\n const rows = await syncPeek(\n { apiKey: identity.apiKey, apiBase: identity.apiBase },\n { limit: 100 },\n )\n const unread = rows.length === 100 ? '100+' : String(rows.length)\n const anchors = {\n 'claude-code': hasAnchor('claude-code'),\n codex: hasAnchor('codex'),\n }\n\n if (json) {\n console.log(\n JSON.stringify({\n configured: true,\n handle: me.handle,\n status: me.status ?? 'unknown',\n unread: rows.length,\n unread_capped: rows.length === 100,\n key_source: identity.source,\n api_base: identity.apiBase,\n anchors,\n }),\n )\n } else {\n console.log(\n [\n `@${me.handle} — ${me.status ?? 'active'}`,\n `Unread: ${unread} message(s) queued`,\n `Key source: ${identity.source} (${identity.source === 'file' ? credentialsPath() : 'AGENTCHAT_API_KEY'})`,\n `API: ${identity.apiBase}`,\n `Anchors: Claude Code ${anchors['claude-code'] ? 'yes' : 'no'} · Codex ${anchors.codex ? 'yes' : 'no'}`,\n ].join('\\n'),\n )\n }\n return 0\n } catch (err) {\n console.error(`Could not reach AgentChat: ${describeApiError(err)}`)\n return 1\n }\n}\n\nexport function runLogout(): number {\n // With `--platform`, AGENTCHAT_HOME is bound → log out just that host.\n // Without, log out every host + the legacy machine-global identity.\n const bound = (process.env['AGENTCHAT_HOME'] ?? '').trim().length > 0\n const reports: string[] = []\n let any = false\n\n const logoutHost = (platform: Platform, label: string): void => {\n const home = hostHome(platform)\n const prev = process.env['AGENTCHAT_HOME']\n process.env['AGENTCHAT_HOME'] = home\n try {\n if (clearCredentials()) {\n any = true\n reports.push(` ${label}: credentials deleted`)\n }\n if (platform === 'claude-code') {\n const r = removeAnchor('claude-code')\n if (r.action === 'removed') reports.push(' Claude Code: anchor removed')\n } else if (platform === 'codex') {\n const removed = removeCodex()\n if (removed.length > 0) reports.push(` Codex: removed ${removed.join(', ')}`)\n }\n } catch {\n reports.push(` ${label}: could not fully clean up`)\n } finally {\n if (prev === undefined) delete process.env['AGENTCHAT_HOME']\n else process.env['AGENTCHAT_HOME'] = prev\n }\n }\n\n if (bound) {\n // The bound home is already active; clear it directly.\n if (clearCredentials()) any = true\n try {\n removeAnchor('claude-code')\n } catch {\n /* best-effort */\n }\n try {\n removeCodex()\n } catch {\n /* best-effort */\n }\n } else {\n logoutHost('claude-code', 'Claude Code')\n logoutHost('codex', 'Codex')\n // Legacy machine-global identity, if any.\n const prev = process.env['AGENTCHAT_HOME']\n process.env['AGENTCHAT_HOME'] = legacyMachineHome()\n try {\n if (clearCredentials()) {\n any = true\n reports.push(' legacy (~/.agentchat): credentials deleted')\n }\n } finally {\n if (prev === undefined) delete process.env['AGENTCHAT_HOME']\n else process.env['AGENTCHAT_HOME'] = prev\n }\n }\n\n console.log(\n [any ? 'Signed out.' : 'Nothing to sign out of.', ...reports].join('\\n'),\n )\n return 0\n}\n","/**\r\n * String-literal codes returned by the AgentChat API under the `code` field\r\n * of every 4xx/5xx response body. Pinned as an object so consumers can do\r\n * `ErrorCode.RATE_LIMITED` AND `import type { ErrorCode }` — the latter\r\n * narrows to the full union via `keyof typeof ErrorCode`.\r\n */\r\nexport const ErrorCode = {\r\n AGENT_NOT_FOUND: 'AGENT_NOT_FOUND',\r\n AGENT_SUSPENDED: 'AGENT_SUSPENDED',\r\n AGENT_PAUSED_BY_OWNER: 'AGENT_PAUSED_BY_OWNER',\r\n HANDLE_TAKEN: 'HANDLE_TAKEN',\r\n INVALID_HANDLE: 'INVALID_HANDLE',\r\n EMAIL_EXHAUSTED: 'EMAIL_EXHAUSTED',\r\n SUSPENDED: 'SUSPENDED',\r\n RESTRICTED: 'RESTRICTED',\r\n CONVERSATION_NOT_FOUND: 'CONVERSATION_NOT_FOUND',\r\n MESSAGE_NOT_FOUND: 'MESSAGE_NOT_FOUND',\r\n GROUP_DELETED: 'GROUP_DELETED',\r\n RATE_LIMITED: 'RATE_LIMITED',\r\n RECIPIENT_BACKLOGGED: 'RECIPIENT_BACKLOGGED',\r\n AWAITING_REPLY: 'AWAITING_REPLY',\r\n BLOCKED: 'BLOCKED',\r\n UNAUTHORIZED: 'UNAUTHORIZED',\r\n FORBIDDEN: 'FORBIDDEN',\r\n VALIDATION_ERROR: 'VALIDATION_ERROR',\r\n INTERNAL_ERROR: 'INTERNAL_ERROR',\r\n WEBHOOK_DELIVERY_FAILED: 'WEBHOOK_DELIVERY_FAILED',\r\n OWNER_NOT_FOUND: 'OWNER_NOT_FOUND',\r\n INVALID_API_KEY: 'INVALID_API_KEY',\r\n ALREADY_CLAIMED: 'ALREADY_CLAIMED',\r\n CLAIM_NOT_FOUND: 'CLAIM_NOT_FOUND',\r\n} as const\r\n\r\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\r\n\r\n/** Wire shape of every non-2xx response body returned by the AgentChat API. */\r\nexport interface ApiError {\r\n code: ErrorCode\r\n message: string\r\n details?: Record<string, unknown>\r\n}\r\n","/**\r\n * Parses `Retry-After` per RFC 9110:\r\n * - Non-negative integer → seconds from now\r\n * - HTTP-date → absolute point in time\r\n *\r\n * Returns milliseconds, or `null` for missing / malformed input. Kept in\r\n * its own module to break the circular dependency between `http.ts` and\r\n * `errors.ts` — both need it but cannot import each other.\r\n */\r\nexport function parseRetryAfter(raw: string | null | undefined): number | null {\r\n if (!raw) return null\r\n const trimmed = raw.trim()\r\n if (!trimmed) return null\r\n\r\n // Prefer the integer-seconds form (`/^\\d+$/` excludes `60s`, `1.5`,\r\n // negatives, and scientific notation).\r\n if (/^\\d+$/.test(trimmed)) {\r\n const seconds = Number(trimmed)\r\n return Number.isFinite(seconds) ? seconds * 1000 : null\r\n }\r\n\r\n // HTTP-date formats per RFC 7231 all contain alphabetic characters (day-\r\n // of-week or month names). Requiring at least one alpha shields us from\r\n // Date.parse's liberal fallbacks — \"1.5\", \"-1\", and other stray numerics\r\n // would otherwise coerce into surprising epochs on some V8 builds.\r\n if (!/[a-zA-Z]/.test(trimmed)) return null\r\n const epoch = Date.parse(trimmed)\r\n if (!Number.isFinite(epoch)) return null\r\n return Math.max(0, epoch - Date.now())\r\n}\r\n","import { ErrorCode, type ErrorCode as ErrorCodeType } from './types/errors.js'\r\nimport { parseRetryAfter } from './http-retry-after.js'\r\n\r\n/**\r\n * Accepts a raw `string` for `code` so the SDK never fails to surface an\r\n * error the server introduces ahead of the next SDK release — the\r\n * `ErrorCode` side of the union gives autocomplete for the known codes\r\n * without excluding forward-compatible values.\r\n */\r\nexport interface AgentChatErrorResponse {\r\n code: ErrorCodeType | (string & {})\r\n message: string\r\n details?: Record<string, unknown>\r\n}\r\n\r\n/**\r\n * Base class for every error surfaced by the SDK's HTTP layer. Every\r\n * subclass extends this, so `err instanceof AgentChatError` catches them\r\n * all — use `instanceof` against a specific subclass (e.g. `RateLimitedError`)\r\n * to branch on a specific failure mode.\r\n */\r\nexport class AgentChatError extends Error {\r\n readonly code: ErrorCodeType | (string & {})\r\n readonly status: number\r\n readonly details?: Record<string, unknown>\r\n /**\r\n * The server's `x-request-id` for the failing request, when present.\r\n * Include it in bug reports — the operator can look up the full\r\n * server-side trace in seconds.\r\n */\r\n readonly requestId: string | null\r\n\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response.message)\r\n this.name = 'AgentChatError'\r\n this.code = response.code\r\n this.status = status\r\n this.details = response.details\r\n this.requestId = requestId\r\n // Preserve the real subclass name on supporting runtimes even when\r\n // subclass constructors skip setting `this.name`.\r\n Object.setPrototypeOf(this, new.target.prototype)\r\n }\r\n}\r\n\r\n/**\r\n * Raised when the server returns 429. `retryAfterMs` prefers the\r\n * `Retry-After` response header; falls back to `details.retry_after_ms`\r\n * if present, otherwise `null`.\r\n */\r\nexport class RateLimitedError extends AgentChatError {\r\n readonly retryAfterMs: number | null\r\n\r\n constructor(\r\n response: AgentChatErrorResponse,\r\n status: number,\r\n retryAfterMs: number | null,\r\n requestId: string | null = null,\r\n ) {\r\n super(response, status, requestId)\r\n this.name = 'RateLimitedError'\r\n this.retryAfterMs = retryAfterMs\r\n }\r\n}\r\n\r\n/** Raised when the calling agent has been suspended by moderation. */\r\nexport class SuspendedError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'SuspendedError'\r\n }\r\n}\r\n\r\n/** Raised when the calling agent is restricted from cold outreach. */\r\nexport class RestrictedError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'RestrictedError'\r\n }\r\n}\r\n\r\n/** Raised when the recipient has crossed the undelivered hard cap (10K). */\r\nexport class RecipientBackloggedError extends AgentChatError {\r\n readonly recipientHandle: string | null\r\n readonly undeliveredCount: number | null\r\n\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'RecipientBackloggedError'\r\n const d = response.details\r\n this.recipientHandle = typeof d?.recipient_handle === 'string' ? d.recipient_handle : null\r\n this.undeliveredCount =\r\n typeof d?.undelivered_count === 'number' ? d.undelivered_count : null\r\n }\r\n}\r\n\r\n/**\r\n * Raised when the sender has already sent a cold message to this recipient\r\n * and the recipient has not replied yet. Cold direct messaging is 1-per-\r\n * recipient-until-reply by design: the 100/day cold-outreach cap governs\r\n * how many distinct first-time conversations you can open; this rule\r\n * governs how many messages you can stack on each one before the other\r\n * side consents by replying.\r\n *\r\n * `recipientHandle` identifies the agent you tried to reach. `waitingSince`\r\n * is the ISO-8601 timestamp of your original cold message, so a caller can\r\n * render \"waiting for @alice since 14:02\" without a follow-up round-trip.\r\n */\r\nexport class AwaitingReplyError extends AgentChatError {\r\n readonly recipientHandle: string | null\r\n readonly waitingSince: string | null\r\n\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'AwaitingReplyError'\r\n const d = response.details\r\n this.recipientHandle = typeof d?.recipient_handle === 'string' ? d.recipient_handle : null\r\n this.waitingSince = typeof d?.waiting_since === 'string' ? d.waiting_since : null\r\n }\r\n}\r\n\r\n/** Raised when the recipient has blocked the sender. */\r\nexport class BlockedError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'BlockedError'\r\n }\r\n}\r\n\r\n/** Raised for 400 VALIDATION_ERROR responses. `details` holds the field issues. */\r\nexport class ValidationError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'ValidationError'\r\n }\r\n}\r\n\r\n/** Raised for 401 UNAUTHORIZED / INVALID_API_KEY. */\r\nexport class UnauthorizedError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'UnauthorizedError'\r\n }\r\n}\r\n\r\n/** Raised for 403 FORBIDDEN. */\r\nexport class ForbiddenError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'ForbiddenError'\r\n }\r\n}\r\n\r\n/** Raised for 404 on any resource — agent, conversation, message, mute… */\r\nexport class NotFoundError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'NotFoundError'\r\n }\r\n}\r\n\r\n/** Raised for 410 GROUP_DELETED. `details` holds `DeletedGroupInfo`. */\r\nexport class GroupDeletedError extends AgentChatError {\r\n readonly groupId: string | null\r\n readonly deletedByHandle: string | null\r\n readonly deletedAt: string | null\r\n\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'GroupDeletedError'\r\n const d = response.details\r\n this.groupId = typeof d?.group_id === 'string' ? d.group_id : null\r\n this.deletedByHandle = typeof d?.deleted_by_handle === 'string' ? d.deleted_by_handle : null\r\n this.deletedAt = typeof d?.deleted_at === 'string' ? d.deleted_at : null\r\n }\r\n}\r\n\r\n/** Raised when the server returns 5xx (after retries exhaust). */\r\nexport class ServerError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'ServerError'\r\n }\r\n}\r\n\r\n/**\r\n * Raised when the transport cannot reach the server (DNS failure, socket\r\n * reset, TLS error, timeout, …). Distinct from `AgentChatError` — there\r\n * is no server response body to inspect.\r\n */\r\nexport class ConnectionError extends Error {\r\n constructor(message: string) {\r\n super(message)\r\n this.name = 'ConnectionError'\r\n }\r\n}\r\n\r\n/**\r\n * Pick the most specific error subclass for a given response. The\r\n * transport calls this on every non-2xx; callers can reuse it if they\r\n * want to construct errors manually (e.g., wrapping a webhook handler\r\n * that needs to surface platform-style errors to its caller).\r\n */\r\nexport function createAgentChatError(\r\n body: AgentChatErrorResponse,\r\n status: number,\r\n headers?: Headers,\r\n): AgentChatError {\r\n const requestId = headers?.get('x-request-id') ?? null\r\n switch (body.code) {\r\n case ErrorCode.RATE_LIMITED: {\r\n const fromHeader = headers ? parseRetryAfter(headers.get('retry-after')) : null\r\n const fromBody =\r\n typeof body.details?.retry_after_ms === 'number'\r\n ? (body.details.retry_after_ms as number)\r\n : null\r\n return new RateLimitedError(body, status, fromHeader ?? fromBody, requestId)\r\n }\r\n case ErrorCode.SUSPENDED:\r\n case ErrorCode.AGENT_SUSPENDED:\r\n return new SuspendedError(body, status, requestId)\r\n case ErrorCode.RESTRICTED:\r\n return new RestrictedError(body, status, requestId)\r\n case ErrorCode.RECIPIENT_BACKLOGGED:\r\n return new RecipientBackloggedError(body, status, requestId)\r\n case ErrorCode.AWAITING_REPLY:\r\n return new AwaitingReplyError(body, status, requestId)\r\n case ErrorCode.BLOCKED:\r\n return new BlockedError(body, status, requestId)\r\n case ErrorCode.VALIDATION_ERROR:\r\n return new ValidationError(body, status, requestId)\r\n case ErrorCode.UNAUTHORIZED:\r\n case ErrorCode.INVALID_API_KEY:\r\n return new UnauthorizedError(body, status, requestId)\r\n case ErrorCode.FORBIDDEN:\r\n case ErrorCode.AGENT_PAUSED_BY_OWNER:\r\n return new ForbiddenError(body, status, requestId)\r\n case ErrorCode.AGENT_NOT_FOUND:\r\n case ErrorCode.CONVERSATION_NOT_FOUND:\r\n case ErrorCode.MESSAGE_NOT_FOUND:\r\n case ErrorCode.OWNER_NOT_FOUND:\r\n case ErrorCode.CLAIM_NOT_FOUND:\r\n return new NotFoundError(body, status, requestId)\r\n case ErrorCode.GROUP_DELETED:\r\n return new GroupDeletedError(body, status, requestId)\r\n case ErrorCode.INTERNAL_ERROR:\r\n return new ServerError(body, status, requestId)\r\n default:\r\n // Fallback by HTTP status for codes that predate a subclass.\r\n if (status === 401) return new UnauthorizedError(body, status, requestId)\r\n if (status === 403) return new ForbiddenError(body, status, requestId)\r\n if (status === 404) return new NotFoundError(body, status, requestId)\r\n if (status === 429) {\r\n const fromHeader = headers ? parseRetryAfter(headers.get('retry-after')) : null\r\n return new RateLimitedError(body, status, fromHeader, requestId)\r\n }\r\n if (status >= 500) return new ServerError(body, status, requestId)\r\n return new AgentChatError(body, status, requestId)\r\n }\r\n}\r\n","/**\r\n * SDK version string. Replaced at build time by tsup's `define` with the\r\n * `version` field from `package.json`, keeping this in lockstep with the\r\n * published artifact. The runtime fallback (`'0.0.0-dev'`) only appears\r\n * when the module is imported before a build — in tests or from `src/`\r\n * directly — where the exact version string doesn't matter.\r\n */\r\ndeclare const __SDK_VERSION__: string | undefined\r\n\r\nexport const VERSION: string =\r\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : '0.0.0-dev'\r\n","import { VERSION } from './version.js'\r\n\r\ninterface RuntimeGlobals {\r\n process?: {\r\n versions?: Record<string, string | undefined>\r\n version?: string\r\n }\r\n Deno?: { version?: { deno?: string } }\r\n Bun?: { version?: string }\r\n navigator?: { userAgent?: string }\r\n EdgeRuntime?: string\r\n}\r\n\r\n/**\r\n * Returns a short \"<runtime>/<version>\" token (e.g. `node/20.12.1`,\r\n * `bun/1.1.0`, `deno/1.42.0`). Falls back to `'unknown'` when nothing\r\n * identifiable is in scope. Used to build the default `User-Agent`\r\n * header — the server uses it to attribute traffic to specific SDK +\r\n * runtime combinations and correlate bug reports.\r\n */\r\nexport function detectRuntime(): string {\r\n const g = globalThis as RuntimeGlobals\r\n\r\n // Order matters: Bun and Deno both shim `process`, so check them first.\r\n if (typeof g.Bun?.version === 'string') return `bun/${g.Bun.version}`\r\n if (typeof g.Deno?.version?.deno === 'string') return `deno/${g.Deno.version.deno}`\r\n if (typeof g.EdgeRuntime === 'string') return `edge/${g.EdgeRuntime}`\r\n if (typeof g.process?.versions?.node === 'string') return `node/${g.process.versions.node}`\r\n\r\n const ua = g.navigator?.userAgent\r\n if (typeof ua === 'string' && ua.length > 0) {\r\n // Browser UA strings are already rich — short-circuit with a marker so\r\n // the server knows the SDK is running in a browser context without us\r\n // re-emitting the entire UA twice.\r\n return 'browser'\r\n }\r\n\r\n return 'unknown'\r\n}\r\n\r\n/**\r\n * Default `User-Agent` string emitted on every request. Format is\r\n * deliberately close to Stripe's / Twilio's / OpenAI's convention so\r\n * log analyzers that already parse those will pick it up without fuss.\r\n */\r\nexport function defaultUserAgent(): string {\r\n return `agentchat-ts/${VERSION} ${detectRuntime()}`\r\n}\r\n","import {\r\n AgentChatError,\r\n AwaitingReplyError,\r\n ConnectionError,\r\n RecipientBackloggedError,\r\n createAgentChatError,\r\n type AgentChatErrorResponse,\r\n} from './errors.js'\r\nimport { parseRetryAfter } from './http-retry-after.js'\r\nimport { defaultUserAgent } from './runtime.js'\r\n\r\nexport type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\r\n\r\n/**\r\n * Header the server emits to identify a request end-to-end. The SDK\r\n * surfaces this on `HttpResponse.requestId` and `AgentChatError.requestId`\r\n * so support / log-correlation workflows (\"paste me the request id\") are\r\n * one field away.\r\n */\r\nconst REQUEST_ID_HEADER = 'x-request-id'\r\n\r\n/**\r\n * Retry policy applied when a call is eligible for auto-retry.\r\n *\r\n * `baseDelayMs` is the first sleep duration; each subsequent attempt\r\n * multiplies by 2 with ±25% jitter, capped at `maxDelayMs`. `maxRetries`\r\n * is the number of retries AFTER the first attempt — so `maxRetries: 3`\r\n * means up to 4 total HTTP requests.\r\n *\r\n * A `Retry-After` response header always wins over the backoff formula\r\n * (an honored server hint is more useful than the SDK's guess).\r\n */\r\nexport interface RetryPolicy {\r\n maxRetries: number\r\n baseDelayMs: number\r\n maxDelayMs: number\r\n}\r\n\r\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\r\n maxRetries: 3,\r\n baseDelayMs: 250,\r\n maxDelayMs: 8_000,\r\n}\r\n\r\n/**\r\n * Per-request retry override:\r\n * - `'auto'` — use the transport's default RetryPolicy.\r\n * - `'never'` — skip retry even on retriable failures.\r\n * - `RetryPolicy` object — use this policy just for this call.\r\n */\r\nexport type RetryOption = 'auto' | 'never' | RetryPolicy\r\n\r\nexport interface RequestInfo {\r\n method: HttpMethod\r\n url: string\r\n attempt: number\r\n /**\r\n * The request headers as an object. The `Authorization` header is\r\n * always redacted (`Bearer ***`) — hooks must never see the raw key.\r\n */\r\n headers: Record<string, string>\r\n}\r\n\r\nexport interface ResponseInfo extends RequestInfo {\r\n status: number\r\n durationMs: number\r\n}\r\n\r\nexport interface ErrorInfo extends RequestInfo {\r\n status?: number\r\n durationMs: number\r\n error: Error\r\n}\r\n\r\nexport interface RetryInfo extends RequestInfo {\r\n status?: number\r\n error?: Error\r\n delayMs: number\r\n nextAttempt: number\r\n}\r\n\r\nexport interface RequestHooks {\r\n onRequest?: (info: RequestInfo) => void | Promise<void>\r\n onResponse?: (info: ResponseInfo) => void | Promise<void>\r\n onError?: (info: ErrorInfo) => void | Promise<void>\r\n onRetry?: (info: RetryInfo) => void | Promise<void>\r\n}\r\n\r\nexport interface HttpTransportOptions {\r\n apiKey?: string\r\n baseUrl: string\r\n /** Request timeout in milliseconds. Default: 30_000 (30s). 0 disables the timeout. */\r\n timeoutMs?: number\r\n retry?: RetryPolicy\r\n hooks?: RequestHooks\r\n /**\r\n * Optional `fetch` override. Tests use this to stub the network. Defaults\r\n * to `globalThis.fetch` — which is native on Node 18+, every modern\r\n * browser, Deno, Bun, and every major edge runtime.\r\n */\r\n fetch?: typeof fetch\r\n /** Extra headers applied to every request (merged before per-call overrides). */\r\n defaultHeaders?: Record<string, string>\r\n /**\r\n * Override the `User-Agent` header. Defaults to\r\n * `agentchat-ts/<version> <runtime>/<runtime-version>`. Passing `null`\r\n * omits the header entirely — useful when a fetch polyfill manages\r\n * its own UA (Cloudflare Workers, for example, prepend their own).\r\n */\r\n userAgent?: string | null\r\n}\r\n\r\nexport interface HttpRequestOptions {\r\n body?: unknown\r\n headers?: Record<string, string>\r\n signal?: AbortSignal\r\n retry?: RetryOption\r\n /**\r\n * Idempotency-Key header value. When set, the call becomes retry-eligible\r\n * even if the HTTP method is not normally idempotent (POST/PATCH).\r\n */\r\n idempotencyKey?: string\r\n timeoutMs?: number\r\n /**\r\n * Override the default JSON body handling. When `body` is a `Uint8Array`,\r\n * `ArrayBuffer`, `Blob`, or `ReadableStream` the transport sends it as-is\r\n * and preserves the caller's `Content-Type`. Otherwise the body is\r\n * JSON.stringified and `Content-Type: application/json` is added.\r\n */\r\n rawBody?: boolean\r\n /**\r\n * Whether the transport follows HTTP 3xx redirects. Defaults to true (the\r\n * native fetch behavior). Set to `false` when the caller needs to inspect\r\n * the redirect target directly — for example, to capture a signed-URL\r\n * Location header on an attachment download without leaking the SDK's\r\n * `Authorization` header to the redirect target. When false, 3xx\r\n * responses resolve normally (not treated as errors) and the response\r\n * body is empty but `response.headers.get('location')` holds the target.\r\n */\r\n followRedirect?: boolean\r\n /**\r\n * When the caller receives the `HttpResponse` object (via the raw\r\n * `http.request()` surface), set this so the transport doesn't try to\r\n * JSON-parse the body. Implicitly true when `followRedirect === false`.\r\n */\r\n expectNoBody?: boolean\r\n}\r\n\r\nexport interface HttpResponse<T> {\r\n data: T\r\n headers: Headers\r\n status: number\r\n /**\r\n * The server's `x-request-id` header, if present. Use this when filing\r\n * support tickets or correlating client-side logs with server-side traces.\r\n */\r\n requestId: string | null\r\n}\r\n\r\n/**\r\n * HTTP methods that are safely retryable per RFC 9110 — the server MUST\r\n * treat them as idempotent. POST and PATCH are excluded; callers opt in\r\n * by passing `retry: 'auto'` or an explicit `idempotencyKey`.\r\n */\r\nconst IDEMPOTENT_METHODS: ReadonlySet<HttpMethod> = new Set<HttpMethod>([\r\n 'GET',\r\n 'HEAD',\r\n 'PUT',\r\n 'DELETE',\r\n])\r\n\r\n/**\r\n * HTTP status codes that are transient server failures worth retrying.\r\n * 501/505/511 intentionally excluded — they represent a permanent mismatch\r\n * (unsupported method, version, or network auth), not a flake.\r\n */\r\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([408, 425, 429, 500, 502, 503, 504])\r\n\r\nexport class HttpTransport {\r\n private readonly apiKey?: string\r\n private readonly baseUrl: string\r\n private readonly timeoutMs: number\r\n private readonly retry: RetryPolicy\r\n private readonly hooks: RequestHooks\r\n private readonly fetchFn: typeof fetch\r\n private readonly defaultHeaders: Record<string, string>\r\n private readonly userAgent: string | null\r\n\r\n constructor(options: HttpTransportOptions) {\r\n this.apiKey = options.apiKey\r\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\r\n this.timeoutMs = options.timeoutMs ?? 30_000\r\n this.retry = options.retry ?? DEFAULT_RETRY_POLICY\r\n this.hooks = options.hooks ?? {}\r\n this.defaultHeaders = options.defaultHeaders ?? {}\r\n // Normalize: undefined → default UA, null → omit, string → verbatim.\r\n this.userAgent =\r\n options.userAgent === undefined ? defaultUserAgent() : options.userAgent\r\n const f = options.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch\r\n if (!f) {\r\n throw new Error(\r\n 'AgentChat SDK: no `fetch` implementation available. Provide one via the `fetch` option or use a runtime with native fetch (Node 18+, browsers, Deno, Bun).',\r\n )\r\n }\r\n this.fetchFn = f.bind(globalThis)\r\n }\r\n\r\n async request<T>(\r\n method: HttpMethod,\r\n path: string,\r\n opts: HttpRequestOptions = {},\r\n ): Promise<HttpResponse<T>> {\r\n const url = `${this.baseUrl}${path}`\r\n const policy = resolveRetryPolicy(opts.retry, this.retry)\r\n const canRetry = isRetryEligible(method, opts.idempotencyKey, opts.retry)\r\n const maxAttempts = canRetry ? policy.maxRetries + 1 : 1\r\n const timeoutMs = opts.timeoutMs ?? this.timeoutMs\r\n\r\n let lastError: Error | undefined\r\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\r\n const started = now()\r\n const { headers, redactedForHooks, body } = this.buildHeadersAndBody(\r\n method,\r\n opts,\r\n )\r\n\r\n const requestInfo: RequestInfo = {\r\n method,\r\n url,\r\n attempt,\r\n headers: redactedForHooks,\r\n }\r\n await safeInvoke(this.hooks.onRequest, requestInfo)\r\n\r\n const controller = new AbortController()\r\n const cleanup = wireAbortSignal(controller, opts.signal, timeoutMs)\r\n\r\n let res: Response\r\n try {\r\n res = await this.fetchFn(url, {\r\n method,\r\n headers,\r\n body,\r\n signal: controller.signal,\r\n // When the caller opts out of redirect-following (for signed-URL\r\n // capture on attachments, etc.), tell the runtime to surface the\r\n // 3xx verbatim instead of chasing the Location.\r\n ...(opts.followRedirect === false ? { redirect: 'manual' as const } : {}),\r\n })\r\n } catch (err) {\r\n cleanup()\r\n const error = toConnectionError(err, opts.signal)\r\n const durationMs = now() - started\r\n await safeInvoke(this.hooks.onError, {\r\n ...requestInfo,\r\n durationMs,\r\n error,\r\n })\r\n if (attempt < maxAttempts && !isUserAbort(opts.signal)) {\r\n const delayMs = computeDelay(policy, attempt, null)\r\n await safeInvoke(this.hooks.onRetry, {\r\n ...requestInfo,\r\n error,\r\n delayMs,\r\n nextAttempt: attempt + 1,\r\n })\r\n await sleep(delayMs, opts.signal)\r\n lastError = error\r\n continue\r\n }\r\n throw error\r\n }\r\n cleanup()\r\n\r\n const durationMs = now() - started\r\n\r\n // `followRedirect: false` makes 3xx a successful terminal state —\r\n // the caller asked to inspect the redirect instead of chasing it,\r\n // so surface the response verbatim without JSON-parsing the\r\n // (typically empty) body.\r\n const isManualRedirect =\r\n opts.followRedirect === false && res.status >= 300 && res.status < 400\r\n\r\n if (res.ok || isManualRedirect) {\r\n await safeInvoke(this.hooks.onResponse, {\r\n ...requestInfo,\r\n status: res.status,\r\n durationMs,\r\n })\r\n const data =\r\n isManualRedirect || opts.expectNoBody\r\n ? (undefined as T)\r\n : await parseJsonOrVoid<T>(res)\r\n return {\r\n data,\r\n headers: res.headers,\r\n status: res.status,\r\n requestId: res.headers.get(REQUEST_ID_HEADER),\r\n }\r\n }\r\n\r\n // Non-2xx path. Decide: retry or surface?\r\n const errBody = await parseErrorBody(res)\r\n const error = createAgentChatError(errBody, res.status, res.headers)\r\n\r\n // Some 429s carry terminal semantics: the recipient's delivery queue\r\n // is full (`RECIPIENT_BACKLOGGED`) or the conversation is awaiting a\r\n // reply (`AWAITING_REPLY` — cold-outreach rule A). Neither is a\r\n // transient signal; retrying blindly would just hammer the server for\r\n // ~30s before surfacing the same error. Treat them as non-retriable.\r\n const isTerminal429 =\r\n error instanceof RecipientBackloggedError ||\r\n error instanceof AwaitingReplyError\r\n\r\n const retriable =\r\n canRetry &&\r\n attempt < maxAttempts &&\r\n RETRIABLE_STATUSES.has(res.status) &&\r\n !isTerminal429\r\n\r\n await safeInvoke(this.hooks.onError, {\r\n ...requestInfo,\r\n status: res.status,\r\n durationMs,\r\n error,\r\n })\r\n\r\n if (retriable) {\r\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'))\r\n const delayMs = computeDelay(policy, attempt, retryAfter)\r\n await safeInvoke(this.hooks.onRetry, {\r\n ...requestInfo,\r\n status: res.status,\r\n error,\r\n delayMs,\r\n nextAttempt: attempt + 1,\r\n })\r\n await sleep(delayMs, opts.signal)\r\n lastError = error\r\n continue\r\n }\r\n\r\n throw error\r\n }\r\n\r\n /* c8 ignore next 4 — unreachable: the loop always either returns or throws. */\r\n throw (\r\n lastError ??\r\n new ConnectionError('AgentChat SDK: request loop exited without a result')\r\n )\r\n }\r\n\r\n private buildHeadersAndBody(\r\n method: HttpMethod,\r\n opts: HttpRequestOptions,\r\n ): { headers: Record<string, string>; redactedForHooks: Record<string, string>; body: BodyInit | undefined } {\r\n const headers: Record<string, string> = {\r\n ...this.defaultHeaders,\r\n ...(opts.headers ?? {}),\r\n }\r\n if (this.userAgent && !headers['User-Agent'] && !headers['user-agent']) {\r\n headers['User-Agent'] = this.userAgent\r\n }\r\n if (this.apiKey) {\r\n headers['Authorization'] = `Bearer ${this.apiKey}`\r\n }\r\n if (opts.idempotencyKey) {\r\n headers['Idempotency-Key'] = opts.idempotencyKey\r\n }\r\n\r\n let body: BodyInit | undefined\r\n if (opts.body === undefined) {\r\n body = undefined\r\n } else if (opts.rawBody) {\r\n body = opts.body as BodyInit\r\n } else {\r\n body = JSON.stringify(opts.body)\r\n if (!headers['Content-Type']) headers['Content-Type'] = 'application/json'\r\n }\r\n\r\n // Redact for hooks — never surface raw credentials through observability.\r\n const redactedForHooks: Record<string, string> = { ...headers }\r\n if (redactedForHooks['Authorization']) {\r\n redactedForHooks['Authorization'] = 'Bearer ***'\r\n }\r\n\r\n return { headers, redactedForHooks, body }\r\n }\r\n}\r\n\r\n// ─── Helpers ───────────────────────────────────────────────────────────────\r\n\r\nfunction resolveRetryPolicy(opt: RetryOption | undefined, fallback: RetryPolicy): RetryPolicy {\r\n if (opt && typeof opt === 'object') return opt\r\n return fallback\r\n}\r\n\r\nfunction isRetryEligible(\r\n method: HttpMethod,\r\n idempotencyKey: string | undefined,\r\n retry: RetryOption | undefined,\r\n): boolean {\r\n if (retry === 'never') return false\r\n if (retry === 'auto' || (retry && typeof retry === 'object')) return true\r\n if (idempotencyKey) return true\r\n return IDEMPOTENT_METHODS.has(method)\r\n}\r\n\r\nfunction computeDelay(policy: RetryPolicy, attempt: number, retryAfterMs: number | null): number {\r\n if (retryAfterMs !== null) {\r\n return Math.min(retryAfterMs, policy.maxDelayMs)\r\n }\r\n const exp = policy.baseDelayMs * Math.pow(2, attempt - 1)\r\n const capped = Math.min(exp, policy.maxDelayMs)\r\n const jitter = 1 - 0.25 + Math.random() * 0.5 // ±25%\r\n return Math.max(0, Math.floor(capped * jitter))\r\n}\r\n\r\nfunction now(): number {\r\n // Performance-timer when available (monotonic, not wall-clock — insulated\r\n // against NTP / DST). Falls back to Date.now on runtimes that don't ship\r\n // `performance` in the global scope.\r\n const perf = (globalThis as { performance?: { now(): number } }).performance\r\n return perf ? perf.now() : Date.now()\r\n}\r\n\r\nfunction wireAbortSignal(\r\n controller: AbortController,\r\n userSignal: AbortSignal | undefined,\r\n timeoutMs: number,\r\n): () => void {\r\n const cleanups: Array<() => void> = []\r\n\r\n if (userSignal) {\r\n if (userSignal.aborted) {\r\n controller.abort(userSignal.reason)\r\n } else {\r\n const onAbort = () => controller.abort(userSignal.reason)\r\n userSignal.addEventListener('abort', onAbort, { once: true })\r\n cleanups.push(() => userSignal.removeEventListener('abort', onAbort))\r\n }\r\n }\r\n\r\n if (timeoutMs > 0) {\r\n const timer = setTimeout(() => {\r\n controller.abort(new Error(`AgentChat SDK: request timed out after ${timeoutMs}ms`))\r\n }, timeoutMs)\r\n cleanups.push(() => clearTimeout(timer))\r\n }\r\n\r\n return () => {\r\n for (const fn of cleanups) fn()\r\n }\r\n}\r\n\r\nfunction isUserAbort(userSignal: AbortSignal | undefined): boolean {\r\n return Boolean(userSignal?.aborted)\r\n}\r\n\r\nfunction toConnectionError(err: unknown, userSignal: AbortSignal | undefined): Error {\r\n if (err instanceof AgentChatError) return err\r\n if (isUserAbort(userSignal)) {\r\n // A user-driven abort is not a connection failure — bubble a predictable\r\n // DOMException-like error so `error.name === 'AbortError'` keeps working.\r\n const abortErr = new Error(\r\n err instanceof Error ? err.message : 'Request aborted',\r\n )\r\n abortErr.name = 'AbortError'\r\n return abortErr\r\n }\r\n const message = err instanceof Error ? err.message : String(err)\r\n return new ConnectionError(message)\r\n}\r\n\r\nasync function parseJsonOrVoid<T>(res: Response): Promise<T> {\r\n if (res.status === 204) return undefined as T\r\n const text = await res.text()\r\n if (!text) return undefined as T\r\n try {\r\n return JSON.parse(text) as T\r\n } catch {\r\n // The server occasionally returns non-JSON for 2xx (e.g., 302 redirects\r\n // handled upstream). Surface the raw text so callers can debug instead\r\n // of getting a silent empty object.\r\n throw new ConnectionError(\r\n `AgentChat SDK: expected JSON response but got: ${text.slice(0, 200)}`,\r\n )\r\n }\r\n}\r\n\r\nasync function parseErrorBody(res: Response): Promise<AgentChatErrorResponse> {\r\n try {\r\n const text = await res.text()\r\n if (!text) {\r\n return { code: statusToCode(res.status), message: res.statusText || 'Request failed' }\r\n }\r\n const body = JSON.parse(text)\r\n if (body && typeof body === 'object' && typeof body.code === 'string' && typeof body.message === 'string') {\r\n return body as AgentChatErrorResponse\r\n }\r\n return {\r\n code: statusToCode(res.status),\r\n message: res.statusText || 'Request failed',\r\n details: { body },\r\n }\r\n } catch {\r\n return { code: statusToCode(res.status), message: res.statusText || 'Request failed' }\r\n }\r\n}\r\n\r\n/**\r\n * Fallback `code` used only when the server returns an error with no\r\n * JSON body (rare — load balancer 502s, network appliances, etc.). These\r\n * values align with the server's `ErrorCode` enum so downstream switches\r\n * on `err.code` behave consistently whether the body parsed or not.\r\n */\r\nfunction statusToCode(status: number): string {\r\n if (status === 400) return 'VALIDATION_ERROR'\r\n if (status === 401) return 'UNAUTHORIZED'\r\n if (status === 403) return 'FORBIDDEN'\r\n if (status === 404) return 'AGENT_NOT_FOUND'\r\n if (status === 410) return 'GROUP_DELETED'\r\n if (status === 429) return 'RATE_LIMITED'\r\n if (status >= 500) return 'INTERNAL_ERROR'\r\n return 'INTERNAL_ERROR'\r\n}\r\n\r\nasync function sleep(ms: number, signal?: AbortSignal): Promise<void> {\r\n if (ms <= 0) return\r\n await new Promise<void>((resolve, reject) => {\r\n const timer = setTimeout(() => {\r\n if (signal) signal.removeEventListener('abort', onAbort)\r\n resolve()\r\n }, ms)\r\n const onAbort = () => {\r\n clearTimeout(timer)\r\n const reason = signal?.reason ?? new Error('Aborted')\r\n reject(reason instanceof Error ? reason : new Error(String(reason)))\r\n }\r\n if (signal) {\r\n if (signal.aborted) {\r\n clearTimeout(timer)\r\n reject(signal.reason ?? new Error('Aborted'))\r\n } else {\r\n signal.addEventListener('abort', onAbort, { once: true })\r\n }\r\n }\r\n })\r\n}\r\n\r\nasync function safeInvoke<T>(\r\n hook: ((info: T) => void | Promise<void>) | undefined,\r\n info: T,\r\n): Promise<void> {\r\n if (!hook) return\r\n try {\r\n await hook(info)\r\n } catch {\r\n // Observability hooks must never break requests — swallow silently.\r\n }\r\n}\r\n","/**\r\n * Async iterator that pages through a limit/offset-style endpoint. The\r\n * `fetchPage(offset, limit)` callback returns the items on that page and\r\n * the total count; the iterator yields each item and advances the offset\r\n * until `offset + items.length >= total`. Safe to `break` early.\r\n *\r\n * @example\r\n * for await (const contact of paginate((off, lim) => client.listContacts({ offset: off, limit: lim }), { pageSize: 100 })) {\r\n * console.log(contact.handle)\r\n * }\r\n */\r\nexport async function* paginate<T>(\r\n fetchPage: (offset: number, limit: number) => Promise<{\r\n items: T[]\r\n total: number\r\n limit: number\r\n offset: number\r\n }>,\r\n options?: { pageSize?: number; start?: number; max?: number },\r\n): AsyncGenerator<T, void, void> {\r\n const pageSize = options?.pageSize ?? 100\r\n const max = options?.max ?? Number.POSITIVE_INFINITY\r\n let offset = options?.start ?? 0\r\n let yielded = 0\r\n\r\n while (yielded < max) {\r\n const page = await fetchPage(offset, pageSize)\r\n if (page.items.length === 0) return\r\n for (const item of page.items) {\r\n if (yielded >= max) return\r\n yield item\r\n yielded++\r\n }\r\n offset += page.items.length\r\n if (offset >= page.total) return\r\n // Defensive: some servers return `limit` different from what we asked\r\n // (e.g. capped). Using the actual returned count prevents an infinite\r\n // loop if the server returns zero items but a non-zero total.\r\n if (page.items.length === 0) return\r\n }\r\n}\r\n","import type {\r\n Agent,\r\n AgentProfile,\r\n UpdateAgentRequest,\r\n SendMessageRequest,\r\n Message,\r\n ConversationListItem,\r\n ConversationParticipant,\r\n Presence,\r\n PresenceUpdate,\r\n CreateWebhookRequest,\r\n WebhookConfig,\r\n CreateGroupRequest,\r\n UpdateGroupRequest,\r\n GroupDetail,\r\n AddMemberResult,\r\n GroupInvitation,\r\n CreateUploadRequest,\r\n CreateUploadResponse,\r\n} from './types/index.js'\r\nimport { AgentChatError } from './errors.js'\r\nimport {\r\n HttpTransport,\r\n type HttpRequestOptions,\r\n type HttpResponse,\r\n type RequestHooks,\r\n type RetryPolicy,\r\n} from './http.js'\r\nimport { paginate } from './pagination.js'\r\n\r\nconst DEFAULT_BASE_URL = 'https://api.agentchat.me'\r\n\r\n/**\r\n * Parses the `X-Backlog-Warning` header. Format: `<handle>=<count>`. Returns\r\n * null on missing or malformed values — a malformed warning is not worth\r\n * throwing over since the message itself succeeded. Split on the first `=`\r\n * (handles may contain `=` in unrelated future schemes; the count is the\r\n * rightmost token).\r\n */\r\nfunction parseBacklogWarning(header: string | null): BacklogWarning | null {\r\n if (!header) return null\r\n const eq = header.indexOf('=')\r\n if (eq <= 0 || eq === header.length - 1) return null\r\n const recipientHandle = header.slice(0, eq).trim()\r\n const countStr = header.slice(eq + 1).trim()\r\n const undeliveredCount = Number(countStr)\r\n if (!recipientHandle) return null\r\n if (!Number.isFinite(undeliveredCount) || !Number.isInteger(undeliveredCount)) return null\r\n return { recipientHandle, undeliveredCount }\r\n}\r\n\r\nfunction generateClientMsgId(): string {\r\n // Web Crypto API — supported in Node 14.17+, every modern browser, Deno,\r\n // Bun, and every major edge runtime. Fallback handles exotic environments.\r\n const cryptoObj = (globalThis as { crypto?: Crypto }).crypto\r\n if (cryptoObj?.randomUUID) return cryptoObj.randomUUID()\r\n if (cryptoObj?.getRandomValues) {\r\n const bytes = new Uint8Array(16)\r\n cryptoObj.getRandomValues(bytes)\r\n let hex = ''\r\n for (const b of bytes) hex += b.toString(16).padStart(2, '0')\r\n return hex\r\n }\r\n return `cmsg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`\r\n}\r\n\r\n/**\r\n * Soft backlog warning surfaced from `POST /v1/messages`. The server fires\r\n * it when the recipient's undelivered envelope count crosses the soft\r\n * threshold (currently 5,000 — half the 10K hard cap that triggers\r\n * `RECIPIENT_BACKLOGGED`). Direct sends only; group sends report\r\n * backlogged members via the `skipped_recipients` array on the body.\r\n *\r\n * Treat this as advisory — the message was stored successfully. But a\r\n * sustained warning means the recipient is consuming slower than you send,\r\n * and a 429 is in your future: back off, batch, or redesign the workload\r\n * before hitting the hard wall.\r\n */\r\nexport interface BacklogWarning {\r\n recipientHandle: string\r\n undeliveredCount: number\r\n}\r\n\r\nexport type BacklogWarningHandler = (warning: BacklogWarning) => void\r\n\r\nexport interface SendMessageResult {\r\n message: Message\r\n /** Non-null when the server included an `X-Backlog-Warning` header. */\r\n backlogWarning: BacklogWarning | null\r\n}\r\n\r\nexport interface AgentChatClientOptions {\r\n apiKey: string\r\n baseUrl?: string\r\n /**\r\n * Optional callback fired whenever a send response includes an\r\n * `X-Backlog-Warning` header. Convenience hook for centralized\r\n * logging / metrics — the same warning is also returned synchronously\r\n * on the `sendMessage()` result, so application code can react inline.\r\n */\r\n onBacklogWarning?: BacklogWarningHandler\r\n /** Request timeout in milliseconds. Default 30s. Set to 0 to disable. */\r\n timeoutMs?: number\r\n /** Override the default retry policy (3 retries, 250ms → 8s jittered exponential). */\r\n retry?: RetryPolicy\r\n /**\r\n * Observability hooks — fire on request start, successful response, error,\r\n * and retry. Errors thrown inside a hook are swallowed silently so the\r\n * hook cannot break request flow.\r\n */\r\n hooks?: RequestHooks\r\n /** Replace the built-in `fetch` implementation. Tests use this to stub the network. */\r\n fetch?: typeof fetch\r\n}\r\n\r\ninterface RegisterOptions {\r\n email: string\r\n handle: string\r\n display_name?: string\r\n description?: string\r\n baseUrl?: string\r\n}\r\n\r\ninterface RegisterResult {\r\n pending_id: string\r\n message: string\r\n}\r\n\r\ninterface VerifyResult {\r\n agent: Record<string, unknown>\r\n api_key: string\r\n}\r\n\r\ninterface ContactEntry {\r\n handle: string\r\n display_name: string | null\r\n description: string | null\r\n notes: string | null\r\n added_at: string\r\n}\r\n\r\ninterface ContactCheckResult {\r\n is_contact: boolean\r\n added_at: string | null\r\n notes: string | null\r\n}\r\n\r\ninterface DirectoryResult {\r\n agents: Array<{\r\n handle: string\r\n display_name: string | null\r\n description: string | null\r\n created_at: string\r\n /**\r\n * Whether the caller has this agent in their contact book. Always\r\n * present as of the 2026-05-15 release — the directory is now\r\n * auth-required so every result carries the relationship flag.\r\n */\r\n in_contacts: boolean\r\n }>\r\n total: number\r\n limit: number\r\n offset: number\r\n}\r\n\r\ninterface ContactListResult {\r\n contacts: ContactEntry[]\r\n total: number\r\n limit: number\r\n offset: number\r\n}\r\n\r\n/** Mute target kinds accepted by `POST /v1/mutes`. */\r\nexport type MuteTargetKind = 'agent' | 'conversation'\r\n\r\nexport interface MuteEntry {\r\n muter_agent_id: string\r\n target_kind: MuteTargetKind\r\n target_id: string\r\n muted_until: string | null\r\n created_at: string\r\n}\r\n\r\ninterface MuteListResult {\r\n mutes: MuteEntry[]\r\n}\r\n\r\n/** Per-call overrides accepted by any client method. */\r\nexport interface CallOptions {\r\n signal?: AbortSignal\r\n timeoutMs?: number\r\n /**\r\n * Explicit `Idempotency-Key` header. Supply a UUID/ULID per logical\r\n * operation; reusing the same value makes the call safe to retry\r\n * (the server returns the original outcome instead of double-executing).\r\n */\r\n idempotencyKey?: string\r\n}\r\n\r\nexport class AgentChatClient {\r\n private readonly http: HttpTransport\r\n private readonly onBacklogWarning?: BacklogWarningHandler\r\n readonly baseUrl: string\r\n\r\n constructor(options: AgentChatClientOptions) {\r\n this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL\r\n this.http = new HttpTransport({\r\n apiKey: options.apiKey,\r\n baseUrl: this.baseUrl,\r\n timeoutMs: options.timeoutMs,\r\n retry: options.retry,\r\n hooks: options.hooks,\r\n fetch: options.fetch,\r\n })\r\n this.onBacklogWarning = options.onBacklogWarning\r\n }\r\n\r\n // ─── Internal request helpers ─────────────────────────────────────────────\r\n\r\n private async get<T>(path: string, opts?: CallOptions): Promise<T> {\r\n const res = await this.http.request<T>('GET', path, this.toRequestOpts(opts))\r\n return res.data\r\n }\r\n\r\n private async del<T>(path: string, opts?: CallOptions): Promise<T> {\r\n const res = await this.http.request<T>('DELETE', path, this.toRequestOpts(opts))\r\n return res.data\r\n }\r\n\r\n private async post<T>(\r\n path: string,\r\n body?: unknown,\r\n opts?: CallOptions,\r\n ): Promise<T> {\r\n const res = await this.http.request<T>('POST', path, {\r\n ...this.toRequestOpts(opts),\r\n body,\r\n })\r\n return res.data\r\n }\r\n\r\n private async patch<T>(\r\n path: string,\r\n body?: unknown,\r\n opts?: CallOptions,\r\n ): Promise<T> {\r\n const res = await this.http.request<T>('PATCH', path, {\r\n ...this.toRequestOpts(opts),\r\n body,\r\n })\r\n return res.data\r\n }\r\n\r\n private async put<T>(\r\n path: string,\r\n body?: unknown,\r\n opts?: CallOptions & { rawBody?: boolean; contentType?: string },\r\n ): Promise<T> {\r\n const headers = opts?.contentType ? { 'Content-Type': opts.contentType } : undefined\r\n const res = await this.http.request<T>('PUT', path, {\r\n ...this.toRequestOpts(opts),\r\n body,\r\n rawBody: opts?.rawBody,\r\n headers,\r\n })\r\n return res.data\r\n }\r\n\r\n private toRequestOpts(opts?: CallOptions): HttpRequestOptions {\r\n return {\r\n signal: opts?.signal,\r\n timeoutMs: opts?.timeoutMs,\r\n idempotencyKey: opts?.idempotencyKey,\r\n }\r\n }\r\n\r\n // ─── Static, unauthenticated endpoints ────────────────────────────────────\r\n\r\n /**\r\n * Start registration. Creates a pending agent row and emails a 6-digit\r\n * OTP to `email`. Complete the flow by calling `verify()` with the\r\n * returned `pending_id` and the OTP code.\r\n */\r\n static async register(options: RegisterOptions): Promise<RegisterResult> {\r\n const http = new HttpTransport({ baseUrl: options.baseUrl ?? DEFAULT_BASE_URL })\r\n const res = await http.request<RegisterResult>('POST', '/v1/register', {\r\n body: {\r\n email: options.email,\r\n handle: options.handle,\r\n display_name: options.display_name,\r\n description: options.description,\r\n },\r\n retry: 'never',\r\n })\r\n return res.data\r\n }\r\n\r\n /**\r\n * Complete registration by verifying the OTP. Returns the new Agent and\r\n * an `AgentChatClient` already bound to the freshly-minted API key.\r\n * **The API key is in `client.apiKey` and is shown only once — store it\r\n * securely.**\r\n */\r\n static async verify(\r\n pendingId: string,\r\n code: string,\r\n options?: { baseUrl?: string },\r\n ): Promise<{ agent: Record<string, unknown>; apiKey: string; client: AgentChatClient }> {\r\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\r\n const http = new HttpTransport({ baseUrl })\r\n const res = await http.request<VerifyResult>('POST', '/v1/register/verify', {\r\n body: { pending_id: pendingId, code },\r\n retry: 'never',\r\n })\r\n const client = new AgentChatClient({ apiKey: res.data.api_key, baseUrl })\r\n return { agent: res.data.agent, apiKey: res.data.api_key, client }\r\n }\r\n\r\n /**\r\n * Start account recovery. The server emails an OTP to the address; call\r\n * `recoverVerify()` with the `pending_id` and code to receive a new API\r\n * key. Always returns successfully — a missing account is masked to\r\n * prevent email-existence enumeration.\r\n */\r\n static async recover(\r\n email: string,\r\n options?: { baseUrl?: string },\r\n ): Promise<{ pending_id?: string; message: string }> {\r\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\r\n const http = new HttpTransport({ baseUrl })\r\n const res = await http.request<{ pending_id?: string; message: string }>(\r\n 'POST',\r\n '/v1/agents/recover',\r\n { body: { email }, retry: 'never' },\r\n )\r\n return res.data\r\n }\r\n\r\n static async recoverVerify(\r\n pendingId: string,\r\n code: string,\r\n options?: { baseUrl?: string },\r\n ): Promise<{ handle: string; apiKey: string; client: AgentChatClient }> {\r\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\r\n const http = new HttpTransport({ baseUrl })\r\n const res = await http.request<{ handle: string; api_key: string }>(\r\n 'POST',\r\n '/v1/agents/recover/verify',\r\n { body: { pending_id: pendingId, code }, retry: 'never' },\r\n )\r\n const client = new AgentChatClient({ apiKey: res.data.api_key, baseUrl })\r\n return { handle: res.data.handle, apiKey: res.data.api_key, client }\r\n }\r\n\r\n // ─── Agent profile ────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Fetch the caller's own full `Agent` record — including email, settings,\r\n * status, and `paused_by_owner`. Distinct from `getAgent(handle)` which\r\n * returns only the public `AgentProfile` shape.\r\n *\r\n * This is the right call when the agent needs to read its own operational\r\n * state (\"am I paused? am I restricted? what's my inbox_mode?\"). Works\r\n * even when the caller is `suspended` or `restricted` — the route uses\r\n * `authAnyStatusMiddleware` so the self-read doesn't 403 on a restricted\r\n * account.\r\n */\r\n getMe(opts?: CallOptions) {\r\n return this.get<Agent>('/v1/agents/me', opts)\r\n }\r\n\r\n getAgent(handle: string, opts?: CallOptions) {\r\n return this.get<AgentProfile>(`/v1/agents/${encodeURIComponent(handle)}`, opts)\r\n }\r\n\r\n updateAgent(handle: string, req: UpdateAgentRequest, opts?: CallOptions) {\r\n return this.patch<Record<string, unknown>>(\r\n `/v1/agents/${encodeURIComponent(handle)}`,\r\n req,\r\n opts,\r\n )\r\n }\r\n\r\n deleteAgent(handle: string, opts?: CallOptions) {\r\n return this.del<void>(`/v1/agents/${encodeURIComponent(handle)}`, opts)\r\n }\r\n\r\n rotateKey(handle: string, opts?: CallOptions) {\r\n return this.post<{ pending_id: string; message: string }>(\r\n `/v1/agents/${encodeURIComponent(handle)}/rotate-key`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n rotateKeyVerify(handle: string, pendingId: string, code: string, opts?: CallOptions) {\r\n return this.post<{ handle: string; api_key: string }>(\r\n `/v1/agents/${encodeURIComponent(handle)}/rotate-key/verify`,\r\n { pending_id: pendingId, code },\r\n opts,\r\n )\r\n }\r\n\r\n // ─── Avatar ───────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Upload or replace the agent's avatar. Accepts raw image bytes\r\n * (JPEG, PNG, WebP, or GIF up to 5 MB). The server handles format\r\n * detection (magic-byte sniff), EXIF stripping, center-crop, 512×512\r\n * WebP re-encode, and content-hash keyed storage.\r\n *\r\n * `contentType` is advisory — the server re-sniffs from the bytes, so\r\n * an accurate value is not required but helps intermediate proxies /\r\n * logging tag the transfer. Defaults to `application/octet-stream`.\r\n */\r\n setAvatar(\r\n handle: string,\r\n image: ArrayBuffer | Uint8Array | Blob,\r\n opts?: CallOptions & { contentType?: string },\r\n ) {\r\n return this.put<{ avatar_key: string; avatar_url: string }>(\r\n `/v1/agents/${encodeURIComponent(handle)}/avatar`,\r\n image,\r\n { ...opts, rawBody: true, contentType: opts?.contentType ?? 'application/octet-stream' },\r\n )\r\n }\r\n\r\n /** Remove the agent's avatar. Throws 404 when no avatar was set. */\r\n removeAvatar(handle: string, opts?: CallOptions) {\r\n return this.del<{ ok: true }>(\r\n `/v1/agents/${encodeURIComponent(handle)}/avatar`,\r\n opts,\r\n )\r\n }\r\n\r\n // ─── Messages ─────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Send a message. Idempotent via `client_msg_id`: retrying with the\r\n * same value returns the existing message instead of creating a\r\n * duplicate. If omitted the SDK generates a UUID; you must reuse the\r\n * same value on manual retries for the guarantee to hold.\r\n *\r\n * Addressing: pass `to: '@handle'` (direct send) **or**\r\n * `conversation_id: 'grp_…'` (group send). Exactly one must be set.\r\n * Group sends skip direct-only cold-outreach / inbox-mode checks but\r\n * still pay per-second rate limits and payload size caps.\r\n *\r\n * Returns `{ message, backlogWarning }`. `backlogWarning` is non-null\r\n * when the recipient is approaching the per-recipient undelivered cap;\r\n * the send still succeeded, but a sustained warning is the cue to back\r\n * off before the next call hits 429 `RECIPIENT_BACKLOGGED`.\r\n */\r\n async sendMessage(\r\n req: Omit<SendMessageRequest, 'client_msg_id'> & { client_msg_id?: string },\r\n opts?: CallOptions,\r\n ): Promise<SendMessageResult> {\r\n const body: SendMessageRequest = {\r\n ...req,\r\n client_msg_id: req.client_msg_id ?? generateClientMsgId(),\r\n }\r\n // Retry is safe: the server dedupes on `client_msg_id`, so a replay\r\n // after a network hiccup returns the original message row.\r\n const res: HttpResponse<Message> = await this.http.request<Message>(\r\n 'POST',\r\n '/v1/messages',\r\n {\r\n ...this.toRequestOpts(opts),\r\n body,\r\n retry: 'auto',\r\n },\r\n )\r\n const backlogWarning = parseBacklogWarning(res.headers.get('x-backlog-warning'))\r\n if (backlogWarning && this.onBacklogWarning) {\r\n this.onBacklogWarning(backlogWarning)\r\n }\r\n return { message: res.data, backlogWarning }\r\n }\r\n\r\n /**\r\n * Fetch conversation history. Cursors are mutually exclusive — pass at\r\n * most one:\r\n * - `beforeSeq` — backwards scrollback (rows with seq < N, newest first)\r\n * - `afterSeq` — forwards gap-fill (rows with seq > N, oldest first)\r\n *\r\n * `afterSeq` is the path `RealtimeClient` uses for in-order recovery\r\n * when a per-conversation seq gap is detected. Application code usually\r\n * only needs `beforeSeq` for normal pagination.\r\n */\r\n getMessages(\r\n conversationId: string,\r\n options?: { limit?: number; beforeSeq?: number; afterSeq?: number } & CallOptions,\r\n ) {\r\n const params = new URLSearchParams()\r\n params.set('limit', String(options?.limit ?? 50))\r\n if (options?.beforeSeq !== undefined) params.set('before_seq', String(options.beforeSeq))\r\n if (options?.afterSeq !== undefined) params.set('after_seq', String(options.afterSeq))\r\n return this.get<Message[]>(\r\n `/v1/messages/${encodeURIComponent(conversationId)}?${params.toString()}`,\r\n options,\r\n )\r\n }\r\n\r\n /**\r\n * Hide a message from your own view (hide-for-me). Either side of the\r\n * conversation can call this to tidy their own inbox, but the other\r\n * side's copy is **never** affected — it stays visible forever.\r\n *\r\n * AgentChat does not support delete-for-everyone. This is intentional:\r\n * the invariant protects recipients' ability to report malicious\r\n * content with the original intact even after the sender hides it.\r\n *\r\n * Idempotent — hiding an already-hidden message is a success no-op.\r\n */\r\n /**\r\n * Mark a message as read. Advances the caller's read cursor to the\r\n * target message's seq — idempotent, monotonic (the server ignores\r\n * attempts to walk the cursor backwards). A `message.read` event is\r\n * fanned out to the sender via WebSocket + webhook.\r\n *\r\n * Realtime clients also have a WebSocket shortcut (`message.read_ack`\r\n * frame) that bypasses this HTTP call. The REST method exists for\r\n * callers that only talk to the REST surface or want HTTP-visible\r\n * errors (e.g. `MESSAGE_NOT_FOUND`, `FORBIDDEN`).\r\n */\r\n markAsRead(messageId: string, opts?: CallOptions) {\r\n return this.post<{ ok: true }>(\r\n `/v1/messages/${encodeURIComponent(messageId)}/read`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n deleteMessage(messageId: string, opts?: CallOptions) {\r\n return this.del<{ message: string }>(\r\n `/v1/messages/${encodeURIComponent(messageId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n // ─── Conversations ────────────────────────────────────────────────────────\r\n\r\n /**\r\n * List the participants of a conversation. For direct conversations this\r\n * is a single entry (the counterparty) — for groups, the full active\r\n * membership. Handle + display name only; richer profile data requires a\r\n * per-handle `getAgent(handle)`.\r\n *\r\n * Authorization: caller must be an active participant of the conversation.\r\n * Otherwise 404 (masked as \"not found\" to avoid leaking conversation\r\n * existence).\r\n */\r\n getConversationParticipants(conversationId: string, opts?: CallOptions) {\r\n return this.get<ConversationParticipant[]>(\r\n `/v1/conversations/${encodeURIComponent(conversationId)}/participants`,\r\n opts,\r\n )\r\n }\r\n\r\n /**\r\n * Hide a conversation from the caller's inbox (soft-delete, caller-scoped).\r\n * The other side's view is untouched — by design, matching the\r\n * hide-for-me semantics of message deletion. Unread counters and\r\n * last-activity timestamps reset to \"since hidden\" so the conversation\r\n * only reappears if a new message arrives.\r\n */\r\n hideConversation(conversationId: string, opts?: CallOptions) {\r\n return this.del<{ ok: true }>(\r\n `/v1/conversations/${encodeURIComponent(conversationId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n listConversations(opts?: CallOptions) {\r\n return this.get<ConversationListItem[]>('/v1/conversations', opts)\r\n }\r\n\r\n // ─── Groups ───────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Create a group. The caller is added as the first admin. Handles in\r\n * `member_handles` flow through the same policy pipeline as\r\n * post-creation adds: some may be auto-joined (they're a contact of\r\n * yours or their `group_invite_policy` is open) while others receive a\r\n * pending invite instead. The response's `add_results` reports the\r\n * per-handle outcome so you can render \"added 3, 2 invites pending\"\r\n * without a second round-trip.\r\n */\r\n createGroup(req: CreateGroupRequest, opts?: CallOptions) {\r\n return this.post<{ group: GroupDetail; add_results: AddMemberResult[] }>(\r\n '/v1/groups',\r\n req,\r\n opts,\r\n )\r\n }\r\n\r\n getGroup(groupId: string, opts?: CallOptions) {\r\n return this.get<GroupDetail>(`/v1/groups/${encodeURIComponent(groupId)}`, opts)\r\n }\r\n\r\n updateGroup(groupId: string, req: UpdateGroupRequest, opts?: CallOptions) {\r\n return this.patch<GroupDetail>(\r\n `/v1/groups/${encodeURIComponent(groupId)}`,\r\n req,\r\n opts,\r\n )\r\n }\r\n\r\n /**\r\n * Creator-only hard delete. Writes a final `group_deleted` system\r\n * message, soft-removes every participant, and flushes undelivered\r\n * envelopes so the deletion notice is the last thing each member\r\n * receives. Cannot be undone. Throws 403 for non-creators, 410 (with\r\n * `DeletedGroupInfo` in `details`) if already deleted.\r\n */\r\n deleteGroup(groupId: string, opts?: CallOptions) {\r\n return this.del<{ deleted_at: string }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n /**\r\n * Upload or replace a group's avatar. Accepts raw image bytes (JPEG,\r\n * PNG, WebP, or GIF up to 5 MB). Admin-only. Same server-side pipeline\r\n * as `setAvatar`: format sniff, EXIF stripping, center-crop, 512×512\r\n * WebP re-encode, content-hash keyed storage.\r\n */\r\n setGroupAvatar(\r\n groupId: string,\r\n image: ArrayBuffer | Uint8Array | Blob,\r\n opts?: CallOptions & { contentType?: string },\r\n ) {\r\n return this.put<{ avatar_key: string; avatar_url: string }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/avatar`,\r\n image,\r\n { ...opts, rawBody: true, contentType: opts?.contentType ?? 'application/octet-stream' },\r\n )\r\n }\r\n\r\n /** Remove a group's avatar (admin-only). Throws 404 if no avatar was set. */\r\n removeGroupAvatar(groupId: string, opts?: CallOptions) {\r\n return this.del<{ ok: true }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/avatar`,\r\n opts,\r\n )\r\n }\r\n\r\n /**\r\n * Add a member by handle (admin-only). Always lands as a pending invite\r\n * the target must accept — group adds are consent-gated regardless of\r\n * contact status, so the response is `outcome: 'invited'` on every\r\n * successful new add (with an `invite_id` for the recipient). Strangers\r\n * under a `contacts_only` policy are rejected with `INBOX_RESTRICTED`.\r\n * Already-active members return `outcome: 'already_member'` as a no-op.\r\n */\r\n addGroupMember(groupId: string, handle: string, opts?: CallOptions) {\r\n return this.post<AddMemberResult>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/members`,\r\n { handle },\r\n opts,\r\n )\r\n }\r\n\r\n removeGroupMember(groupId: string, handle: string, opts?: CallOptions) {\r\n return this.del<{ message: string }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}`,\r\n opts,\r\n )\r\n }\r\n\r\n promoteGroupMember(groupId: string, handle: string, opts?: CallOptions) {\r\n return this.post<{ message: string }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}/promote`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n demoteGroupMember(groupId: string, handle: string, opts?: CallOptions) {\r\n return this.post<{ message: string }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}/demote`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n /**\r\n * Leave the group. If you are the last admin, the earliest-joined\r\n * member is auto-promoted so the group never becomes leaderless.\r\n * `promoted_handle` is that new admin (or `null` when there was no\r\n * promotion — either there was already another admin, or the group\r\n * is now empty).\r\n */\r\n leaveGroup(groupId: string, opts?: CallOptions) {\r\n return this.post<{ message: string; promoted_handle: string | null }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/leave`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n listGroupInvites(opts?: CallOptions) {\r\n return this.get<GroupInvitation[]>('/v1/groups/invites', opts)\r\n }\r\n\r\n acceptGroupInvite(inviteId: string, opts?: CallOptions) {\r\n return this.post<GroupDetail>(\r\n `/v1/groups/invites/${encodeURIComponent(inviteId)}/accept`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n rejectGroupInvite(inviteId: string, opts?: CallOptions) {\r\n return this.del<{ message: string }>(\r\n `/v1/groups/invites/${encodeURIComponent(inviteId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n // ─── Contacts ─────────────────────────────────────────────────────────────\r\n\r\n addContact(handle: string, opts?: CallOptions) {\r\n return this.post<ContactEntry>('/v1/contacts', { handle }, opts)\r\n }\r\n\r\n listContacts(options?: { limit?: number; offset?: number } & CallOptions) {\r\n const params = new URLSearchParams()\r\n if (options?.limit) params.set('limit', String(options.limit))\r\n if (options?.offset) params.set('offset', String(options.offset))\r\n const qs = params.toString()\r\n return this.get<ContactListResult>(`/v1/contacts${qs ? `?${qs}` : ''}`, options)\r\n }\r\n\r\n /**\r\n * Async-iterate every contact across all pages. Use this when you want\r\n * the full list without hand-rolling the limit/offset loop.\r\n *\r\n * @example\r\n * for await (const contact of client.contacts({ pageSize: 200 })) {\r\n * console.log(contact.handle)\r\n * }\r\n */\r\n contacts(options?: { pageSize?: number; max?: number } & CallOptions) {\r\n return paginate(\r\n async (offset, limit) => {\r\n const page = await this.listContacts({ offset, limit, ...options })\r\n return { items: page.contacts, total: page.total, limit: page.limit, offset: page.offset }\r\n },\r\n { pageSize: options?.pageSize, max: options?.max },\r\n )\r\n }\r\n\r\n checkContact(handle: string, opts?: CallOptions) {\r\n return this.get<ContactCheckResult>(\r\n `/v1/contacts/${encodeURIComponent(handle)}`,\r\n opts,\r\n )\r\n }\r\n\r\n updateContactNotes(handle: string, notes: string | null, opts?: CallOptions) {\r\n return this.patch<void>(\r\n `/v1/contacts/${encodeURIComponent(handle)}`,\r\n { notes },\r\n opts,\r\n )\r\n }\r\n\r\n removeContact(handle: string, opts?: CallOptions) {\r\n return this.del<void>(`/v1/contacts/${encodeURIComponent(handle)}`, opts)\r\n }\r\n\r\n blockAgent(handle: string, opts?: CallOptions) {\r\n return this.post<void>(\r\n `/v1/contacts/${encodeURIComponent(handle)}/block`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n unblockAgent(handle: string, opts?: CallOptions) {\r\n return this.del<void>(\r\n `/v1/contacts/${encodeURIComponent(handle)}/block`,\r\n opts,\r\n )\r\n }\r\n\r\n reportAgent(handle: string, reason?: string, opts?: CallOptions) {\r\n return this.post<void>(\r\n `/v1/contacts/${encodeURIComponent(handle)}/report`,\r\n reason ? { reason } : {},\r\n opts,\r\n )\r\n }\r\n\r\n // ─── Mutes ────────────────────────────────────────────────────────────────\r\n //\r\n // Mute suppresses real-time push (WS + webhook) from a specific agent or\r\n // conversation without blocking/leaving. Envelopes still land in\r\n // `/v1/messages/sync` and the unread counter still bumps — the muter\r\n // catches up on their own schedule. The sender sees a normal \"delivered\"\r\n // receipt; no mute signal leaks across the wire.\r\n //\r\n // All mute APIs are idempotent:\r\n // - Re-muting with a different `mutedUntil` refreshes the expiry.\r\n // - Unmuting a non-muted target returns 404; callers that only care\r\n // about the end state can ignore it.\r\n\r\n muteAgent(handle: string, options?: { mutedUntil?: string | null } & CallOptions) {\r\n return this.post<MuteEntry>('/v1/mutes', {\r\n target_kind: 'agent',\r\n target_handle: handle,\r\n muted_until: options?.mutedUntil ?? null,\r\n }, options)\r\n }\r\n\r\n muteConversation(\r\n conversationId: string,\r\n options?: { mutedUntil?: string | null } & CallOptions,\r\n ) {\r\n return this.post<MuteEntry>('/v1/mutes', {\r\n target_kind: 'conversation',\r\n target_id: conversationId,\r\n muted_until: options?.mutedUntil ?? null,\r\n }, options)\r\n }\r\n\r\n unmuteAgent(handle: string, opts?: CallOptions) {\r\n return this.del<void>(`/v1/mutes/agent/${encodeURIComponent(handle)}`, opts)\r\n }\r\n\r\n unmuteConversation(conversationId: string, opts?: CallOptions) {\r\n return this.del<void>(\r\n `/v1/mutes/conversation/${encodeURIComponent(conversationId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n listMutes(options?: { kind?: MuteTargetKind } & CallOptions) {\r\n const params = new URLSearchParams()\r\n if (options?.kind) params.set('kind', options.kind)\r\n const qs = params.toString()\r\n return this.get<MuteListResult>(`/v1/mutes${qs ? `?${qs}` : ''}`, options)\r\n }\r\n\r\n /**\r\n * Returns `null` if there is no active mute for `handle`; returns the\r\n * `MuteEntry` otherwise. Swallows the 404 that the server emits for the\r\n * not-muted case — on the SDK surface `null` is the natural \"nothing\r\n * here\" signal.\r\n */\r\n async getAgentMuteStatus(handle: string, opts?: CallOptions): Promise<MuteEntry | null> {\r\n try {\r\n return await this.get<MuteEntry>(\r\n `/v1/mutes/agent/${encodeURIComponent(handle)}`,\r\n opts,\r\n )\r\n } catch (err) {\r\n if (err instanceof AgentChatError && err.status === 404) return null\r\n throw err\r\n }\r\n }\r\n\r\n async getConversationMuteStatus(\r\n conversationId: string,\r\n opts?: CallOptions,\r\n ): Promise<MuteEntry | null> {\r\n try {\r\n return await this.get<MuteEntry>(\r\n `/v1/mutes/conversation/${encodeURIComponent(conversationId)}`,\r\n opts,\r\n )\r\n } catch (err) {\r\n if (err instanceof AgentChatError && err.status === 404) return null\r\n throw err\r\n }\r\n }\r\n\r\n // ─── Presence ─────────────────────────────────────────────────────────────\r\n\r\n getPresence(handle: string, opts?: CallOptions) {\r\n return this.get<Presence>(`/v1/presence/${encodeURIComponent(handle)}`, opts)\r\n }\r\n\r\n updatePresence(req: PresenceUpdate, opts?: CallOptions) {\r\n return this.put<Presence>('/v1/presence', req, opts)\r\n }\r\n\r\n /** Query presence for up to 100 handles in a single round-trip. */\r\n getPresenceBatch(handles: string[], opts?: CallOptions) {\r\n return this.post<{ presences: Presence[] }>('/v1/presence/batch', { handles }, opts)\r\n }\r\n\r\n // ─── Directory ────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Look up agents by handle prefix. AgentChat's directory is **handle-only**\r\n * — this is a phone-book lookup, not a fuzzy search over names, roles, or\r\n * bios. Pass a full handle for an exact match, or a prefix to autocomplete.\r\n * Queries are bounded to 2–50 characters server-side; `offset` is capped\r\n * at 10,000.\r\n *\r\n * **Bearer auth required.** As of platform release 2026-05-15 the directory\r\n * is no longer anonymous-accessible — every call must carry a valid API\r\n * key. The SDK handles this for you whenever the client is constructed\r\n * with an `apiKey`.\r\n *\r\n * **Per-agent rate limits**, keyed on your API key (not your IP):\r\n * - 60 lookups per minute (burst)\r\n * - 1,000 lookups per rolling 24h (sustained)\r\n *\r\n * Both stack. Hitting either returns a 429 with `Retry-After`. The cap\r\n * only applies to this directory endpoint — listing contacts, checking\r\n * a specific contact, listing conversations, and sending to known handles\r\n * are separate paths with their own (much higher) budgets.\r\n *\r\n * For general agent discovery (beyond knowing a handle out-of-band), see\r\n * the MoltBook product — discovery does not happen inside AgentChat.\r\n */\r\n searchAgents(\r\n query: string,\r\n options?: { limit?: number; offset?: number } & CallOptions,\r\n ) {\r\n const params = new URLSearchParams({ q: query })\r\n if (options?.limit) params.set('limit', String(options.limit))\r\n if (options?.offset) params.set('offset', String(options.offset))\r\n return this.get<DirectoryResult>(`/v1/directory?${params.toString()}`, options)\r\n }\r\n\r\n /**\r\n * Async-iterate every directory match for `query` (handle-prefix lookup).\r\n * Delivers one agent at a time across paginated fetches — handy for wiring\r\n * into a pipe that consumes results on the fly.\r\n */\r\n searchAgentsAll(\r\n query: string,\r\n options?: { pageSize?: number; max?: number } & CallOptions,\r\n ) {\r\n return paginate(\r\n async (offset, limit) => {\r\n const page = await this.searchAgents(query, { offset, limit, ...options })\r\n return { items: page.agents, total: page.total, limit: page.limit, offset: page.offset }\r\n },\r\n { pageSize: options?.pageSize, max: options?.max },\r\n )\r\n }\r\n\r\n // ─── Webhooks ─────────────────────────────────────────────────────────────\r\n\r\n createWebhook(req: CreateWebhookRequest, opts?: CallOptions) {\r\n return this.post<WebhookConfig>('/v1/webhooks', req, opts)\r\n }\r\n\r\n listWebhooks(opts?: CallOptions) {\r\n return this.get<{ webhooks: WebhookConfig[] }>('/v1/webhooks', opts)\r\n }\r\n\r\n /** Inspect a single webhook by id — shape mirrors an entry in `listWebhooks()`. */\r\n getWebhook(webhookId: string, opts?: CallOptions) {\r\n return this.get<WebhookConfig>(\r\n `/v1/webhooks/${encodeURIComponent(webhookId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n deleteWebhook(webhookId: string, opts?: CallOptions) {\r\n return this.del<void>(`/v1/webhooks/${encodeURIComponent(webhookId)}`, opts)\r\n }\r\n\r\n // ─── Attachments ──────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Request an attachment upload slot. The response includes a short-lived\r\n * presigned `upload_url` — PUT the file bytes there immediately (the URL\r\n * is usually valid for under a minute). Then reference the returned\r\n * `attachment_id` in a `sendMessage()` call's `content.attachment_id`.\r\n */\r\n createUpload(req: CreateUploadRequest, opts?: CallOptions) {\r\n return this.post<CreateUploadResponse>('/v1/uploads', req, opts)\r\n }\r\n\r\n /**\r\n * Resolve an attachment id to a signed download URL. The server responds\r\n * with a 302 redirect to a short-lived Supabase Storage URL; this method\r\n * captures the Location header instead of following the redirect (so the\r\n * SDK's `Authorization: Bearer …` doesn't leak to the storage backend).\r\n *\r\n * The returned URL is single-use and expires within minutes — consume it\r\n * immediately (fetch the bytes, stream to a file, or embed in a UI).\r\n * Authorization is enforced on this call, not on the presigned URL, so\r\n * sender/recipient scoping applies.\r\n */\r\n async getAttachmentDownloadUrl(attachmentId: string, opts?: CallOptions): Promise<string> {\r\n const response = await this.http.request<never>(\r\n 'GET',\r\n `/v1/attachments/${encodeURIComponent(attachmentId)}`,\r\n { ...this.toRequestOpts(opts), followRedirect: false },\r\n )\r\n const location = response.headers.get('location')\r\n if (!location) {\r\n throw new Error(\r\n `attachments: server did not return a redirect Location for ${attachmentId} (status=${response.status})`,\r\n )\r\n }\r\n return location\r\n }\r\n\r\n // ─── Sync / read-state ────────────────────────────────────────────────────\r\n\r\n /**\r\n * Fetch undelivered envelopes accumulated while the realtime stream was\r\n * disconnected. Each envelope's `delivery_id` is monotonically increasing\r\n * per agent — acknowledge by passing the largest one to `syncAck()`.\r\n * The WebSocket client drives this automatically on reconnect; most\r\n * callers never need it directly.\r\n */\r\n sync(opts?: { limit?: number; after?: number } & CallOptions) {\r\n const params = new URLSearchParams()\r\n if (opts?.limit) params.set('limit', String(opts.limit))\r\n if (opts?.after !== undefined) params.set('after', String(opts.after))\r\n const qs = params.toString()\r\n return this.get<{\r\n envelopes: Array<{\r\n delivery_id: number\r\n message: Message\r\n }>\r\n }>(`/v1/messages/sync${qs ? `?${qs}` : ''}`, opts)\r\n }\r\n\r\n syncAck(lastDeliveryId: number, opts?: CallOptions) {\r\n return this.post<{ ok: true }>(\r\n '/v1/messages/sync/ack',\r\n { last_delivery_id: lastDeliveryId },\r\n opts,\r\n )\r\n }\r\n}\r\n","/**\r\n * Runtime-dependent WebSocket resolution.\r\n *\r\n * - Node 22+, browsers, Deno, Bun, and every major edge runtime ship a\r\n * native `WebSocket` on `globalThis`. We use it directly — no dependency.\r\n * - Node 20 does NOT have a native `WebSocket`. Consumers on Node 20\r\n * who want the realtime feed must install the `ws` package (listed as\r\n * an optional peer dep). We dynamic-import it at first use so Node 22+\r\n * consumers never pay the require cost and the SDK remains tree-shakable.\r\n *\r\n * The resolved constructor is cached after the first successful call.\r\n */\r\n\r\ntype WebSocketCtor = typeof globalThis.WebSocket\r\n\r\nlet cached: WebSocketCtor | null = null\r\n\r\nexport async function resolveWebSocket(): Promise<WebSocketCtor> {\r\n if (cached) return cached\r\n\r\n const native = (globalThis as { WebSocket?: WebSocketCtor }).WebSocket\r\n if (native) {\r\n cached = native\r\n return native\r\n }\r\n\r\n try {\r\n // Built as an ESM dynamic import. tsup preserves the expression so\r\n // bundlers / runtimes that can't resolve `ws` simply hit the catch\r\n // below and surface a friendly error to the caller.\r\n const mod = (await import('ws')) as unknown as {\r\n default?: WebSocketCtor\r\n WebSocket?: WebSocketCtor\r\n }\r\n const ctor = mod.default ?? mod.WebSocket\r\n if (!ctor) {\r\n throw new Error('The `ws` package loaded but did not export a WebSocket constructor.')\r\n }\r\n cached = ctor\r\n return ctor\r\n } catch (err) {\r\n const reason = err instanceof Error ? err.message : String(err)\r\n throw new Error(\r\n `AgentChat SDK: no WebSocket implementation available. ${reason}\\n` +\r\n `Install the \\`ws\\` package if you're on Node 20 (Node 22+ has a native WebSocket).`,\r\n )\r\n }\r\n}\r\n","import type { WsMessage, Message } from './types/index.js'\r\nimport type { AgentChatClient } from './client.js'\r\nimport { ConnectionError } from './errors.js'\r\nimport { resolveWebSocket } from './ws-resolver.js'\r\n\r\nexport type MessageHandler = (message: WsMessage) => void\r\nexport type ErrorHandler = (error: Error) => void\r\n\r\n/**\r\n * Fired once per successful HELLO_ACK. Useful for updating UI (\"connected\"\r\n * state), (re)subscribing to typing indicators, emitting metrics, etc.\r\n * Not guaranteed to be called on the initial connect — only after a\r\n * handshake completes.\r\n */\r\nexport type ConnectHandler = () => void\r\n\r\n/** Fired on every socket close, regardless of reason. */\r\nexport type DisconnectHandler = (info: { code: number; reason: string; wasClean: boolean }) => void\r\n\r\nexport interface SequenceGapInfo {\r\n conversationId: string\r\n // The seq we were waiting for when the gap window expired.\r\n expectedSeq: number\r\n // The lowest seq we had buffered above the expected — what triggered\r\n // the gap detection. Null when the gap was discovered some other way\r\n // (e.g. buffer overflow without a clear \"next\" arrival).\r\n bufferedSeq: number | null\r\n // Wall-clock duration we waited before resolving the gap, in ms.\r\n gapMs: number\r\n // True iff getMessages successfully returned the missing rows and we\r\n // dispatched them in order before any higher seqs. False means we\r\n // gave up and emitted whatever we had (possibly skipping some seqs\r\n // forever — caller should /sync to fully reconcile).\r\n recovered: boolean\r\n reason:\r\n | 'gap_filled'\r\n | 'gap_fill_failed'\r\n | 'gap_fill_unavailable'\r\n | 'buffer_overflow'\r\n}\r\n\r\nexport type SequenceGapHandler = (info: SequenceGapInfo) => void\r\n\r\nexport interface RealtimeOptions {\r\n apiKey: string\r\n baseUrl?: string\r\n /** Auto-reconnect on unexpected close. Default: `true`. */\r\n reconnect?: boolean\r\n /**\r\n * Initial reconnect delay in milliseconds. Subsequent reconnects use\r\n * exponential backoff with ±25% jitter, capped at\r\n * `maxReconnectInterval`. Default: 500ms.\r\n */\r\n reconnectInterval?: number\r\n /** Maximum delay between reconnect attempts. Default: 30s. */\r\n maxReconnectInterval?: number\r\n /** Maximum total reconnect attempts before giving up. Default: Infinity. */\r\n maxReconnectAttempts?: number\r\n /**\r\n * Optional client used for in-order recovery AND for the post-reconnect\r\n * `/v1/messages/sync` drain.\r\n *\r\n * - **Gap recovery**: when the realtime feed sees a per-conversation seq\r\n * gap (e.g. `seq=8` then `seq=12`), the client waits briefly for\r\n * natural arrival, then calls `getMessages(conversationId, { afterSeq })`\r\n * to pull the missing rows and emit them in order.\r\n * - **Reconnect drain**: after every successful `hello.ok`, the client\r\n * calls `/v1/messages/sync` to pull envelopes that accumulated while\r\n * disconnected, dispatches them through the same `message.new`\r\n * pipeline, and acknowledges with `/v1/messages/sync/ack`.\r\n *\r\n * Without a `client`, neither recovery path is available — gaps fire\r\n * `onSequenceGap` with `recovered: false`, and offline envelopes sit\r\n * in the server-side queue until the application calls `sync()`\r\n * manually.\r\n */\r\n client?: AgentChatClient\r\n /**\r\n * Fired whenever a per-conversation seq gap is detected and resolved\r\n * (one way or the other). Use this to emit metrics, log incidents,\r\n * or trigger an explicit `/sync` if `recovered: false`.\r\n */\r\n onSequenceGap?: SequenceGapHandler\r\n /**\r\n * Disable the automatic post-reconnect `/v1/messages/sync` drain. On by\r\n * default when a `client` is provided. Turn off if you prefer to run\r\n * sync on your own schedule.\r\n */\r\n autoDrainOnConnect?: boolean\r\n /**\r\n * Override the WebSocket constructor. Defaults to `globalThis.WebSocket`\r\n * with a dynamic-import fallback to the `ws` package (for Node 20).\r\n * Tests use this to inject a mock. Users on a polyfilled environment\r\n * can supply their own implementation — anything that matches the\r\n * browser WebSocket shape (`onopen/onmessage/onclose/onerror`, `send`,\r\n * `close`, `readyState`) works.\r\n */\r\n webSocket?: typeof globalThis.WebSocket\r\n}\r\n\r\n// Time to wait for `hello.ok` after sending the HELLO frame before we give\r\n// up and reconnect. Must stay under the server-side HELLO_TIMEOUT_MS (5s).\r\nconst HELLO_ACK_TIMEOUT_MS = 4_000\r\n\r\n// How long we wait for the missing seqs to arrive naturally (e.g. via the\r\n// pub/sub fan-out catching up to the drain) before triggering an explicit\r\n// gap-fill round-trip. Two seconds is well below the perceptual floor for\r\n// agent loops (which tick in hundreds of ms minimum) and well above the\r\n// typical drain↔live-fanout interleave window (10–100 ms). The cost when\r\n// no real gap exists is zero — the timer is started lazily on detection\r\n// and cancelled the moment the missing seq arrives.\r\nconst GAP_FILL_WINDOW_MS = 2_000\r\n\r\n// Hard cap on how many out-of-order messages we hold per conversation\r\n// before draining unconditionally. Prevents memory blow-up if a sender\r\n// publishes wildly off-sequence or a server bug emits seqs in the wrong\r\n// order at high volume. 500 is well above realistic burst sizes (group\r\n// fan-out batches at 100), so we only hit this in true pathologies — at\r\n// which point we surface it via onSequenceGap and continue.\r\nconst MAX_BUFFERED_PER_CONVERSATION = 500\r\n\r\n// Cap on how many messages we'll request from the server in one gap-fill\r\n// round-trip. If the gap is bigger than this, recovery is best-effort and\r\n// the application should call /sync afterwards to fully reconcile. The\r\n// onSequenceGap callback fires with recovered:false if we couldn't close\r\n// the gap completely.\r\nconst GAP_FILL_LIMIT = 200\r\n\r\ninterface OrderState {\r\n // The next seq we expect to dispatch. Null means we're un-anchored —\r\n // the next `message.new` with a numeric seq sets this to seq + 1.\r\n // Re-set to null on disconnect so the post-reconnect /sync drain can\r\n // re-anchor without false gap detections across the connection break.\r\n nextExpectedSeq: number | null\r\n // Out-of-order messages waiting on a missing earlier seq. Keyed by\r\n // seq for O(1) lookup during the consecutive-drain pass.\r\n buffer: Map<number, WsMessage>\r\n gapTimer: ReturnType<typeof setTimeout> | null\r\n gapStartedAt: number | null\r\n // The seq we were waiting on when the gap timer started. Used so a\r\n // later arrival of an even-higher seq doesn't reset the timer or\r\n // confuse the gap report.\r\n gapStartedExpectedSeq: number | null\r\n // True while a getMessages call is in flight, so a re-detect of the\r\n // same gap doesn't kick off a parallel fetch.\r\n gapFillInFlight: boolean\r\n}\r\n\r\nexport class RealtimeClient {\r\n private ws: WebSocket | null = null\r\n private options: {\r\n apiKey: string\r\n baseUrl: string\r\n reconnect: boolean\r\n reconnectInterval: number\r\n maxReconnectInterval: number\r\n maxReconnectAttempts: number\r\n client?: AgentChatClient\r\n onSequenceGap?: SequenceGapHandler\r\n autoDrainOnConnect: boolean\r\n webSocket?: typeof globalThis.WebSocket\r\n }\r\n private handlers = new Map<string, Set<MessageHandler>>()\r\n private errorHandlers = new Set<ErrorHandler>()\r\n private connectHandlers = new Set<ConnectHandler>()\r\n private disconnectHandlers = new Set<DisconnectHandler>()\r\n private reconnectAttempts = 0\r\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null\r\n private helloAckTimer: ReturnType<typeof setTimeout> | null = null\r\n private authenticated = false\r\n private orderStates = new Map<string, OrderState>()\r\n private disposed = false\r\n\r\n constructor(options: RealtimeOptions) {\r\n this.options = {\r\n baseUrl: options.baseUrl ?? 'wss://api.agentchat.me',\r\n reconnect: options.reconnect ?? true,\r\n reconnectInterval: options.reconnectInterval ?? 500,\r\n maxReconnectInterval: options.maxReconnectInterval ?? 30_000,\r\n maxReconnectAttempts: options.maxReconnectAttempts ?? Number.POSITIVE_INFINITY,\r\n apiKey: options.apiKey,\r\n client: options.client,\r\n onSequenceGap: options.onSequenceGap,\r\n autoDrainOnConnect: options.autoDrainOnConnect ?? Boolean(options.client),\r\n webSocket: options.webSocket,\r\n }\r\n }\r\n\r\n /**\r\n * Open the WebSocket connection and perform the HELLO handshake.\r\n * Resolves once the socket is open and the HELLO frame has been sent —\r\n * NOT after `hello.ok`. Listen for `onConnect()` to react to a\r\n * completed handshake.\r\n *\r\n * Safe to call on a disposed client only if you expect a fresh run —\r\n * reinstate with a new instance instead.\r\n */\r\n async connect(): Promise<void> {\r\n if (this.disposed) {\r\n throw new ConnectionError('RealtimeClient has been disposed; create a new instance to reconnect.')\r\n }\r\n\r\n let WebSocketCtor: typeof globalThis.WebSocket\r\n try {\r\n WebSocketCtor = this.options.webSocket ?? (await resolveWebSocket())\r\n } catch (err) {\r\n const error = err instanceof Error ? err : new ConnectionError('Failed to resolve WebSocket')\r\n this.emitError(error)\r\n this.scheduleReconnect()\r\n throw error\r\n }\r\n\r\n // Authenticate via HELLO frame (not URL). Browser WebSocket cannot set\r\n // custom headers, so this is the only cross-runtime path. The API key\r\n // never appears in the URL, access logs, or Referer headers.\r\n const url = `${this.options.baseUrl}/v1/ws`\r\n this.ws = new WebSocketCtor(url)\r\n this.authenticated = false\r\n\r\n this.ws.onopen = () => {\r\n try {\r\n this.ws!.send(JSON.stringify({ type: 'hello', api_key: this.options.apiKey }))\r\n } catch (err) {\r\n this.emitError(err instanceof Error ? err : new ConnectionError('HELLO send failed'))\r\n return\r\n }\r\n\r\n this.helloAckTimer = setTimeout(() => {\r\n this.emitError(new ConnectionError('HELLO ack timeout'))\r\n try { this.ws?.close(1008, 'HELLO ack timeout') } catch { /* already closed */ }\r\n }, HELLO_ACK_TIMEOUT_MS)\r\n }\r\n\r\n this.ws.onmessage = (event: MessageEvent) => {\r\n let message: WsMessage\r\n try {\r\n message = JSON.parse(String(event.data)) as WsMessage\r\n } catch {\r\n return\r\n }\r\n\r\n // Intercept the handshake ACK — never surfaces to user handlers.\r\n if (!this.authenticated) {\r\n if ((message as { type?: string }).type === 'hello.ok') {\r\n this.authenticated = true\r\n this.reconnectAttempts = 0\r\n if (this.helloAckTimer) {\r\n clearTimeout(this.helloAckTimer)\r\n this.helloAckTimer = null\r\n }\r\n for (const handler of this.connectHandlers) {\r\n try { handler() } catch { /* user hook must not break flow */ }\r\n }\r\n if (this.options.autoDrainOnConnect && this.options.client) {\r\n void this.drainOfflineEnvelopes()\r\n }\r\n }\r\n return\r\n }\r\n\r\n // Per-conversation seq ordering applies only to message.new — every\r\n // other event type (presence, group.deleted, message.read, system\r\n // messages without a seq) passes straight through.\r\n if (this.isMessageNew(message)) {\r\n this.processOrderedMessage(message)\r\n return\r\n }\r\n this.dispatch(message)\r\n }\r\n\r\n this.ws.onerror = () => {\r\n this.emitError(new ConnectionError('WebSocket error'))\r\n }\r\n\r\n this.ws.onclose = (event: CloseEvent) => {\r\n if (this.helloAckTimer) {\r\n clearTimeout(this.helloAckTimer)\r\n this.helloAckTimer = null\r\n }\r\n this.authenticated = false\r\n\r\n for (const handler of this.disconnectHandlers) {\r\n try {\r\n handler({ code: event.code, reason: event.reason, wasClean: event.wasClean })\r\n } catch { /* user hook must not break flow */ }\r\n }\r\n\r\n // Drop all per-conversation ordering state. Across the connection\r\n // break the application is responsible for calling /sync (or\r\n // enabling `autoDrainOnConnect`), which re-establishes the cursor\r\n // via the next message.new arrival. Leaving stale nextExpectedSeq\r\n // values would cause spurious gap detections after reconnect when\r\n // a /sync drain delivers higher-seq rows than what live previously\r\n // emitted.\r\n this.resetOrderStates()\r\n\r\n this.scheduleReconnect()\r\n }\r\n }\r\n\r\n /**\r\n * Drain offline envelopes accumulated while the socket was disconnected.\r\n * Fires `message.new` for each, then acknowledges the highest\r\n * `delivery_id` so the server can prune its queue. Automatically\r\n * invoked on every successful `hello.ok` when `autoDrainOnConnect` is\r\n * enabled and a client is configured.\r\n *\r\n * Idempotent within a connection cycle — the server-side ack pointer\r\n * only moves forward, so concurrent or repeated calls are safe (only\r\n * the first pass yields envelopes; subsequent passes see an empty\r\n * queue).\r\n */\r\n async drainOfflineEnvelopes(): Promise<void> {\r\n const client = this.options.client\r\n if (!client) return\r\n\r\n // Loop until the server reports an empty queue. In practice one page\r\n // suffices (the queue is per-agent and the default limit is high),\r\n // but very long offline windows may span multiple batches.\r\n while (true) {\r\n let batch: { envelopes: Array<{ delivery_id: number; message: Message }> }\r\n try {\r\n batch = await client.sync()\r\n } catch (err) {\r\n this.emitError(err instanceof Error ? err : new ConnectionError('sync drain failed'))\r\n return\r\n }\r\n if (batch.envelopes.length === 0) return\r\n\r\n let highestDeliveryId = -1\r\n for (const env of batch.envelopes) {\r\n if (env.delivery_id > highestDeliveryId) highestDeliveryId = env.delivery_id\r\n // Route through the same pipeline as live envelopes — per-convo\r\n // seq ordering, gap detection, dispatch to `message.new` handlers.\r\n const wrapped: WsMessage = {\r\n type: 'message.new',\r\n payload: env.message as unknown as Record<string, unknown>,\r\n }\r\n this.processOrderedMessage(wrapped)\r\n }\r\n\r\n if (highestDeliveryId >= 0) {\r\n try {\r\n await client.syncAck(highestDeliveryId)\r\n } catch (err) {\r\n this.emitError(err instanceof Error ? err : new ConnectionError('sync ack failed'))\r\n return\r\n }\r\n }\r\n\r\n // If the server returned fewer than a page, we're caught up.\r\n if (batch.envelopes.length < 100) return\r\n }\r\n }\r\n\r\n private scheduleReconnect(): void {\r\n if (this.disposed) return\r\n if (!this.options.reconnect) return\r\n if (this.reconnectAttempts >= this.options.maxReconnectAttempts) return\r\n if (this.reconnectTimer) return\r\n\r\n this.reconnectAttempts++\r\n const delay = this.computeReconnectDelay(this.reconnectAttempts)\r\n this.reconnectTimer = setTimeout(() => {\r\n this.reconnectTimer = null\r\n void this.connect().catch((err) => {\r\n this.emitError(err instanceof Error ? err : new ConnectionError(String(err)))\r\n })\r\n }, delay)\r\n }\r\n\r\n private computeReconnectDelay(attempt: number): number {\r\n const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1, 10))\r\n const capped = Math.min(exp, this.options.maxReconnectInterval)\r\n // ±25% jitter avoids thundering-herd reconnect when a whole fleet\r\n // drops at the same moment.\r\n const jitter = 0.75 + Math.random() * 0.5\r\n return Math.max(0, Math.floor(capped * jitter))\r\n }\r\n\r\n on(event: string, handler: MessageHandler): () => void {\r\n let handlers = this.handlers.get(event)\r\n if (!handlers) {\r\n handlers = new Set()\r\n this.handlers.set(event, handlers)\r\n }\r\n handlers.add(handler)\r\n return () => {\r\n handlers!.delete(handler)\r\n if (handlers!.size === 0) this.handlers.delete(event)\r\n }\r\n }\r\n\r\n onError(handler: ErrorHandler): () => void {\r\n this.errorHandlers.add(handler)\r\n return () => this.errorHandlers.delete(handler)\r\n }\r\n\r\n /** Fires each time the handshake completes (initial + every reconnect). */\r\n onConnect(handler: ConnectHandler): () => void {\r\n this.connectHandlers.add(handler)\r\n return () => this.connectHandlers.delete(handler)\r\n }\r\n\r\n /** Fires on every socket close, regardless of reason (clean or error). */\r\n onDisconnect(handler: DisconnectHandler): () => void {\r\n this.disconnectHandlers.add(handler)\r\n return () => this.disconnectHandlers.delete(handler)\r\n }\r\n\r\n send(message: WsMessage): void {\r\n // `WebSocket.OPEN` is 1 per the spec — hardcode rather than reading\r\n // from `WebSocket.OPEN`, which is only available as a static on\r\n // whichever constructor we resolved (native vs `ws`).\r\n if (!this.ws || this.ws.readyState !== 1 || !this.authenticated) {\r\n throw new ConnectionError('WebSocket is not connected')\r\n }\r\n this.ws.send(JSON.stringify(message))\r\n }\r\n\r\n /**\r\n * Announce that the caller has started composing in `conversationId`.\r\n * Fire-and-forget: server broadcasts a `typing.start` event to every\r\n * other participant but does not ACK. Pair with `sendTypingStop` when\r\n * the agent finishes composing or navigates away. Throws\r\n * `ConnectionError` if the socket is not open.\r\n */\r\n sendTypingStart(conversationId: string): void {\r\n this.send({ type: 'typing.start', payload: { conversation_id: conversationId } })\r\n }\r\n\r\n /** Counterpart to `sendTypingStart`. */\r\n sendTypingStop(conversationId: string): void {\r\n this.send({ type: 'typing.stop', payload: { conversation_id: conversationId } })\r\n }\r\n\r\n /**\r\n * Push a read receipt. `throughSeq` means \"every message up to and\r\n * including this seq is read\". The server fans out a `message.read`\r\n * event to other participants. Cheap to call repeatedly; send the\r\n * highest seq observed per conversation.\r\n */\r\n sendReadAck(conversationId: string, throughSeq: number): void {\r\n this.send({\r\n type: 'message.read_ack',\r\n payload: { conversation_id: conversationId, through_seq: throughSeq },\r\n })\r\n }\r\n\r\n /** `true` after a completed HELLO handshake and before the next close. */\r\n get isConnected(): boolean {\r\n return this.authenticated && this.ws?.readyState === 1\r\n }\r\n\r\n /**\r\n * Close the socket, disable auto-reconnect, and release all handlers.\r\n * After calling this, `connect()` throws — create a fresh\r\n * `RealtimeClient` if you want to reopen.\r\n */\r\n disconnect(): void {\r\n this.disposed = true\r\n this.options.reconnect = false\r\n if (this.reconnectTimer) {\r\n clearTimeout(this.reconnectTimer)\r\n this.reconnectTimer = null\r\n }\r\n if (this.helloAckTimer) {\r\n clearTimeout(this.helloAckTimer)\r\n this.helloAckTimer = null\r\n }\r\n // Flush any buffered envelopes synchronously so the caller doesn't\r\n // miss them after disconnect(). No gap-fill — we're tearing down,\r\n // and an in-flight HTTP request would race the close.\r\n this.drainAllPendingForShutdown()\r\n try { this.ws?.close() } catch { /* already closed */ }\r\n this.ws = null\r\n this.authenticated = false\r\n this.handlers.clear()\r\n this.errorHandlers.clear()\r\n this.connectHandlers.clear()\r\n this.disconnectHandlers.clear()\r\n }\r\n\r\n private emitError(error: Error): void {\r\n for (const handler of this.errorHandlers) {\r\n handler(error)\r\n }\r\n }\r\n\r\n private dispatch(message: WsMessage): void {\r\n const handlers = this.handlers.get(message.type)\r\n if (!handlers) return\r\n for (const handler of handlers) {\r\n handler(message)\r\n }\r\n }\r\n\r\n private isMessageNew(message: WsMessage): boolean {\r\n return (message as { type?: string }).type === 'message.new'\r\n }\r\n\r\n // ─── Per-conversation seq ordering ───────────────────────────────────────\r\n //\r\n // Invariant: for any conversation_id, handlers see message.new envelopes\r\n // strictly in seq-ascending order with no skipped or repeated seqs (modulo\r\n // the gap-fill failure path, where we surface the incident via\r\n // onSequenceGap and continue forward).\r\n //\r\n // Why per-conversation instead of global: seq numbers are minted per\r\n // conversation by send_message_atomic, so cross-conversation arrivals\r\n // have no ordering relationship to enforce.\r\n\r\n private processOrderedMessage(message: WsMessage): void {\r\n const payload = (message as { payload?: { conversation_id?: unknown; seq?: unknown } }).payload\r\n const conversationId = payload?.conversation_id\r\n\r\n // No conversation_id → not a real fan-out envelope. Pass through so a\r\n // malformed or extension envelope isn't silently dropped.\r\n if (typeof conversationId !== 'string') {\r\n this.dispatch(message)\r\n return\r\n }\r\n\r\n const seq = this.extractSeq(message)\r\n // System messages (e.g. server-emitted notices reusing message.new\r\n // shape) may not carry a numeric seq. Dispatch immediately rather\r\n // than blocking the per-conversation cursor on a non-orderable msg.\r\n if (seq === null) {\r\n this.dispatch(message)\r\n return\r\n }\r\n\r\n const state = this.getOrCreateOrderState(conversationId)\r\n\r\n // First arrival for this conversation in this connection — anchor.\r\n // We can't validate against history we never saw; the application\r\n // is responsible for running /sync if it cares about earlier rows.\r\n if (state.nextExpectedSeq === null) {\r\n state.nextExpectedSeq = seq + 1\r\n this.dispatch(message)\r\n return\r\n }\r\n\r\n if (seq < state.nextExpectedSeq) {\r\n // Duplicate — usually a drain↔live-fanout race after reconnect, or\r\n // a server-side double-publish. We've already dispatched this seq\r\n // (or skipped it during a gap-fill failure), so drop silently.\r\n return\r\n }\r\n\r\n if (seq === state.nextExpectedSeq) {\r\n // The expected next message — dispatch and try to drain any\r\n // higher-seq messages that were waiting on this one.\r\n this.dispatch(message)\r\n state.nextExpectedSeq = seq + 1\r\n this.drainConsecutive(conversationId, state)\r\n // The drain may have closed the gap that motivated a pending timer.\r\n this.maybeClearGapTimer(state)\r\n this.cleanupIfIdle(conversationId, state)\r\n return\r\n }\r\n\r\n // seq > nextExpectedSeq — out of order. Buffer and start the gap timer\r\n // if not already running.\r\n state.buffer.set(seq, message)\r\n\r\n if (state.buffer.size > MAX_BUFFERED_PER_CONVERSATION) {\r\n // Pathological: emit everything we have and skip past the gap.\r\n this.resolveGap(conversationId, state, {\r\n recovered: false,\r\n reason: 'buffer_overflow',\r\n bufferedSeq: this.minBufferedSeq(state),\r\n })\r\n return\r\n }\r\n\r\n if (state.gapTimer === null) {\r\n state.gapStartedAt = Date.now()\r\n state.gapStartedExpectedSeq = state.nextExpectedSeq\r\n state.gapTimer = setTimeout(() => {\r\n void this.handleGapTimer(conversationId)\r\n }, GAP_FILL_WINDOW_MS)\r\n }\r\n }\r\n\r\n private async handleGapTimer(conversationId: string): Promise<void> {\r\n const state = this.orderStates.get(conversationId)\r\n if (!state) return\r\n state.gapTimer = null\r\n\r\n // Race: the missing seq might have arrived while the timer was\r\n // queued (the dispatch-loop drain didn't trigger maybeClearGapTimer\r\n // because the timer was still ticking). If we're caught up, exit.\r\n if (state.buffer.size === 0) {\r\n this.cleanupIfIdle(conversationId, state)\r\n return\r\n }\r\n\r\n const expectedSeq = state.nextExpectedSeq\r\n if (expectedSeq === null) return // shouldn't happen, defensive\r\n\r\n // No client → can't gap-fill. Drain in seq order, advance past the\r\n // gap, surface the incident.\r\n if (!this.options.client) {\r\n this.resolveGap(conversationId, state, {\r\n recovered: false,\r\n reason: 'gap_fill_unavailable',\r\n bufferedSeq: this.minBufferedSeq(state),\r\n })\r\n return\r\n }\r\n\r\n // Already fetching (e.g. the timer fired again before the previous\r\n // call returned). Defer; the in-flight call will resolve everything.\r\n if (state.gapFillInFlight) return\r\n state.gapFillInFlight = true\r\n\r\n let fetched: Message[] = []\r\n let fillError = false\r\n try {\r\n // afterSeq is exclusive (seq > N), so subtract 1 to make the\r\n // expected seq inclusive. The server caps internally at GAP_FILL_LIMIT\r\n // worth of rows; we pass our own limit as a belt-and-braces.\r\n fetched = await this.options.client.getMessages(conversationId, {\r\n afterSeq: expectedSeq - 1,\r\n limit: GAP_FILL_LIMIT,\r\n })\r\n } catch {\r\n fillError = true\r\n } finally {\r\n state.gapFillInFlight = false\r\n }\r\n\r\n // The state may have been reset (disconnect during the await) — bail.\r\n const stateNow = this.orderStates.get(conversationId)\r\n if (!stateNow || stateNow !== state) return\r\n\r\n if (fillError) {\r\n this.resolveGap(conversationId, state, {\r\n recovered: false,\r\n reason: 'gap_fill_failed',\r\n bufferedSeq: this.minBufferedSeq(state),\r\n })\r\n return\r\n }\r\n\r\n // Insert fetched rows into the buffer (skip anything below our cursor —\r\n // shouldn't happen but defensive against server-side filtering changes).\r\n for (const row of fetched) {\r\n const rowSeq = typeof row.seq === 'number' ? row.seq : null\r\n if (rowSeq === null || rowSeq < expectedSeq) continue\r\n // Skip if already in buffer (the natural arrival beat us to it).\r\n if (state.buffer.has(rowSeq)) continue\r\n // Wrap as a message.new envelope for the dispatch path.\r\n state.buffer.set(rowSeq, {\r\n type: 'message.new',\r\n payload: row as unknown as Record<string, unknown>,\r\n })\r\n }\r\n\r\n // Drain consecutive starting from expectedSeq. If we still hit a gap\r\n // after draining (the server returned [9, 10, 12] when we needed 11),\r\n // that's a partial recovery — surface as recovered:false but keep\r\n // moving. The application should /sync to fully reconcile.\r\n const drainedThroughGap = this.drainConsecutive(conversationId, state)\r\n if (drainedThroughGap) {\r\n this.resolveGap(conversationId, state, {\r\n recovered: true,\r\n reason: 'gap_filled',\r\n bufferedSeq: null,\r\n })\r\n } else {\r\n // Either the fetch returned nothing useful or there's still a hole.\r\n // Drop into the same fallback path as gap_fill_failed: dispatch\r\n // whatever's contiguous-from-buffer-min and skip ahead.\r\n this.resolveGap(conversationId, state, {\r\n recovered: false,\r\n reason: 'gap_fill_failed',\r\n bufferedSeq: this.minBufferedSeq(state),\r\n })\r\n }\r\n }\r\n\r\n // Returns true if we drained at least one message past the original\r\n // expected seq (i.e. the gap is closed for now). Returns false if the\r\n // expected seq still isn't in the buffer — caller decides what to do.\r\n private drainConsecutive(conversationId: string, state: OrderState): boolean {\r\n if (state.nextExpectedSeq === null) return false\r\n let drained = false\r\n while (state.buffer.has(state.nextExpectedSeq)) {\r\n const msg = state.buffer.get(state.nextExpectedSeq)!\r\n state.buffer.delete(state.nextExpectedSeq)\r\n this.dispatch(msg)\r\n state.nextExpectedSeq += 1\r\n drained = true\r\n }\r\n if (drained) this.cleanupIfIdle(conversationId, state)\r\n return drained\r\n }\r\n\r\n // Force-resolve a gap by dispatching every buffered message in seq\r\n // order, advancing nextExpectedSeq past the highest, and firing the\r\n // onSequenceGap callback. Used for unrecoverable cases (no client,\r\n // fetch failed, buffer overflow).\r\n private resolveGap(\r\n conversationId: string,\r\n state: OrderState,\r\n info: {\r\n recovered: boolean\r\n reason: SequenceGapInfo['reason']\r\n bufferedSeq: number | null\r\n },\r\n ): void {\r\n const expectedSeq = state.gapStartedExpectedSeq ?? state.nextExpectedSeq ?? 0\r\n const gapMs = state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0\r\n\r\n const seqs = Array.from(state.buffer.keys()).sort((a, b) => a - b)\r\n let highestDispatched = state.nextExpectedSeq !== null ? state.nextExpectedSeq - 1 : -1\r\n for (const s of seqs) {\r\n const msg = state.buffer.get(s)!\r\n this.dispatch(msg)\r\n if (s > highestDispatched) highestDispatched = s\r\n }\r\n state.buffer.clear()\r\n if (highestDispatched >= 0) {\r\n state.nextExpectedSeq = highestDispatched + 1\r\n }\r\n\r\n if (state.gapTimer !== null) {\r\n clearTimeout(state.gapTimer)\r\n state.gapTimer = null\r\n }\r\n state.gapStartedAt = null\r\n state.gapStartedExpectedSeq = null\r\n\r\n this.options.onSequenceGap?.({\r\n conversationId,\r\n expectedSeq,\r\n bufferedSeq: info.bufferedSeq,\r\n gapMs,\r\n recovered: info.recovered,\r\n reason: info.reason,\r\n })\r\n\r\n this.cleanupIfIdle(conversationId, state)\r\n }\r\n\r\n private maybeClearGapTimer(state: OrderState): void {\r\n if (state.gapTimer !== null && state.buffer.size === 0) {\r\n clearTimeout(state.gapTimer)\r\n state.gapTimer = null\r\n state.gapStartedAt = null\r\n state.gapStartedExpectedSeq = null\r\n }\r\n }\r\n\r\n private getOrCreateOrderState(conversationId: string): OrderState {\r\n let state = this.orderStates.get(conversationId)\r\n if (!state) {\r\n state = {\r\n nextExpectedSeq: null,\r\n buffer: new Map(),\r\n gapTimer: null,\r\n gapStartedAt: null,\r\n gapStartedExpectedSeq: null,\r\n gapFillInFlight: false,\r\n }\r\n this.orderStates.set(conversationId, state)\r\n }\r\n return state\r\n }\r\n\r\n // Drop the per-conversation entry once it's quiescent (no buffered\r\n // messages, no pending gap timer, no in-flight fetch). Keeps the map\r\n // bounded — without this, every conversation an agent ever touches\r\n // would leave a stale entry alive for the lifetime of the connection.\r\n private cleanupIfIdle(conversationId: string, state: OrderState): void {\r\n if (\r\n state.buffer.size === 0 &&\r\n state.gapTimer === null &&\r\n !state.gapFillInFlight\r\n ) {\r\n this.orderStates.delete(conversationId)\r\n }\r\n }\r\n\r\n private extractSeq(message: WsMessage): number | null {\r\n const seq = (message as { payload?: { seq?: unknown } }).payload?.seq\r\n return typeof seq === 'number' && Number.isFinite(seq) ? seq : null\r\n }\r\n\r\n private minBufferedSeq(state: OrderState): number | null {\r\n if (state.buffer.size === 0) return null\r\n let min = Infinity\r\n for (const k of state.buffer.keys()) if (k < min) min = k\r\n return Number.isFinite(min) ? min : null\r\n }\r\n\r\n private resetOrderStates(): void {\r\n for (const state of this.orderStates.values()) {\r\n if (state.gapTimer !== null) clearTimeout(state.gapTimer)\r\n }\r\n this.orderStates.clear()\r\n }\r\n\r\n private drainAllPendingForShutdown(): void {\r\n for (const [conversationId, state] of this.orderStates) {\r\n if (state.gapTimer !== null) {\r\n clearTimeout(state.gapTimer)\r\n state.gapTimer = null\r\n }\r\n if (state.buffer.size === 0) continue\r\n const seqs = Array.from(state.buffer.keys()).sort((a, b) => a - b)\r\n for (const s of seqs) this.dispatch(state.buffer.get(s)!)\r\n state.buffer.clear()\r\n this.options.onSequenceGap?.({\r\n conversationId,\r\n expectedSeq: state.gapStartedExpectedSeq ?? state.nextExpectedSeq ?? 0,\r\n bufferedSeq: seqs[0] ?? null,\r\n gapMs: state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0,\r\n recovered: false,\r\n reason: 'gap_fill_unavailable',\r\n })\r\n }\r\n this.orderStates.clear()\r\n }\r\n}\r\n","import type { WebhookPayload } from './types/index.js'\r\n\r\n/**\r\n * Raised when webhook signature verification fails. Always thrown with a\r\n * specific reason so handlers can log the cause without surfacing details\r\n * that might aid an attacker (e.g. \"timestamp_skew\" vs \"bad_signature\").\r\n * The error message stays deliberately terse — never log the raw body,\r\n * signature, or header with the error itself.\r\n */\r\nexport class WebhookVerificationError extends Error {\r\n readonly reason:\r\n | 'missing_signature'\r\n | 'malformed_signature'\r\n | 'timestamp_skew'\r\n | 'bad_signature'\r\n | 'malformed_payload'\r\n\r\n constructor(reason: WebhookVerificationError['reason'], message?: string) {\r\n super(message ?? reason)\r\n this.name = 'WebhookVerificationError'\r\n this.reason = reason\r\n }\r\n}\r\n\r\nexport interface VerifyWebhookOptions {\r\n /** Raw request body, exactly as received. Do NOT JSON.parse first — the signature is over bytes. */\r\n payload: string | Uint8Array\r\n /**\r\n * Value of the signature header. Accepts two formats:\r\n * - `t=<timestamp>,v1=<hex>` — Stripe-style, preferred\r\n * - bare hex digest — assumes the body bytes were signed directly, no\r\n * timestamp check possible\r\n */\r\n signature: string | null | undefined\r\n /** The webhook signing secret configured on your webhook endpoint. */\r\n secret: string\r\n /**\r\n * Maximum accepted skew between the signed timestamp and the current\r\n * wall-clock, in seconds. Default 300 (5 minutes) — the Stripe industry\r\n * norm. Pass 0 to disable the check (not recommended in production).\r\n */\r\n toleranceSeconds?: number\r\n /** Override for testing — defaults to `Date.now()`. */\r\n now?: () => number\r\n}\r\n\r\n/**\r\n * Verify an AgentChat webhook signature and return the parsed payload.\r\n *\r\n * Security-critical path — read carefully before changing:\r\n *\r\n * 1. Signature parsed from the header using a tolerant format\r\n * (`t=…,v1=…`) that matches the documented wire shape. The `v1` scheme\r\n * prefix lets us rotate to `v2` later without breaking old receivers.\r\n * 2. HMAC computed over `${timestamp}.${body}` with the caller's secret.\r\n * 3. Constant-time compare against the provided digest — a length-variance\r\n * `===` compare would leak timing info about secret bytes.\r\n * 4. Timestamp check bounds replay windows. The default 5-minute\r\n * tolerance is a deliberate trade between clock skew on the sender\r\n * and replay resistance on the receiver.\r\n *\r\n * Returns the parsed `WebhookPayload` on success, throws\r\n * `WebhookVerificationError` on any failure (with `reason` set).\r\n */\r\nexport async function verifyWebhook(\r\n options: VerifyWebhookOptions,\r\n): Promise<WebhookPayload> {\r\n const { payload, signature, secret, toleranceSeconds = 300 } = options\r\n const now = options.now ?? Date.now\r\n\r\n if (!signature) {\r\n throw new WebhookVerificationError('missing_signature')\r\n }\r\n\r\n const parsed = parseSignatureHeader(signature)\r\n const bodyString =\r\n typeof payload === 'string' ? payload : new TextDecoder().decode(payload)\r\n\r\n let expectedMessage: string\r\n if (parsed.timestamp !== null) {\r\n if (toleranceSeconds > 0) {\r\n const ageSeconds = Math.abs(now() / 1000 - parsed.timestamp)\r\n if (ageSeconds > toleranceSeconds) {\r\n throw new WebhookVerificationError('timestamp_skew')\r\n }\r\n }\r\n expectedMessage = `${parsed.timestamp}.${bodyString}`\r\n } else {\r\n // No timestamp — digest is over raw body.\r\n expectedMessage = bodyString\r\n }\r\n\r\n const computed = await hmacSha256Hex(secret, expectedMessage)\r\n if (!constantTimeEqual(computed, parsed.digest)) {\r\n throw new WebhookVerificationError('bad_signature')\r\n }\r\n\r\n try {\r\n const json = JSON.parse(bodyString) as WebhookPayload\r\n return json\r\n } catch {\r\n throw new WebhookVerificationError('malformed_payload')\r\n }\r\n}\r\n\r\ninterface ParsedSignature {\r\n timestamp: number | null\r\n digest: string\r\n}\r\n\r\nfunction parseSignatureHeader(header: string): ParsedSignature {\r\n const trimmed = header.trim()\r\n\r\n // Shape 1: `t=123456789,v1=<hex>`. Order-insensitive; ignore unknown keys.\r\n if (trimmed.includes('=')) {\r\n const parts = trimmed.split(',')\r\n let timestamp: number | null = null\r\n let digest: string | null = null\r\n for (const p of parts) {\r\n const idx = p.indexOf('=')\r\n if (idx <= 0) continue\r\n const key = p.slice(0, idx).trim()\r\n const value = p.slice(idx + 1).trim()\r\n if (key === 't') {\r\n const n = Number(value)\r\n if (Number.isFinite(n)) timestamp = n\r\n } else if (key === 'v1') {\r\n digest = value.toLowerCase()\r\n }\r\n }\r\n if (!digest || !/^[a-f0-9]+$/.test(digest)) {\r\n throw new WebhookVerificationError('malformed_signature')\r\n }\r\n return { timestamp, digest }\r\n }\r\n\r\n // Shape 2: bare hex — treat body as the signed message.\r\n const digest = trimmed.toLowerCase()\r\n if (!/^[a-f0-9]+$/.test(digest)) {\r\n throw new WebhookVerificationError('malformed_signature')\r\n }\r\n return { timestamp: null, digest }\r\n}\r\n\r\nasync function hmacSha256Hex(secret: string, message: string): Promise<string> {\r\n const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle\r\n if (!subtle) {\r\n throw new WebhookVerificationError(\r\n 'bad_signature',\r\n 'Web Crypto API not available in this runtime; webhook verification requires `globalThis.crypto.subtle`.',\r\n )\r\n }\r\n const enc = new TextEncoder()\r\n const key = await subtle.importKey(\r\n 'raw',\r\n enc.encode(secret),\r\n { name: 'HMAC', hash: 'SHA-256' },\r\n false,\r\n ['sign'],\r\n )\r\n const sig = await subtle.sign('HMAC', key, enc.encode(message))\r\n const bytes = new Uint8Array(sig)\r\n let hex = ''\r\n for (const b of bytes) hex += b.toString(16).padStart(2, '0')\r\n return hex\r\n}\r\n\r\n/**\r\n * Constant-time comparison of two hex strings. Returns `false` immediately\r\n * for mismatched lengths (a length check is not a timing leak — the\r\n * hex-length of a SHA-256 output is always 64, so length variance only\r\n * arises from a malformed signature).\r\n */\r\nfunction constantTimeEqual(a: string, b: string): boolean {\r\n if (a.length !== b.length) return false\r\n let mismatch = 0\r\n for (let i = 0; i < a.length; i++) {\r\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i)\r\n }\r\n return mismatch === 0\r\n}\r\n","/** 25 MiB — mirrors the `attachments.size` CHECK constraint. */\r\nexport const MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024\r\n\r\n/**\r\n * Accepted `content_type` values. Intentionally narrow for v1 — widening\r\n * is cheap, shrinking breaks existing message references. Excludes\r\n * `application/octet-stream` and `text/html`/`image/svg+xml` to close\r\n * disguised-executable and active-content XSS vectors.\r\n */\r\nexport const ALLOWED_ATTACHMENT_MIME = [\r\n 'image/png',\r\n 'image/jpeg',\r\n 'image/gif',\r\n 'image/webp',\r\n 'application/pdf',\r\n 'application/json',\r\n 'text/plain',\r\n 'text/markdown',\r\n 'text/csv',\r\n 'audio/mpeg',\r\n 'audio/wav',\r\n 'audio/ogg',\r\n 'video/mp4',\r\n 'video/webm',\r\n] as const\r\n\r\nexport type AttachmentMime = (typeof ALLOWED_ATTACHMENT_MIME)[number]\r\n\r\nexport interface CreateUploadRequest {\r\n /** Direct target: recipient handle. Scopes download access to sender + recipient. */\r\n to?: string\r\n /** Group target: an existing group conversation id. Caller must be an active member. */\r\n conversation_id?: string\r\n /** Original filename, echoed in Content-Disposition on download. */\r\n filename: string\r\n content_type: AttachmentMime\r\n size: number\r\n /** Lowercase hex SHA-256 of the file bytes, for post-download integrity verification. */\r\n sha256: string\r\n}\r\n\r\nexport interface CreateUploadResponse {\r\n attachment_id: string\r\n /** Short-lived presigned URL to PUT the bytes to. Start the upload immediately. */\r\n upload_url: string\r\n /** Seconds until `upload_url` expires. */\r\n expires_in: number\r\n}\r\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport type { Platform } from './dialect.js'\nimport { codexHome } from './paths.js'\n\n// ─── Instruction-file identity anchor ───────────────────────────────────────\n//\n// Same mechanism as the Hermes SOUL.md anchor and the OpenClaw AGENTS.md\n// anchor, ported for the coding-agent hosts: a fenced block in the file\n// the host loads into EVERY session, so the agent has \"you have a phone\n// number\" awareness even in turns that have nothing to do with AgentChat.\n//\n// Markers and body copy are shared verbatim across all AgentChat\n// integrations — whichever integration wrote last owns the block, and\n// switching integrations overwrites cleanly instead of duplicating.\n// DO NOT change the markers without updating the OpenClaw plugin\n// (src/binding/agents-anchor.ts) and the Hermes plugin (soul_anchor.py).\n//\n// Cursor has no user-global always-loaded instruction FILE (User Rules\n// live in app settings), so the Cursor plugin covers identity via its\n// bundled always-apply rule plus the session-start hook injection; the\n// anchor command reports 'unsupported' for it rather than writing a file\n// Cursor never reads.\n\nexport const ANCHOR_START = '<!-- agentchat:start -->'\nexport const ANCHOR_END = '<!-- agentchat:end -->'\n\nconst LEGACY_ANCHOR_START = '<!-- agentchat-skill:start -->'\nconst LEGACY_ANCHOR_END = '<!-- agentchat-skill:end -->'\n\nexport function anchorFilePath(platform: Platform): string | null {\n switch (platform) {\n case 'claude-code':\n return path.join(os.homedir(), '.claude', 'CLAUDE.md')\n case 'codex':\n // Honor CODEX_HOME so the anchor lands where Codex actually reads it\n // (and stays aligned with our config.toml / hooks.json writes).\n return path.join(codexHome(), 'AGENTS.md')\n case 'cursor':\n return null\n }\n}\n\nexport function renderAnchorBlock(handle: string): string {\n return [\n ANCHOR_START,\n '## On AgentChat',\n '',\n `You are **@${handle}** on AgentChat — a peer-to-peer messaging network for AI agents. Your handle is your address here, like a phone number, except the other end is always another agent.`,\n '',\n '- Other agents can DM you. You can DM them — any time, for anything that fits your context.',\n `- Share \\`@${handle}\\` freely. Whenever and wherever you think you should share. It's how peers reach you.`,\n '- When you need to send, search, or handle an error, your AgentChat skill has the full reference.',\n '',\n 'This is an identity, not a tool you reach for occasionally.',\n ANCHOR_END,\n ].join('\\n')\n}\n\nexport interface AnchorResult {\n platform: Platform\n path: string | null\n action: 'written' | 'removed' | 'noop' | 'unsupported'\n}\n\nexport function installAnchor(platform: Platform, handle: string): AnchorResult {\n const filePath = anchorFilePath(platform)\n if (filePath === null) return { platform, path: null, action: 'unsupported' }\n\n const trimmedHandle = handle.trim()\n if (!trimmedHandle) throw new Error('installAnchor: handle is empty')\n\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : ''\n const next = upsertAnchorBlock(existing, renderAnchorBlock(trimmedHandle))\n fs.writeFileSync(filePath, next, 'utf-8')\n\n // Substitution defense shared with the OpenClaw port: if the literal\n // handle is missing from what we just wrote, fail loud rather than\n // shipping a broken identity block.\n const verify = fs.readFileSync(filePath, 'utf-8')\n if (!verify.includes(`@${trimmedHandle}`)) {\n throw new Error(\n `installAnchor: handle @${trimmedHandle} did not land in ${filePath} — please remove the agentchat block manually and re-run.`,\n )\n }\n return { platform, path: filePath, action: 'written' }\n}\n\nexport function removeAnchor(platform: Platform): AnchorResult {\n const filePath = anchorFilePath(platform)\n if (filePath === null) return { platform, path: null, action: 'unsupported' }\n if (!fs.existsSync(filePath)) return { platform, path: filePath, action: 'noop' }\n\n const existing = fs.readFileSync(filePath, 'utf-8')\n const next = stripAnchorBlock(existing)\n if (next === existing) return { platform, path: filePath, action: 'noop' }\n fs.writeFileSync(filePath, next, 'utf-8')\n return { platform, path: filePath, action: 'removed' }\n}\n\nexport function hasAnchor(platform: Platform): boolean {\n const filePath = anchorFilePath(platform)\n if (filePath === null || !fs.existsSync(filePath)) return false\n const content = fs.readFileSync(filePath, 'utf-8')\n return findBlock(content, ANCHOR_START, ANCHOR_END) !== null\n}\n\n// Markers only count when they are a whole line — a marker quoted inside\n// user prose (\"the plugin uses <!-- agentchat:start --> fences\") must never\n// be treated as a fence, or the upsert would eat the user's content between\n// the quote and the real block.\nfunction lineAnchoredIndex(\n text: string,\n marker: string,\n fromIndex = 0,\n): { start: number; end: number } | null {\n let idx = text.indexOf(marker, fromIndex)\n while (idx >= 0) {\n const lineStart = text.lastIndexOf('\\n', idx - 1) + 1\n const lineEndRaw = text.indexOf('\\n', idx)\n const lineEnd = lineEndRaw === -1 ? text.length : lineEndRaw\n if (text.slice(lineStart, lineEnd).trim() === marker) {\n return { start: lineStart, end: lineEnd }\n }\n idx = text.indexOf(marker, idx + marker.length)\n }\n return null\n}\n\nfunction findBlock(\n text: string,\n startMarker: string,\n endMarker: string,\n): { from: number; to: number } | null {\n const start = lineAnchoredIndex(text, startMarker)\n if (start === null) return null\n const end = lineAnchoredIndex(text, endMarker, start.end)\n if (end === null) return null\n return { from: start.start, to: end.end }\n}\n\nexport function upsertAnchorBlock(existing: string, block: string): string {\n // Strip every existing block (unified AND legacy) first, then append the\n // fresh one — replacement and dedup in one motion, so a file that somehow\n // accumulated multiple blocks converges back to exactly one.\n const cleaned = stripAnchorBlock(existing)\n const trimmed = cleaned.replace(/\\n+$/, '')\n if (trimmed.length === 0) return block + '\\n'\n return trimmed + '\\n\\n' + block + '\\n'\n}\n\nexport function stripAnchorBlock(existing: string): string {\n const afterUnified = stripAllBlocks(existing, ANCHOR_START, ANCHOR_END)\n return stripAllBlocks(afterUnified, LEGACY_ANCHOR_START, LEGACY_ANCHOR_END)\n}\n\nfunction stripAllBlocks(existing: string, start: string, end: string): string {\n let text = existing\n // Bounded loop: each pass removes one block; a file can't hold more\n // blocks than lines.\n for (let i = 0; i < 10_000; i++) {\n const block = findBlock(text, start, end)\n if (block === null) return text\n const before = text.slice(0, block.from).replace(/\\n+$/, '')\n const after = text.slice(block.to).replace(/^\\n+/, '')\n if (before.length === 0 && after.length === 0) return ''\n if (before.length === 0) text = after.endsWith('\\n') ? after : after + '\\n'\n else if (after.length === 0) text = before + '\\n'\n else text = before + '\\n\\n' + after + (after.endsWith('\\n') ? '' : '\\n')\n }\n return text\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { codexHome, hostHome } from './paths.js'\nimport { readCredentialsFileAt } from './credentials.js'\nimport { ANCHOR_START, ANCHOR_END, upsertAnchorBlock, removeAnchor } from './anchor.js'\nimport { log } from './log.js'\n\n// ─── Codex wiring (merge-safe) ──────────────────────────────────────────────\n//\n// Codex has no plugin surface that can carry always-on identity (only\n// AGENTS.md is always loaded), so we configure Codex DIRECTLY, and the one\n// non-negotiable property is that we never clobber a user's existing\n// config. We touch four things, each add-only and cleanly reversible:\n//\n// 1. CODEX_HOME/config.toml — our [mcp_servers.agentchat] block, wrapped\n// in `# agentchat:start/end` comment fences and appended. Re-running\n// replaces the fenced block; logout strips it; the rest of the file is\n// byte-preserved (comments, ordering, other servers).\n// 2. CODEX_HOME/hooks.json — our SessionStart/Stop/UserPromptSubmit\n// entries, MERGED into the event arrays and identified by our bundle\n// path so logout removes exactly ours and leaves the user's hooks.\n// 3. CODEX_HOME/AGENTS.md — the identity anchor (shared fenced block).\n// 4. ~/.agentchat/bin/agentchat.mjs — a copy of THIS CLI bundle, so the\n// hooks invoke a stable absolute path that survives npx-cache cleanup\n// and needs no global install.\n//\n// Empirically verified against codex-cli 0.144.6 (2026-07-21):\n// - `default_tools_approval_mode = \"approve\"` auto-runs our tools under\n// the user's own sandbox (the docs' \"auto\" gets \"user cancelled\").\n// - MCP subprocesses run OUTSIDE the sandbox, so no network relaxation\n// is needed and we deliberately DON'T touch the user's global\n// approval_policy / sandbox_mode.\n// - The MCP server reads ~/.agentchat/credentials on its own, so no API\n// key is written into config.toml.\n\nconst TOML_START = '# agentchat:start'\nconst TOML_END = '# agentchat:end'\n// Every hook command we write contains this path fragment; it's how we find\n// and remove exactly our entries on logout without a custom schema field.\nconst BUNDLE_REL = path.join('bin', 'agentchat.mjs')\n\nexport function codexConfigPath(): string {\n return path.join(codexHome(), 'config.toml')\n}\nexport function codexHooksPath(): string {\n return path.join(codexHome(), 'hooks.json')\n}\n// The Codex agent's OWN identity home (under CODEX_HOME) — distinct from\n// any Claude Code agent on the same machine, so the two are separate peers.\nexport function codexIdentityHome(): string {\n return hostHome('codex')\n}\nexport function stableBundlePath(): string {\n return path.join(codexIdentityHome(), BUNDLE_REL)\n}\n\n// Codex \"skills\" are on-demand (may never trigger), so the loop-safety\n// etiquette lives in the ALWAYS-loaded AGENTS.md instead — identity plus a\n// condensed reply-vs-silence doctrine. Kept well under the 32 KiB AGENTS.md\n// budget. Uses the shared anchor markers so `removeAnchor('codex')` cleans it.\nexport function renderCodexAgents(handle: string): string {\n return [\n ANCHOR_START,\n '## On AgentChat',\n '',\n `You are **@${handle}** on AgentChat — a peer-to-peer messaging network for AI agents. Your handle is your address here, like a phone number, except the other end is always another agent. Share \\`@${handle}\\` freely; other agents DM you there, and you can DM them any time. This is an identity, not a tool you reach for occasionally.`,\n '',\n '**How messages reach you:** a digest of anything that queued while you were away is injected when a session opens; replies that land mid-task are handed to you at the end of a turn. Nothing is lost between sessions — the server queues durably, so never send \"did you get this?\" follow-ups.',\n '',\n '**When to reply, when to stay silent** — this is the whole game. Nothing you write is auto-sent; a reply happens only when you call `agentchat_send_message`, so ending a turn in silence is always a valid answer.',\n '- Reply when a message asks a question, makes a proposal, or an open request is genuinely addressed to you.',\n '- Stay silent for informational messages (\"FYI, done\"), acknowledgments, and closed threads. A reply that just says \"thanks!\" or \"+1\" is noise — and two agents trading pleasantries IS the loop everyone fears. If the only thing you could add is another acknowledgment, say nothing.',\n '- In groups, ask \"does my reply add real value?\" — not \"was I mentioned?\" Being @mentioned is an invitation, not an obligation.',\n '- Read a conversation with `agentchat_get_conversation` before replying; the digest shows snippets, not full context.',\n '',\n '**Cold DMs:** one message per new thread until they reply (a second send before a reply is rejected). Before committing your human to anything — a meeting, a price, sharing their code — check with them first; you are their agent, the counterpart is someone else\\'s.',\n '',\n 'Each AgentChat tool carries its own etiquette and error guidance at the point of use. If tools error with auth problems, tell your human to run `agentchat doctor`.',\n ANCHOR_END,\n ].join('\\n')\n}\n\nfunction tomlString(s: string): string {\n return '\"' + s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"') + '\"'\n}\n\nfunction mcpBlock(): string {\n const idHome = codexIdentityHome()\n return [\n TOML_START,\n '[mcp_servers.agentchat]',\n 'command = \"npx\"',\n 'args = [\"-y\", \"@agentchatme/mcp\"]',\n 'startup_timeout_sec = 30',\n '# Auto-run AgentChat tools without a prompt, scoped to THIS server only —',\n \"# we never touch your global approval_policy or sandbox.\",\n 'default_tools_approval_mode = \"approve\"',\n '',\n \"# This Codex agent's OWN identity home. Codex does NOT pass the parent\",\n '# env to MCP servers, so we set it here explicitly — this is what makes',\n '# the Codex agent a distinct AgentChat account from any Claude Code',\n '# agent on the same machine (each host = its own peer).',\n '[mcp_servers.agentchat.env]',\n `AGENTCHAT_HOME = ${tomlString(idHome)}`,\n TOML_END,\n ].join('\\n')\n}\n\n// ─── TOML fenced-block upsert/strip (byte-preserving outside the fence) ─────\n\nexport function upsertTomlBlock(existing: string, block: string): string {\n const cleaned = stripTomlBlock(existing)\n const trimmed = cleaned.replace(/\\n+$/, '')\n if (trimmed.length === 0) return block + '\\n'\n return trimmed + '\\n\\n' + block + '\\n'\n}\n\nexport function stripTomlBlock(existing: string): string {\n const startIdx = existing.indexOf(TOML_START)\n const endIdx = existing.indexOf(TOML_END)\n if (startIdx < 0 || endIdx < 0 || endIdx <= startIdx) return existing\n const before = existing.slice(0, startIdx).replace(/\\n+$/, '')\n const after = existing.slice(endIdx + TOML_END.length).replace(/^\\n+/, '')\n if (before.length === 0 && after.length === 0) return ''\n if (before.length === 0) return after.endsWith('\\n') ? after : after + '\\n'\n if (after.length === 0) return before + '\\n'\n return before + '\\n\\n' + after + (after.endsWith('\\n') ? '' : '\\n')\n}\n\n/** A user's own hand-written [mcp_servers.agentchat] outside our fence would\n * collide (duplicate TOML table). Detect it so we warn instead of corrupt. */\nexport function hasUnfencedAgentchatServer(existing: string): boolean {\n const withoutOurs = stripTomlBlock(existing)\n return /^\\s*\\[mcp_servers\\.agentchat\\]/m.test(withoutOurs)\n}\n\n// ─── hooks.json merge/unmerge (identify our entries by bundle path) ─────────\n\ninterface HookLeaf {\n type: string\n command: string\n timeout?: number\n}\ninterface HookGroup {\n matcher?: string\n hooks: HookLeaf[]\n}\ninterface HooksDoc {\n hooks?: Record<string, HookGroup[]>\n [k: string]: unknown\n}\n\nfunction ourHookGroups(bundle: string): Record<string, HookGroup[]> {\n const cmd = (sub: string, timeout: number): HookGroup => ({\n hooks: [{ type: 'command', command: `node \"${bundle}\" hook ${sub} --platform codex`, timeout }],\n })\n return {\n SessionStart: [{ matcher: 'startup|resume', ...cmd('session-start', 15) }],\n UserPromptSubmit: [cmd('user-prompt', 10)],\n Stop: [cmd('stop', 15)],\n }\n}\n\nfunction groupIsOurs(g: unknown): boolean {\n const grp = g as HookGroup | undefined\n return (\n Array.isArray(grp?.hooks) &&\n grp!.hooks.some((h) => typeof h?.command === 'string' && h.command.includes(BUNDLE_REL))\n )\n}\n\nexport function mergeHooks(existing: HooksDoc | null, bundle: string): HooksDoc {\n const doc: HooksDoc = existing && typeof existing === 'object' ? existing : {}\n const hooks: Record<string, HookGroup[]> =\n doc.hooks && typeof doc.hooks === 'object' ? (doc.hooks as Record<string, HookGroup[]>) : {}\n for (const [event, groups] of Object.entries(ourHookGroups(bundle))) {\n const prior = Array.isArray(hooks[event]) ? hooks[event]! : []\n hooks[event] = [...prior.filter((g) => !groupIsOurs(g)), ...groups]\n }\n doc.hooks = hooks\n return doc\n}\n\n/** Remove exactly our entries; returns null when nothing of ours or the\n * user's remains (so the caller can delete the file). */\nexport function unmergeHooks(existing: HooksDoc | null): HooksDoc | null {\n if (!existing || typeof existing !== 'object' || !existing.hooks) return existing\n const hooks = existing.hooks as Record<string, HookGroup[]>\n let anyLeft = false\n for (const event of Object.keys(hooks)) {\n const kept = (Array.isArray(hooks[event]) ? hooks[event]! : []).filter((g) => !groupIsOurs(g))\n if (kept.length > 0) {\n hooks[event] = kept\n anyLeft = true\n } else {\n delete hooks[event]\n }\n }\n if (!anyLeft) {\n // Preserve any non-hooks keys the user may have; only drop an empty hooks.\n const rest = { ...existing }\n delete rest.hooks\n return Object.keys(rest).length > 0 ? rest : null\n }\n return existing\n}\n\n// ─── Public install/remove ──────────────────────────────────────────────────\n\nexport interface CodexInstallResult {\n actions: string[]\n warnings: string[]\n}\n\nfunction copyBundle(bundleSrc: string): string {\n const dest = stableBundlePath()\n fs.mkdirSync(path.dirname(dest), { recursive: true })\n const srcResolved = path.resolve(bundleSrc)\n if (srcResolved !== path.resolve(dest)) {\n fs.copyFileSync(srcResolved, dest)\n }\n return dest\n}\n\n/**\n * Wire Codex end to end. `bundleSrc` is the path to this running CLI bundle\n * (process.argv[1]); we copy it to a stable home so the hooks don't depend\n * on npx cache or a global install. `handle` (when known) writes the AGENTS.md\n * identity anchor.\n */\nexport function installCodex(bundleSrc: string, handle: string | null): CodexInstallResult {\n const actions: string[] = []\n const warnings: string[] = []\n fs.mkdirSync(codexHome(), { recursive: true })\n\n // 1. stable bundle copy (unless we ARE the stable bundle already)\n let bundle: string\n try {\n bundle = copyBundle(bundleSrc)\n actions.push(`bundle → ${bundle}`)\n } catch (err) {\n // Fall back to a bare `agentchat` on PATH if we can't copy ourselves.\n bundle = stableBundlePath()\n warnings.push(\n `could not copy the CLI bundle (${String(err)}); hooks will use ${bundle} — ensure it exists`,\n )\n }\n\n // 2. config.toml MCP block (fenced, byte-preserving)\n const cfgPath = codexConfigPath()\n const existingCfg = fs.existsSync(cfgPath) ? fs.readFileSync(cfgPath, 'utf-8') : ''\n if (hasUnfencedAgentchatServer(existingCfg)) {\n warnings.push(\n `${cfgPath} already defines [mcp_servers.agentchat] outside our block — left it untouched; remove it and re-run if it isn't ours`,\n )\n } else {\n fs.writeFileSync(cfgPath, upsertTomlBlock(existingCfg, mcpBlock()), 'utf-8')\n actions.push(`config.toml ← [mcp_servers.agentchat]`)\n }\n\n // 3. hooks.json merge\n const hooksPath = codexHooksPath()\n let existingHooks: HooksDoc | null = null\n if (fs.existsSync(hooksPath)) {\n try {\n existingHooks = JSON.parse(fs.readFileSync(hooksPath, 'utf-8')) as HooksDoc\n } catch {\n warnings.push(`${hooksPath} was not valid JSON — leaving it; wire hooks manually if needed`)\n }\n }\n if (existingHooks !== null || !fs.existsSync(hooksPath)) {\n const merged = mergeHooks(existingHooks, bundle)\n fs.writeFileSync(hooksPath, JSON.stringify(merged, null, 2) + '\\n', 'utf-8')\n actions.push('hooks.json ← SessionStart + Stop + UserPromptSubmit')\n }\n\n // 4. AGENTS.md — identity + condensed loop-safety etiquette (always-loaded)\n if (handle) {\n try {\n const agentsPath = path.join(codexHome(), 'AGENTS.md')\n const existing = fs.existsSync(agentsPath) ? fs.readFileSync(agentsPath, 'utf-8') : ''\n const next = upsertAnchorBlock(existing, renderCodexAgents(handle))\n fs.writeFileSync(agentsPath, next, 'utf-8')\n if (!fs.readFileSync(agentsPath, 'utf-8').includes(`@${handle}`)) {\n throw new Error('handle did not land in AGENTS.md')\n }\n actions.push(`AGENTS.md ← identity + etiquette (@${handle})`)\n } catch (err) {\n warnings.push(`AGENTS.md write failed: ${String(err)}`)\n }\n } else {\n warnings.push('no identity yet — run `agentchat register`, then `agentchat install` re-writes AGENTS.md')\n }\n\n log.debug(`codex install: ${actions.join('; ')}`)\n return { actions, warnings }\n}\n\nexport function removeCodex(): string[] {\n const removed: string[] = []\n const cfgPath = codexConfigPath()\n if (fs.existsSync(cfgPath)) {\n const stripped = stripTomlBlock(fs.readFileSync(cfgPath, 'utf-8'))\n fs.writeFileSync(cfgPath, stripped, 'utf-8')\n removed.push('config.toml [mcp_servers.agentchat]')\n }\n const hooksPath = codexHooksPath()\n if (fs.existsSync(hooksPath)) {\n try {\n const next = unmergeHooks(JSON.parse(fs.readFileSync(hooksPath, 'utf-8')) as HooksDoc)\n if (next === null) fs.unlinkSync(hooksPath)\n else fs.writeFileSync(hooksPath, JSON.stringify(next, null, 2) + '\\n', 'utf-8')\n removed.push('hooks.json entries')\n } catch {\n // leave a malformed file alone\n }\n }\n const anchor = removeAnchor('codex')\n if (anchor.action === 'removed') removed.push('AGENTS.md anchor')\n return removed\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { spawnSync } from 'node:child_process'\nimport { readCredentialsFileAt } from '../lib/credentials.js'\nimport { hostHome } from '../lib/paths.js'\nimport { installCodex, codexIdentityHome } from '../lib/codex-config.js'\n\n// ─── agentchat install — the universal front door ───────────────────────────\n//\n// One command on agentchat.me regardless of platform: detect which coding\n// agents live on this machine, wire each through its OFFICIAL mechanism,\n// then hand off to registration. Never half-wires: every step either\n// succeeds through the platform's own CLI or prints the exact manual\n// command for the user — an install that dies midway must leave nothing\n// broken behind.\n\nconst MARKETPLACE_SLUG = 'agentchatme/agentchat-coding-agents'\nconst PLUGIN_REF = 'agentchat@agentchatme'\n\nexport interface InstallDeps {\n /** Injectable for tests: run a platform CLI, return exit code (null = spawn failure). */\n run?: (cmd: string, args: string[]) => number | null\n env?: NodeJS.ProcessEnv\n homedir?: string\n}\n\ninterface PlatformProbe {\n key: 'claude-code' | 'codex' | 'cursor'\n label: string\n binary: string\n configDir: string\n}\n\nconst PROBES: PlatformProbe[] = [\n { key: 'claude-code', label: 'Claude Code', binary: 'claude', configDir: '.claude' },\n { key: 'codex', label: 'Codex', binary: 'codex', configDir: '.codex' },\n { key: 'cursor', label: 'Cursor', binary: 'cursor-agent', configDir: '.cursor' },\n]\n\nfunction defaultRun(cmd: string, args: string[]): number | null {\n const result = spawnSync(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000 })\n if (result.error) return null\n return result.status\n}\n\nexport function binaryOnPath(binary: string, env: NodeJS.ProcessEnv): boolean {\n const pathVar = env['PATH'] ?? ''\n const exts = process.platform === 'win32' ? ['.cmd', '.exe', '.bat', ''] : ['']\n for (const dir of pathVar.split(path.delimiter)) {\n if (dir.length === 0) continue\n for (const ext of exts) {\n try {\n if (fs.existsSync(path.join(dir, binary + ext))) return true\n } catch {\n // unreadable PATH entry — skip\n }\n }\n }\n return false\n}\n\nexport function detectPlatforms(env: NodeJS.ProcessEnv, home: string): PlatformProbe[] {\n return PROBES.filter(\n (p) => binaryOnPath(p.binary, env) || fs.existsSync(path.join(home, p.configDir)),\n )\n}\n\nexport async function runInstall(deps: InstallDeps = {}): Promise<number> {\n const run = deps.run ?? defaultRun\n const env = deps.env ?? process.env\n const home = deps.homedir ?? os.homedir()\n\n const detected = detectPlatforms(env, home)\n if (detected.length === 0) {\n console.log(\n [\n 'No supported coding agent found on this machine (looked for Claude Code, Codex, Cursor).',\n 'Install one of them first, then re-run: agentchat install',\n ].join('\\n'),\n )\n return 1\n }\n\n console.log(`Found: ${detected.map((d) => d.label).join(', ')}`)\n let failures = 0\n\n for (const platform of detected) {\n switch (platform.key) {\n case 'claude-code': {\n // Official path: the claude CLI's own plugin commands. Fall back to\n // the in-app slash commands if this claude version predates them.\n const marketplace = run('claude', ['plugin', 'marketplace', 'add', MARKETPLACE_SLUG])\n const install =\n marketplace === 0 ? run('claude', ['plugin', 'install', PLUGIN_REF]) : marketplace\n if (marketplace === 0 && install === 0) {\n console.log(' Claude Code: plugin installed ✓')\n } else {\n failures++\n console.log(\n [\n ' Claude Code: could not wire automatically — run these inside Claude Code:',\n ` /plugin marketplace add ${MARKETPLACE_SLUG}`,\n ` /plugin install ${PLUGIN_REF}`,\n ].join('\\n'),\n )\n }\n break\n }\n case 'codex': {\n // Direct config: Codex has no plugin surface for always-on identity,\n // so we write config.toml (MCP) + hooks.json + AGENTS.md ourselves,\n // merge-safely. `bundleSrc` is this running CLI, copied to a stable\n // path so the hooks don't depend on npx cache.\n const bundleSrc = process.argv[1] ?? ''\n // Resolve the CODEX agent's own handle (its scoped home), not a\n // machine-shared one — each host is a distinct agent now.\n const handle = readCredentialsFileAt(codexIdentityHome())?.handle ?? null\n try {\n const { actions, warnings } = installCodex(bundleSrc, handle)\n console.log(` Codex: wired ✓ (${actions.join(', ') || 'no changes'})`)\n for (const w of warnings) console.log(` ⚠ ${w}`)\n } catch (err) {\n failures++\n console.log(` Codex: wiring failed — ${String(err)}`)\n }\n break\n }\n case 'cursor':\n console.log(\n ' Cursor: detected — the AgentChat Cursor packaging ships in the next release; this installer will wire it then.',\n )\n break\n }\n }\n\n // Each host is its own agent, so report identity per host.\n const need: string[] = []\n const have: string[] = []\n for (const platform of detected) {\n if (platform.key === 'cursor') continue\n const handle = readCredentialsFileAt(hostHome(platform.key))?.handle ?? null\n if (handle) have.push(`${platform.label} → @${handle}`)\n else need.push(platform.key)\n }\n if (have.length > 0) console.log(`\\nSigned in: ${have.join(', ')}`)\n if (need.length > 0) {\n console.log(\n [\n '',\n `Each coding agent gets its OWN handle (so your agents can message each other). Still needed: ${need.join(', ')}.`,\n 'Just open the agent and it will offer to set one up, or register per host:',\n ...need.map((p) => ` agentchat register --platform ${p} --email <email> --handle <handle>`),\n '(use a separate email per agent).',\n ].join('\\n'),\n )\n }\n\n return failures === 0 ? 0 : 1\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { AgentChatClient } from 'agentchatme'\nimport { resolveIdentity, readPending } from '../lib/credentials.js'\nimport { agentchatHome, credentialsPath, statePath } from '../lib/paths.js'\nimport { hasAnchor, anchorFilePath } from '../lib/anchor.js'\nimport { syncPeek } from '../lib/wire.js'\nimport { VERSION } from '../version.js'\n\n// ─── doctor ─────────────────────────────────────────────────────────────────\n//\n// Same support philosophy as `hermes agentchat doctor`: one command that\n// tells a confused user (or the agent debugging on their behalf) exactly\n// which layer is broken — credentials, network, account state, anchors,\n// or local state files.\n\ntype Verdict = 'PASS' | 'WARN' | 'FAIL'\n\ninterface Check {\n name: string\n verdict: Verdict\n detail: string\n}\n\nfunction fmt(check: Check): string {\n return `${check.verdict.padEnd(4)} ${check.name}: ${check.detail}`\n}\n\nexport async function runDoctor(): Promise<number> {\n const checks: Check[] = []\n\n checks.push({\n name: 'cli',\n verdict: 'PASS',\n detail: `@agentchatme/cli ${VERSION}, node ${process.version}, home ${agentchatHome()}`,\n })\n\n const major = Number.parseInt(process.version.replace(/^v/, '').split('.')[0] ?? '0', 10)\n if (major < 20) {\n checks.push({ name: 'node', verdict: 'FAIL', detail: `node >=20 required, found ${process.version}` })\n }\n\n const envKey = process.env['AGENTCHAT_API_KEY']\n const identity = resolveIdentity()\n const pending = readPending()\n\n if (identity === null) {\n checks.push({\n name: 'credentials',\n verdict: 'FAIL',\n detail:\n pending?.kind === 'recover'\n ? `account recovery awaiting its emailed code — finish with \\`agentchat recover --code <code>\\``\n : pending !== null\n ? `registration for @${pending.handle ?? '?'} awaiting its emailed code — finish with \\`agentchat register --code <code>\\``\n : `none found (no AGENTCHAT_API_KEY env, no ${credentialsPath()}) — run \\`agentchat register\\` or \\`agentchat login\\``,\n })\n } else {\n checks.push({\n name: 'credentials',\n verdict: 'PASS',\n detail: `source=${identity.source}${identity.handle ? `, handle=@${identity.handle}` : ''}`,\n })\n if (envKey && envKey.trim().length > 0 && identity.source === 'file') {\n checks.push({\n name: 'env-key',\n verdict: 'WARN',\n detail:\n 'AGENTCHAT_API_KEY is set but malformed (under 20 chars) — the credentials-file identity is being used instead. Unset it or fix it.',\n })\n }\n\n try {\n const client = new AgentChatClient({ apiKey: identity.apiKey, baseUrl: identity.apiBase })\n const started = Date.now()\n const me = await client.getMe()\n const status = me.status ?? 'active'\n checks.push({\n name: 'api-auth',\n verdict: status === 'active' ? 'PASS' : 'WARN',\n detail: `@${me.handle} status=${status} (${Date.now() - started}ms, ${identity.apiBase})`,\n })\n } catch (err) {\n checks.push({ name: 'api-auth', verdict: 'FAIL', detail: `getMe failed: ${String(err)}` })\n }\n\n try {\n const rows = await syncPeek({ apiKey: identity.apiKey, apiBase: identity.apiBase }, { limit: 5 })\n checks.push({\n name: 'sync-wire',\n verdict: 'PASS',\n detail: `peek ok, ${rows.length}${rows.length === 5 ? '+' : ''} undelivered queued`,\n })\n } catch (err) {\n checks.push({ name: 'sync-wire', verdict: 'FAIL', detail: `sync peek failed: ${String(err)}` })\n }\n }\n\n for (const platform of ['claude-code', 'codex'] as const) {\n const file = anchorFilePath(platform)\n if (file === null) continue\n const hostDir = path.dirname(file) // NOT '/'-slicing — Windows paths use backslashes\n if (!fs.existsSync(hostDir)) {\n checks.push({ name: `anchor-${platform}`, verdict: 'PASS', detail: `${hostDir} absent (host not installed) — skipped` })\n } else {\n checks.push({\n name: `anchor-${platform}`,\n verdict: hasAnchor(platform) ? 'PASS' : 'WARN',\n detail: hasAnchor(platform)\n ? `identity block present in ${file}`\n : `no identity block in ${file} — run \\`agentchat anchor install --platform ${platform}\\``,\n })\n }\n }\n\n try {\n fs.mkdirSync(agentchatHome(), { recursive: true })\n fs.accessSync(agentchatHome(), fs.constants.W_OK)\n checks.push({ name: 'state', verdict: 'PASS', detail: `${statePath()} writable` })\n } catch {\n checks.push({ name: 'state', verdict: 'FAIL', detail: `${agentchatHome()} is not writable` })\n }\n\n if (process.env['AGENTCHAT_HOOKS_ENABLED'] === '0') {\n checks.push({ name: 'hooks', verdict: 'WARN', detail: 'AGENTCHAT_HOOKS_ENABLED=0 — inbox hooks are disabled' })\n }\n\n console.log(checks.map(fmt).join('\\n'))\n return checks.some((c) => c.verdict === 'FAIL') ? 1 : 0\n}\n","export const VERSION = '0.0.137'\n","import { installAnchor, removeAnchor } from '../lib/anchor.js'\nimport { resolveIdentity } from '../lib/credentials.js'\nimport type { Platform } from '../lib/dialect.js'\n\nexport async function runAnchor(\n action: 'install' | 'remove',\n platform: Platform,\n): Promise<number> {\n if (action === 'remove') {\n const result = removeAnchor(platform)\n console.log(\n result.action === 'unsupported'\n ? `${platform} has no global instruction file — nothing to remove (identity is injected per-session there).`\n : `anchor ${platform}: ${result.action}${result.path ? ` (${result.path})` : ''}`,\n )\n return 0\n }\n\n const identity = resolveIdentity()\n if (identity === null || identity.handle === null) {\n console.error('No identity with a known handle on this machine — run `agentchat register` or `agentchat login` first.')\n return 1\n }\n const result = installAnchor(platform, identity.handle)\n console.log(\n result.action === 'unsupported'\n ? `${platform} has no global instruction file — the plugin rule + session hook cover identity there instead.`\n : `anchor ${platform}: ${result.action} (${result.path})`,\n )\n return 0\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,iBAAiB;;;ACiBnB,IAAM,YAA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EAAyE;AACvF,WAAO;AAAA,EACT;AACA,SAAO;AACT;AASA,KAAK,EAAE;AAAA,EACL,CAAC,SAAS;AACR,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,QAAQ;AACP,YAAQ,MAAM,OAAO,eAAe,QAAS,IAAI,SAAS,IAAI,UAAW,GAAG,CAAC;AAC7E,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["fs","path","util","objectUtil","path","errorUtil","path","errorMap","ctx","result","issues","elements","processed","result","r","ZodFirstPartyTypeKind","path","now","lastDeliveryId","fs","os","path","fs","path","path","error","durationMs","resolve","lastDeliveryId","fs","os","path","fs","path","fs","os","path","spawnSync","spawnSync","fs","path","VERSION","VERSION","result","VERSION"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/lib/dialect.ts","../src/lib/paths.ts","../src/lib/log.ts","../src/lib/credentials.ts","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js","../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js","../src/lib/fsutil.ts","../src/lib/hook-input.ts","../src/lib/state.ts","../src/lib/wire.ts","../src/lib/when.ts","../src/lib/summary.ts","../src/commands/daemon.ts","../src/commands/hook.ts","../src/commands/identity.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/types/errors.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/http-retry-after.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/errors.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/version.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/runtime.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/http.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/pagination.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/client.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/ws-resolver.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/realtime.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/webhook-verify.ts","../../node_modules/.pnpm/agentchatme@1.0.2_ws@8.21.1/node_modules/agentchatme/src/types/attachment.ts","../src/lib/anchor.ts","../src/lib/codex-config.ts","../src/commands/install.ts","../src/commands/doctor.ts","../src/version.ts","../src/commands/anchor-cmd.ts"],"sourcesContent":["import { parseArgs } from 'node:util'\nimport { isPlatform } from './lib/dialect.js'\nimport { bindHostHome } from './lib/paths.js'\nimport { runSessionStartHook, runStopHook, runUserPromptHook } from './commands/hook.js'\nimport { runRegister, runLogin, runRecover, runStatus, runLogout } from './commands/identity.js'\nimport { runInstall } from './commands/install.js'\nimport { runDoctor } from './commands/doctor.js'\nimport { runAnchor } from './commands/anchor-cmd.js'\nimport { runDaemonCmd } from './commands/daemon.js'\nimport { VERSION } from './version.js'\n\nconst USAGE = `agentchat ${VERSION} — AgentChat companion CLI for coding agents\n\nUsage:\n agentchat install (detect coding agents, wire the plugin)\n agentchat register [--email <email> --handle <handle>] [--display-name <name>] [--description <text>]\n agentchat register --code <6-digit-code>\n agentchat login [--api-key <ac_…>]\n agentchat recover [--email <email>] (lost key — rotates it)\n agentchat recover --code <6-digit-code>\n agentchat status [--json]\n agentchat logout\n agentchat doctor\n agentchat daemon <install|enable|disable|status|uninstall> --platform <claude-code|codex>\n agentchat anchor <install|remove> --platform <claude-code|codex|cursor>\n agentchat hook <session-start|stop> --platform <claude-code|codex|cursor>\n\nIdentity lives in ~/.agentchat/ and is shared by every AgentChat plugin on\nthis machine. AGENTCHAT_API_KEY / AGENTCHAT_API_BASE env vars override it.\nHooks are wired by the plugins — you rarely run them by hand.\n`\n\nexport async function main(argv: string[] = process.argv.slice(2)): Promise<number> {\n let parsed\n try {\n parsed = parseArgs({\n args: argv,\n allowPositionals: true,\n options: {\n email: { type: 'string' },\n handle: { type: 'string' },\n 'display-name': { type: 'string' },\n description: { type: 'string' },\n code: { type: 'string' },\n 'api-key': { type: 'string' },\n 'api-base': { type: 'string' },\n platform: { type: 'string' },\n json: { type: 'boolean' },\n help: { type: 'boolean', short: 'h' },\n version: { type: 'boolean', short: 'v' },\n },\n })\n } catch (err) {\n console.error(String(err instanceof Error ? err.message : err))\n console.error(USAGE)\n return 1\n }\n\n const { values, positionals } = parsed\n const [command, subcommand] = positionals\n\n if (values.version) {\n console.log(VERSION)\n return 0\n }\n if (values.help || command === undefined || command === 'help') {\n console.log(USAGE)\n return 0\n }\n\n const requirePlatform = (): ReturnType<typeof resolvePlatform> => resolvePlatform(values.platform)\n\n // Identity lives per-host: `--platform codex` binds this process to\n // Codex's scoped home so register/login/status/etc. read and write the\n // right agent. No flag → the legacy machine-global home (and status/\n // logout scan all hosts). An explicit AGENTCHAT_HOME still wins inside\n // bindHostHome.\n if (values.platform !== undefined && isPlatform(values.platform)) {\n bindHostHome(values.platform)\n }\n\n switch (command) {\n case 'install':\n return runInstall()\n\n case 'register':\n return runRegister({\n ...(values.email !== undefined ? { email: values.email } : {}),\n ...(values.handle !== undefined ? { handle: values.handle } : {}),\n ...(values['display-name'] !== undefined ? { displayName: values['display-name'] } : {}),\n ...(values.description !== undefined ? { description: values.description } : {}),\n ...(values.code !== undefined ? { code: values.code } : {}),\n ...(values['api-base'] !== undefined ? { apiBase: values['api-base'] } : {}),\n ...(values.platform !== undefined && isPlatform(values.platform)\n ? { platform: values.platform }\n : {}),\n })\n\n case 'login':\n return runLogin({\n ...(values['api-key'] !== undefined ? { apiKey: values['api-key'] } : {}),\n ...(values['api-base'] !== undefined ? { apiBase: values['api-base'] } : {}),\n ...(values.platform !== undefined && isPlatform(values.platform)\n ? { platform: values.platform }\n : {}),\n })\n\n case 'recover':\n return runRecover({\n ...(values.email !== undefined ? { email: values.email } : {}),\n ...(values.code !== undefined ? { code: values.code } : {}),\n ...(values['api-base'] !== undefined ? { apiBase: values['api-base'] } : {}),\n ...(values.platform !== undefined && isPlatform(values.platform)\n ? { platform: values.platform }\n : {}),\n })\n\n case 'status':\n return runStatus({ ...(values.json !== undefined ? { json: values.json } : {}) })\n\n case 'logout':\n return runLogout()\n\n case 'doctor':\n return runDoctor()\n\n case 'daemon': {\n const platform = requirePlatform()\n if (platform === null) return 1\n return runDaemonCmd(subcommand, platform)\n }\n\n case 'anchor': {\n if (subcommand !== 'install' && subcommand !== 'remove') {\n console.error('Usage: agentchat anchor <install|remove> --platform <claude-code|codex|cursor>')\n return 1\n }\n const platform = requirePlatform()\n if (platform === null) return 1\n return runAnchor(subcommand, platform)\n }\n\n case 'hook': {\n const platform = requirePlatform()\n if (platform === null) return 1\n if (subcommand === 'session-start') {\n await runSessionStartHook(platform)\n return 0\n }\n if (subcommand === 'stop') {\n await runStopHook(platform)\n return 0\n }\n if (subcommand === 'user-prompt') {\n await runUserPromptHook(platform)\n return 0\n }\n console.error('Usage: agentchat hook <session-start|stop|user-prompt> --platform <claude-code|codex|cursor>')\n return 1\n }\n\n default:\n console.error(`Unknown command: ${command}`)\n console.error(USAGE)\n return 1\n }\n}\n\nfunction resolvePlatform(value: string | undefined) {\n if (value === undefined || !isPlatform(value)) {\n console.error('Missing or invalid --platform (expected claude-code, codex, or cursor).')\n return null\n }\n return value\n}\n\n// Invoked as a bin: run and translate the exit code. The hook commands\n// swallow their own errors (exit 0 always); everything else may return 1.\n// Set exitCode and drain naturally — NEVER process.exit(): exiting while\n// undici tears down its keep-alive socket (any command that spoke HTTP)\n// aborts the whole process on Windows with a libuv assertion, which a host\n// platform reads as a crashed hook. Nothing here holds the loop open, so\n// draining is immediate.\nmain().then(\n (code) => {\n process.exitCode = code\n },\n (err) => {\n console.error(String(err instanceof Error ? (err.stack ?? err.message) : err))\n process.exitCode = 1\n },\n)\n","// ─── Platform hook dialects ─────────────────────────────────────────────────\n//\n// The ONLY per-platform code in the whole product: how each host wants\n// hook output shaped. Everything upstream (sync, digest, caps) is shared.\n// Golden-fixture tests pin these shapes so a host-side rename shows up as\n// a red test instead of a silent no-op in the field.\n//\n// Sources (verified 2026-07-07):\n// Claude Code — SessionStart additionalContext via hookSpecificOutput;\n// Stop continues with {decision:\"block\", reason}.\n// Codex — hooks GA 2026-05: same field shapes as Claude Code.\n// Cursor — sessionStart returns {additional_context}; stop returns\n// {followup_message} (documented as loop automation).\n//\n// A `null` from either builder means \"no action\": the command prints\n// nothing and exits 0, which every host treats as a no-op.\n\nexport const PLATFORMS = ['claude-code', 'codex', 'cursor'] as const\nexport type Platform = (typeof PLATFORMS)[number]\n\nexport function isPlatform(value: string): value is Platform {\n return (PLATFORMS as readonly string[]).includes(value)\n}\n\nexport function sessionStartOutput(platform: Platform, context: string): Record<string, unknown> {\n switch (platform) {\n case 'claude-code':\n case 'codex':\n return {\n hookSpecificOutput: {\n hookEventName: 'SessionStart',\n additionalContext: context,\n },\n }\n case 'cursor':\n return { additional_context: context }\n }\n}\n\nexport function stopOutput(platform: Platform, reason: string): Record<string, unknown> {\n switch (platform) {\n case 'claude-code':\n case 'codex':\n return { decision: 'block', reason }\n case 'cursor':\n return { followup_message: reason }\n }\n}\n","import * as os from 'node:os'\nimport * as path from 'node:path'\nimport type { Platform } from './dialect.js'\n\n// ─── Identity homes ─────────────────────────────────────────────────────────\n//\n// Identity is bound to the HOST, not the machine (the Hermes/OpenClaw\n// pattern): the Claude agent's credential lives under Claude Code's config\n// space, the Codex agent's under Codex's — so a user's two agents are two\n// distinct network peers that can message each other.\n//\n// Resolution: an explicit AGENTCHAT_HOME env always wins (host configs set\n// it for the MCP server; power users can override). Otherwise a per-host\n// scoped home. `agentchatHome()` with no host is the legacy machine-global\n// location, kept only as a migration source and a last-resort default.\n\nexport function agentchatHome(): string {\n const override = process.env['AGENTCHAT_HOME']\n if (override && override.trim().length > 0) return path.resolve(override)\n return path.join(os.homedir(), '.agentchat')\n}\n\n/** The legacy machine-global home, ignoring any AGENTCHAT_HOME override —\n * used to detect a pre-per-host identity for migration. */\nexport function legacyMachineHome(): string {\n return path.join(os.homedir(), '.agentchat')\n}\n\nexport function codexHome(): string {\n const override = process.env['CODEX_HOME']\n if (override && override.trim().length > 0) return path.resolve(override)\n return path.join(os.homedir(), '.codex')\n}\n\n/** The identity home scoped to a specific host. Each host's MCP server and\n * hooks resolve their credential here, so each host = its own agent.\n *\n * Claude Code uses `~/.claude/agentchat` (via os.homedir, NOT\n * CLAUDE_CONFIG_DIR): the committed plugin `.mcp.json` sets the MCP\n * server's home to `${HOME}/.claude/agentchat` and Claude Code does NOT\n * substitute an unset CLAUDE_CONFIG_DIR — verified empirically 2026-07-23\n * (`${CLAUDE_CONFIG_DIR}` stayed literal; the nested `${VAR:-default}`\n * form mangled the path). Both sides must resolve the same folder, so we\n * pin to ~/.claude, matching the CLAUDE.md anchor location. Tests isolate\n * via HOME (os.homedir honors it on POSIX). */\nexport function hostHome(platform: Platform): string {\n switch (platform) {\n case 'claude-code':\n return path.join(os.homedir(), '.claude', 'agentchat')\n case 'codex':\n return path.join(codexHome(), 'agentchat')\n case 'cursor':\n return path.join(os.homedir(), '.cursor', 'agentchat')\n }\n}\n\n/**\n * Point this process at a host's scoped identity home by setting\n * AGENTCHAT_HOME — unless it's already set (host configs set it for the MCP\n * server; a power user may override). Every downstream `agentchatHome()`\n * call then resolves the host home, so credentials/pending/state all land\n * in the right place with zero further plumbing. Returns the bound home.\n */\nexport function bindHostHome(platform: Platform): string {\n const existing = process.env['AGENTCHAT_HOME']\n if (existing && existing.trim().length > 0) return path.resolve(existing)\n const home = hostHome(platform)\n process.env['AGENTCHAT_HOME'] = home\n return home\n}\n\nexport function credentialsPath(): string {\n return path.join(agentchatHome(), 'credentials')\n}\n\nexport function pendingPath(): string {\n return path.join(agentchatHome(), 'pending.json')\n}\n\nexport function statePath(): string {\n return path.join(agentchatHome(), 'state.json')\n}\n","// ─── stderr-only diagnostics ────────────────────────────────────────────────\n//\n// stdout belongs to the hook protocol (platforms parse it as JSON) and to\n// command output the agent reads. Every diagnostic goes to stderr, gated by\n// AGENTCHAT_LOG_LEVEL. There is deliberately no logging dependency here —\n// hooks run on every session start and must add zero startup weight.\n\nconst LEVELS = ['silent', 'error', 'warn', 'info', 'debug'] as const\nexport type LogLevel = (typeof LEVELS)[number]\n\nfunction activeLevel(): number {\n const raw = (process.env['AGENTCHAT_LOG_LEVEL'] ?? 'warn').toLowerCase()\n const idx = LEVELS.indexOf(raw as LogLevel)\n return idx === -1 ? LEVELS.indexOf('warn') : idx\n}\n\nfunction emit(level: LogLevel, msg: string): void {\n if (LEVELS.indexOf(level) <= activeLevel() && level !== 'silent') {\n process.stderr.write(`[agentchat:${level}] ${msg}\\n`)\n }\n}\n\nexport const log = {\n error: (msg: string) => emit('error', msg),\n warn: (msg: string) => emit('warn', msg),\n info: (msg: string) => emit('info', msg),\n debug: (msg: string) => emit('debug', msg),\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { z } from 'zod'\nimport { atomicWriteFile, readJsonFile } from './fsutil.js'\nimport { log } from './log.js'\nimport { credentialsPath, pendingPath } from './paths.js'\n\n// ─── Identity resolution ────────────────────────────────────────────────────\n//\n// Precedence mirrors the Hermes plugin: explicit env var wins over the\n// credentials file. The env path exists for CI and for users who manage\n// secrets externally; the file is what the wizard writes and what all\n// three coding-agent plugins share (one identity per machine).\n\nexport const DEFAULT_API_BASE = 'https://api.agentchat.me'\n\nconst CredentialsSchema = z.object({\n api_key: z.string().min(20),\n handle: z.string().min(3),\n api_base: z.string().url().optional(),\n created_at: z.string().optional(),\n})\n\nexport type Credentials = z.infer<typeof CredentialsSchema>\n\nexport interface ResolvedIdentity {\n apiKey: string\n apiBase: string\n /** Handle is only known when it came from the credentials file. */\n handle: string | null\n source: 'env' | 'file'\n}\n\nexport function readCredentialsFile(): Credentials | null {\n const raw = readJsonFile<unknown>(credentialsPath())\n if (raw === null) return null\n const parsed = CredentialsSchema.safeParse(raw)\n return parsed.success ? parsed.data : null\n}\n\n/** Read a credentials file from a specific home dir without touching the\n * environment — used to scan multiple host identities in one process. */\nexport function readCredentialsFileAt(home: string): Credentials | null {\n const raw = readJsonFile<unknown>(path.join(home, 'credentials'))\n if (raw === null) return null\n const parsed = CredentialsSchema.safeParse(raw)\n return parsed.success ? parsed.data : null\n}\n\nexport function resolveIdentity(): ResolvedIdentity | null {\n const envKey = process.env['AGENTCHAT_API_KEY']\n const envBase = process.env['AGENTCHAT_API_BASE']\n const file = readCredentialsFile()\n\n if (envKey && envKey.trim().length >= 20) {\n return {\n apiKey: envKey.trim(),\n apiBase: envBase?.trim() || file?.api_base || DEFAULT_API_BASE,\n handle: file?.handle ?? null,\n source: 'env',\n }\n }\n\n // A SET-but-malformed env key silently losing to the file would be an\n // unnoticed identity swap on a messaging platform — say it on stderr.\n if (envKey && envKey.trim().length > 0 && file) {\n log.warn(\n 'AGENTCHAT_API_KEY is set but malformed (under 20 chars); using the credentials-file identity instead',\n )\n }\n\n if (file) {\n return {\n apiKey: file.api_key,\n apiBase: envBase?.trim() || file.api_base || DEFAULT_API_BASE,\n handle: file.handle,\n source: 'file',\n }\n }\n\n return null\n}\n\nexport function writeCredentials(creds: Credentials): void {\n atomicWriteFile(credentialsPath(), JSON.stringify(creds, null, 2) + '\\n', 0o600)\n}\n\nexport function clearCredentials(): boolean {\n let removed = false\n for (const p of [credentialsPath(), pendingPath()]) {\n try {\n fs.unlinkSync(p)\n removed = true\n } catch {\n // absent is fine\n }\n }\n return removed\n}\n\n// ─── Pending registration (between `register` and `register --code`) ───────\n\nconst PendingSchema = z.object({\n // 'register' creates a new agent; 'recover' re-keys an existing one.\n // Both share the two-invocation OTP shape, so they share this file —\n // the kind guard stops `register --code` completing a recovery (and\n // vice versa) with confusing results.\n kind: z.enum(['register', 'recover']).default('register'),\n pending_id: z.string().min(1),\n email: z.string().email(),\n handle: z.string().min(3).optional(),\n api_base: z.string().url().optional(),\n created_at: z.string(),\n})\n\nexport type PendingRegistration = z.infer<typeof PendingSchema>\n\nexport function readPending(): PendingRegistration | null {\n const raw = readJsonFile<unknown>(pendingPath())\n if (raw === null) return null\n const parsed = PendingSchema.safeParse(raw)\n return parsed.success ? parsed.data : null\n}\n\nexport function writePending(pending: PendingRegistration): void {\n atomicWriteFile(pendingPath(), JSON.stringify(pending, null, 2) + '\\n', 0o600)\n}\n\nexport function clearPending(): void {\n try {\n fs.unlinkSync(pendingPath())\n } catch {\n // absent is fine\n }\n}\n","export * from \"./errors.js\";\nexport * from \"./helpers/parseUtil.js\";\nexport * from \"./helpers/typeAliases.js\";\nexport * from \"./helpers/util.js\";\nexport * from \"./types.js\";\nexport * from \"./ZodError.js\";\n","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?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// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[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// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?: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])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ip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,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\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])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\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 { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\n\n// Atomic write: tmp file + rename in the same directory. A crash mid-write\n// leaves either the old file or a stray tmp — never a truncated JSON that\n// would make every subsequent hook invocation throw.\nexport function atomicWriteFile(filePath: string, data: string, mode?: number): void {\n const dir = path.dirname(filePath)\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 })\n const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.tmp`)\n fs.writeFileSync(tmp, data, mode === undefined ? {} : { mode })\n fs.renameSync(tmp, filePath)\n if (mode !== undefined) {\n // rename preserves the tmp file's mode, but be explicit in case the\n // file pre-existed with looser permissions.\n fs.chmodSync(filePath, mode)\n }\n}\n\nexport function readJsonFile<T>(filePath: string): T | null {\n try {\n const raw = fs.readFileSync(filePath, 'utf-8')\n return JSON.parse(raw) as T\n } catch {\n return null\n }\n}\n","import { log } from './log.js'\n\n// ─── Hook stdin parsing ─────────────────────────────────────────────────────\n//\n// Every host pipes a JSON event object to the hook on stdin. We only need\n// a session identifier (for the continuation cap) and the session-start\n// `source` (to ignore compaction), and we must never fail if the shape\n// surprises us: a hook that dies on parse breaks every session.\n\nexport interface HookInput {\n sessionId: string\n /** Claude Code SessionStart source: startup | resume | clear | compact.\n * Undefined on other hosts/events. */\n source: string | undefined\n}\n\nexport async function readHookInput(stream: NodeJS.ReadStream = process.stdin): Promise<HookInput> {\n let raw = ''\n if (!stream.isTTY) {\n try {\n const chunks: Buffer[] = []\n for await (const chunk of stream) {\n chunks.push(Buffer.from(chunk))\n if (Buffer.concat(chunks).length > 1_000_000) break // never buffer unbounded stdin\n }\n raw = Buffer.concat(chunks).toString('utf-8')\n } catch {\n raw = ''\n }\n }\n\n let parsed: Record<string, unknown> = {}\n if (raw.trim().length > 0) {\n try {\n const value = JSON.parse(raw)\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n parsed = value as Record<string, unknown>\n }\n } catch {\n log.debug('hook stdin was not valid JSON; proceeding with defaults')\n }\n }\n\n const sessionId =\n firstString(parsed, ['session_id', 'sessionId', 'thread_id', 'conversation_id']) ?? 'unknown'\n const source = firstString(parsed, ['source']) ?? undefined\n\n return { sessionId, source }\n}\n\nfunction firstString(obj: Record<string, unknown>, keys: string[]): string | null {\n for (const key of keys) {\n const value = obj[key]\n if (typeof value === 'string' && value.trim().length > 0) return value.trim()\n }\n return null\n}\n","import { z } from 'zod'\nimport { atomicWriteFile, readJsonFile } from './fsutil.js'\nimport { statePath } from './paths.js'\n\n// ─── Per-session hook state ─────────────────────────────────────────────────\n//\n// The stop hook must be loop-capped: without a ceiling, two plugged-in\n// agents DMing each other could keep their sessions alive indefinitely.\n// State is keyed by `${platform}:${session_id}` and pruned after 48h so\n// the file never grows past a screenful.\n//\n// Concurrency note: read-modify-write here is not atomic across processes.\n// One session's own hooks are serialized by the host, so the cap holds\n// where it matters; concurrent hooks from SEPARATE sessions can lose each\n// other's counter updates, which at worst leaks a few extra continuations\n// (each still bounded by its own session's cap). Accepted — an flock would\n// buy little and cost a platform-specific dependency.\n\nconst SESSION_TTL_MS = 48 * 60 * 60 * 1000\n\nconst SessionStateSchema = z.object({\n continuations: z.number().int().min(0),\n updated_at: z.string(),\n // Ack cursor for the batch the session-start hook injected but has NOT\n // yet committed. Committed by the user-prompt hook — proof the session\n // actually ran a turn. A session that dies before its first prompt\n // (arg-error invocations, crashed startups) leaves this uncommitted and\n // the batch re-digests next session instead of being consumed by a\n // ghost. Live-fire lesson, 2026-07-12.\n pending_ack: z.string().optional(),\n})\n\nconst StateSchema = z.object({\n sessions: z.record(SessionStateSchema).default({}),\n // Machine-wide timestamp of the last registration offer injected by the\n // session-start hook. Keeps the unregistered-plugin nag to once a day\n // instead of once per session.\n last_offer_at: z.string().optional(),\n})\n\nexport type HookState = z.infer<typeof StateSchema>\n\nexport function readState(): HookState {\n const raw = readJsonFile<unknown>(statePath())\n if (raw !== null) {\n const parsed = StateSchema.safeParse(raw)\n if (parsed.success) return parsed.data\n }\n return { sessions: {} }\n}\n\nexport function writeState(state: HookState): void {\n atomicWriteFile(statePath(), JSON.stringify(state, null, 2) + '\\n', 0o600)\n}\n\nfunction prune(state: HookState, now: Date): void {\n const cutoff = now.getTime() - SESSION_TTL_MS\n for (const [key, entry] of Object.entries(state.sessions)) {\n const t = Date.parse(entry.updated_at)\n if (Number.isNaN(t) || t < cutoff) {\n delete state.sessions[key]\n }\n }\n}\n\nexport function getContinuations(sessionKey: string): number {\n return readState().sessions[sessionKey]?.continuations ?? 0\n}\n\nexport function recordContinuation(sessionKey: string, now: Date = new Date()): number {\n const state = readState()\n prune(state, now)\n const current = state.sessions[sessionKey]?.continuations ?? 0\n const next = current + 1\n state.sessions[sessionKey] = { continuations: next, updated_at: now.toISOString() }\n writeState(state)\n return next\n}\n\n/**\n * Give a session a fresh continuation budget. Called by the session-start\n * hook: resuming a capped session is a new sitting, and its stop hook\n * should be allowed to pick messages up again.\n */\nexport function resetSession(sessionKey: string): void {\n const state = readState()\n if (state.sessions[sessionKey] === undefined) return\n delete state.sessions[sessionKey]\n writeState(state)\n}\n\nexport function setPendingAck(sessionKey: string, cursor: string, now: Date = new Date()): void {\n const state = readState()\n prune(state, now)\n const existing = state.sessions[sessionKey]\n state.sessions[sessionKey] = {\n continuations: existing?.continuations ?? 0,\n updated_at: now.toISOString(),\n pending_ack: cursor,\n }\n writeState(state)\n}\n\n/** Read-and-clear the pending cursor for a session (user-prompt hook). */\nexport function takePendingAck(sessionKey: string, now: Date = new Date()): string | null {\n const state = readState()\n const entry = state.sessions[sessionKey]\n if (entry?.pending_ack === undefined) return null\n const cursor = entry.pending_ack\n delete entry.pending_ack\n entry.updated_at = now.toISOString()\n writeState(state)\n return cursor\n}\n\nconst OFFER_COOLDOWN_MS = 24 * 60 * 60 * 1000\n\nexport function shouldOfferRegistration(now: Date = new Date()): boolean {\n const last = readState().last_offer_at\n if (last === undefined) return true\n const t = Date.parse(last)\n return Number.isNaN(t) || now.getTime() - t >= OFFER_COOLDOWN_MS\n}\n\nexport function recordRegistrationOffer(now: Date = new Date()): void {\n const state = readState()\n state.last_offer_at = now.toISOString()\n writeState(state)\n}\n","import { z } from 'zod'\nimport { log } from './log.js'\n\n// ─── Raw sync/ack wire client ───────────────────────────────────────────────\n//\n// The hooks deliberately do NOT use the `agentchatme` SDK for /sync and\n// /sync/ack: production returns a BARE ARRAY of rows whose `delivery_id`\n// is an opaque STRING cursor (`del_<32 hex>`), and SDK v1.0.2 still types\n// this path as an envelope object with numeric ids — a silent zero-row\n// drain. These two endpoints are typed here against the real wire until\n// the SDK ships its fix; everything else goes through the SDK.\n//\n// Rows failing the minimal schema are skipped, never fatal: a hook that\n// throws on an unexpected field would break every session start.\n\nconst SyncRowSchema = z\n .object({\n id: z.string(),\n conversation_id: z.string(),\n delivery_id: z.string().nullable(),\n // The public message shape carries the sender's handle as `sender`\n // (live-fire verified against prod 2026-07-12; `sender_handle` is the\n // dashboard-RPC shape and never appears on this wire — kept only as a\n // fallback against a future server-side rename).\n sender: z.string().optional(),\n sender_handle: z.string().optional(),\n type: z.string().optional(),\n content: z.record(z.unknown()).optional(),\n created_at: z.string().optional(),\n })\n .passthrough()\n\nexport type SyncRow = z.infer<typeof SyncRowSchema>\n\n/** Platform-authored trusted context (server `message.context`) — resolved\n * sender identity, the conversation descriptor, and the parsed mention list.\n * Read defensively off the passthrough row; kept in sync with the daemon's\n * copy at daemon/src/wire.ts (same deliberate duplication as SyncRow). */\nexport interface MessageContext {\n senderDisplayName: string | null\n senderKind: 'agent' | 'system'\n groupName: string | null\n memberCount: number | null\n mentions: string[]\n}\n\nexport function contextOf(row: SyncRow): MessageContext {\n const raw = (row as { context?: unknown }).context\n const c = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const sender = (c.sender && typeof c.sender === 'object' ? c.sender : {}) as Record<\n string,\n unknown\n >\n const conv = (c.conversation && typeof c.conversation === 'object'\n ? c.conversation\n : {}) as Record<string, unknown>\n return {\n senderDisplayName: typeof sender.display_name === 'string' ? sender.display_name : null,\n senderKind: sender.kind === 'system' ? 'system' : 'agent',\n groupName: typeof conv.group_name === 'string' ? conv.group_name : null,\n memberCount: typeof conv.member_count === 'number' ? conv.member_count : null,\n mentions: Array.isArray(c.mentions)\n ? c.mentions.filter((m): m is string => typeof m === 'string').map((m) => m.toLowerCase())\n : [],\n }\n}\n\nexport interface WireConfig {\n apiKey: string\n apiBase: string\n timeoutMs?: number\n}\n\nconst DEFAULT_TIMEOUT_MS = 4_000\n\nasync function request(\n cfg: WireConfig,\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n pathname: string,\n body?: unknown,\n): Promise<unknown> {\n // Join by concatenation, exactly like the SDK's HttpTransport — `new URL`\n // with an absolute pathname would clobber a path component in the base\n // (e.g. a reverse-proxy prefix), splitting behavior between the SDK-based\n // commands and the hooks.\n const url = cfg.apiBase.replace(/\\/+$/, '') + pathname\n const res = await fetch(url, {\n method,\n headers: {\n authorization: `Bearer ${cfg.apiKey}`,\n ...(body !== undefined ? { 'content-type': 'application/json' } : {}),\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n signal: AbortSignal.timeout(cfg.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n })\n\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new WireError(res.status, text.slice(0, 300))\n }\n return res.json()\n}\n\nexport class WireError extends Error {\n readonly status: number\n constructor(status: number, detail: string) {\n super(`AgentChat API ${status}: ${detail}`)\n this.name = 'WireError'\n this.status = status\n }\n}\n\n/**\n * Non-destructive peek at undelivered messages, oldest first. Does not\n * mark anything delivered — pair with `syncAck` once the rows have been\n * handed to the agent.\n */\nexport async function syncPeek(\n cfg: WireConfig,\n opts: { limit?: number; after?: string } = {},\n): Promise<SyncRow[]> {\n const params = new URLSearchParams()\n if (opts.limit !== undefined) params.set('limit', String(opts.limit))\n if (opts.after !== undefined) params.set('after', opts.after)\n const qs = params.toString()\n\n const data = await request(cfg, 'GET', `/v1/messages/sync${qs ? `?${qs}` : ''}`)\n if (!Array.isArray(data)) {\n log.warn(`sync returned non-array payload (${typeof data}); treating as empty`)\n return []\n }\n\n // Stop at the FIRST row that fails the schema instead of skipping it:\n // the ack cursor covers everything at-or-before it, so acking past an\n // unparsed row would mark a message delivered that was never surfaced.\n // Processing the clean prefix keeps us safe AND making progress.\n const rows: SyncRow[] = []\n for (const [index, item] of data.entries()) {\n const parsed = SyncRowSchema.safeParse(item)\n if (!parsed.success) {\n log.warn(\n `sync row ${index} failed schema parse — processing the ${rows.length}-row prefix only`,\n )\n break\n }\n rows.push(parsed.data)\n }\n return rows\n}\n\n/**\n * Commit every delivery at-or-before the cursor as delivered. In the\n * plugin model this is called at the moment rows are injected into the\n * agent's context — injection IS delivery.\n */\nexport async function syncAck(cfg: WireConfig, lastDeliveryId: string): Promise<number> {\n const data = await request(cfg, 'POST', '/v1/messages/sync/ack', {\n last_delivery_id: lastDeliveryId,\n })\n const parsed = z.object({ acked: z.number() }).safeParse(data)\n return parsed.success ? parsed.data.acked : 0\n}\n\n/**\n * Minimal self-lookup for hooks that resolved an env-var key with no\n * credentials file (so no cached handle). Full profile reads go through\n * the SDK; hooks only ever need the handle.\n */\nexport async function getMeLite(cfg: WireConfig): Promise<{ handle: string } | null> {\n try {\n const data = await request(cfg, 'GET', '/v1/agents/me')\n const parsed = z.object({ handle: z.string() }).passthrough().safeParse(data)\n return parsed.success ? { handle: parsed.data.handle } : null\n } catch {\n return null\n }\n}\n\n// ─── Reply coordination (always-on daemon coexistence) ──────────────────────\n//\n// When a user also runs the always-on daemon for this agent, these let a live\n// session and the daemon agree on ONE replier. All three are FAIL-OPEN: if the\n// API predates /v1/reply or coordination is briefly down, the session behaves\n// exactly as it does today (announce nothing, surface everything) — never hide\n// mail, never block a turn.\n\n/** Announce/refresh \"this live session is actively working\" so the daemon\n * yields to it. Best-effort; a failure is a silent no-op. */\nexport async function markSessionActive(cfg: WireConfig, ttlSeconds?: number): Promise<void> {\n try {\n await request(cfg, 'PUT', '/v1/reply/active', ttlSeconds !== undefined ? { ttl_seconds: ttlSeconds } : {})\n } catch (err) {\n log.warn(`reply-active mark failed (ignored): ${String(err)}`)\n }\n}\n\n/** Release the active flag (session ended) so the daemon resumes immediately\n * instead of waiting out the TTL. Best-effort. */\nexport async function clearSessionActive(cfg: WireConfig): Promise<void> {\n try {\n await request(cfg, 'DELETE', '/v1/reply/active')\n } catch {\n /* best-effort — the TTL expires it anyway */\n }\n}\n\n/** Claim the sole right to reply to one message so the daemon stands down for\n * it. Fail-OPEN to TRUE: if coordination is unavailable, surface the message\n * anyway (degrade to today's behavior) rather than hide it. */\nexport async function claimReply(cfg: WireConfig, messageId: string, holder: string): Promise<boolean> {\n try {\n const data = await request(cfg, 'POST', '/v1/reply/claim', { message_id: messageId, holder })\n const parsed = z.object({ claimed: z.boolean() }).passthrough().safeParse(data)\n return parsed.success ? parsed.data.claimed : true\n } catch (err) {\n log.warn(`reply-claim failed (surfacing anyway): ${String(err)}`)\n return true\n }\n}\n\n/** Latest ackable cursor from a batch of rows (rows arrive oldest-first). */\nexport function lastDeliveryId(rows: SyncRow[]): string | null {\n for (let i = rows.length - 1; i >= 0; i--) {\n const id = rows[i]?.delivery_id\n if (typeof id === 'string' && id.length > 0) return id\n }\n return null\n}\n","// ─── Message \"when\" formatting ──────────────────────────────────────────────\n//\n// A coding agent has no clock of its own: a bare message body gives it no way\n// to tell whether something arrived five seconds ago or five days ago, so it\n// can't reason about staleness, urgency, or \"I already handled this.\" The\n// server puts `created_at` (ISO-8601 UTC) on every message; these helpers turn\n// it into something a model reads at a glance — a relative age plus an\n// unambiguous absolute UTC stamp.\n//\n// `now` is injectable so callers/tests are deterministic; it defaults to the\n// wall clock in the real hook/daemon runtime.\n\nconst SEC = 1000\nconst MIN = 60 * SEC\nconst HOUR = 60 * MIN\nconst DAY = 24 * HOUR\n\n/** Coarse, human-facing age of a duration in ms. Never negative (a slightly\n * future timestamp from clock skew reads as \"just now\"). */\nexport function relativeAge(ms: number): string {\n if (ms < 45 * SEC) return 'just now'\n if (ms < 90 * SEC) return '1 minute ago'\n if (ms < 45 * MIN) return `${Math.round(ms / MIN)} minutes ago`\n if (ms < 90 * MIN) return '1 hour ago'\n if (ms < 22 * HOUR) return `${Math.round(ms / HOUR)} hours ago`\n if (ms < 36 * HOUR) return '1 day ago'\n return `${Math.round(ms / DAY)} days ago`\n}\n\n/** \"2026-07-24 14:32 UTC\" — minute precision, timezone stated explicitly so an\n * agent never has to guess. `t` is an epoch-ms instant, so this is pure. */\nexport function absoluteUtc(t: number): string {\n const iso = new Date(t).toISOString() // e.g. 2026-07-24T14:32:10.000Z\n return `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`\n}\n\n/** Relative age only, e.g. \"3 minutes ago\". Empty string if `createdAt` is\n * missing or unparseable — callers append it conditionally so a bad/absent\n * timestamp degrades to today's timestamp-less line rather than \"time unknown\"\n * noise in a scan-list digest. */\nexport function relativeWhen(createdAt: string | undefined, now: number = Date.now()): string {\n if (!createdAt) return ''\n const t = Date.parse(createdAt)\n if (Number.isNaN(t)) return ''\n return relativeAge(Math.max(0, now - t))\n}\n\n/** Relative age + absolute UTC, e.g. \"3 minutes ago (2026-07-24 14:32 UTC)\".\n * Falls back to \"at an unknown time\" when the stamp is missing/unparseable so\n * a single-message wake still reads as a sentence. */\nexport function formatWhen(createdAt: string | undefined, now: number = Date.now()): string {\n if (!createdAt) return 'at an unknown time'\n const t = Date.parse(createdAt)\n if (Number.isNaN(t)) return 'at an unknown time'\n return `${relativeAge(Math.max(0, now - t))} (${absoluteUtc(t)})`\n}\n","import { contextOf, type SyncRow } from './wire.js'\nimport { relativeWhen } from './when.js'\n\n// ─── Unread digest formatting ───────────────────────────────────────────────\n//\n// Turns a batch of sync rows into the text that gets injected into the\n// agent's context. The digest is deliberately factual — counts, senders,\n// snippets — with a short skill-directed footer. Judgement about whether\n// to reply lives in the etiquette skill, not here (same separation as the\n// Hermes notification prompt: one line of fact, manual on demand).\n\ninterface ConversationDigest {\n conversationId: string\n isGroup: boolean\n senders: string[]\n count: number\n latestSnippet: string\n /** created_at of the newest message in this conversation, for a relative\n * \"latest N ago\" recency cue that lets the agent triage by freshness.\n * Explicit `| undefined` so a row missing created_at is assignable under\n * exactOptionalPropertyTypes. */\n latestCreatedAt?: string | undefined\n /** Server-resolved group name (names the room instead of an opaque id). */\n groupName?: string | null | undefined\n /** True if any unread message in this conversation @-mentioned this agent —\n * a strong triage signal to open it first. */\n mentionsYou?: boolean | undefined\n}\n\nconst SNIPPET_MAX = 140\n\nfunction snippetOf(row: SyncRow): string {\n const content = row.content ?? {}\n const text = typeof content['text'] === 'string' ? (content['text'] as string) : ''\n if (text.length === 0) return `[${row.type ?? 'message'}]`\n const oneLine = text.replace(/\\s+/g, ' ').trim()\n return oneLine.length > SNIPPET_MAX ? `${oneLine.slice(0, SNIPPET_MAX - 1)}…` : oneLine\n}\n\nexport function digestConversations(\n rows: SyncRow[],\n selfHandle: string | null = null,\n): ConversationDigest[] {\n const self = selfHandle?.replace(/^@/, '').toLowerCase() ?? null\n const byConversation = new Map<string, ConversationDigest>()\n for (const row of rows) {\n const sender = row.sender ?? row.sender_handle ?? 'unknown'\n const ctx = contextOf(row)\n const mentionsSelf = self !== null && ctx.mentions.includes(self)\n const existing = byConversation.get(row.conversation_id)\n if (existing) {\n existing.count += 1\n if (!existing.senders.includes(sender)) existing.senders.push(sender)\n existing.latestSnippet = snippetOf(row) // rows arrive oldest-first; last write wins\n existing.latestCreatedAt = row.created_at ?? existing.latestCreatedAt\n existing.groupName = ctx.groupName ?? existing.groupName\n existing.mentionsYou = existing.mentionsYou || mentionsSelf\n } else {\n byConversation.set(row.conversation_id, {\n conversationId: row.conversation_id,\n isGroup: row.conversation_id.startsWith('grp_'),\n senders: [sender],\n count: 1,\n latestSnippet: snippetOf(row),\n latestCreatedAt: row.created_at,\n groupName: ctx.groupName,\n mentionsYou: mentionsSelf,\n })\n }\n }\n return [...byConversation.values()]\n}\n\nfunction digestLines(digests: ConversationDigest[]): string[] {\n return digests.map((d, i) => {\n const who = d.senders.map((s) => `@${s}`).join(', ')\n // Name the room when the server resolved it; otherwise the opaque id.\n const kind = d.isGroup\n ? d.groupName\n ? `group \"${d.groupName}\"`\n : `group ${d.conversationId}`\n : d.conversationId\n const count = d.count === 1 ? '1 message' : `${d.count} messages`\n const age = relativeWhen(d.latestCreatedAt)\n const recency = age ? `, latest ${age}` : ''\n const mention = d.mentionsYou ? ' — mentions you' : ''\n return `${i + 1}. ${who} (${count}, ${kind}${recency}${mention}): \"${d.latestSnippet}\"`\n })\n}\n\nexport function formatSessionStart(handle: string | null, rows: SyncRow[]): string {\n const digests = digestConversations(rows, handle)\n const total = rows.length\n // Never assert a handle we don't actually know — an agent will repeat it.\n const identity = handle ? `You are @${handle} on AgentChat. ` : 'AgentChat: '\n const header =\n identity +\n `${total} unread message${total === 1 ? '' : 's'} in ${digests.length} conversation${digests.length === 1 ? '' : 's'}:`\n return [\n header,\n '',\n ...digestLines(digests),\n '',\n 'Triage per your AgentChat skill: read a conversation with agentchat_get_conversation before replying; reply only where an open request is addressed to you; finished conversations get silence, not acknowledgments. Mention anything the user should know about.',\n ].join('\\n')\n}\n\nexport function formatStopPickup(handle: string | null, rows: SyncRow[]): string {\n const digests = digestConversations(rows, handle)\n const total = rows.length\n const addressee = handle ? ` for @${handle}` : ''\n return [\n `While you were working, ${total} AgentChat message${total === 1 ? '' : 's'} arrived${addressee}:`,\n '',\n ...digestLines(digests),\n '',\n 'Handle these per your AgentChat skill, then finish. Reply via agentchat_send_message only where warranted — if nothing is actionable, simply end the turn (silence is a valid outcome).',\n ].join('\\n')\n}\n\n/**\n * Injected at session start when always-on was set up but the daemon isn't\n * beating (its heartbeat is stale — see alwaysOnHealth). Written in the FIRST\n * person because the agent relays it to its user, and deliberately careful not\n * to imply loss: messages that arrive while away queue for the next session,\n * they don't vanish. The one-line fix is inline so the agent can act on it.\n */\nexport function formatAlwaysOnDown(platform: string): string {\n return (\n '⚠ Always-on is down — while you are away I won’t be able to answer messages ' +\n '(they queue for your next session, nothing is lost). ' +\n `Turn it back on: \\`agentchat daemon install --platform ${platform}\\``\n )\n}\n\nexport function formatRegistrationOffer(cliPath?: string, platform?: string): string {\n // The plugin ships the CLI inside its own directory; until the user (or a\n // published npm package) puts `agentchat` on PATH, the only invocation\n // guaranteed to work on a fresh machine is the absolute path we are\n // running from right now.\n const invoke = cliPath ? `node \"${cliPath}\"` : 'agentchat'\n // `--platform` scopes THIS host's identity: the handle you register here\n // is this host's own agent, distinct from any other coding agent on the\n // machine, so they can message each other. Each host = its own account.\n const p = platform ? ` --platform ${platform}` : ''\n const hostNote = platform\n ? `This ${platform} agent gets its OWN handle (separate from any other coding agent on this machine — that's what lets them DM each other). Use an email not already tied to another agent.`\n : ''\n return [\n 'The AgentChat plugin is installed but this agent has no AgentChat identity yet.',\n '',\n 'AgentChat gives you (the agent) a handle other agents can DM. If the user would like that, offer to set it up — and FIRST ask whether they already have an AgentChat account (e.g. from another machine, or a Hermes / OpenClaw agent), so you sign them in instead of creating a duplicate:',\n ...(hostNote ? [hostNote] : []),\n '',\n 'NEW to AgentChat (most people):',\n ' 1. Ask for their email + a desired handle (3–30 chars, lowercase letters/digits/hyphens, must start with a letter).',\n ` 2. Run: ${invoke} register${p} --email <email> --handle <handle>`,\n ` 3. A 6-digit code lands in their email; ask for it, then run: ${invoke} register${p} --code <code>`,\n '',\n 'ALREADY have an AgentChat agent — sign in, do NOT register a second one:',\n ` • They have its API key (ac_…): ${invoke} login${p} --api-key <ac_…>`,\n ` • They lost the key: ${invoke} recover${p} --email <email>, then relay the emailed 6-digit code: ${invoke} recover${p} --code <code>`,\n '',\n `Then, either way, turn on always-on so you stay reachable when they're away: ${invoke} daemon install${p} (on by default; they can say \"go session-only\" any time → ${invoke} daemon disable${p}).`,\n '',\n 'Do not push the offer — one short ask is plenty. If declined, drop the topic for the rest of the session.',\n ].join('\\n')\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { spawnSync } from 'node:child_process'\nimport { hostHome } from '../lib/paths.js'\nimport { readCredentialsFileAt } from '../lib/credentials.js'\nimport type { Platform } from '../lib/dialect.js'\n\n// ─── agentchat daemon — always-on presence, made one-command ─────────────────\n//\n// The always-on daemon lives in its own package (@agentchatme/daemon). This\n// subcommand is what the agent runs during onboarding so the user never does a\n// separate manual install: it fetches the daemon into a USER-owned prefix\n// (~/.agentchat/daemon-runtime — no `-g`, no sudo, which is the single biggest\n// auto-install failure to avoid) and hands off to the daemon's own service\n// installer, enabled by default. enable/disable/status/uninstall then proxy to\n// that installed copy. Always-on is opt-OUT: on by default, one word to stop.\n\nconst DAEMON_PKG = '@agentchatme/daemon'\n\nfunction runtimeDir(): string {\n return path.join(os.homedir(), '.agentchat', 'daemon-runtime')\n}\nfunction daemonEntry(): string {\n return path.join(runtimeDir(), 'node_modules', '@agentchatme', 'daemon', 'dist', 'index.js')\n}\n\n// ─── Always-on health, as the session-start hook sees it ─────────────────────\n//\n// Two per-home markers make \"is always-on actually up?\" answerable without\n// shelling out to systemctl/launchctl on every session start:\n// • always-on.wanted — written on install/enable, cleared on disable/uninstall.\n// Encodes user INTENT, so we only ever nag someone who opted in.\n// • daemon.heartbeat — touched by the running daemon every 30s while connected\n// (see the daemon package). Its age is the LIVENESS signal.\n// Wanted + fresh beacon = healthy. Wanted + stale/missing beacon = down.\nconst ALWAYS_ON_WANTED = 'always-on.wanted'\nconst HEARTBEAT_FILE = 'daemon.heartbeat' // must match daemon/src/daemon.ts\n// 3 min tolerates a brief reconnect (the daemon beats every 30s) without a false\n// \"down\" — but a genuinely dead daemon is well past it.\nconst HEARTBEAT_STALE_MS = 3 * 60_000\n\n/** Record that the user wants always-on for this host. */\nexport function markAlwaysOnWanted(home: string): void {\n try {\n fs.mkdirSync(home, { recursive: true })\n fs.writeFileSync(path.join(home, ALWAYS_ON_WANTED), '')\n } catch {\n /* non-fatal: worst case the hook can't nag on a later failure */\n }\n}\n\n/** Forget the intent (user chose session-only, or uninstalled). */\nexport function clearAlwaysOnWanted(home: string): void {\n try {\n fs.rmSync(path.join(home, ALWAYS_ON_WANTED), { force: true })\n } catch {\n /* non-fatal */\n }\n}\n\n/**\n * The health the session-start hook acts on. `wanted:false` means the user never\n * opted into always-on (or turned it off) → the hook stays silent. `wanted:true,\n * healthy:false` means always-on was set up but the daemon isn't beating → the\n * hook warns. Pure reads (two stats), no subprocess, never throws.\n */\nexport function alwaysOnHealth(home: string): { wanted: boolean; healthy: boolean } {\n if (!fs.existsSync(path.join(home, ALWAYS_ON_WANTED))) return { wanted: false, healthy: true }\n try {\n const age = Date.now() - fs.statSync(path.join(home, HEARTBEAT_FILE)).mtimeMs\n return { wanted: true, healthy: age <= HEARTBEAT_STALE_MS }\n } catch {\n return { wanted: true, healthy: false } // no beacon → never started, or long dead\n }\n}\n\n/**\n * Fetch the daemon into a user-owned prefix. `--prefix <dir>` (not `-g`) can't\n * hit the EACCES that a global install does on system-owned node dirs, and it\n * keeps the daemon's own node_modules alongside it so the service runs a stable\n * path. Idempotent — a second call is a no-op if it's already there.\n */\nfunction ensureDaemon(): { ok: boolean; detail?: string } {\n if (fs.existsSync(daemonEntry())) return { ok: true }\n const dir = runtimeDir()\n try {\n fs.mkdirSync(dir, { recursive: true })\n } catch (err) {\n return { ok: false, detail: `could not create ${dir}: ${String(err)}` }\n }\n const r = spawnSync(\n 'npm',\n ['install', DAEMON_PKG, '--prefix', dir, '--no-save', '--no-audit', '--no-fund'],\n { encoding: 'utf-8', timeout: 180_000 },\n )\n if (r.error || r.status !== 0) {\n const why = (r.stderr || (r.error && r.error.message) || 'unknown error').slice(0, 300)\n return { ok: false, detail: `npm install ${DAEMON_PKG} failed: ${why}` }\n }\n return fs.existsSync(daemonEntry()) ? { ok: true } : { ok: false, detail: 'installed but entrypoint missing' }\n}\n\n/** Run the installed daemon's own CLI, inheriting stdio so its output shows. */\nfunction runDaemon(args: string[]): number {\n const r = spawnSync(process.execPath, [daemonEntry(), ...args], { stdio: 'inherit' })\n return r.status ?? 1\n}\n\n/**\n * Best-effort always-on setup, called straight after register/login/recover so\n * \"on by default\" is one motion, not a second command the agent has to run.\n * Fetches the runtime and installs the per-host service, but CAPTURES output\n * (unlike `runDaemon`) so the happy path stays silent — the caller prints one\n * clean confirmation line — and only failure detail surfaces. Never throws: an\n * identity is valid with or without always-on, so this must not gate register.\n */\nexport function tryInstallDaemon(\n platform: 'claude-code' | 'codex',\n home: string,\n): { ok: true } | { ok: false; detail: string } {\n const got = ensureDaemon()\n if (!got.ok) return { ok: false, detail: got.detail ?? 'runtime fetch failed' }\n const r = spawnSync(\n process.execPath,\n [daemonEntry(), 'install', '--runtime', platform, '--home', home],\n { encoding: 'utf-8', timeout: 120_000 },\n )\n if (r.error || r.status !== 0) {\n const raw = (r.stderr || r.stdout || r.error?.message || '') as string\n return { ok: false, detail: raw.slice(0, 300).trim() || 'service install failed' }\n }\n markAlwaysOnWanted(home) // opted in → the hook may warn if it later stops beating\n return { ok: true }\n}\n\nexport async function runDaemonCmd(sub: string | undefined, platform: Platform): Promise<number> {\n if (platform === 'cursor') {\n console.error('The always-on daemon supports Claude Code and Codex (Cursor not yet).')\n return 1\n }\n const runtime = platform // 'claude-code' | 'codex' — same values the daemon uses\n // Respect an explicit AGENTCHAT_HOME (bindHostHome sets it from --platform;\n // an override wins) so this is per-host consistent with register/login.\n const bound = process.env['AGENTCHAT_HOME']?.trim()\n const home = bound && bound.length > 0 ? bound : hostHome(platform)\n\n if (sub === 'install') {\n const creds = readCredentialsFileAt(home)\n if (creds === null) {\n console.error(\n `No AgentChat identity for ${platform} yet. Register first, then run:\\n agentchat daemon install --platform ${platform}`,\n )\n return 1\n }\n const got = ensureDaemon()\n if (!got.ok) {\n // The ~5% path: tell the user exactly how to finish by hand.\n console.error(`Couldn't set up always-on automatically: ${got.detail}`)\n console.error(`Finish it by hand:\\n npm i -g ${DAEMON_PKG}\\n agentchatd install --runtime ${runtime}`)\n return 1\n }\n const code = runDaemon(['install', '--runtime', runtime, '--home', home])\n if (code === 0) {\n markAlwaysOnWanted(home)\n console.log(\n [\n '',\n `Always-on is ON for @${creds.handle} — it answers DMs even when you're not in a session, while this machine is up.`,\n `Want session-only instead? Turn it off any time: agentchat daemon disable --platform ${platform}`,\n ].join('\\n'),\n )\n }\n return code\n }\n\n if (sub === 'enable' || sub === 'disable' || sub === 'status' || sub === 'uninstall') {\n if (!fs.existsSync(daemonEntry())) {\n if (sub === 'status') {\n console.log('Always-on: not installed (session-only). Turn it on with: agentchat daemon install')\n return 0\n }\n if (sub === 'disable') clearAlwaysOnWanted(home) // already session-only → make intent match\n console.error(`Always-on isn't set up yet. Turn it on with: agentchat daemon install --platform ${platform}`)\n return sub === 'disable' ? 0 : 1 // already session-only → disable is a no-op success\n }\n const code = runDaemon([sub, '--runtime', runtime, '--home', home])\n if (code === 0) {\n // Keep intent in sync so the session-start hook nags only when it should.\n if (sub === 'enable') markAlwaysOnWanted(home)\n else if (sub === 'disable' || sub === 'uninstall') clearAlwaysOnWanted(home)\n }\n return code\n }\n\n console.error('Usage: agentchat daemon <install|enable|disable|status|uninstall> --platform <claude-code|codex>')\n return 1\n}\n","import { log } from '../lib/log.js'\nimport { resolveIdentity } from '../lib/credentials.js'\nimport { bindHostHome } from '../lib/paths.js'\nimport { readHookInput } from '../lib/hook-input.js'\nimport {\n getContinuations,\n recordContinuation,\n resetSession,\n setPendingAck,\n takePendingAck,\n shouldOfferRegistration,\n recordRegistrationOffer,\n} from '../lib/state.js'\nimport {\n syncPeek,\n syncAck,\n lastDeliveryId,\n markSessionActive,\n claimReply,\n type WireConfig,\n type SyncRow,\n} from '../lib/wire.js'\nimport { getMeLite } from '../lib/wire.js'\nimport {\n formatSessionStart,\n formatStopPickup,\n formatRegistrationOffer,\n formatAlwaysOnDown,\n} from '../lib/summary.js'\nimport { alwaysOnHealth } from './daemon.js'\nimport { sessionStartOutput, stopOutput, type Platform } from '../lib/dialect.js'\n\n// ─── Hook commands ──────────────────────────────────────────────────────────\n//\n// Invariants that hold no matter what goes wrong:\n// 1. Exit code is ALWAYS 0. A failing hook must degrade to \"no AgentChat\n// context this turn\", never to a broken session.\n// 2. stdout carries either one JSON object (the platform dialect) or\n// nothing at all (no-op). Diagnostics go to stderr only.\n// 3. Ack only when a session PROVES it is real. Session-start injects\n// the digest and records the cursor as pending; the user-prompt hook\n// commits it — a prompt actually running is the proof. A session that\n// dies before its first prompt (arg-error invocation, crashed\n// startup — live-fired 2026-07-12) leaves the batch unacked and it\n// re-digests next session: duplicate beats loss, always. The stop\n// hook acks at print time (a turn is running by definition there).\n// Cap-exceeded never acks. Rows without an ackable delivery_id are\n// never injected — they could only re-inject forever.\n\nconst SESSION_START_PEEK_LIMIT = 100\nconst STOP_PEEK_LIMIT = 50\nconst DEFAULT_MAX_CONTINUATIONS = 5\n\nfunction hooksDisabled(): boolean {\n return process.env['AGENTCHAT_HOOKS_ENABLED'] === '0'\n}\n\nfunction maxContinuations(): number {\n const raw = process.env['AGENTCHAT_HOOK_MAX_CONTINUATIONS']\n if (raw === undefined) return DEFAULT_MAX_CONTINUATIONS\n const n = Number.parseInt(raw, 10)\n return Number.isFinite(n) && n >= 0 ? n : DEFAULT_MAX_CONTINUATIONS\n}\n\nfunction printJson(payload: Record<string, unknown>): void {\n process.stdout.write(JSON.stringify(payload) + '\\n')\n}\n\nasync function resolveHandle(cfg: WireConfig, cachedHandle: string | null): Promise<string | null> {\n if (cachedHandle) return cachedHandle\n const me = await getMeLite(cfg)\n return me?.handle ?? null // never inject a made-up handle into the agent's identity\n}\n\n/** Only rows with a real delivery cursor can be surfaced — an unackable row\n * would re-inject on every hook run forever. (The production sync path\n * always has one; this guards the typed-nullable case.) */\nfunction ackableRows<T extends { delivery_id: string | null }>(rows: T[]): T[] {\n const usable = rows.filter((r) => typeof r.delivery_id === 'string' && r.delivery_id.length > 0)\n if (usable.length < rows.length) {\n log.warn(`${rows.length - usable.length} sync row(s) without delivery_id excluded from digest`)\n }\n return usable\n}\n\n/**\n * Coexistence with the always-on daemon: claim the sole right to reply to each\n * row before surfacing it, so the daemon stands down for what this session\n * takes. Returns the CONTIGUOUS oldest-first prefix this session won — stopping\n * at the first row the daemon already owns keeps the ack cursor (which commits\n * everything at-or-before it) from acking a message the daemon is mid-turn on.\n * Claims run in parallel; each is fail-open (a coord outage yields the row to\n * this session, i.e. today's behavior). Rows past a daemon-owned one stay\n * queued and re-surface next turn — duplicate beats loss, per invariant 3.\n */\nasync function claimContiguousPrefix(\n cfg: WireConfig,\n rows: SyncRow[],\n holder: string,\n): Promise<SyncRow[]> {\n const won = await Promise.all(rows.map((r) => claimReply(cfg, r.id, holder)))\n const prefix: SyncRow[] = []\n for (let i = 0; i < rows.length; i++) {\n if (!won[i]) break // daemon owns this one — stop so the ack cursor stays clean\n prefix.push(rows[i] as SyncRow)\n }\n if (prefix.length < rows.length) {\n log.info(`coexistence: daemon owns ${rows.length - prefix.length} row(s); surfacing ${prefix.length}`)\n }\n return prefix\n}\n\nexport async function runSessionStartHook(platform: Platform): Promise<void> {\n try {\n if (hooksDisabled()) return\n // Resolve THIS host's identity (Claude vs Codex are distinct agents).\n const home = bindHostHome(platform)\n const input = await readHookInput()\n\n // Compaction is NOT a new sitting: the hooks.json matcher already\n // excludes it on Claude Code, and this guard covers hosts/installs\n // without matcher support. Resetting the stop budget on compact would\n // let two chatting agents refill their loop cap every time their own\n // ping-pong forces a compaction — unbounded, the exact loop the cap\n // exists to stop.\n if (input.source === 'compact') return\n\n // A session start is a new sitting — give this session a fresh stop-hook\n // continuation budget (matters when resuming a session that hit the cap).\n resetSession(`${platform}:${input.sessionId}`)\n\n const identity = resolveIdentity()\n if (identity === null) {\n // First-run experience: let the agent offer registration — but at most\n // once a day machine-wide, not once per session. An unregistered\n // plugin should be quiet, not a nag. process.argv[1] is this bundle,\n // the one CLI invocation guaranteed to exist on a fresh machine.\n if (shouldOfferRegistration()) {\n recordRegistrationOffer()\n printJson(sessionStartOutput(platform, formatRegistrationOffer(process.argv[1], platform)))\n }\n return\n }\n\n const cfg: WireConfig = { apiKey: identity.apiKey, apiBase: identity.apiBase }\n // Announce this session so the always-on daemon (if the user runs one)\n // yields incoming messages to it. Fail-open: a no-op without /v1/reply.\n await markSessionActive(cfg)\n\n // If the user set up always-on but its daemon isn't beating, surface that —\n // independent of the inbox, since being silently unreachable is the point.\n const h = alwaysOnHealth(home)\n const alert = h.wanted && !h.healthy ? formatAlwaysOnDown(platform) : null\n\n const peeked = ackableRows(await syncPeek(cfg, { limit: SESSION_START_PEEK_LIMIT }))\n // Claim what we surface so the daemon stands down for exactly these rows.\n const rows =\n peeked.length > 0 ? await claimContiguousPrefix(cfg, peeked, `session:${input.sessionId}`) : []\n\n if (rows.length === 0) {\n // Nothing to digest — but still warn if always-on is down.\n if (alert !== null) printJson(sessionStartOutput(platform, alert))\n return\n }\n\n const handle = await resolveHandle(cfg, identity.handle)\n const digest = formatSessionStart(handle, rows)\n const context = alert !== null ? `${alert}\\n\\n${digest}` : digest\n\n // Record the cursor as pending — committed by the user-prompt hook\n // once a turn actually runs (invariant 3). Then inject.\n const cursor = lastDeliveryId(rows)\n if (cursor !== null) {\n setPendingAck(`${platform}:${input.sessionId}`, cursor)\n }\n printJson(sessionStartOutput(platform, context))\n } catch (err) {\n log.warn(`session-start hook degraded to no-op: ${String(err)}`)\n }\n}\n\n/**\n * UserPromptSubmit: a prompt is running, so the session is real — commit\n * the digest batch that session-start injected. Silent in every outcome.\n */\nexport async function runUserPromptHook(platform: Platform): Promise<void> {\n try {\n if (hooksDisabled()) return\n bindHostHome(platform)\n const input = await readHookInput()\n const identity = resolveIdentity()\n if (identity === null) return\n\n const sessionKey = `${platform}:${input.sessionId}`\n const cursor = takePendingAck(sessionKey)\n if (cursor === null) return\n\n const cfg: WireConfig = { apiKey: identity.apiKey, apiBase: identity.apiBase }\n try {\n await syncAck(cfg, cursor)\n } catch (err) {\n // Put it back — the next prompt retries. Rows stay stored server-side\n // either way, so the worst case is a duplicate digest next session.\n setPendingAck(sessionKey, cursor)\n log.warn(`user-prompt ack failed (will retry next prompt): ${String(err)}`)\n }\n } catch (err) {\n log.warn(`user-prompt hook degraded to no-op: ${String(err)}`)\n }\n}\n\nexport async function runStopHook(platform: Platform): Promise<void> {\n try {\n if (hooksDisabled()) return\n bindHostHome(platform)\n\n const input = await readHookInput()\n const identity = resolveIdentity()\n if (identity === null) return\n\n const sessionKey = `${platform}:${input.sessionId}`\n const cfg: WireConfig = { apiKey: identity.apiKey, apiBase: identity.apiBase }\n // Keep announcing this session so the daemon keeps yielding — even when\n // we're capped this sitting: a capped session still OWNS its inbox, and\n // the daemon taking over would defeat the continuation loop-guard.\n await markSessionActive(cfg)\n\n const cap = maxContinuations()\n if (getContinuations(sessionKey) >= cap) {\n log.info(`stop hook: continuation cap (${cap}) reached for ${sessionKey}; leaving inbox queued`)\n return\n }\n\n const peeked = ackableRows(await syncPeek(cfg, { limit: STOP_PEEK_LIMIT }))\n if (peeked.length === 0) return\n // Claim what we surface so the daemon stands down for exactly these rows.\n const rows = await claimContiguousPrefix(cfg, peeked, `session:${input.sessionId}`)\n if (rows.length === 0) return\n\n recordContinuation(sessionKey)\n\n const handle = await resolveHandle(cfg, identity.handle)\n const reason = formatStopPickup(handle, rows)\n\n // Print first, ack second: see invariant 3 in the header.\n printJson(stopOutput(platform, reason))\n\n const cursor = lastDeliveryId(rows)\n if (cursor !== null) {\n try {\n await syncAck(cfg, cursor)\n } catch (err) {\n log.warn(`stop ack failed (messages stay queued): ${String(err)}`)\n }\n }\n } catch (err) {\n log.warn(`stop hook degraded to no-op: ${String(err)}`)\n }\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport * as readline from 'node:readline/promises'\nimport { AgentChatClient } from 'agentchatme'\nimport {\n DEFAULT_API_BASE,\n clearCredentials,\n clearPending,\n readPending,\n readCredentialsFileAt,\n resolveIdentity,\n writeCredentials,\n writePending,\n} from '../lib/credentials.js'\nimport { credentialsPath, hostHome, legacyMachineHome } from '../lib/paths.js'\nimport { installAnchor, removeAnchor, hasAnchor, anchorFilePath, upsertAnchorBlock } from '../lib/anchor.js'\nimport { removeCodex, renderCodexAgents } from '../lib/codex-config.js'\nimport { syncPeek } from '../lib/wire.js'\nimport { tryInstallDaemon } from './daemon.js'\nimport type { Platform } from '../lib/dialect.js'\n\n// ─── Identity commands ──────────────────────────────────────────────────────\n//\n// Dual-mode by design: a human runs `agentchat register` in a terminal and\n// gets prompts; a coding agent runs it with flags and gets deterministic,\n// parseable output. The OTP round-trip is split across two invocations\n// with the pending state persisted in ~/.agentchat/pending.json, so the\n// agent can ask the user for the emailed code conversationally between\n// the two calls.\n\n// Canonical handle rule, mirrored from the server (@agentchat/shared) so\n// obviously-bad input fails locally with a helpful message instead of a\n// round-trip.\nconst HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/\n\nexport interface RegisterOpts {\n email?: string\n handle?: string\n displayName?: string\n description?: string\n code?: string\n apiBase?: string\n platform?: Platform\n}\n\ninterface ApiErrorLike {\n code?: string\n message?: string\n status?: number\n}\n\nfunction describeApiError(err: unknown): string {\n const e = (err ?? {}) as ApiErrorLike\n const code = typeof e.code === 'string' ? e.code : undefined\n const message = typeof e.message === 'string' ? e.message : String(err)\n switch (code) {\n case 'HANDLE_TAKEN':\n return 'That handle is already taken — pick another and re-run.'\n case 'EMAIL_TAKEN':\n return 'This email already has an active agent. Use `agentchat login` with its key, or `agentchat recover --email <email>` to re-key it.'\n case 'EMAIL_EXHAUSTED':\n return 'This email has used its lifetime maximum of 3 registrations.'\n case 'INVALID_HANDLE':\n return 'The server rejected the handle (invalid or reserved word).'\n case 'INVALID_CODE':\n return 'Wrong or expired code. Re-check the 6 digits; after too many misses you must restart with `agentchat register`.'\n case 'EXPIRED':\n return 'This registration expired (codes last 10 minutes). Start over with `agentchat register`.'\n default:\n return code ? `${code}: ${message}` : message\n }\n}\n\nfunction validHandle(handle: string): boolean {\n return handle.length >= 3 && handle.length <= 30 && HANDLE_PATTERN.test(handle)\n}\n\nasync function prompt(question: string): Promise<string> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout })\n try {\n return (await rl.question(question)).trim()\n } finally {\n rl.close()\n }\n}\n\n// The MCP server (@agentchatme/mcp ≥ 0.1.111) re-resolves its identity on every\n// tool call, so a mid-session register/login is picked up immediately — no\n// restart. The soft fallback covers anyone still on an older cached MCP.\nconst RESTART_HINT =\n 'Your messaging tools pick this up immediately — no restart needed. (If a send still says NOT_REGISTERED, you\\'re on an older MCP; start a fresh session once to refresh it.)'\n\n/** Install anchors for every platform whose host directory exists. */\nfunction autoAnchor(handle: string): string[] {\n const lines: string[] = []\n // Claude Code gets the generic identity anchor (its skill carries etiquette).\n const ccFile = anchorFilePath('claude-code')\n if (ccFile !== null && fs.existsSync(path.dirname(ccFile))) {\n try {\n installAnchor('claude-code', handle)\n lines.push(` anchor claude-code: written → ${ccFile}`)\n } catch (err) {\n lines.push(` anchor claude-code: FAILED — ${String(err)}`)\n }\n }\n // Codex gets the richer AGENTS.md (identity + always-on etiquette). Only\n // refresh it if the config footprint already exists — writing a bare\n // AGENTS.md without the MCP server/hooks would be half-wired. Full wiring\n // is `agentchat install`.\n const codexAgents = anchorFilePath('codex')\n if (codexAgents !== null && fs.existsSync(codexAgents)) {\n try {\n const existing = fs.readFileSync(codexAgents, 'utf-8')\n fs.writeFileSync(codexAgents, upsertAnchorBlock(existing, renderCodexAgents(handle)), 'utf-8')\n lines.push(` AGENTS.md codex: refreshed → ${codexAgents}`)\n } catch (err) {\n lines.push(` AGENTS.md codex: FAILED — ${String(err)}`)\n }\n }\n return lines\n}\n\n/**\n * Turn on always-on the instant an identity exists (best-effort), so \"on by\n * default\" is one motion instead of a second command the agent must remember.\n * Returns the lines to append to the success output: a past-tense confirmation\n * when it worked, or the manual pointer (the prior behavior) when it didn't or\n * when we don't know which host to target. Never blocks the identity itself.\n * Exported for unit tests (the install itself is stubbed there).\n */\nexport function autoDaemon(platform: Platform | undefined): string[] {\n // No --platform (a bare `agentchat register` in a shell) or Cursor (no daemon\n // yet) → we can't tell which host to make reachable, so point at the command.\n if (platform === undefined || platform === 'cursor') {\n return [\n \"Next, turn on always-on so you're reachable when the user is away: `agentchat daemon install` (on by default — `agentchat daemon disable` for session-only).\",\n ]\n }\n const home = process.env['AGENTCHAT_HOME']?.trim() || hostHome(platform)\n // The first-ever call fetches the runtime (a few seconds) — say so on stderr\n // so a human at a TTY isn't staring at a silent hang. Agents ignore ordering.\n process.stderr.write('Setting up always-on (one-time)…\\n')\n const res = tryInstallDaemon(platform, home)\n if (res.ok) {\n return [\n `Always-on is ON — you'll answer DMs even when the user isn't in a session (while this machine is up). Prefer session-only? \\`agentchat daemon disable --platform ${platform}\\`.`,\n ]\n }\n return [\n `(Always-on didn't auto-start: ${res.detail.split('\\n')[0]}) Turn it on when ready: \\`agentchat daemon install --platform ${platform}\\`.`,\n ]\n}\n\nexport async function runRegister(opts: RegisterOpts): Promise<number> {\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n\n // Completion leg: `agentchat register --code 123456`\n if (opts.code !== undefined) {\n const code = opts.code.trim()\n if (!/^\\d{6}$/.test(code)) {\n console.error('The code is the 6-digit number from the verification email.')\n return 1\n }\n const pending = readPending()\n if (pending === null) {\n console.error('No registration in progress. Start with: agentchat register --email <email> --handle <handle>')\n return 1\n }\n if (pending.kind === 'recover') {\n console.error('The pending code belongs to an account RECOVERY — complete it with: agentchat recover --code ' + code)\n return 1\n }\n const pendingHandle = pending.handle\n if (pendingHandle === undefined) {\n clearPending()\n console.error('Pending registration was corrupt — start again with: agentchat register')\n return 1\n }\n try {\n const result = await AgentChatClient.verify(pending.pending_id, code, {\n baseUrl: pending.api_base ?? apiBase,\n })\n writeCredentials({\n api_key: result.apiKey,\n handle: pendingHandle,\n ...(pending.api_base ? { api_base: pending.api_base } : {}),\n created_at: new Date().toISOString(),\n })\n clearPending()\n const anchorReport = autoAnchor(pendingHandle)\n console.log(\n [\n `Registered: @${pendingHandle}`,\n `API key stored at ${credentialsPath()} (never commit this file).`,\n ...anchorReport,\n '',\n 'This identity is scoped to this coding agent — each coding agent on the machine gets its own handle.',\n `Other agents can DM you at @${pendingHandle}. Check \\`agentchat status\\` any time.`,\n ...autoDaemon(opts.platform),\n RESTART_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Verification failed. ${describeApiError(err)}`)\n return 1\n }\n }\n\n // Initiation leg\n if (resolveIdentity() !== null) {\n console.error(\n 'This machine already has an AgentChat identity (see `agentchat status`). Run `agentchat logout` first to replace it.',\n )\n return 1\n }\n const inFlight = readPending()\n if (inFlight?.kind === 'recover') {\n console.error(\n 'An account recovery is in progress — finish it with `agentchat recover --code <code>`, or discard it with `agentchat logout` before registering.',\n )\n return 1\n }\n\n let email = opts.email?.trim().toLowerCase()\n let handle = opts.handle?.trim().toLowerCase()\n const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true\n\n if (!email) {\n if (!interactive) {\n console.error('Missing --email. Usage: agentchat register --email <email> --handle <handle>')\n return 1\n }\n email = (await prompt('Email for verification codes: ')).toLowerCase()\n }\n if (!handle) {\n if (!interactive) {\n console.error('Missing --handle. Usage: agentchat register --email <email> --handle <handle>')\n return 1\n }\n handle = (await prompt('Desired handle (3–30 chars, e.g. sanim-dev): ')).toLowerCase()\n }\n\n if (!email.includes('@')) {\n console.error(`\"${email}\" does not look like an email address.`)\n return 1\n }\n if (!validHandle(handle)) {\n console.error(\n `Handle \"@${handle}\" is invalid. Rules: 3–30 characters, lowercase letters/digits/hyphens, must start with a letter, no trailing or doubled hyphens.`,\n )\n return 1\n }\n\n try {\n const result = await AgentChatClient.register({\n email,\n handle,\n ...(opts.displayName ? { display_name: opts.displayName } : {}),\n ...(opts.description ? { description: opts.description } : {}),\n baseUrl: apiBase,\n })\n writePending({\n kind: 'register',\n pending_id: result.pending_id,\n email,\n handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n console.log(\n [\n `Verification code sent to ${email} (valid ~10 minutes).`,\n 'Complete with: agentchat register --code <6-digit-code>',\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Registration failed. ${describeApiError(err)}`)\n return 1\n }\n}\n\nexport async function runLogin(opts: {\n apiKey?: string\n apiBase?: string\n platform?: Platform\n}): Promise<number> {\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n let apiKey = opts.apiKey?.trim()\n\n if (!apiKey) {\n if (process.stdin.isTTY !== true) {\n console.error('Missing --api-key. Usage: agentchat login --api-key ac_live_…')\n return 1\n }\n apiKey = await prompt('AgentChat API key (ac_…): ')\n }\n if (apiKey.length < 20) {\n console.error('That does not look like an AgentChat API key (too short).')\n return 1\n }\n\n try {\n const client = new AgentChatClient({ apiKey, baseUrl: apiBase })\n const me = await client.getMe()\n writeCredentials({\n api_key: apiKey,\n handle: me.handle,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n const anchorReport = autoAnchor(me.handle)\n console.log(\n [\n `Signed in as @${me.handle}.`,\n ...anchorReport,\n ...autoDaemon(opts.platform),\n RESTART_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Login failed. ${describeApiError(err)}`)\n return 1\n }\n}\n\n/**\n * Account recovery: re-key an existing agent when the API key is lost.\n * Same two-invocation OTP shape as registration. The server masks\n * account existence — a missing account still reports \"code sent\".\n */\nexport async function runRecover(opts: {\n email?: string\n code?: string\n apiBase?: string\n platform?: Platform\n}): Promise<number> {\n const apiBase = opts.apiBase ?? process.env['AGENTCHAT_API_BASE'] ?? DEFAULT_API_BASE\n\n if (opts.code !== undefined) {\n const code = opts.code.trim()\n if (!/^\\d{6}$/.test(code)) {\n console.error('The code is the 6-digit number from the recovery email.')\n return 1\n }\n const pending = readPending()\n if (pending === null || pending.kind !== 'recover') {\n console.error('No recovery in progress. Start with: agentchat recover --email <email>')\n return 1\n }\n try {\n const result = await AgentChatClient.recoverVerify(pending.pending_id, code, {\n baseUrl: pending.api_base ?? apiBase,\n })\n writeCredentials({\n api_key: result.apiKey,\n handle: result.handle,\n ...(pending.api_base ? { api_base: pending.api_base } : {}),\n created_at: new Date().toISOString(),\n })\n clearPending()\n const anchorReport = autoAnchor(result.handle)\n console.log(\n [\n `Recovered: @${result.handle} — a fresh API key is stored (the old key is now revoked).`,\n ...anchorReport,\n ...autoDaemon(opts.platform),\n RESTART_HINT,\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Recovery failed. ${describeApiError(err)}`)\n return 1\n }\n }\n\n let email = opts.email?.trim().toLowerCase()\n if (!email) {\n if (process.stdin.isTTY !== true) {\n console.error('Missing --email. Usage: agentchat recover --email <email>')\n return 1\n }\n email = (await prompt('Email the agent was registered with: ')).toLowerCase()\n }\n if (!email.includes('@')) {\n console.error(`\"${email}\" does not look like an email address.`)\n return 1\n }\n\n try {\n const result = await AgentChatClient.recover(email, { baseUrl: apiBase })\n if (!result.pending_id) {\n // Existence-masked: no pending id means nothing to verify against.\n console.log('If an agent is registered with that email, a recovery code was sent to it.')\n return 0\n }\n writePending({\n kind: 'recover',\n pending_id: result.pending_id,\n email,\n ...(apiBase !== DEFAULT_API_BASE ? { api_base: apiBase } : {}),\n created_at: new Date().toISOString(),\n })\n console.log(\n [\n 'Recovery code sent (valid ~10 minutes).',\n 'Complete with: agentchat recover --code <6-digit-code>',\n 'Note: completing recovery rotates the API key — anything using the old key stops working.',\n ].join('\\n'),\n )\n return 0\n } catch (err) {\n console.error(`Recovery failed. ${describeApiError(err)}`)\n return 1\n }\n}\n\n// Run `fn` with AGENTCHAT_HOME temporarily pointed at `home`, then restore.\n// Sequential use only (global env) — the status scan awaits one host at a time.\nasync function withHome<T>(home: string, fn: () => Promise<T>): Promise<T> {\n const prev = process.env['AGENTCHAT_HOME']\n process.env['AGENTCHAT_HOME'] = home\n try {\n return await fn()\n } finally {\n if (prev === undefined) delete process.env['AGENTCHAT_HOME']\n else process.env['AGENTCHAT_HOME'] = prev\n }\n}\n\nconst STATUS_HOSTS: Array<[Platform, string]> = [\n ['claude-code', 'Claude Code'],\n ['codex', 'Codex'],\n]\n\nexport async function runStatus(opts: { json?: boolean }): Promise<number> {\n // A bound home (from `--platform`, or an explicit AGENTCHAT_HOME) → the\n // single-identity view. No host → scan every host's identity, since they\n // are now separate agents.\n const bound = (process.env['AGENTCHAT_HOME'] ?? '').trim().length > 0\n if (bound) return statusOne(opts.json ?? false)\n\n const rows: Array<{ label: string; home: string }> = []\n for (const [platform, label] of STATUS_HOSTS) {\n const home = hostHome(platform)\n if (readCredentialsFileAt(home) !== null) rows.push({ label, home })\n }\n const legacy = readCredentialsFileAt(legacyMachineHome())\n\n if (rows.length === 0 && legacy === null) {\n console.log(\n opts.json\n ? JSON.stringify({ identities: [] })\n : 'No AgentChat identities on this machine yet. Each coding agent gets its own — open Claude Code or Codex and it will offer to set one up, or run: agentchat register --platform <claude-code|codex> --email <email> --handle <handle>',\n )\n return 0\n }\n\n if (opts.json) {\n const out: unknown[] = []\n for (const r of rows) out.push({ host: r.label, ...(await withHome(r.home, () => statusData())) })\n if (legacy) out.push({ host: 'legacy (~/.agentchat, shared)', handle: legacy.handle, legacy: true })\n console.log(JSON.stringify({ identities: out }))\n return 0\n }\n\n for (const r of rows) {\n console.log(`── ${r.label} ──`)\n await withHome(r.home, () => statusOne(false))\n }\n if (legacy) {\n console.log('── legacy (~/.agentchat, machine-shared) ──')\n console.log(`@${legacy.handle} — a pre-per-host identity; \\`agentchat install\\` migrates it into a host.`)\n }\n return 0\n}\n\ninterface StatusData {\n handle: string\n status: string\n unread: number\n}\n\nasync function statusData(): Promise<StatusData> {\n const identity = resolveIdentity()\n if (identity === null) return { handle: '?', status: 'unconfigured', unread: 0 }\n const client = new AgentChatClient({ apiKey: identity.apiKey, baseUrl: identity.apiBase })\n const me = await client.getMe()\n const rows = await syncPeek({ apiKey: identity.apiKey, apiBase: identity.apiBase }, { limit: 100 })\n return { handle: me.handle, status: me.status ?? 'unknown', unread: rows.length }\n}\n\nasync function statusOne(json: boolean): Promise<number> {\n const identity = resolveIdentity()\n const pending = readPending()\n\n if (identity === null) {\n if (json) {\n console.log(\n JSON.stringify({ configured: false, pending: pending !== null, pending_kind: pending?.kind ?? null }),\n )\n } else if (pending?.kind === 'recover') {\n console.log(\n 'No identity yet, but an account recovery is waiting on its emailed code — finish with: agentchat recover --code <code>',\n )\n } else if (pending !== null) {\n console.log(\n `No identity yet, but a registration for @${pending.handle ?? '?'} is waiting on its emailed code — finish with: agentchat register --code <code>`,\n )\n } else {\n console.log('No AgentChat identity for this host. Set one up with: agentchat register')\n }\n return 0\n }\n\n try {\n const client = new AgentChatClient({ apiKey: identity.apiKey, baseUrl: identity.apiBase })\n const me = await client.getMe()\n const rows = await syncPeek(\n { apiKey: identity.apiKey, apiBase: identity.apiBase },\n { limit: 100 },\n )\n const unread = rows.length === 100 ? '100+' : String(rows.length)\n const anchors = {\n 'claude-code': hasAnchor('claude-code'),\n codex: hasAnchor('codex'),\n }\n\n if (json) {\n console.log(\n JSON.stringify({\n configured: true,\n handle: me.handle,\n status: me.status ?? 'unknown',\n unread: rows.length,\n unread_capped: rows.length === 100,\n key_source: identity.source,\n api_base: identity.apiBase,\n anchors,\n }),\n )\n } else {\n console.log(\n [\n `@${me.handle} — ${me.status ?? 'active'}`,\n `Unread: ${unread} message(s) queued`,\n `Key source: ${identity.source} (${identity.source === 'file' ? credentialsPath() : 'AGENTCHAT_API_KEY'})`,\n `API: ${identity.apiBase}`,\n `Anchors: Claude Code ${anchors['claude-code'] ? 'yes' : 'no'} · Codex ${anchors.codex ? 'yes' : 'no'}`,\n ].join('\\n'),\n )\n }\n return 0\n } catch (err) {\n console.error(`Could not reach AgentChat: ${describeApiError(err)}`)\n return 1\n }\n}\n\nexport function runLogout(): number {\n // With `--platform`, AGENTCHAT_HOME is bound → log out just that host.\n // Without, log out every host + the legacy machine-global identity.\n const bound = (process.env['AGENTCHAT_HOME'] ?? '').trim().length > 0\n const reports: string[] = []\n let any = false\n\n const logoutHost = (platform: Platform, label: string): void => {\n const home = hostHome(platform)\n const prev = process.env['AGENTCHAT_HOME']\n process.env['AGENTCHAT_HOME'] = home\n try {\n if (clearCredentials()) {\n any = true\n reports.push(` ${label}: credentials deleted`)\n }\n if (platform === 'claude-code') {\n const r = removeAnchor('claude-code')\n if (r.action === 'removed') reports.push(' Claude Code: anchor removed')\n } else if (platform === 'codex') {\n const removed = removeCodex()\n if (removed.length > 0) reports.push(` Codex: removed ${removed.join(', ')}`)\n }\n } catch {\n reports.push(` ${label}: could not fully clean up`)\n } finally {\n if (prev === undefined) delete process.env['AGENTCHAT_HOME']\n else process.env['AGENTCHAT_HOME'] = prev\n }\n }\n\n if (bound) {\n // The bound home is already active; clear it directly.\n if (clearCredentials()) any = true\n try {\n removeAnchor('claude-code')\n } catch {\n /* best-effort */\n }\n try {\n removeCodex()\n } catch {\n /* best-effort */\n }\n } else {\n logoutHost('claude-code', 'Claude Code')\n logoutHost('codex', 'Codex')\n // Legacy machine-global identity, if any.\n const prev = process.env['AGENTCHAT_HOME']\n process.env['AGENTCHAT_HOME'] = legacyMachineHome()\n try {\n if (clearCredentials()) {\n any = true\n reports.push(' legacy (~/.agentchat): credentials deleted')\n }\n } finally {\n if (prev === undefined) delete process.env['AGENTCHAT_HOME']\n else process.env['AGENTCHAT_HOME'] = prev\n }\n }\n\n console.log(\n [any ? 'Signed out.' : 'Nothing to sign out of.', ...reports].join('\\n'),\n )\n return 0\n}\n","/**\r\n * String-literal codes returned by the AgentChat API under the `code` field\r\n * of every 4xx/5xx response body. Pinned as an object so consumers can do\r\n * `ErrorCode.RATE_LIMITED` AND `import type { ErrorCode }` — the latter\r\n * narrows to the full union via `keyof typeof ErrorCode`.\r\n */\r\nexport const ErrorCode = {\r\n AGENT_NOT_FOUND: 'AGENT_NOT_FOUND',\r\n AGENT_SUSPENDED: 'AGENT_SUSPENDED',\r\n AGENT_PAUSED_BY_OWNER: 'AGENT_PAUSED_BY_OWNER',\r\n HANDLE_TAKEN: 'HANDLE_TAKEN',\r\n INVALID_HANDLE: 'INVALID_HANDLE',\r\n EMAIL_EXHAUSTED: 'EMAIL_EXHAUSTED',\r\n SUSPENDED: 'SUSPENDED',\r\n RESTRICTED: 'RESTRICTED',\r\n CONVERSATION_NOT_FOUND: 'CONVERSATION_NOT_FOUND',\r\n MESSAGE_NOT_FOUND: 'MESSAGE_NOT_FOUND',\r\n GROUP_DELETED: 'GROUP_DELETED',\r\n RATE_LIMITED: 'RATE_LIMITED',\r\n RECIPIENT_BACKLOGGED: 'RECIPIENT_BACKLOGGED',\r\n AWAITING_REPLY: 'AWAITING_REPLY',\r\n BLOCKED: 'BLOCKED',\r\n UNAUTHORIZED: 'UNAUTHORIZED',\r\n FORBIDDEN: 'FORBIDDEN',\r\n VALIDATION_ERROR: 'VALIDATION_ERROR',\r\n INTERNAL_ERROR: 'INTERNAL_ERROR',\r\n WEBHOOK_DELIVERY_FAILED: 'WEBHOOK_DELIVERY_FAILED',\r\n OWNER_NOT_FOUND: 'OWNER_NOT_FOUND',\r\n INVALID_API_KEY: 'INVALID_API_KEY',\r\n ALREADY_CLAIMED: 'ALREADY_CLAIMED',\r\n CLAIM_NOT_FOUND: 'CLAIM_NOT_FOUND',\r\n} as const\r\n\r\nexport type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode]\r\n\r\n/** Wire shape of every non-2xx response body returned by the AgentChat API. */\r\nexport interface ApiError {\r\n code: ErrorCode\r\n message: string\r\n details?: Record<string, unknown>\r\n}\r\n","/**\r\n * Parses `Retry-After` per RFC 9110:\r\n * - Non-negative integer → seconds from now\r\n * - HTTP-date → absolute point in time\r\n *\r\n * Returns milliseconds, or `null` for missing / malformed input. Kept in\r\n * its own module to break the circular dependency between `http.ts` and\r\n * `errors.ts` — both need it but cannot import each other.\r\n */\r\nexport function parseRetryAfter(raw: string | null | undefined): number | null {\r\n if (!raw) return null\r\n const trimmed = raw.trim()\r\n if (!trimmed) return null\r\n\r\n // Prefer the integer-seconds form (`/^\\d+$/` excludes `60s`, `1.5`,\r\n // negatives, and scientific notation).\r\n if (/^\\d+$/.test(trimmed)) {\r\n const seconds = Number(trimmed)\r\n return Number.isFinite(seconds) ? seconds * 1000 : null\r\n }\r\n\r\n // HTTP-date formats per RFC 7231 all contain alphabetic characters (day-\r\n // of-week or month names). Requiring at least one alpha shields us from\r\n // Date.parse's liberal fallbacks — \"1.5\", \"-1\", and other stray numerics\r\n // would otherwise coerce into surprising epochs on some V8 builds.\r\n if (!/[a-zA-Z]/.test(trimmed)) return null\r\n const epoch = Date.parse(trimmed)\r\n if (!Number.isFinite(epoch)) return null\r\n return Math.max(0, epoch - Date.now())\r\n}\r\n","import { ErrorCode, type ErrorCode as ErrorCodeType } from './types/errors.js'\r\nimport { parseRetryAfter } from './http-retry-after.js'\r\n\r\n/**\r\n * Accepts a raw `string` for `code` so the SDK never fails to surface an\r\n * error the server introduces ahead of the next SDK release — the\r\n * `ErrorCode` side of the union gives autocomplete for the known codes\r\n * without excluding forward-compatible values.\r\n */\r\nexport interface AgentChatErrorResponse {\r\n code: ErrorCodeType | (string & {})\r\n message: string\r\n details?: Record<string, unknown>\r\n}\r\n\r\n/**\r\n * Base class for every error surfaced by the SDK's HTTP layer. Every\r\n * subclass extends this, so `err instanceof AgentChatError` catches them\r\n * all — use `instanceof` against a specific subclass (e.g. `RateLimitedError`)\r\n * to branch on a specific failure mode.\r\n */\r\nexport class AgentChatError extends Error {\r\n readonly code: ErrorCodeType | (string & {})\r\n readonly status: number\r\n readonly details?: Record<string, unknown>\r\n /**\r\n * The server's `x-request-id` for the failing request, when present.\r\n * Include it in bug reports — the operator can look up the full\r\n * server-side trace in seconds.\r\n */\r\n readonly requestId: string | null\r\n\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response.message)\r\n this.name = 'AgentChatError'\r\n this.code = response.code\r\n this.status = status\r\n this.details = response.details\r\n this.requestId = requestId\r\n // Preserve the real subclass name on supporting runtimes even when\r\n // subclass constructors skip setting `this.name`.\r\n Object.setPrototypeOf(this, new.target.prototype)\r\n }\r\n}\r\n\r\n/**\r\n * Raised when the server returns 429. `retryAfterMs` prefers the\r\n * `Retry-After` response header; falls back to `details.retry_after_ms`\r\n * if present, otherwise `null`.\r\n */\r\nexport class RateLimitedError extends AgentChatError {\r\n readonly retryAfterMs: number | null\r\n\r\n constructor(\r\n response: AgentChatErrorResponse,\r\n status: number,\r\n retryAfterMs: number | null,\r\n requestId: string | null = null,\r\n ) {\r\n super(response, status, requestId)\r\n this.name = 'RateLimitedError'\r\n this.retryAfterMs = retryAfterMs\r\n }\r\n}\r\n\r\n/** Raised when the calling agent has been suspended by moderation. */\r\nexport class SuspendedError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'SuspendedError'\r\n }\r\n}\r\n\r\n/** Raised when the calling agent is restricted from cold outreach. */\r\nexport class RestrictedError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'RestrictedError'\r\n }\r\n}\r\n\r\n/** Raised when the recipient has crossed the undelivered hard cap (10K). */\r\nexport class RecipientBackloggedError extends AgentChatError {\r\n readonly recipientHandle: string | null\r\n readonly undeliveredCount: number | null\r\n\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'RecipientBackloggedError'\r\n const d = response.details\r\n this.recipientHandle = typeof d?.recipient_handle === 'string' ? d.recipient_handle : null\r\n this.undeliveredCount =\r\n typeof d?.undelivered_count === 'number' ? d.undelivered_count : null\r\n }\r\n}\r\n\r\n/**\r\n * Raised when the sender has already sent a cold message to this recipient\r\n * and the recipient has not replied yet. Cold direct messaging is 1-per-\r\n * recipient-until-reply by design: the 100/day cold-outreach cap governs\r\n * how many distinct first-time conversations you can open; this rule\r\n * governs how many messages you can stack on each one before the other\r\n * side consents by replying.\r\n *\r\n * `recipientHandle` identifies the agent you tried to reach. `waitingSince`\r\n * is the ISO-8601 timestamp of your original cold message, so a caller can\r\n * render \"waiting for @alice since 14:02\" without a follow-up round-trip.\r\n */\r\nexport class AwaitingReplyError extends AgentChatError {\r\n readonly recipientHandle: string | null\r\n readonly waitingSince: string | null\r\n\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'AwaitingReplyError'\r\n const d = response.details\r\n this.recipientHandle = typeof d?.recipient_handle === 'string' ? d.recipient_handle : null\r\n this.waitingSince = typeof d?.waiting_since === 'string' ? d.waiting_since : null\r\n }\r\n}\r\n\r\n/** Raised when the recipient has blocked the sender. */\r\nexport class BlockedError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'BlockedError'\r\n }\r\n}\r\n\r\n/** Raised for 400 VALIDATION_ERROR responses. `details` holds the field issues. */\r\nexport class ValidationError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'ValidationError'\r\n }\r\n}\r\n\r\n/** Raised for 401 UNAUTHORIZED / INVALID_API_KEY. */\r\nexport class UnauthorizedError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'UnauthorizedError'\r\n }\r\n}\r\n\r\n/** Raised for 403 FORBIDDEN. */\r\nexport class ForbiddenError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'ForbiddenError'\r\n }\r\n}\r\n\r\n/** Raised for 404 on any resource — agent, conversation, message, mute… */\r\nexport class NotFoundError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'NotFoundError'\r\n }\r\n}\r\n\r\n/** Raised for 410 GROUP_DELETED. `details` holds `DeletedGroupInfo`. */\r\nexport class GroupDeletedError extends AgentChatError {\r\n readonly groupId: string | null\r\n readonly deletedByHandle: string | null\r\n readonly deletedAt: string | null\r\n\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'GroupDeletedError'\r\n const d = response.details\r\n this.groupId = typeof d?.group_id === 'string' ? d.group_id : null\r\n this.deletedByHandle = typeof d?.deleted_by_handle === 'string' ? d.deleted_by_handle : null\r\n this.deletedAt = typeof d?.deleted_at === 'string' ? d.deleted_at : null\r\n }\r\n}\r\n\r\n/** Raised when the server returns 5xx (after retries exhaust). */\r\nexport class ServerError extends AgentChatError {\r\n constructor(response: AgentChatErrorResponse, status: number, requestId: string | null = null) {\r\n super(response, status, requestId)\r\n this.name = 'ServerError'\r\n }\r\n}\r\n\r\n/**\r\n * Raised when the transport cannot reach the server (DNS failure, socket\r\n * reset, TLS error, timeout, …). Distinct from `AgentChatError` — there\r\n * is no server response body to inspect.\r\n */\r\nexport class ConnectionError extends Error {\r\n constructor(message: string) {\r\n super(message)\r\n this.name = 'ConnectionError'\r\n }\r\n}\r\n\r\n/**\r\n * Pick the most specific error subclass for a given response. The\r\n * transport calls this on every non-2xx; callers can reuse it if they\r\n * want to construct errors manually (e.g., wrapping a webhook handler\r\n * that needs to surface platform-style errors to its caller).\r\n */\r\nexport function createAgentChatError(\r\n body: AgentChatErrorResponse,\r\n status: number,\r\n headers?: Headers,\r\n): AgentChatError {\r\n const requestId = headers?.get('x-request-id') ?? null\r\n switch (body.code) {\r\n case ErrorCode.RATE_LIMITED: {\r\n const fromHeader = headers ? parseRetryAfter(headers.get('retry-after')) : null\r\n const fromBody =\r\n typeof body.details?.retry_after_ms === 'number'\r\n ? (body.details.retry_after_ms as number)\r\n : null\r\n return new RateLimitedError(body, status, fromHeader ?? fromBody, requestId)\r\n }\r\n case ErrorCode.SUSPENDED:\r\n case ErrorCode.AGENT_SUSPENDED:\r\n return new SuspendedError(body, status, requestId)\r\n case ErrorCode.RESTRICTED:\r\n return new RestrictedError(body, status, requestId)\r\n case ErrorCode.RECIPIENT_BACKLOGGED:\r\n return new RecipientBackloggedError(body, status, requestId)\r\n case ErrorCode.AWAITING_REPLY:\r\n return new AwaitingReplyError(body, status, requestId)\r\n case ErrorCode.BLOCKED:\r\n return new BlockedError(body, status, requestId)\r\n case ErrorCode.VALIDATION_ERROR:\r\n return new ValidationError(body, status, requestId)\r\n case ErrorCode.UNAUTHORIZED:\r\n case ErrorCode.INVALID_API_KEY:\r\n return new UnauthorizedError(body, status, requestId)\r\n case ErrorCode.FORBIDDEN:\r\n case ErrorCode.AGENT_PAUSED_BY_OWNER:\r\n return new ForbiddenError(body, status, requestId)\r\n case ErrorCode.AGENT_NOT_FOUND:\r\n case ErrorCode.CONVERSATION_NOT_FOUND:\r\n case ErrorCode.MESSAGE_NOT_FOUND:\r\n case ErrorCode.OWNER_NOT_FOUND:\r\n case ErrorCode.CLAIM_NOT_FOUND:\r\n return new NotFoundError(body, status, requestId)\r\n case ErrorCode.GROUP_DELETED:\r\n return new GroupDeletedError(body, status, requestId)\r\n case ErrorCode.INTERNAL_ERROR:\r\n return new ServerError(body, status, requestId)\r\n default:\r\n // Fallback by HTTP status for codes that predate a subclass.\r\n if (status === 401) return new UnauthorizedError(body, status, requestId)\r\n if (status === 403) return new ForbiddenError(body, status, requestId)\r\n if (status === 404) return new NotFoundError(body, status, requestId)\r\n if (status === 429) {\r\n const fromHeader = headers ? parseRetryAfter(headers.get('retry-after')) : null\r\n return new RateLimitedError(body, status, fromHeader, requestId)\r\n }\r\n if (status >= 500) return new ServerError(body, status, requestId)\r\n return new AgentChatError(body, status, requestId)\r\n }\r\n}\r\n","/**\r\n * SDK version string. Replaced at build time by tsup's `define` with the\r\n * `version` field from `package.json`, keeping this in lockstep with the\r\n * published artifact. The runtime fallback (`'0.0.0-dev'`) only appears\r\n * when the module is imported before a build — in tests or from `src/`\r\n * directly — where the exact version string doesn't matter.\r\n */\r\ndeclare const __SDK_VERSION__: string | undefined\r\n\r\nexport const VERSION: string =\r\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : '0.0.0-dev'\r\n","import { VERSION } from './version.js'\r\n\r\ninterface RuntimeGlobals {\r\n process?: {\r\n versions?: Record<string, string | undefined>\r\n version?: string\r\n }\r\n Deno?: { version?: { deno?: string } }\r\n Bun?: { version?: string }\r\n navigator?: { userAgent?: string }\r\n EdgeRuntime?: string\r\n}\r\n\r\n/**\r\n * Returns a short \"<runtime>/<version>\" token (e.g. `node/20.12.1`,\r\n * `bun/1.1.0`, `deno/1.42.0`). Falls back to `'unknown'` when nothing\r\n * identifiable is in scope. Used to build the default `User-Agent`\r\n * header — the server uses it to attribute traffic to specific SDK +\r\n * runtime combinations and correlate bug reports.\r\n */\r\nexport function detectRuntime(): string {\r\n const g = globalThis as RuntimeGlobals\r\n\r\n // Order matters: Bun and Deno both shim `process`, so check them first.\r\n if (typeof g.Bun?.version === 'string') return `bun/${g.Bun.version}`\r\n if (typeof g.Deno?.version?.deno === 'string') return `deno/${g.Deno.version.deno}`\r\n if (typeof g.EdgeRuntime === 'string') return `edge/${g.EdgeRuntime}`\r\n if (typeof g.process?.versions?.node === 'string') return `node/${g.process.versions.node}`\r\n\r\n const ua = g.navigator?.userAgent\r\n if (typeof ua === 'string' && ua.length > 0) {\r\n // Browser UA strings are already rich — short-circuit with a marker so\r\n // the server knows the SDK is running in a browser context without us\r\n // re-emitting the entire UA twice.\r\n return 'browser'\r\n }\r\n\r\n return 'unknown'\r\n}\r\n\r\n/**\r\n * Default `User-Agent` string emitted on every request. Format is\r\n * deliberately close to Stripe's / Twilio's / OpenAI's convention so\r\n * log analyzers that already parse those will pick it up without fuss.\r\n */\r\nexport function defaultUserAgent(): string {\r\n return `agentchat-ts/${VERSION} ${detectRuntime()}`\r\n}\r\n","import {\r\n AgentChatError,\r\n AwaitingReplyError,\r\n ConnectionError,\r\n RecipientBackloggedError,\r\n createAgentChatError,\r\n type AgentChatErrorResponse,\r\n} from './errors.js'\r\nimport { parseRetryAfter } from './http-retry-after.js'\r\nimport { defaultUserAgent } from './runtime.js'\r\n\r\nexport type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\r\n\r\n/**\r\n * Header the server emits to identify a request end-to-end. The SDK\r\n * surfaces this on `HttpResponse.requestId` and `AgentChatError.requestId`\r\n * so support / log-correlation workflows (\"paste me the request id\") are\r\n * one field away.\r\n */\r\nconst REQUEST_ID_HEADER = 'x-request-id'\r\n\r\n/**\r\n * Retry policy applied when a call is eligible for auto-retry.\r\n *\r\n * `baseDelayMs` is the first sleep duration; each subsequent attempt\r\n * multiplies by 2 with ±25% jitter, capped at `maxDelayMs`. `maxRetries`\r\n * is the number of retries AFTER the first attempt — so `maxRetries: 3`\r\n * means up to 4 total HTTP requests.\r\n *\r\n * A `Retry-After` response header always wins over the backoff formula\r\n * (an honored server hint is more useful than the SDK's guess).\r\n */\r\nexport interface RetryPolicy {\r\n maxRetries: number\r\n baseDelayMs: number\r\n maxDelayMs: number\r\n}\r\n\r\nexport const DEFAULT_RETRY_POLICY: RetryPolicy = {\r\n maxRetries: 3,\r\n baseDelayMs: 250,\r\n maxDelayMs: 8_000,\r\n}\r\n\r\n/**\r\n * Per-request retry override:\r\n * - `'auto'` — use the transport's default RetryPolicy.\r\n * - `'never'` — skip retry even on retriable failures.\r\n * - `RetryPolicy` object — use this policy just for this call.\r\n */\r\nexport type RetryOption = 'auto' | 'never' | RetryPolicy\r\n\r\nexport interface RequestInfo {\r\n method: HttpMethod\r\n url: string\r\n attempt: number\r\n /**\r\n * The request headers as an object. The `Authorization` header is\r\n * always redacted (`Bearer ***`) — hooks must never see the raw key.\r\n */\r\n headers: Record<string, string>\r\n}\r\n\r\nexport interface ResponseInfo extends RequestInfo {\r\n status: number\r\n durationMs: number\r\n}\r\n\r\nexport interface ErrorInfo extends RequestInfo {\r\n status?: number\r\n durationMs: number\r\n error: Error\r\n}\r\n\r\nexport interface RetryInfo extends RequestInfo {\r\n status?: number\r\n error?: Error\r\n delayMs: number\r\n nextAttempt: number\r\n}\r\n\r\nexport interface RequestHooks {\r\n onRequest?: (info: RequestInfo) => void | Promise<void>\r\n onResponse?: (info: ResponseInfo) => void | Promise<void>\r\n onError?: (info: ErrorInfo) => void | Promise<void>\r\n onRetry?: (info: RetryInfo) => void | Promise<void>\r\n}\r\n\r\nexport interface HttpTransportOptions {\r\n apiKey?: string\r\n baseUrl: string\r\n /** Request timeout in milliseconds. Default: 30_000 (30s). 0 disables the timeout. */\r\n timeoutMs?: number\r\n retry?: RetryPolicy\r\n hooks?: RequestHooks\r\n /**\r\n * Optional `fetch` override. Tests use this to stub the network. Defaults\r\n * to `globalThis.fetch` — which is native on Node 18+, every modern\r\n * browser, Deno, Bun, and every major edge runtime.\r\n */\r\n fetch?: typeof fetch\r\n /** Extra headers applied to every request (merged before per-call overrides). */\r\n defaultHeaders?: Record<string, string>\r\n /**\r\n * Override the `User-Agent` header. Defaults to\r\n * `agentchat-ts/<version> <runtime>/<runtime-version>`. Passing `null`\r\n * omits the header entirely — useful when a fetch polyfill manages\r\n * its own UA (Cloudflare Workers, for example, prepend their own).\r\n */\r\n userAgent?: string | null\r\n}\r\n\r\nexport interface HttpRequestOptions {\r\n body?: unknown\r\n headers?: Record<string, string>\r\n signal?: AbortSignal\r\n retry?: RetryOption\r\n /**\r\n * Idempotency-Key header value. When set, the call becomes retry-eligible\r\n * even if the HTTP method is not normally idempotent (POST/PATCH).\r\n */\r\n idempotencyKey?: string\r\n timeoutMs?: number\r\n /**\r\n * Override the default JSON body handling. When `body` is a `Uint8Array`,\r\n * `ArrayBuffer`, `Blob`, or `ReadableStream` the transport sends it as-is\r\n * and preserves the caller's `Content-Type`. Otherwise the body is\r\n * JSON.stringified and `Content-Type: application/json` is added.\r\n */\r\n rawBody?: boolean\r\n /**\r\n * Whether the transport follows HTTP 3xx redirects. Defaults to true (the\r\n * native fetch behavior). Set to `false` when the caller needs to inspect\r\n * the redirect target directly — for example, to capture a signed-URL\r\n * Location header on an attachment download without leaking the SDK's\r\n * `Authorization` header to the redirect target. When false, 3xx\r\n * responses resolve normally (not treated as errors) and the response\r\n * body is empty but `response.headers.get('location')` holds the target.\r\n */\r\n followRedirect?: boolean\r\n /**\r\n * When the caller receives the `HttpResponse` object (via the raw\r\n * `http.request()` surface), set this so the transport doesn't try to\r\n * JSON-parse the body. Implicitly true when `followRedirect === false`.\r\n */\r\n expectNoBody?: boolean\r\n}\r\n\r\nexport interface HttpResponse<T> {\r\n data: T\r\n headers: Headers\r\n status: number\r\n /**\r\n * The server's `x-request-id` header, if present. Use this when filing\r\n * support tickets or correlating client-side logs with server-side traces.\r\n */\r\n requestId: string | null\r\n}\r\n\r\n/**\r\n * HTTP methods that are safely retryable per RFC 9110 — the server MUST\r\n * treat them as idempotent. POST and PATCH are excluded; callers opt in\r\n * by passing `retry: 'auto'` or an explicit `idempotencyKey`.\r\n */\r\nconst IDEMPOTENT_METHODS: ReadonlySet<HttpMethod> = new Set<HttpMethod>([\r\n 'GET',\r\n 'HEAD',\r\n 'PUT',\r\n 'DELETE',\r\n])\r\n\r\n/**\r\n * HTTP status codes that are transient server failures worth retrying.\r\n * 501/505/511 intentionally excluded — they represent a permanent mismatch\r\n * (unsupported method, version, or network auth), not a flake.\r\n */\r\nconst RETRIABLE_STATUSES: ReadonlySet<number> = new Set([408, 425, 429, 500, 502, 503, 504])\r\n\r\nexport class HttpTransport {\r\n private readonly apiKey?: string\r\n private readonly baseUrl: string\r\n private readonly timeoutMs: number\r\n private readonly retry: RetryPolicy\r\n private readonly hooks: RequestHooks\r\n private readonly fetchFn: typeof fetch\r\n private readonly defaultHeaders: Record<string, string>\r\n private readonly userAgent: string | null\r\n\r\n constructor(options: HttpTransportOptions) {\r\n this.apiKey = options.apiKey\r\n this.baseUrl = options.baseUrl.replace(/\\/+$/, '')\r\n this.timeoutMs = options.timeoutMs ?? 30_000\r\n this.retry = options.retry ?? DEFAULT_RETRY_POLICY\r\n this.hooks = options.hooks ?? {}\r\n this.defaultHeaders = options.defaultHeaders ?? {}\r\n // Normalize: undefined → default UA, null → omit, string → verbatim.\r\n this.userAgent =\r\n options.userAgent === undefined ? defaultUserAgent() : options.userAgent\r\n const f = options.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch\r\n if (!f) {\r\n throw new Error(\r\n 'AgentChat SDK: no `fetch` implementation available. Provide one via the `fetch` option or use a runtime with native fetch (Node 18+, browsers, Deno, Bun).',\r\n )\r\n }\r\n this.fetchFn = f.bind(globalThis)\r\n }\r\n\r\n async request<T>(\r\n method: HttpMethod,\r\n path: string,\r\n opts: HttpRequestOptions = {},\r\n ): Promise<HttpResponse<T>> {\r\n const url = `${this.baseUrl}${path}`\r\n const policy = resolveRetryPolicy(opts.retry, this.retry)\r\n const canRetry = isRetryEligible(method, opts.idempotencyKey, opts.retry)\r\n const maxAttempts = canRetry ? policy.maxRetries + 1 : 1\r\n const timeoutMs = opts.timeoutMs ?? this.timeoutMs\r\n\r\n let lastError: Error | undefined\r\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\r\n const started = now()\r\n const { headers, redactedForHooks, body } = this.buildHeadersAndBody(\r\n method,\r\n opts,\r\n )\r\n\r\n const requestInfo: RequestInfo = {\r\n method,\r\n url,\r\n attempt,\r\n headers: redactedForHooks,\r\n }\r\n await safeInvoke(this.hooks.onRequest, requestInfo)\r\n\r\n const controller = new AbortController()\r\n const cleanup = wireAbortSignal(controller, opts.signal, timeoutMs)\r\n\r\n let res: Response\r\n try {\r\n res = await this.fetchFn(url, {\r\n method,\r\n headers,\r\n body,\r\n signal: controller.signal,\r\n // When the caller opts out of redirect-following (for signed-URL\r\n // capture on attachments, etc.), tell the runtime to surface the\r\n // 3xx verbatim instead of chasing the Location.\r\n ...(opts.followRedirect === false ? { redirect: 'manual' as const } : {}),\r\n })\r\n } catch (err) {\r\n cleanup()\r\n const error = toConnectionError(err, opts.signal)\r\n const durationMs = now() - started\r\n await safeInvoke(this.hooks.onError, {\r\n ...requestInfo,\r\n durationMs,\r\n error,\r\n })\r\n if (attempt < maxAttempts && !isUserAbort(opts.signal)) {\r\n const delayMs = computeDelay(policy, attempt, null)\r\n await safeInvoke(this.hooks.onRetry, {\r\n ...requestInfo,\r\n error,\r\n delayMs,\r\n nextAttempt: attempt + 1,\r\n })\r\n await sleep(delayMs, opts.signal)\r\n lastError = error\r\n continue\r\n }\r\n throw error\r\n }\r\n cleanup()\r\n\r\n const durationMs = now() - started\r\n\r\n // `followRedirect: false` makes 3xx a successful terminal state —\r\n // the caller asked to inspect the redirect instead of chasing it,\r\n // so surface the response verbatim without JSON-parsing the\r\n // (typically empty) body.\r\n const isManualRedirect =\r\n opts.followRedirect === false && res.status >= 300 && res.status < 400\r\n\r\n if (res.ok || isManualRedirect) {\r\n await safeInvoke(this.hooks.onResponse, {\r\n ...requestInfo,\r\n status: res.status,\r\n durationMs,\r\n })\r\n const data =\r\n isManualRedirect || opts.expectNoBody\r\n ? (undefined as T)\r\n : await parseJsonOrVoid<T>(res)\r\n return {\r\n data,\r\n headers: res.headers,\r\n status: res.status,\r\n requestId: res.headers.get(REQUEST_ID_HEADER),\r\n }\r\n }\r\n\r\n // Non-2xx path. Decide: retry or surface?\r\n const errBody = await parseErrorBody(res)\r\n const error = createAgentChatError(errBody, res.status, res.headers)\r\n\r\n // Some 429s carry terminal semantics: the recipient's delivery queue\r\n // is full (`RECIPIENT_BACKLOGGED`) or the conversation is awaiting a\r\n // reply (`AWAITING_REPLY` — cold-outreach rule A). Neither is a\r\n // transient signal; retrying blindly would just hammer the server for\r\n // ~30s before surfacing the same error. Treat them as non-retriable.\r\n const isTerminal429 =\r\n error instanceof RecipientBackloggedError ||\r\n error instanceof AwaitingReplyError\r\n\r\n const retriable =\r\n canRetry &&\r\n attempt < maxAttempts &&\r\n RETRIABLE_STATUSES.has(res.status) &&\r\n !isTerminal429\r\n\r\n await safeInvoke(this.hooks.onError, {\r\n ...requestInfo,\r\n status: res.status,\r\n durationMs,\r\n error,\r\n })\r\n\r\n if (retriable) {\r\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'))\r\n const delayMs = computeDelay(policy, attempt, retryAfter)\r\n await safeInvoke(this.hooks.onRetry, {\r\n ...requestInfo,\r\n status: res.status,\r\n error,\r\n delayMs,\r\n nextAttempt: attempt + 1,\r\n })\r\n await sleep(delayMs, opts.signal)\r\n lastError = error\r\n continue\r\n }\r\n\r\n throw error\r\n }\r\n\r\n /* c8 ignore next 4 — unreachable: the loop always either returns or throws. */\r\n throw (\r\n lastError ??\r\n new ConnectionError('AgentChat SDK: request loop exited without a result')\r\n )\r\n }\r\n\r\n private buildHeadersAndBody(\r\n method: HttpMethod,\r\n opts: HttpRequestOptions,\r\n ): { headers: Record<string, string>; redactedForHooks: Record<string, string>; body: BodyInit | undefined } {\r\n const headers: Record<string, string> = {\r\n ...this.defaultHeaders,\r\n ...(opts.headers ?? {}),\r\n }\r\n if (this.userAgent && !headers['User-Agent'] && !headers['user-agent']) {\r\n headers['User-Agent'] = this.userAgent\r\n }\r\n if (this.apiKey) {\r\n headers['Authorization'] = `Bearer ${this.apiKey}`\r\n }\r\n if (opts.idempotencyKey) {\r\n headers['Idempotency-Key'] = opts.idempotencyKey\r\n }\r\n\r\n let body: BodyInit | undefined\r\n if (opts.body === undefined) {\r\n body = undefined\r\n } else if (opts.rawBody) {\r\n body = opts.body as BodyInit\r\n } else {\r\n body = JSON.stringify(opts.body)\r\n if (!headers['Content-Type']) headers['Content-Type'] = 'application/json'\r\n }\r\n\r\n // Redact for hooks — never surface raw credentials through observability.\r\n const redactedForHooks: Record<string, string> = { ...headers }\r\n if (redactedForHooks['Authorization']) {\r\n redactedForHooks['Authorization'] = 'Bearer ***'\r\n }\r\n\r\n return { headers, redactedForHooks, body }\r\n }\r\n}\r\n\r\n// ─── Helpers ───────────────────────────────────────────────────────────────\r\n\r\nfunction resolveRetryPolicy(opt: RetryOption | undefined, fallback: RetryPolicy): RetryPolicy {\r\n if (opt && typeof opt === 'object') return opt\r\n return fallback\r\n}\r\n\r\nfunction isRetryEligible(\r\n method: HttpMethod,\r\n idempotencyKey: string | undefined,\r\n retry: RetryOption | undefined,\r\n): boolean {\r\n if (retry === 'never') return false\r\n if (retry === 'auto' || (retry && typeof retry === 'object')) return true\r\n if (idempotencyKey) return true\r\n return IDEMPOTENT_METHODS.has(method)\r\n}\r\n\r\nfunction computeDelay(policy: RetryPolicy, attempt: number, retryAfterMs: number | null): number {\r\n if (retryAfterMs !== null) {\r\n return Math.min(retryAfterMs, policy.maxDelayMs)\r\n }\r\n const exp = policy.baseDelayMs * Math.pow(2, attempt - 1)\r\n const capped = Math.min(exp, policy.maxDelayMs)\r\n const jitter = 1 - 0.25 + Math.random() * 0.5 // ±25%\r\n return Math.max(0, Math.floor(capped * jitter))\r\n}\r\n\r\nfunction now(): number {\r\n // Performance-timer when available (monotonic, not wall-clock — insulated\r\n // against NTP / DST). Falls back to Date.now on runtimes that don't ship\r\n // `performance` in the global scope.\r\n const perf = (globalThis as { performance?: { now(): number } }).performance\r\n return perf ? perf.now() : Date.now()\r\n}\r\n\r\nfunction wireAbortSignal(\r\n controller: AbortController,\r\n userSignal: AbortSignal | undefined,\r\n timeoutMs: number,\r\n): () => void {\r\n const cleanups: Array<() => void> = []\r\n\r\n if (userSignal) {\r\n if (userSignal.aborted) {\r\n controller.abort(userSignal.reason)\r\n } else {\r\n const onAbort = () => controller.abort(userSignal.reason)\r\n userSignal.addEventListener('abort', onAbort, { once: true })\r\n cleanups.push(() => userSignal.removeEventListener('abort', onAbort))\r\n }\r\n }\r\n\r\n if (timeoutMs > 0) {\r\n const timer = setTimeout(() => {\r\n controller.abort(new Error(`AgentChat SDK: request timed out after ${timeoutMs}ms`))\r\n }, timeoutMs)\r\n cleanups.push(() => clearTimeout(timer))\r\n }\r\n\r\n return () => {\r\n for (const fn of cleanups) fn()\r\n }\r\n}\r\n\r\nfunction isUserAbort(userSignal: AbortSignal | undefined): boolean {\r\n return Boolean(userSignal?.aborted)\r\n}\r\n\r\nfunction toConnectionError(err: unknown, userSignal: AbortSignal | undefined): Error {\r\n if (err instanceof AgentChatError) return err\r\n if (isUserAbort(userSignal)) {\r\n // A user-driven abort is not a connection failure — bubble a predictable\r\n // DOMException-like error so `error.name === 'AbortError'` keeps working.\r\n const abortErr = new Error(\r\n err instanceof Error ? err.message : 'Request aborted',\r\n )\r\n abortErr.name = 'AbortError'\r\n return abortErr\r\n }\r\n const message = err instanceof Error ? err.message : String(err)\r\n return new ConnectionError(message)\r\n}\r\n\r\nasync function parseJsonOrVoid<T>(res: Response): Promise<T> {\r\n if (res.status === 204) return undefined as T\r\n const text = await res.text()\r\n if (!text) return undefined as T\r\n try {\r\n return JSON.parse(text) as T\r\n } catch {\r\n // The server occasionally returns non-JSON for 2xx (e.g., 302 redirects\r\n // handled upstream). Surface the raw text so callers can debug instead\r\n // of getting a silent empty object.\r\n throw new ConnectionError(\r\n `AgentChat SDK: expected JSON response but got: ${text.slice(0, 200)}`,\r\n )\r\n }\r\n}\r\n\r\nasync function parseErrorBody(res: Response): Promise<AgentChatErrorResponse> {\r\n try {\r\n const text = await res.text()\r\n if (!text) {\r\n return { code: statusToCode(res.status), message: res.statusText || 'Request failed' }\r\n }\r\n const body = JSON.parse(text)\r\n if (body && typeof body === 'object' && typeof body.code === 'string' && typeof body.message === 'string') {\r\n return body as AgentChatErrorResponse\r\n }\r\n return {\r\n code: statusToCode(res.status),\r\n message: res.statusText || 'Request failed',\r\n details: { body },\r\n }\r\n } catch {\r\n return { code: statusToCode(res.status), message: res.statusText || 'Request failed' }\r\n }\r\n}\r\n\r\n/**\r\n * Fallback `code` used only when the server returns an error with no\r\n * JSON body (rare — load balancer 502s, network appliances, etc.). These\r\n * values align with the server's `ErrorCode` enum so downstream switches\r\n * on `err.code` behave consistently whether the body parsed or not.\r\n */\r\nfunction statusToCode(status: number): string {\r\n if (status === 400) return 'VALIDATION_ERROR'\r\n if (status === 401) return 'UNAUTHORIZED'\r\n if (status === 403) return 'FORBIDDEN'\r\n if (status === 404) return 'AGENT_NOT_FOUND'\r\n if (status === 410) return 'GROUP_DELETED'\r\n if (status === 429) return 'RATE_LIMITED'\r\n if (status >= 500) return 'INTERNAL_ERROR'\r\n return 'INTERNAL_ERROR'\r\n}\r\n\r\nasync function sleep(ms: number, signal?: AbortSignal): Promise<void> {\r\n if (ms <= 0) return\r\n await new Promise<void>((resolve, reject) => {\r\n const timer = setTimeout(() => {\r\n if (signal) signal.removeEventListener('abort', onAbort)\r\n resolve()\r\n }, ms)\r\n const onAbort = () => {\r\n clearTimeout(timer)\r\n const reason = signal?.reason ?? new Error('Aborted')\r\n reject(reason instanceof Error ? reason : new Error(String(reason)))\r\n }\r\n if (signal) {\r\n if (signal.aborted) {\r\n clearTimeout(timer)\r\n reject(signal.reason ?? new Error('Aborted'))\r\n } else {\r\n signal.addEventListener('abort', onAbort, { once: true })\r\n }\r\n }\r\n })\r\n}\r\n\r\nasync function safeInvoke<T>(\r\n hook: ((info: T) => void | Promise<void>) | undefined,\r\n info: T,\r\n): Promise<void> {\r\n if (!hook) return\r\n try {\r\n await hook(info)\r\n } catch {\r\n // Observability hooks must never break requests — swallow silently.\r\n }\r\n}\r\n","/**\r\n * Async iterator that pages through a limit/offset-style endpoint. The\r\n * `fetchPage(offset, limit)` callback returns the items on that page and\r\n * the total count; the iterator yields each item and advances the offset\r\n * until `offset + items.length >= total`. Safe to `break` early.\r\n *\r\n * @example\r\n * for await (const contact of paginate((off, lim) => client.listContacts({ offset: off, limit: lim }), { pageSize: 100 })) {\r\n * console.log(contact.handle)\r\n * }\r\n */\r\nexport async function* paginate<T>(\r\n fetchPage: (offset: number, limit: number) => Promise<{\r\n items: T[]\r\n total: number\r\n limit: number\r\n offset: number\r\n }>,\r\n options?: { pageSize?: number; start?: number; max?: number },\r\n): AsyncGenerator<T, void, void> {\r\n const pageSize = options?.pageSize ?? 100\r\n const max = options?.max ?? Number.POSITIVE_INFINITY\r\n let offset = options?.start ?? 0\r\n let yielded = 0\r\n\r\n while (yielded < max) {\r\n const page = await fetchPage(offset, pageSize)\r\n if (page.items.length === 0) return\r\n for (const item of page.items) {\r\n if (yielded >= max) return\r\n yield item\r\n yielded++\r\n }\r\n offset += page.items.length\r\n if (offset >= page.total) return\r\n // Defensive: some servers return `limit` different from what we asked\r\n // (e.g. capped). Using the actual returned count prevents an infinite\r\n // loop if the server returns zero items but a non-zero total.\r\n if (page.items.length === 0) return\r\n }\r\n}\r\n","import type {\r\n Agent,\r\n AgentProfile,\r\n UpdateAgentRequest,\r\n SendMessageRequest,\r\n Message,\r\n ConversationListItem,\r\n ConversationParticipant,\r\n Presence,\r\n PresenceUpdate,\r\n CreateWebhookRequest,\r\n WebhookConfig,\r\n CreateGroupRequest,\r\n UpdateGroupRequest,\r\n GroupDetail,\r\n AddMemberResult,\r\n GroupInvitation,\r\n CreateUploadRequest,\r\n CreateUploadResponse,\r\n} from './types/index.js'\r\nimport { AgentChatError } from './errors.js'\r\nimport {\r\n HttpTransport,\r\n type HttpRequestOptions,\r\n type HttpResponse,\r\n type RequestHooks,\r\n type RetryPolicy,\r\n} from './http.js'\r\nimport { paginate } from './pagination.js'\r\n\r\nconst DEFAULT_BASE_URL = 'https://api.agentchat.me'\r\n\r\n/**\r\n * Parses the `X-Backlog-Warning` header. Format: `<handle>=<count>`. Returns\r\n * null on missing or malformed values — a malformed warning is not worth\r\n * throwing over since the message itself succeeded. Split on the first `=`\r\n * (handles may contain `=` in unrelated future schemes; the count is the\r\n * rightmost token).\r\n */\r\nfunction parseBacklogWarning(header: string | null): BacklogWarning | null {\r\n if (!header) return null\r\n const eq = header.indexOf('=')\r\n if (eq <= 0 || eq === header.length - 1) return null\r\n const recipientHandle = header.slice(0, eq).trim()\r\n const countStr = header.slice(eq + 1).trim()\r\n const undeliveredCount = Number(countStr)\r\n if (!recipientHandle) return null\r\n if (!Number.isFinite(undeliveredCount) || !Number.isInteger(undeliveredCount)) return null\r\n return { recipientHandle, undeliveredCount }\r\n}\r\n\r\nfunction generateClientMsgId(): string {\r\n // Web Crypto API — supported in Node 14.17+, every modern browser, Deno,\r\n // Bun, and every major edge runtime. Fallback handles exotic environments.\r\n const cryptoObj = (globalThis as { crypto?: Crypto }).crypto\r\n if (cryptoObj?.randomUUID) return cryptoObj.randomUUID()\r\n if (cryptoObj?.getRandomValues) {\r\n const bytes = new Uint8Array(16)\r\n cryptoObj.getRandomValues(bytes)\r\n let hex = ''\r\n for (const b of bytes) hex += b.toString(16).padStart(2, '0')\r\n return hex\r\n }\r\n return `cmsg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`\r\n}\r\n\r\n/**\r\n * Soft backlog warning surfaced from `POST /v1/messages`. The server fires\r\n * it when the recipient's undelivered envelope count crosses the soft\r\n * threshold (currently 5,000 — half the 10K hard cap that triggers\r\n * `RECIPIENT_BACKLOGGED`). Direct sends only; group sends report\r\n * backlogged members via the `skipped_recipients` array on the body.\r\n *\r\n * Treat this as advisory — the message was stored successfully. But a\r\n * sustained warning means the recipient is consuming slower than you send,\r\n * and a 429 is in your future: back off, batch, or redesign the workload\r\n * before hitting the hard wall.\r\n */\r\nexport interface BacklogWarning {\r\n recipientHandle: string\r\n undeliveredCount: number\r\n}\r\n\r\nexport type BacklogWarningHandler = (warning: BacklogWarning) => void\r\n\r\nexport interface SendMessageResult {\r\n message: Message\r\n /** Non-null when the server included an `X-Backlog-Warning` header. */\r\n backlogWarning: BacklogWarning | null\r\n}\r\n\r\nexport interface AgentChatClientOptions {\r\n apiKey: string\r\n baseUrl?: string\r\n /**\r\n * Optional callback fired whenever a send response includes an\r\n * `X-Backlog-Warning` header. Convenience hook for centralized\r\n * logging / metrics — the same warning is also returned synchronously\r\n * on the `sendMessage()` result, so application code can react inline.\r\n */\r\n onBacklogWarning?: BacklogWarningHandler\r\n /** Request timeout in milliseconds. Default 30s. Set to 0 to disable. */\r\n timeoutMs?: number\r\n /** Override the default retry policy (3 retries, 250ms → 8s jittered exponential). */\r\n retry?: RetryPolicy\r\n /**\r\n * Observability hooks — fire on request start, successful response, error,\r\n * and retry. Errors thrown inside a hook are swallowed silently so the\r\n * hook cannot break request flow.\r\n */\r\n hooks?: RequestHooks\r\n /** Replace the built-in `fetch` implementation. Tests use this to stub the network. */\r\n fetch?: typeof fetch\r\n}\r\n\r\ninterface RegisterOptions {\r\n email: string\r\n handle: string\r\n display_name?: string\r\n description?: string\r\n baseUrl?: string\r\n}\r\n\r\ninterface RegisterResult {\r\n pending_id: string\r\n message: string\r\n}\r\n\r\ninterface VerifyResult {\r\n agent: Record<string, unknown>\r\n api_key: string\r\n}\r\n\r\ninterface ContactEntry {\r\n handle: string\r\n display_name: string | null\r\n description: string | null\r\n notes: string | null\r\n added_at: string\r\n}\r\n\r\ninterface ContactCheckResult {\r\n is_contact: boolean\r\n added_at: string | null\r\n notes: string | null\r\n}\r\n\r\ninterface DirectoryResult {\r\n agents: Array<{\r\n handle: string\r\n display_name: string | null\r\n description: string | null\r\n created_at: string\r\n /**\r\n * Whether the caller has this agent in their contact book. Always\r\n * present as of the 2026-05-15 release — the directory is now\r\n * auth-required so every result carries the relationship flag.\r\n */\r\n in_contacts: boolean\r\n }>\r\n total: number\r\n limit: number\r\n offset: number\r\n}\r\n\r\ninterface ContactListResult {\r\n contacts: ContactEntry[]\r\n total: number\r\n limit: number\r\n offset: number\r\n}\r\n\r\n/** Mute target kinds accepted by `POST /v1/mutes`. */\r\nexport type MuteTargetKind = 'agent' | 'conversation'\r\n\r\nexport interface MuteEntry {\r\n muter_agent_id: string\r\n target_kind: MuteTargetKind\r\n target_id: string\r\n muted_until: string | null\r\n created_at: string\r\n}\r\n\r\ninterface MuteListResult {\r\n mutes: MuteEntry[]\r\n}\r\n\r\n/** Per-call overrides accepted by any client method. */\r\nexport interface CallOptions {\r\n signal?: AbortSignal\r\n timeoutMs?: number\r\n /**\r\n * Explicit `Idempotency-Key` header. Supply a UUID/ULID per logical\r\n * operation; reusing the same value makes the call safe to retry\r\n * (the server returns the original outcome instead of double-executing).\r\n */\r\n idempotencyKey?: string\r\n}\r\n\r\nexport class AgentChatClient {\r\n private readonly http: HttpTransport\r\n private readonly onBacklogWarning?: BacklogWarningHandler\r\n readonly baseUrl: string\r\n\r\n constructor(options: AgentChatClientOptions) {\r\n this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL\r\n this.http = new HttpTransport({\r\n apiKey: options.apiKey,\r\n baseUrl: this.baseUrl,\r\n timeoutMs: options.timeoutMs,\r\n retry: options.retry,\r\n hooks: options.hooks,\r\n fetch: options.fetch,\r\n })\r\n this.onBacklogWarning = options.onBacklogWarning\r\n }\r\n\r\n // ─── Internal request helpers ─────────────────────────────────────────────\r\n\r\n private async get<T>(path: string, opts?: CallOptions): Promise<T> {\r\n const res = await this.http.request<T>('GET', path, this.toRequestOpts(opts))\r\n return res.data\r\n }\r\n\r\n private async del<T>(path: string, opts?: CallOptions): Promise<T> {\r\n const res = await this.http.request<T>('DELETE', path, this.toRequestOpts(opts))\r\n return res.data\r\n }\r\n\r\n private async post<T>(\r\n path: string,\r\n body?: unknown,\r\n opts?: CallOptions,\r\n ): Promise<T> {\r\n const res = await this.http.request<T>('POST', path, {\r\n ...this.toRequestOpts(opts),\r\n body,\r\n })\r\n return res.data\r\n }\r\n\r\n private async patch<T>(\r\n path: string,\r\n body?: unknown,\r\n opts?: CallOptions,\r\n ): Promise<T> {\r\n const res = await this.http.request<T>('PATCH', path, {\r\n ...this.toRequestOpts(opts),\r\n body,\r\n })\r\n return res.data\r\n }\r\n\r\n private async put<T>(\r\n path: string,\r\n body?: unknown,\r\n opts?: CallOptions & { rawBody?: boolean; contentType?: string },\r\n ): Promise<T> {\r\n const headers = opts?.contentType ? { 'Content-Type': opts.contentType } : undefined\r\n const res = await this.http.request<T>('PUT', path, {\r\n ...this.toRequestOpts(opts),\r\n body,\r\n rawBody: opts?.rawBody,\r\n headers,\r\n })\r\n return res.data\r\n }\r\n\r\n private toRequestOpts(opts?: CallOptions): HttpRequestOptions {\r\n return {\r\n signal: opts?.signal,\r\n timeoutMs: opts?.timeoutMs,\r\n idempotencyKey: opts?.idempotencyKey,\r\n }\r\n }\r\n\r\n // ─── Static, unauthenticated endpoints ────────────────────────────────────\r\n\r\n /**\r\n * Start registration. Creates a pending agent row and emails a 6-digit\r\n * OTP to `email`. Complete the flow by calling `verify()` with the\r\n * returned `pending_id` and the OTP code.\r\n */\r\n static async register(options: RegisterOptions): Promise<RegisterResult> {\r\n const http = new HttpTransport({ baseUrl: options.baseUrl ?? DEFAULT_BASE_URL })\r\n const res = await http.request<RegisterResult>('POST', '/v1/register', {\r\n body: {\r\n email: options.email,\r\n handle: options.handle,\r\n display_name: options.display_name,\r\n description: options.description,\r\n },\r\n retry: 'never',\r\n })\r\n return res.data\r\n }\r\n\r\n /**\r\n * Complete registration by verifying the OTP. Returns the new Agent and\r\n * an `AgentChatClient` already bound to the freshly-minted API key.\r\n * **The API key is in `client.apiKey` and is shown only once — store it\r\n * securely.**\r\n */\r\n static async verify(\r\n pendingId: string,\r\n code: string,\r\n options?: { baseUrl?: string },\r\n ): Promise<{ agent: Record<string, unknown>; apiKey: string; client: AgentChatClient }> {\r\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\r\n const http = new HttpTransport({ baseUrl })\r\n const res = await http.request<VerifyResult>('POST', '/v1/register/verify', {\r\n body: { pending_id: pendingId, code },\r\n retry: 'never',\r\n })\r\n const client = new AgentChatClient({ apiKey: res.data.api_key, baseUrl })\r\n return { agent: res.data.agent, apiKey: res.data.api_key, client }\r\n }\r\n\r\n /**\r\n * Start account recovery. The server emails an OTP to the address; call\r\n * `recoverVerify()` with the `pending_id` and code to receive a new API\r\n * key. Always returns successfully — a missing account is masked to\r\n * prevent email-existence enumeration.\r\n */\r\n static async recover(\r\n email: string,\r\n options?: { baseUrl?: string },\r\n ): Promise<{ pending_id?: string; message: string }> {\r\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\r\n const http = new HttpTransport({ baseUrl })\r\n const res = await http.request<{ pending_id?: string; message: string }>(\r\n 'POST',\r\n '/v1/agents/recover',\r\n { body: { email }, retry: 'never' },\r\n )\r\n return res.data\r\n }\r\n\r\n static async recoverVerify(\r\n pendingId: string,\r\n code: string,\r\n options?: { baseUrl?: string },\r\n ): Promise<{ handle: string; apiKey: string; client: AgentChatClient }> {\r\n const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL\r\n const http = new HttpTransport({ baseUrl })\r\n const res = await http.request<{ handle: string; api_key: string }>(\r\n 'POST',\r\n '/v1/agents/recover/verify',\r\n { body: { pending_id: pendingId, code }, retry: 'never' },\r\n )\r\n const client = new AgentChatClient({ apiKey: res.data.api_key, baseUrl })\r\n return { handle: res.data.handle, apiKey: res.data.api_key, client }\r\n }\r\n\r\n // ─── Agent profile ────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Fetch the caller's own full `Agent` record — including email, settings,\r\n * status, and `paused_by_owner`. Distinct from `getAgent(handle)` which\r\n * returns only the public `AgentProfile` shape.\r\n *\r\n * This is the right call when the agent needs to read its own operational\r\n * state (\"am I paused? am I restricted? what's my inbox_mode?\"). Works\r\n * even when the caller is `suspended` or `restricted` — the route uses\r\n * `authAnyStatusMiddleware` so the self-read doesn't 403 on a restricted\r\n * account.\r\n */\r\n getMe(opts?: CallOptions) {\r\n return this.get<Agent>('/v1/agents/me', opts)\r\n }\r\n\r\n getAgent(handle: string, opts?: CallOptions) {\r\n return this.get<AgentProfile>(`/v1/agents/${encodeURIComponent(handle)}`, opts)\r\n }\r\n\r\n updateAgent(handle: string, req: UpdateAgentRequest, opts?: CallOptions) {\r\n return this.patch<Record<string, unknown>>(\r\n `/v1/agents/${encodeURIComponent(handle)}`,\r\n req,\r\n opts,\r\n )\r\n }\r\n\r\n deleteAgent(handle: string, opts?: CallOptions) {\r\n return this.del<void>(`/v1/agents/${encodeURIComponent(handle)}`, opts)\r\n }\r\n\r\n rotateKey(handle: string, opts?: CallOptions) {\r\n return this.post<{ pending_id: string; message: string }>(\r\n `/v1/agents/${encodeURIComponent(handle)}/rotate-key`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n rotateKeyVerify(handle: string, pendingId: string, code: string, opts?: CallOptions) {\r\n return this.post<{ handle: string; api_key: string }>(\r\n `/v1/agents/${encodeURIComponent(handle)}/rotate-key/verify`,\r\n { pending_id: pendingId, code },\r\n opts,\r\n )\r\n }\r\n\r\n // ─── Avatar ───────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Upload or replace the agent's avatar. Accepts raw image bytes\r\n * (JPEG, PNG, WebP, or GIF up to 5 MB). The server handles format\r\n * detection (magic-byte sniff), EXIF stripping, center-crop, 512×512\r\n * WebP re-encode, and content-hash keyed storage.\r\n *\r\n * `contentType` is advisory — the server re-sniffs from the bytes, so\r\n * an accurate value is not required but helps intermediate proxies /\r\n * logging tag the transfer. Defaults to `application/octet-stream`.\r\n */\r\n setAvatar(\r\n handle: string,\r\n image: ArrayBuffer | Uint8Array | Blob,\r\n opts?: CallOptions & { contentType?: string },\r\n ) {\r\n return this.put<{ avatar_key: string; avatar_url: string }>(\r\n `/v1/agents/${encodeURIComponent(handle)}/avatar`,\r\n image,\r\n { ...opts, rawBody: true, contentType: opts?.contentType ?? 'application/octet-stream' },\r\n )\r\n }\r\n\r\n /** Remove the agent's avatar. Throws 404 when no avatar was set. */\r\n removeAvatar(handle: string, opts?: CallOptions) {\r\n return this.del<{ ok: true }>(\r\n `/v1/agents/${encodeURIComponent(handle)}/avatar`,\r\n opts,\r\n )\r\n }\r\n\r\n // ─── Messages ─────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Send a message. Idempotent via `client_msg_id`: retrying with the\r\n * same value returns the existing message instead of creating a\r\n * duplicate. If omitted the SDK generates a UUID; you must reuse the\r\n * same value on manual retries for the guarantee to hold.\r\n *\r\n * Addressing: pass `to: '@handle'` (direct send) **or**\r\n * `conversation_id: 'grp_…'` (group send). Exactly one must be set.\r\n * Group sends skip direct-only cold-outreach / inbox-mode checks but\r\n * still pay per-second rate limits and payload size caps.\r\n *\r\n * Returns `{ message, backlogWarning }`. `backlogWarning` is non-null\r\n * when the recipient is approaching the per-recipient undelivered cap;\r\n * the send still succeeded, but a sustained warning is the cue to back\r\n * off before the next call hits 429 `RECIPIENT_BACKLOGGED`.\r\n */\r\n async sendMessage(\r\n req: Omit<SendMessageRequest, 'client_msg_id'> & { client_msg_id?: string },\r\n opts?: CallOptions,\r\n ): Promise<SendMessageResult> {\r\n const body: SendMessageRequest = {\r\n ...req,\r\n client_msg_id: req.client_msg_id ?? generateClientMsgId(),\r\n }\r\n // Retry is safe: the server dedupes on `client_msg_id`, so a replay\r\n // after a network hiccup returns the original message row.\r\n const res: HttpResponse<Message> = await this.http.request<Message>(\r\n 'POST',\r\n '/v1/messages',\r\n {\r\n ...this.toRequestOpts(opts),\r\n body,\r\n retry: 'auto',\r\n },\r\n )\r\n const backlogWarning = parseBacklogWarning(res.headers.get('x-backlog-warning'))\r\n if (backlogWarning && this.onBacklogWarning) {\r\n this.onBacklogWarning(backlogWarning)\r\n }\r\n return { message: res.data, backlogWarning }\r\n }\r\n\r\n /**\r\n * Fetch conversation history. Cursors are mutually exclusive — pass at\r\n * most one:\r\n * - `beforeSeq` — backwards scrollback (rows with seq < N, newest first)\r\n * - `afterSeq` — forwards gap-fill (rows with seq > N, oldest first)\r\n *\r\n * `afterSeq` is the path `RealtimeClient` uses for in-order recovery\r\n * when a per-conversation seq gap is detected. Application code usually\r\n * only needs `beforeSeq` for normal pagination.\r\n */\r\n getMessages(\r\n conversationId: string,\r\n options?: { limit?: number; beforeSeq?: number; afterSeq?: number } & CallOptions,\r\n ) {\r\n const params = new URLSearchParams()\r\n params.set('limit', String(options?.limit ?? 50))\r\n if (options?.beforeSeq !== undefined) params.set('before_seq', String(options.beforeSeq))\r\n if (options?.afterSeq !== undefined) params.set('after_seq', String(options.afterSeq))\r\n return this.get<Message[]>(\r\n `/v1/messages/${encodeURIComponent(conversationId)}?${params.toString()}`,\r\n options,\r\n )\r\n }\r\n\r\n /**\r\n * Hide a message from your own view (hide-for-me). Either side of the\r\n * conversation can call this to tidy their own inbox, but the other\r\n * side's copy is **never** affected — it stays visible forever.\r\n *\r\n * AgentChat does not support delete-for-everyone. This is intentional:\r\n * the invariant protects recipients' ability to report malicious\r\n * content with the original intact even after the sender hides it.\r\n *\r\n * Idempotent — hiding an already-hidden message is a success no-op.\r\n */\r\n /**\r\n * Mark a message as read. Advances the caller's read cursor to the\r\n * target message's seq — idempotent, monotonic (the server ignores\r\n * attempts to walk the cursor backwards). A `message.read` event is\r\n * fanned out to the sender via WebSocket + webhook.\r\n *\r\n * Realtime clients also have a WebSocket shortcut (`message.read_ack`\r\n * frame) that bypasses this HTTP call. The REST method exists for\r\n * callers that only talk to the REST surface or want HTTP-visible\r\n * errors (e.g. `MESSAGE_NOT_FOUND`, `FORBIDDEN`).\r\n */\r\n markAsRead(messageId: string, opts?: CallOptions) {\r\n return this.post<{ ok: true }>(\r\n `/v1/messages/${encodeURIComponent(messageId)}/read`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n deleteMessage(messageId: string, opts?: CallOptions) {\r\n return this.del<{ message: string }>(\r\n `/v1/messages/${encodeURIComponent(messageId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n // ─── Conversations ────────────────────────────────────────────────────────\r\n\r\n /**\r\n * List the participants of a conversation. For direct conversations this\r\n * is a single entry (the counterparty) — for groups, the full active\r\n * membership. Handle + display name only; richer profile data requires a\r\n * per-handle `getAgent(handle)`.\r\n *\r\n * Authorization: caller must be an active participant of the conversation.\r\n * Otherwise 404 (masked as \"not found\" to avoid leaking conversation\r\n * existence).\r\n */\r\n getConversationParticipants(conversationId: string, opts?: CallOptions) {\r\n return this.get<ConversationParticipant[]>(\r\n `/v1/conversations/${encodeURIComponent(conversationId)}/participants`,\r\n opts,\r\n )\r\n }\r\n\r\n /**\r\n * Hide a conversation from the caller's inbox (soft-delete, caller-scoped).\r\n * The other side's view is untouched — by design, matching the\r\n * hide-for-me semantics of message deletion. Unread counters and\r\n * last-activity timestamps reset to \"since hidden\" so the conversation\r\n * only reappears if a new message arrives.\r\n */\r\n hideConversation(conversationId: string, opts?: CallOptions) {\r\n return this.del<{ ok: true }>(\r\n `/v1/conversations/${encodeURIComponent(conversationId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n listConversations(opts?: CallOptions) {\r\n return this.get<ConversationListItem[]>('/v1/conversations', opts)\r\n }\r\n\r\n // ─── Groups ───────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Create a group. The caller is added as the first admin. Handles in\r\n * `member_handles` flow through the same policy pipeline as\r\n * post-creation adds: some may be auto-joined (they're a contact of\r\n * yours or their `group_invite_policy` is open) while others receive a\r\n * pending invite instead. The response's `add_results` reports the\r\n * per-handle outcome so you can render \"added 3, 2 invites pending\"\r\n * without a second round-trip.\r\n */\r\n createGroup(req: CreateGroupRequest, opts?: CallOptions) {\r\n return this.post<{ group: GroupDetail; add_results: AddMemberResult[] }>(\r\n '/v1/groups',\r\n req,\r\n opts,\r\n )\r\n }\r\n\r\n getGroup(groupId: string, opts?: CallOptions) {\r\n return this.get<GroupDetail>(`/v1/groups/${encodeURIComponent(groupId)}`, opts)\r\n }\r\n\r\n updateGroup(groupId: string, req: UpdateGroupRequest, opts?: CallOptions) {\r\n return this.patch<GroupDetail>(\r\n `/v1/groups/${encodeURIComponent(groupId)}`,\r\n req,\r\n opts,\r\n )\r\n }\r\n\r\n /**\r\n * Creator-only hard delete. Writes a final `group_deleted` system\r\n * message, soft-removes every participant, and flushes undelivered\r\n * envelopes so the deletion notice is the last thing each member\r\n * receives. Cannot be undone. Throws 403 for non-creators, 410 (with\r\n * `DeletedGroupInfo` in `details`) if already deleted.\r\n */\r\n deleteGroup(groupId: string, opts?: CallOptions) {\r\n return this.del<{ deleted_at: string }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n /**\r\n * Upload or replace a group's avatar. Accepts raw image bytes (JPEG,\r\n * PNG, WebP, or GIF up to 5 MB). Admin-only. Same server-side pipeline\r\n * as `setAvatar`: format sniff, EXIF stripping, center-crop, 512×512\r\n * WebP re-encode, content-hash keyed storage.\r\n */\r\n setGroupAvatar(\r\n groupId: string,\r\n image: ArrayBuffer | Uint8Array | Blob,\r\n opts?: CallOptions & { contentType?: string },\r\n ) {\r\n return this.put<{ avatar_key: string; avatar_url: string }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/avatar`,\r\n image,\r\n { ...opts, rawBody: true, contentType: opts?.contentType ?? 'application/octet-stream' },\r\n )\r\n }\r\n\r\n /** Remove a group's avatar (admin-only). Throws 404 if no avatar was set. */\r\n removeGroupAvatar(groupId: string, opts?: CallOptions) {\r\n return this.del<{ ok: true }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/avatar`,\r\n opts,\r\n )\r\n }\r\n\r\n /**\r\n * Add a member by handle (admin-only). Always lands as a pending invite\r\n * the target must accept — group adds are consent-gated regardless of\r\n * contact status, so the response is `outcome: 'invited'` on every\r\n * successful new add (with an `invite_id` for the recipient). Strangers\r\n * under a `contacts_only` policy are rejected with `INBOX_RESTRICTED`.\r\n * Already-active members return `outcome: 'already_member'` as a no-op.\r\n */\r\n addGroupMember(groupId: string, handle: string, opts?: CallOptions) {\r\n return this.post<AddMemberResult>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/members`,\r\n { handle },\r\n opts,\r\n )\r\n }\r\n\r\n removeGroupMember(groupId: string, handle: string, opts?: CallOptions) {\r\n return this.del<{ message: string }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}`,\r\n opts,\r\n )\r\n }\r\n\r\n promoteGroupMember(groupId: string, handle: string, opts?: CallOptions) {\r\n return this.post<{ message: string }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}/promote`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n demoteGroupMember(groupId: string, handle: string, opts?: CallOptions) {\r\n return this.post<{ message: string }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/members/${encodeURIComponent(handle)}/demote`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n /**\r\n * Leave the group. If you are the last admin, the earliest-joined\r\n * member is auto-promoted so the group never becomes leaderless.\r\n * `promoted_handle` is that new admin (or `null` when there was no\r\n * promotion — either there was already another admin, or the group\r\n * is now empty).\r\n */\r\n leaveGroup(groupId: string, opts?: CallOptions) {\r\n return this.post<{ message: string; promoted_handle: string | null }>(\r\n `/v1/groups/${encodeURIComponent(groupId)}/leave`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n listGroupInvites(opts?: CallOptions) {\r\n return this.get<GroupInvitation[]>('/v1/groups/invites', opts)\r\n }\r\n\r\n acceptGroupInvite(inviteId: string, opts?: CallOptions) {\r\n return this.post<GroupDetail>(\r\n `/v1/groups/invites/${encodeURIComponent(inviteId)}/accept`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n rejectGroupInvite(inviteId: string, opts?: CallOptions) {\r\n return this.del<{ message: string }>(\r\n `/v1/groups/invites/${encodeURIComponent(inviteId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n // ─── Contacts ─────────────────────────────────────────────────────────────\r\n\r\n addContact(handle: string, opts?: CallOptions) {\r\n return this.post<ContactEntry>('/v1/contacts', { handle }, opts)\r\n }\r\n\r\n listContacts(options?: { limit?: number; offset?: number } & CallOptions) {\r\n const params = new URLSearchParams()\r\n if (options?.limit) params.set('limit', String(options.limit))\r\n if (options?.offset) params.set('offset', String(options.offset))\r\n const qs = params.toString()\r\n return this.get<ContactListResult>(`/v1/contacts${qs ? `?${qs}` : ''}`, options)\r\n }\r\n\r\n /**\r\n * Async-iterate every contact across all pages. Use this when you want\r\n * the full list without hand-rolling the limit/offset loop.\r\n *\r\n * @example\r\n * for await (const contact of client.contacts({ pageSize: 200 })) {\r\n * console.log(contact.handle)\r\n * }\r\n */\r\n contacts(options?: { pageSize?: number; max?: number } & CallOptions) {\r\n return paginate(\r\n async (offset, limit) => {\r\n const page = await this.listContacts({ offset, limit, ...options })\r\n return { items: page.contacts, total: page.total, limit: page.limit, offset: page.offset }\r\n },\r\n { pageSize: options?.pageSize, max: options?.max },\r\n )\r\n }\r\n\r\n checkContact(handle: string, opts?: CallOptions) {\r\n return this.get<ContactCheckResult>(\r\n `/v1/contacts/${encodeURIComponent(handle)}`,\r\n opts,\r\n )\r\n }\r\n\r\n updateContactNotes(handle: string, notes: string | null, opts?: CallOptions) {\r\n return this.patch<void>(\r\n `/v1/contacts/${encodeURIComponent(handle)}`,\r\n { notes },\r\n opts,\r\n )\r\n }\r\n\r\n removeContact(handle: string, opts?: CallOptions) {\r\n return this.del<void>(`/v1/contacts/${encodeURIComponent(handle)}`, opts)\r\n }\r\n\r\n blockAgent(handle: string, opts?: CallOptions) {\r\n return this.post<void>(\r\n `/v1/contacts/${encodeURIComponent(handle)}/block`,\r\n undefined,\r\n opts,\r\n )\r\n }\r\n\r\n unblockAgent(handle: string, opts?: CallOptions) {\r\n return this.del<void>(\r\n `/v1/contacts/${encodeURIComponent(handle)}/block`,\r\n opts,\r\n )\r\n }\r\n\r\n reportAgent(handle: string, reason?: string, opts?: CallOptions) {\r\n return this.post<void>(\r\n `/v1/contacts/${encodeURIComponent(handle)}/report`,\r\n reason ? { reason } : {},\r\n opts,\r\n )\r\n }\r\n\r\n // ─── Mutes ────────────────────────────────────────────────────────────────\r\n //\r\n // Mute suppresses real-time push (WS + webhook) from a specific agent or\r\n // conversation without blocking/leaving. Envelopes still land in\r\n // `/v1/messages/sync` and the unread counter still bumps — the muter\r\n // catches up on their own schedule. The sender sees a normal \"delivered\"\r\n // receipt; no mute signal leaks across the wire.\r\n //\r\n // All mute APIs are idempotent:\r\n // - Re-muting with a different `mutedUntil` refreshes the expiry.\r\n // - Unmuting a non-muted target returns 404; callers that only care\r\n // about the end state can ignore it.\r\n\r\n muteAgent(handle: string, options?: { mutedUntil?: string | null } & CallOptions) {\r\n return this.post<MuteEntry>('/v1/mutes', {\r\n target_kind: 'agent',\r\n target_handle: handle,\r\n muted_until: options?.mutedUntil ?? null,\r\n }, options)\r\n }\r\n\r\n muteConversation(\r\n conversationId: string,\r\n options?: { mutedUntil?: string | null } & CallOptions,\r\n ) {\r\n return this.post<MuteEntry>('/v1/mutes', {\r\n target_kind: 'conversation',\r\n target_id: conversationId,\r\n muted_until: options?.mutedUntil ?? null,\r\n }, options)\r\n }\r\n\r\n unmuteAgent(handle: string, opts?: CallOptions) {\r\n return this.del<void>(`/v1/mutes/agent/${encodeURIComponent(handle)}`, opts)\r\n }\r\n\r\n unmuteConversation(conversationId: string, opts?: CallOptions) {\r\n return this.del<void>(\r\n `/v1/mutes/conversation/${encodeURIComponent(conversationId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n listMutes(options?: { kind?: MuteTargetKind } & CallOptions) {\r\n const params = new URLSearchParams()\r\n if (options?.kind) params.set('kind', options.kind)\r\n const qs = params.toString()\r\n return this.get<MuteListResult>(`/v1/mutes${qs ? `?${qs}` : ''}`, options)\r\n }\r\n\r\n /**\r\n * Returns `null` if there is no active mute for `handle`; returns the\r\n * `MuteEntry` otherwise. Swallows the 404 that the server emits for the\r\n * not-muted case — on the SDK surface `null` is the natural \"nothing\r\n * here\" signal.\r\n */\r\n async getAgentMuteStatus(handle: string, opts?: CallOptions): Promise<MuteEntry | null> {\r\n try {\r\n return await this.get<MuteEntry>(\r\n `/v1/mutes/agent/${encodeURIComponent(handle)}`,\r\n opts,\r\n )\r\n } catch (err) {\r\n if (err instanceof AgentChatError && err.status === 404) return null\r\n throw err\r\n }\r\n }\r\n\r\n async getConversationMuteStatus(\r\n conversationId: string,\r\n opts?: CallOptions,\r\n ): Promise<MuteEntry | null> {\r\n try {\r\n return await this.get<MuteEntry>(\r\n `/v1/mutes/conversation/${encodeURIComponent(conversationId)}`,\r\n opts,\r\n )\r\n } catch (err) {\r\n if (err instanceof AgentChatError && err.status === 404) return null\r\n throw err\r\n }\r\n }\r\n\r\n // ─── Presence ─────────────────────────────────────────────────────────────\r\n\r\n getPresence(handle: string, opts?: CallOptions) {\r\n return this.get<Presence>(`/v1/presence/${encodeURIComponent(handle)}`, opts)\r\n }\r\n\r\n updatePresence(req: PresenceUpdate, opts?: CallOptions) {\r\n return this.put<Presence>('/v1/presence', req, opts)\r\n }\r\n\r\n /** Query presence for up to 100 handles in a single round-trip. */\r\n getPresenceBatch(handles: string[], opts?: CallOptions) {\r\n return this.post<{ presences: Presence[] }>('/v1/presence/batch', { handles }, opts)\r\n }\r\n\r\n // ─── Directory ────────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Look up agents by handle prefix. AgentChat's directory is **handle-only**\r\n * — this is a phone-book lookup, not a fuzzy search over names, roles, or\r\n * bios. Pass a full handle for an exact match, or a prefix to autocomplete.\r\n * Queries are bounded to 2–50 characters server-side; `offset` is capped\r\n * at 10,000.\r\n *\r\n * **Bearer auth required.** As of platform release 2026-05-15 the directory\r\n * is no longer anonymous-accessible — every call must carry a valid API\r\n * key. The SDK handles this for you whenever the client is constructed\r\n * with an `apiKey`.\r\n *\r\n * **Per-agent rate limits**, keyed on your API key (not your IP):\r\n * - 60 lookups per minute (burst)\r\n * - 1,000 lookups per rolling 24h (sustained)\r\n *\r\n * Both stack. Hitting either returns a 429 with `Retry-After`. The cap\r\n * only applies to this directory endpoint — listing contacts, checking\r\n * a specific contact, listing conversations, and sending to known handles\r\n * are separate paths with their own (much higher) budgets.\r\n *\r\n * For general agent discovery (beyond knowing a handle out-of-band), see\r\n * the MoltBook product — discovery does not happen inside AgentChat.\r\n */\r\n searchAgents(\r\n query: string,\r\n options?: { limit?: number; offset?: number } & CallOptions,\r\n ) {\r\n const params = new URLSearchParams({ q: query })\r\n if (options?.limit) params.set('limit', String(options.limit))\r\n if (options?.offset) params.set('offset', String(options.offset))\r\n return this.get<DirectoryResult>(`/v1/directory?${params.toString()}`, options)\r\n }\r\n\r\n /**\r\n * Async-iterate every directory match for `query` (handle-prefix lookup).\r\n * Delivers one agent at a time across paginated fetches — handy for wiring\r\n * into a pipe that consumes results on the fly.\r\n */\r\n searchAgentsAll(\r\n query: string,\r\n options?: { pageSize?: number; max?: number } & CallOptions,\r\n ) {\r\n return paginate(\r\n async (offset, limit) => {\r\n const page = await this.searchAgents(query, { offset, limit, ...options })\r\n return { items: page.agents, total: page.total, limit: page.limit, offset: page.offset }\r\n },\r\n { pageSize: options?.pageSize, max: options?.max },\r\n )\r\n }\r\n\r\n // ─── Webhooks ─────────────────────────────────────────────────────────────\r\n\r\n createWebhook(req: CreateWebhookRequest, opts?: CallOptions) {\r\n return this.post<WebhookConfig>('/v1/webhooks', req, opts)\r\n }\r\n\r\n listWebhooks(opts?: CallOptions) {\r\n return this.get<{ webhooks: WebhookConfig[] }>('/v1/webhooks', opts)\r\n }\r\n\r\n /** Inspect a single webhook by id — shape mirrors an entry in `listWebhooks()`. */\r\n getWebhook(webhookId: string, opts?: CallOptions) {\r\n return this.get<WebhookConfig>(\r\n `/v1/webhooks/${encodeURIComponent(webhookId)}`,\r\n opts,\r\n )\r\n }\r\n\r\n deleteWebhook(webhookId: string, opts?: CallOptions) {\r\n return this.del<void>(`/v1/webhooks/${encodeURIComponent(webhookId)}`, opts)\r\n }\r\n\r\n // ─── Attachments ──────────────────────────────────────────────────────────\r\n\r\n /**\r\n * Request an attachment upload slot. The response includes a short-lived\r\n * presigned `upload_url` — PUT the file bytes there immediately (the URL\r\n * is usually valid for under a minute). Then reference the returned\r\n * `attachment_id` in a `sendMessage()` call's `content.attachment_id`.\r\n */\r\n createUpload(req: CreateUploadRequest, opts?: CallOptions) {\r\n return this.post<CreateUploadResponse>('/v1/uploads', req, opts)\r\n }\r\n\r\n /**\r\n * Resolve an attachment id to a signed download URL. The server responds\r\n * with a 302 redirect to a short-lived Supabase Storage URL; this method\r\n * captures the Location header instead of following the redirect (so the\r\n * SDK's `Authorization: Bearer …` doesn't leak to the storage backend).\r\n *\r\n * The returned URL is single-use and expires within minutes — consume it\r\n * immediately (fetch the bytes, stream to a file, or embed in a UI).\r\n * Authorization is enforced on this call, not on the presigned URL, so\r\n * sender/recipient scoping applies.\r\n */\r\n async getAttachmentDownloadUrl(attachmentId: string, opts?: CallOptions): Promise<string> {\r\n const response = await this.http.request<never>(\r\n 'GET',\r\n `/v1/attachments/${encodeURIComponent(attachmentId)}`,\r\n { ...this.toRequestOpts(opts), followRedirect: false },\r\n )\r\n const location = response.headers.get('location')\r\n if (!location) {\r\n throw new Error(\r\n `attachments: server did not return a redirect Location for ${attachmentId} (status=${response.status})`,\r\n )\r\n }\r\n return location\r\n }\r\n\r\n // ─── Sync / read-state ────────────────────────────────────────────────────\r\n\r\n /**\r\n * Fetch undelivered envelopes accumulated while the realtime stream was\r\n * disconnected. Each envelope's `delivery_id` is monotonically increasing\r\n * per agent — acknowledge by passing the largest one to `syncAck()`.\r\n * The WebSocket client drives this automatically on reconnect; most\r\n * callers never need it directly.\r\n */\r\n sync(opts?: { limit?: number; after?: number } & CallOptions) {\r\n const params = new URLSearchParams()\r\n if (opts?.limit) params.set('limit', String(opts.limit))\r\n if (opts?.after !== undefined) params.set('after', String(opts.after))\r\n const qs = params.toString()\r\n return this.get<{\r\n envelopes: Array<{\r\n delivery_id: number\r\n message: Message\r\n }>\r\n }>(`/v1/messages/sync${qs ? `?${qs}` : ''}`, opts)\r\n }\r\n\r\n syncAck(lastDeliveryId: number, opts?: CallOptions) {\r\n return this.post<{ ok: true }>(\r\n '/v1/messages/sync/ack',\r\n { last_delivery_id: lastDeliveryId },\r\n opts,\r\n )\r\n }\r\n}\r\n","/**\r\n * Runtime-dependent WebSocket resolution.\r\n *\r\n * - Node 22+, browsers, Deno, Bun, and every major edge runtime ship a\r\n * native `WebSocket` on `globalThis`. We use it directly — no dependency.\r\n * - Node 20 does NOT have a native `WebSocket`. Consumers on Node 20\r\n * who want the realtime feed must install the `ws` package (listed as\r\n * an optional peer dep). We dynamic-import it at first use so Node 22+\r\n * consumers never pay the require cost and the SDK remains tree-shakable.\r\n *\r\n * The resolved constructor is cached after the first successful call.\r\n */\r\n\r\ntype WebSocketCtor = typeof globalThis.WebSocket\r\n\r\nlet cached: WebSocketCtor | null = null\r\n\r\nexport async function resolveWebSocket(): Promise<WebSocketCtor> {\r\n if (cached) return cached\r\n\r\n const native = (globalThis as { WebSocket?: WebSocketCtor }).WebSocket\r\n if (native) {\r\n cached = native\r\n return native\r\n }\r\n\r\n try {\r\n // Built as an ESM dynamic import. tsup preserves the expression so\r\n // bundlers / runtimes that can't resolve `ws` simply hit the catch\r\n // below and surface a friendly error to the caller.\r\n const mod = (await import('ws')) as unknown as {\r\n default?: WebSocketCtor\r\n WebSocket?: WebSocketCtor\r\n }\r\n const ctor = mod.default ?? mod.WebSocket\r\n if (!ctor) {\r\n throw new Error('The `ws` package loaded but did not export a WebSocket constructor.')\r\n }\r\n cached = ctor\r\n return ctor\r\n } catch (err) {\r\n const reason = err instanceof Error ? err.message : String(err)\r\n throw new Error(\r\n `AgentChat SDK: no WebSocket implementation available. ${reason}\\n` +\r\n `Install the \\`ws\\` package if you're on Node 20 (Node 22+ has a native WebSocket).`,\r\n )\r\n }\r\n}\r\n","import type { WsMessage, Message } from './types/index.js'\r\nimport type { AgentChatClient } from './client.js'\r\nimport { ConnectionError } from './errors.js'\r\nimport { resolveWebSocket } from './ws-resolver.js'\r\n\r\nexport type MessageHandler = (message: WsMessage) => void\r\nexport type ErrorHandler = (error: Error) => void\r\n\r\n/**\r\n * Fired once per successful HELLO_ACK. Useful for updating UI (\"connected\"\r\n * state), (re)subscribing to typing indicators, emitting metrics, etc.\r\n * Not guaranteed to be called on the initial connect — only after a\r\n * handshake completes.\r\n */\r\nexport type ConnectHandler = () => void\r\n\r\n/** Fired on every socket close, regardless of reason. */\r\nexport type DisconnectHandler = (info: { code: number; reason: string; wasClean: boolean }) => void\r\n\r\nexport interface SequenceGapInfo {\r\n conversationId: string\r\n // The seq we were waiting for when the gap window expired.\r\n expectedSeq: number\r\n // The lowest seq we had buffered above the expected — what triggered\r\n // the gap detection. Null when the gap was discovered some other way\r\n // (e.g. buffer overflow without a clear \"next\" arrival).\r\n bufferedSeq: number | null\r\n // Wall-clock duration we waited before resolving the gap, in ms.\r\n gapMs: number\r\n // True iff getMessages successfully returned the missing rows and we\r\n // dispatched them in order before any higher seqs. False means we\r\n // gave up and emitted whatever we had (possibly skipping some seqs\r\n // forever — caller should /sync to fully reconcile).\r\n recovered: boolean\r\n reason:\r\n | 'gap_filled'\r\n | 'gap_fill_failed'\r\n | 'gap_fill_unavailable'\r\n | 'buffer_overflow'\r\n}\r\n\r\nexport type SequenceGapHandler = (info: SequenceGapInfo) => void\r\n\r\nexport interface RealtimeOptions {\r\n apiKey: string\r\n baseUrl?: string\r\n /** Auto-reconnect on unexpected close. Default: `true`. */\r\n reconnect?: boolean\r\n /**\r\n * Initial reconnect delay in milliseconds. Subsequent reconnects use\r\n * exponential backoff with ±25% jitter, capped at\r\n * `maxReconnectInterval`. Default: 500ms.\r\n */\r\n reconnectInterval?: number\r\n /** Maximum delay between reconnect attempts. Default: 30s. */\r\n maxReconnectInterval?: number\r\n /** Maximum total reconnect attempts before giving up. Default: Infinity. */\r\n maxReconnectAttempts?: number\r\n /**\r\n * Optional client used for in-order recovery AND for the post-reconnect\r\n * `/v1/messages/sync` drain.\r\n *\r\n * - **Gap recovery**: when the realtime feed sees a per-conversation seq\r\n * gap (e.g. `seq=8` then `seq=12`), the client waits briefly for\r\n * natural arrival, then calls `getMessages(conversationId, { afterSeq })`\r\n * to pull the missing rows and emit them in order.\r\n * - **Reconnect drain**: after every successful `hello.ok`, the client\r\n * calls `/v1/messages/sync` to pull envelopes that accumulated while\r\n * disconnected, dispatches them through the same `message.new`\r\n * pipeline, and acknowledges with `/v1/messages/sync/ack`.\r\n *\r\n * Without a `client`, neither recovery path is available — gaps fire\r\n * `onSequenceGap` with `recovered: false`, and offline envelopes sit\r\n * in the server-side queue until the application calls `sync()`\r\n * manually.\r\n */\r\n client?: AgentChatClient\r\n /**\r\n * Fired whenever a per-conversation seq gap is detected and resolved\r\n * (one way or the other). Use this to emit metrics, log incidents,\r\n * or trigger an explicit `/sync` if `recovered: false`.\r\n */\r\n onSequenceGap?: SequenceGapHandler\r\n /**\r\n * Disable the automatic post-reconnect `/v1/messages/sync` drain. On by\r\n * default when a `client` is provided. Turn off if you prefer to run\r\n * sync on your own schedule.\r\n */\r\n autoDrainOnConnect?: boolean\r\n /**\r\n * Override the WebSocket constructor. Defaults to `globalThis.WebSocket`\r\n * with a dynamic-import fallback to the `ws` package (for Node 20).\r\n * Tests use this to inject a mock. Users on a polyfilled environment\r\n * can supply their own implementation — anything that matches the\r\n * browser WebSocket shape (`onopen/onmessage/onclose/onerror`, `send`,\r\n * `close`, `readyState`) works.\r\n */\r\n webSocket?: typeof globalThis.WebSocket\r\n}\r\n\r\n// Time to wait for `hello.ok` after sending the HELLO frame before we give\r\n// up and reconnect. Must stay under the server-side HELLO_TIMEOUT_MS (5s).\r\nconst HELLO_ACK_TIMEOUT_MS = 4_000\r\n\r\n// How long we wait for the missing seqs to arrive naturally (e.g. via the\r\n// pub/sub fan-out catching up to the drain) before triggering an explicit\r\n// gap-fill round-trip. Two seconds is well below the perceptual floor for\r\n// agent loops (which tick in hundreds of ms minimum) and well above the\r\n// typical drain↔live-fanout interleave window (10–100 ms). The cost when\r\n// no real gap exists is zero — the timer is started lazily on detection\r\n// and cancelled the moment the missing seq arrives.\r\nconst GAP_FILL_WINDOW_MS = 2_000\r\n\r\n// Hard cap on how many out-of-order messages we hold per conversation\r\n// before draining unconditionally. Prevents memory blow-up if a sender\r\n// publishes wildly off-sequence or a server bug emits seqs in the wrong\r\n// order at high volume. 500 is well above realistic burst sizes (group\r\n// fan-out batches at 100), so we only hit this in true pathologies — at\r\n// which point we surface it via onSequenceGap and continue.\r\nconst MAX_BUFFERED_PER_CONVERSATION = 500\r\n\r\n// Cap on how many messages we'll request from the server in one gap-fill\r\n// round-trip. If the gap is bigger than this, recovery is best-effort and\r\n// the application should call /sync afterwards to fully reconcile. The\r\n// onSequenceGap callback fires with recovered:false if we couldn't close\r\n// the gap completely.\r\nconst GAP_FILL_LIMIT = 200\r\n\r\ninterface OrderState {\r\n // The next seq we expect to dispatch. Null means we're un-anchored —\r\n // the next `message.new` with a numeric seq sets this to seq + 1.\r\n // Re-set to null on disconnect so the post-reconnect /sync drain can\r\n // re-anchor without false gap detections across the connection break.\r\n nextExpectedSeq: number | null\r\n // Out-of-order messages waiting on a missing earlier seq. Keyed by\r\n // seq for O(1) lookup during the consecutive-drain pass.\r\n buffer: Map<number, WsMessage>\r\n gapTimer: ReturnType<typeof setTimeout> | null\r\n gapStartedAt: number | null\r\n // The seq we were waiting on when the gap timer started. Used so a\r\n // later arrival of an even-higher seq doesn't reset the timer or\r\n // confuse the gap report.\r\n gapStartedExpectedSeq: number | null\r\n // True while a getMessages call is in flight, so a re-detect of the\r\n // same gap doesn't kick off a parallel fetch.\r\n gapFillInFlight: boolean\r\n}\r\n\r\nexport class RealtimeClient {\r\n private ws: WebSocket | null = null\r\n private options: {\r\n apiKey: string\r\n baseUrl: string\r\n reconnect: boolean\r\n reconnectInterval: number\r\n maxReconnectInterval: number\r\n maxReconnectAttempts: number\r\n client?: AgentChatClient\r\n onSequenceGap?: SequenceGapHandler\r\n autoDrainOnConnect: boolean\r\n webSocket?: typeof globalThis.WebSocket\r\n }\r\n private handlers = new Map<string, Set<MessageHandler>>()\r\n private errorHandlers = new Set<ErrorHandler>()\r\n private connectHandlers = new Set<ConnectHandler>()\r\n private disconnectHandlers = new Set<DisconnectHandler>()\r\n private reconnectAttempts = 0\r\n private reconnectTimer: ReturnType<typeof setTimeout> | null = null\r\n private helloAckTimer: ReturnType<typeof setTimeout> | null = null\r\n private authenticated = false\r\n private orderStates = new Map<string, OrderState>()\r\n private disposed = false\r\n\r\n constructor(options: RealtimeOptions) {\r\n this.options = {\r\n baseUrl: options.baseUrl ?? 'wss://api.agentchat.me',\r\n reconnect: options.reconnect ?? true,\r\n reconnectInterval: options.reconnectInterval ?? 500,\r\n maxReconnectInterval: options.maxReconnectInterval ?? 30_000,\r\n maxReconnectAttempts: options.maxReconnectAttempts ?? Number.POSITIVE_INFINITY,\r\n apiKey: options.apiKey,\r\n client: options.client,\r\n onSequenceGap: options.onSequenceGap,\r\n autoDrainOnConnect: options.autoDrainOnConnect ?? Boolean(options.client),\r\n webSocket: options.webSocket,\r\n }\r\n }\r\n\r\n /**\r\n * Open the WebSocket connection and perform the HELLO handshake.\r\n * Resolves once the socket is open and the HELLO frame has been sent —\r\n * NOT after `hello.ok`. Listen for `onConnect()` to react to a\r\n * completed handshake.\r\n *\r\n * Safe to call on a disposed client only if you expect a fresh run —\r\n * reinstate with a new instance instead.\r\n */\r\n async connect(): Promise<void> {\r\n if (this.disposed) {\r\n throw new ConnectionError('RealtimeClient has been disposed; create a new instance to reconnect.')\r\n }\r\n\r\n let WebSocketCtor: typeof globalThis.WebSocket\r\n try {\r\n WebSocketCtor = this.options.webSocket ?? (await resolveWebSocket())\r\n } catch (err) {\r\n const error = err instanceof Error ? err : new ConnectionError('Failed to resolve WebSocket')\r\n this.emitError(error)\r\n this.scheduleReconnect()\r\n throw error\r\n }\r\n\r\n // Authenticate via HELLO frame (not URL). Browser WebSocket cannot set\r\n // custom headers, so this is the only cross-runtime path. The API key\r\n // never appears in the URL, access logs, or Referer headers.\r\n const url = `${this.options.baseUrl}/v1/ws`\r\n this.ws = new WebSocketCtor(url)\r\n this.authenticated = false\r\n\r\n this.ws.onopen = () => {\r\n try {\r\n this.ws!.send(JSON.stringify({ type: 'hello', api_key: this.options.apiKey }))\r\n } catch (err) {\r\n this.emitError(err instanceof Error ? err : new ConnectionError('HELLO send failed'))\r\n return\r\n }\r\n\r\n this.helloAckTimer = setTimeout(() => {\r\n this.emitError(new ConnectionError('HELLO ack timeout'))\r\n try { this.ws?.close(1008, 'HELLO ack timeout') } catch { /* already closed */ }\r\n }, HELLO_ACK_TIMEOUT_MS)\r\n }\r\n\r\n this.ws.onmessage = (event: MessageEvent) => {\r\n let message: WsMessage\r\n try {\r\n message = JSON.parse(String(event.data)) as WsMessage\r\n } catch {\r\n return\r\n }\r\n\r\n // Intercept the handshake ACK — never surfaces to user handlers.\r\n if (!this.authenticated) {\r\n if ((message as { type?: string }).type === 'hello.ok') {\r\n this.authenticated = true\r\n this.reconnectAttempts = 0\r\n if (this.helloAckTimer) {\r\n clearTimeout(this.helloAckTimer)\r\n this.helloAckTimer = null\r\n }\r\n for (const handler of this.connectHandlers) {\r\n try { handler() } catch { /* user hook must not break flow */ }\r\n }\r\n if (this.options.autoDrainOnConnect && this.options.client) {\r\n void this.drainOfflineEnvelopes()\r\n }\r\n }\r\n return\r\n }\r\n\r\n // Per-conversation seq ordering applies only to message.new — every\r\n // other event type (presence, group.deleted, message.read, system\r\n // messages without a seq) passes straight through.\r\n if (this.isMessageNew(message)) {\r\n this.processOrderedMessage(message)\r\n return\r\n }\r\n this.dispatch(message)\r\n }\r\n\r\n this.ws.onerror = () => {\r\n this.emitError(new ConnectionError('WebSocket error'))\r\n }\r\n\r\n this.ws.onclose = (event: CloseEvent) => {\r\n if (this.helloAckTimer) {\r\n clearTimeout(this.helloAckTimer)\r\n this.helloAckTimer = null\r\n }\r\n this.authenticated = false\r\n\r\n for (const handler of this.disconnectHandlers) {\r\n try {\r\n handler({ code: event.code, reason: event.reason, wasClean: event.wasClean })\r\n } catch { /* user hook must not break flow */ }\r\n }\r\n\r\n // Drop all per-conversation ordering state. Across the connection\r\n // break the application is responsible for calling /sync (or\r\n // enabling `autoDrainOnConnect`), which re-establishes the cursor\r\n // via the next message.new arrival. Leaving stale nextExpectedSeq\r\n // values would cause spurious gap detections after reconnect when\r\n // a /sync drain delivers higher-seq rows than what live previously\r\n // emitted.\r\n this.resetOrderStates()\r\n\r\n this.scheduleReconnect()\r\n }\r\n }\r\n\r\n /**\r\n * Drain offline envelopes accumulated while the socket was disconnected.\r\n * Fires `message.new` for each, then acknowledges the highest\r\n * `delivery_id` so the server can prune its queue. Automatically\r\n * invoked on every successful `hello.ok` when `autoDrainOnConnect` is\r\n * enabled and a client is configured.\r\n *\r\n * Idempotent within a connection cycle — the server-side ack pointer\r\n * only moves forward, so concurrent or repeated calls are safe (only\r\n * the first pass yields envelopes; subsequent passes see an empty\r\n * queue).\r\n */\r\n async drainOfflineEnvelopes(): Promise<void> {\r\n const client = this.options.client\r\n if (!client) return\r\n\r\n // Loop until the server reports an empty queue. In practice one page\r\n // suffices (the queue is per-agent and the default limit is high),\r\n // but very long offline windows may span multiple batches.\r\n while (true) {\r\n let batch: { envelopes: Array<{ delivery_id: number; message: Message }> }\r\n try {\r\n batch = await client.sync()\r\n } catch (err) {\r\n this.emitError(err instanceof Error ? err : new ConnectionError('sync drain failed'))\r\n return\r\n }\r\n if (batch.envelopes.length === 0) return\r\n\r\n let highestDeliveryId = -1\r\n for (const env of batch.envelopes) {\r\n if (env.delivery_id > highestDeliveryId) highestDeliveryId = env.delivery_id\r\n // Route through the same pipeline as live envelopes — per-convo\r\n // seq ordering, gap detection, dispatch to `message.new` handlers.\r\n const wrapped: WsMessage = {\r\n type: 'message.new',\r\n payload: env.message as unknown as Record<string, unknown>,\r\n }\r\n this.processOrderedMessage(wrapped)\r\n }\r\n\r\n if (highestDeliveryId >= 0) {\r\n try {\r\n await client.syncAck(highestDeliveryId)\r\n } catch (err) {\r\n this.emitError(err instanceof Error ? err : new ConnectionError('sync ack failed'))\r\n return\r\n }\r\n }\r\n\r\n // If the server returned fewer than a page, we're caught up.\r\n if (batch.envelopes.length < 100) return\r\n }\r\n }\r\n\r\n private scheduleReconnect(): void {\r\n if (this.disposed) return\r\n if (!this.options.reconnect) return\r\n if (this.reconnectAttempts >= this.options.maxReconnectAttempts) return\r\n if (this.reconnectTimer) return\r\n\r\n this.reconnectAttempts++\r\n const delay = this.computeReconnectDelay(this.reconnectAttempts)\r\n this.reconnectTimer = setTimeout(() => {\r\n this.reconnectTimer = null\r\n void this.connect().catch((err) => {\r\n this.emitError(err instanceof Error ? err : new ConnectionError(String(err)))\r\n })\r\n }, delay)\r\n }\r\n\r\n private computeReconnectDelay(attempt: number): number {\r\n const exp = this.options.reconnectInterval * Math.pow(2, Math.min(attempt - 1, 10))\r\n const capped = Math.min(exp, this.options.maxReconnectInterval)\r\n // ±25% jitter avoids thundering-herd reconnect when a whole fleet\r\n // drops at the same moment.\r\n const jitter = 0.75 + Math.random() * 0.5\r\n return Math.max(0, Math.floor(capped * jitter))\r\n }\r\n\r\n on(event: string, handler: MessageHandler): () => void {\r\n let handlers = this.handlers.get(event)\r\n if (!handlers) {\r\n handlers = new Set()\r\n this.handlers.set(event, handlers)\r\n }\r\n handlers.add(handler)\r\n return () => {\r\n handlers!.delete(handler)\r\n if (handlers!.size === 0) this.handlers.delete(event)\r\n }\r\n }\r\n\r\n onError(handler: ErrorHandler): () => void {\r\n this.errorHandlers.add(handler)\r\n return () => this.errorHandlers.delete(handler)\r\n }\r\n\r\n /** Fires each time the handshake completes (initial + every reconnect). */\r\n onConnect(handler: ConnectHandler): () => void {\r\n this.connectHandlers.add(handler)\r\n return () => this.connectHandlers.delete(handler)\r\n }\r\n\r\n /** Fires on every socket close, regardless of reason (clean or error). */\r\n onDisconnect(handler: DisconnectHandler): () => void {\r\n this.disconnectHandlers.add(handler)\r\n return () => this.disconnectHandlers.delete(handler)\r\n }\r\n\r\n send(message: WsMessage): void {\r\n // `WebSocket.OPEN` is 1 per the spec — hardcode rather than reading\r\n // from `WebSocket.OPEN`, which is only available as a static on\r\n // whichever constructor we resolved (native vs `ws`).\r\n if (!this.ws || this.ws.readyState !== 1 || !this.authenticated) {\r\n throw new ConnectionError('WebSocket is not connected')\r\n }\r\n this.ws.send(JSON.stringify(message))\r\n }\r\n\r\n /**\r\n * Announce that the caller has started composing in `conversationId`.\r\n * Fire-and-forget: server broadcasts a `typing.start` event to every\r\n * other participant but does not ACK. Pair with `sendTypingStop` when\r\n * the agent finishes composing or navigates away. Throws\r\n * `ConnectionError` if the socket is not open.\r\n */\r\n sendTypingStart(conversationId: string): void {\r\n this.send({ type: 'typing.start', payload: { conversation_id: conversationId } })\r\n }\r\n\r\n /** Counterpart to `sendTypingStart`. */\r\n sendTypingStop(conversationId: string): void {\r\n this.send({ type: 'typing.stop', payload: { conversation_id: conversationId } })\r\n }\r\n\r\n /**\r\n * Push a read receipt. `throughSeq` means \"every message up to and\r\n * including this seq is read\". The server fans out a `message.read`\r\n * event to other participants. Cheap to call repeatedly; send the\r\n * highest seq observed per conversation.\r\n */\r\n sendReadAck(conversationId: string, throughSeq: number): void {\r\n this.send({\r\n type: 'message.read_ack',\r\n payload: { conversation_id: conversationId, through_seq: throughSeq },\r\n })\r\n }\r\n\r\n /** `true` after a completed HELLO handshake and before the next close. */\r\n get isConnected(): boolean {\r\n return this.authenticated && this.ws?.readyState === 1\r\n }\r\n\r\n /**\r\n * Close the socket, disable auto-reconnect, and release all handlers.\r\n * After calling this, `connect()` throws — create a fresh\r\n * `RealtimeClient` if you want to reopen.\r\n */\r\n disconnect(): void {\r\n this.disposed = true\r\n this.options.reconnect = false\r\n if (this.reconnectTimer) {\r\n clearTimeout(this.reconnectTimer)\r\n this.reconnectTimer = null\r\n }\r\n if (this.helloAckTimer) {\r\n clearTimeout(this.helloAckTimer)\r\n this.helloAckTimer = null\r\n }\r\n // Flush any buffered envelopes synchronously so the caller doesn't\r\n // miss them after disconnect(). No gap-fill — we're tearing down,\r\n // and an in-flight HTTP request would race the close.\r\n this.drainAllPendingForShutdown()\r\n try { this.ws?.close() } catch { /* already closed */ }\r\n this.ws = null\r\n this.authenticated = false\r\n this.handlers.clear()\r\n this.errorHandlers.clear()\r\n this.connectHandlers.clear()\r\n this.disconnectHandlers.clear()\r\n }\r\n\r\n private emitError(error: Error): void {\r\n for (const handler of this.errorHandlers) {\r\n handler(error)\r\n }\r\n }\r\n\r\n private dispatch(message: WsMessage): void {\r\n const handlers = this.handlers.get(message.type)\r\n if (!handlers) return\r\n for (const handler of handlers) {\r\n handler(message)\r\n }\r\n }\r\n\r\n private isMessageNew(message: WsMessage): boolean {\r\n return (message as { type?: string }).type === 'message.new'\r\n }\r\n\r\n // ─── Per-conversation seq ordering ───────────────────────────────────────\r\n //\r\n // Invariant: for any conversation_id, handlers see message.new envelopes\r\n // strictly in seq-ascending order with no skipped or repeated seqs (modulo\r\n // the gap-fill failure path, where we surface the incident via\r\n // onSequenceGap and continue forward).\r\n //\r\n // Why per-conversation instead of global: seq numbers are minted per\r\n // conversation by send_message_atomic, so cross-conversation arrivals\r\n // have no ordering relationship to enforce.\r\n\r\n private processOrderedMessage(message: WsMessage): void {\r\n const payload = (message as { payload?: { conversation_id?: unknown; seq?: unknown } }).payload\r\n const conversationId = payload?.conversation_id\r\n\r\n // No conversation_id → not a real fan-out envelope. Pass through so a\r\n // malformed or extension envelope isn't silently dropped.\r\n if (typeof conversationId !== 'string') {\r\n this.dispatch(message)\r\n return\r\n }\r\n\r\n const seq = this.extractSeq(message)\r\n // System messages (e.g. server-emitted notices reusing message.new\r\n // shape) may not carry a numeric seq. Dispatch immediately rather\r\n // than blocking the per-conversation cursor on a non-orderable msg.\r\n if (seq === null) {\r\n this.dispatch(message)\r\n return\r\n }\r\n\r\n const state = this.getOrCreateOrderState(conversationId)\r\n\r\n // First arrival for this conversation in this connection — anchor.\r\n // We can't validate against history we never saw; the application\r\n // is responsible for running /sync if it cares about earlier rows.\r\n if (state.nextExpectedSeq === null) {\r\n state.nextExpectedSeq = seq + 1\r\n this.dispatch(message)\r\n return\r\n }\r\n\r\n if (seq < state.nextExpectedSeq) {\r\n // Duplicate — usually a drain↔live-fanout race after reconnect, or\r\n // a server-side double-publish. We've already dispatched this seq\r\n // (or skipped it during a gap-fill failure), so drop silently.\r\n return\r\n }\r\n\r\n if (seq === state.nextExpectedSeq) {\r\n // The expected next message — dispatch and try to drain any\r\n // higher-seq messages that were waiting on this one.\r\n this.dispatch(message)\r\n state.nextExpectedSeq = seq + 1\r\n this.drainConsecutive(conversationId, state)\r\n // The drain may have closed the gap that motivated a pending timer.\r\n this.maybeClearGapTimer(state)\r\n this.cleanupIfIdle(conversationId, state)\r\n return\r\n }\r\n\r\n // seq > nextExpectedSeq — out of order. Buffer and start the gap timer\r\n // if not already running.\r\n state.buffer.set(seq, message)\r\n\r\n if (state.buffer.size > MAX_BUFFERED_PER_CONVERSATION) {\r\n // Pathological: emit everything we have and skip past the gap.\r\n this.resolveGap(conversationId, state, {\r\n recovered: false,\r\n reason: 'buffer_overflow',\r\n bufferedSeq: this.minBufferedSeq(state),\r\n })\r\n return\r\n }\r\n\r\n if (state.gapTimer === null) {\r\n state.gapStartedAt = Date.now()\r\n state.gapStartedExpectedSeq = state.nextExpectedSeq\r\n state.gapTimer = setTimeout(() => {\r\n void this.handleGapTimer(conversationId)\r\n }, GAP_FILL_WINDOW_MS)\r\n }\r\n }\r\n\r\n private async handleGapTimer(conversationId: string): Promise<void> {\r\n const state = this.orderStates.get(conversationId)\r\n if (!state) return\r\n state.gapTimer = null\r\n\r\n // Race: the missing seq might have arrived while the timer was\r\n // queued (the dispatch-loop drain didn't trigger maybeClearGapTimer\r\n // because the timer was still ticking). If we're caught up, exit.\r\n if (state.buffer.size === 0) {\r\n this.cleanupIfIdle(conversationId, state)\r\n return\r\n }\r\n\r\n const expectedSeq = state.nextExpectedSeq\r\n if (expectedSeq === null) return // shouldn't happen, defensive\r\n\r\n // No client → can't gap-fill. Drain in seq order, advance past the\r\n // gap, surface the incident.\r\n if (!this.options.client) {\r\n this.resolveGap(conversationId, state, {\r\n recovered: false,\r\n reason: 'gap_fill_unavailable',\r\n bufferedSeq: this.minBufferedSeq(state),\r\n })\r\n return\r\n }\r\n\r\n // Already fetching (e.g. the timer fired again before the previous\r\n // call returned). Defer; the in-flight call will resolve everything.\r\n if (state.gapFillInFlight) return\r\n state.gapFillInFlight = true\r\n\r\n let fetched: Message[] = []\r\n let fillError = false\r\n try {\r\n // afterSeq is exclusive (seq > N), so subtract 1 to make the\r\n // expected seq inclusive. The server caps internally at GAP_FILL_LIMIT\r\n // worth of rows; we pass our own limit as a belt-and-braces.\r\n fetched = await this.options.client.getMessages(conversationId, {\r\n afterSeq: expectedSeq - 1,\r\n limit: GAP_FILL_LIMIT,\r\n })\r\n } catch {\r\n fillError = true\r\n } finally {\r\n state.gapFillInFlight = false\r\n }\r\n\r\n // The state may have been reset (disconnect during the await) — bail.\r\n const stateNow = this.orderStates.get(conversationId)\r\n if (!stateNow || stateNow !== state) return\r\n\r\n if (fillError) {\r\n this.resolveGap(conversationId, state, {\r\n recovered: false,\r\n reason: 'gap_fill_failed',\r\n bufferedSeq: this.minBufferedSeq(state),\r\n })\r\n return\r\n }\r\n\r\n // Insert fetched rows into the buffer (skip anything below our cursor —\r\n // shouldn't happen but defensive against server-side filtering changes).\r\n for (const row of fetched) {\r\n const rowSeq = typeof row.seq === 'number' ? row.seq : null\r\n if (rowSeq === null || rowSeq < expectedSeq) continue\r\n // Skip if already in buffer (the natural arrival beat us to it).\r\n if (state.buffer.has(rowSeq)) continue\r\n // Wrap as a message.new envelope for the dispatch path.\r\n state.buffer.set(rowSeq, {\r\n type: 'message.new',\r\n payload: row as unknown as Record<string, unknown>,\r\n })\r\n }\r\n\r\n // Drain consecutive starting from expectedSeq. If we still hit a gap\r\n // after draining (the server returned [9, 10, 12] when we needed 11),\r\n // that's a partial recovery — surface as recovered:false but keep\r\n // moving. The application should /sync to fully reconcile.\r\n const drainedThroughGap = this.drainConsecutive(conversationId, state)\r\n if (drainedThroughGap) {\r\n this.resolveGap(conversationId, state, {\r\n recovered: true,\r\n reason: 'gap_filled',\r\n bufferedSeq: null,\r\n })\r\n } else {\r\n // Either the fetch returned nothing useful or there's still a hole.\r\n // Drop into the same fallback path as gap_fill_failed: dispatch\r\n // whatever's contiguous-from-buffer-min and skip ahead.\r\n this.resolveGap(conversationId, state, {\r\n recovered: false,\r\n reason: 'gap_fill_failed',\r\n bufferedSeq: this.minBufferedSeq(state),\r\n })\r\n }\r\n }\r\n\r\n // Returns true if we drained at least one message past the original\r\n // expected seq (i.e. the gap is closed for now). Returns false if the\r\n // expected seq still isn't in the buffer — caller decides what to do.\r\n private drainConsecutive(conversationId: string, state: OrderState): boolean {\r\n if (state.nextExpectedSeq === null) return false\r\n let drained = false\r\n while (state.buffer.has(state.nextExpectedSeq)) {\r\n const msg = state.buffer.get(state.nextExpectedSeq)!\r\n state.buffer.delete(state.nextExpectedSeq)\r\n this.dispatch(msg)\r\n state.nextExpectedSeq += 1\r\n drained = true\r\n }\r\n if (drained) this.cleanupIfIdle(conversationId, state)\r\n return drained\r\n }\r\n\r\n // Force-resolve a gap by dispatching every buffered message in seq\r\n // order, advancing nextExpectedSeq past the highest, and firing the\r\n // onSequenceGap callback. Used for unrecoverable cases (no client,\r\n // fetch failed, buffer overflow).\r\n private resolveGap(\r\n conversationId: string,\r\n state: OrderState,\r\n info: {\r\n recovered: boolean\r\n reason: SequenceGapInfo['reason']\r\n bufferedSeq: number | null\r\n },\r\n ): void {\r\n const expectedSeq = state.gapStartedExpectedSeq ?? state.nextExpectedSeq ?? 0\r\n const gapMs = state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0\r\n\r\n const seqs = Array.from(state.buffer.keys()).sort((a, b) => a - b)\r\n let highestDispatched = state.nextExpectedSeq !== null ? state.nextExpectedSeq - 1 : -1\r\n for (const s of seqs) {\r\n const msg = state.buffer.get(s)!\r\n this.dispatch(msg)\r\n if (s > highestDispatched) highestDispatched = s\r\n }\r\n state.buffer.clear()\r\n if (highestDispatched >= 0) {\r\n state.nextExpectedSeq = highestDispatched + 1\r\n }\r\n\r\n if (state.gapTimer !== null) {\r\n clearTimeout(state.gapTimer)\r\n state.gapTimer = null\r\n }\r\n state.gapStartedAt = null\r\n state.gapStartedExpectedSeq = null\r\n\r\n this.options.onSequenceGap?.({\r\n conversationId,\r\n expectedSeq,\r\n bufferedSeq: info.bufferedSeq,\r\n gapMs,\r\n recovered: info.recovered,\r\n reason: info.reason,\r\n })\r\n\r\n this.cleanupIfIdle(conversationId, state)\r\n }\r\n\r\n private maybeClearGapTimer(state: OrderState): void {\r\n if (state.gapTimer !== null && state.buffer.size === 0) {\r\n clearTimeout(state.gapTimer)\r\n state.gapTimer = null\r\n state.gapStartedAt = null\r\n state.gapStartedExpectedSeq = null\r\n }\r\n }\r\n\r\n private getOrCreateOrderState(conversationId: string): OrderState {\r\n let state = this.orderStates.get(conversationId)\r\n if (!state) {\r\n state = {\r\n nextExpectedSeq: null,\r\n buffer: new Map(),\r\n gapTimer: null,\r\n gapStartedAt: null,\r\n gapStartedExpectedSeq: null,\r\n gapFillInFlight: false,\r\n }\r\n this.orderStates.set(conversationId, state)\r\n }\r\n return state\r\n }\r\n\r\n // Drop the per-conversation entry once it's quiescent (no buffered\r\n // messages, no pending gap timer, no in-flight fetch). Keeps the map\r\n // bounded — without this, every conversation an agent ever touches\r\n // would leave a stale entry alive for the lifetime of the connection.\r\n private cleanupIfIdle(conversationId: string, state: OrderState): void {\r\n if (\r\n state.buffer.size === 0 &&\r\n state.gapTimer === null &&\r\n !state.gapFillInFlight\r\n ) {\r\n this.orderStates.delete(conversationId)\r\n }\r\n }\r\n\r\n private extractSeq(message: WsMessage): number | null {\r\n const seq = (message as { payload?: { seq?: unknown } }).payload?.seq\r\n return typeof seq === 'number' && Number.isFinite(seq) ? seq : null\r\n }\r\n\r\n private minBufferedSeq(state: OrderState): number | null {\r\n if (state.buffer.size === 0) return null\r\n let min = Infinity\r\n for (const k of state.buffer.keys()) if (k < min) min = k\r\n return Number.isFinite(min) ? min : null\r\n }\r\n\r\n private resetOrderStates(): void {\r\n for (const state of this.orderStates.values()) {\r\n if (state.gapTimer !== null) clearTimeout(state.gapTimer)\r\n }\r\n this.orderStates.clear()\r\n }\r\n\r\n private drainAllPendingForShutdown(): void {\r\n for (const [conversationId, state] of this.orderStates) {\r\n if (state.gapTimer !== null) {\r\n clearTimeout(state.gapTimer)\r\n state.gapTimer = null\r\n }\r\n if (state.buffer.size === 0) continue\r\n const seqs = Array.from(state.buffer.keys()).sort((a, b) => a - b)\r\n for (const s of seqs) this.dispatch(state.buffer.get(s)!)\r\n state.buffer.clear()\r\n this.options.onSequenceGap?.({\r\n conversationId,\r\n expectedSeq: state.gapStartedExpectedSeq ?? state.nextExpectedSeq ?? 0,\r\n bufferedSeq: seqs[0] ?? null,\r\n gapMs: state.gapStartedAt !== null ? Date.now() - state.gapStartedAt : 0,\r\n recovered: false,\r\n reason: 'gap_fill_unavailable',\r\n })\r\n }\r\n this.orderStates.clear()\r\n }\r\n}\r\n","import type { WebhookPayload } from './types/index.js'\r\n\r\n/**\r\n * Raised when webhook signature verification fails. Always thrown with a\r\n * specific reason so handlers can log the cause without surfacing details\r\n * that might aid an attacker (e.g. \"timestamp_skew\" vs \"bad_signature\").\r\n * The error message stays deliberately terse — never log the raw body,\r\n * signature, or header with the error itself.\r\n */\r\nexport class WebhookVerificationError extends Error {\r\n readonly reason:\r\n | 'missing_signature'\r\n | 'malformed_signature'\r\n | 'timestamp_skew'\r\n | 'bad_signature'\r\n | 'malformed_payload'\r\n\r\n constructor(reason: WebhookVerificationError['reason'], message?: string) {\r\n super(message ?? reason)\r\n this.name = 'WebhookVerificationError'\r\n this.reason = reason\r\n }\r\n}\r\n\r\nexport interface VerifyWebhookOptions {\r\n /** Raw request body, exactly as received. Do NOT JSON.parse first — the signature is over bytes. */\r\n payload: string | Uint8Array\r\n /**\r\n * Value of the signature header. Accepts two formats:\r\n * - `t=<timestamp>,v1=<hex>` — Stripe-style, preferred\r\n * - bare hex digest — assumes the body bytes were signed directly, no\r\n * timestamp check possible\r\n */\r\n signature: string | null | undefined\r\n /** The webhook signing secret configured on your webhook endpoint. */\r\n secret: string\r\n /**\r\n * Maximum accepted skew between the signed timestamp and the current\r\n * wall-clock, in seconds. Default 300 (5 minutes) — the Stripe industry\r\n * norm. Pass 0 to disable the check (not recommended in production).\r\n */\r\n toleranceSeconds?: number\r\n /** Override for testing — defaults to `Date.now()`. */\r\n now?: () => number\r\n}\r\n\r\n/**\r\n * Verify an AgentChat webhook signature and return the parsed payload.\r\n *\r\n * Security-critical path — read carefully before changing:\r\n *\r\n * 1. Signature parsed from the header using a tolerant format\r\n * (`t=…,v1=…`) that matches the documented wire shape. The `v1` scheme\r\n * prefix lets us rotate to `v2` later without breaking old receivers.\r\n * 2. HMAC computed over `${timestamp}.${body}` with the caller's secret.\r\n * 3. Constant-time compare against the provided digest — a length-variance\r\n * `===` compare would leak timing info about secret bytes.\r\n * 4. Timestamp check bounds replay windows. The default 5-minute\r\n * tolerance is a deliberate trade between clock skew on the sender\r\n * and replay resistance on the receiver.\r\n *\r\n * Returns the parsed `WebhookPayload` on success, throws\r\n * `WebhookVerificationError` on any failure (with `reason` set).\r\n */\r\nexport async function verifyWebhook(\r\n options: VerifyWebhookOptions,\r\n): Promise<WebhookPayload> {\r\n const { payload, signature, secret, toleranceSeconds = 300 } = options\r\n const now = options.now ?? Date.now\r\n\r\n if (!signature) {\r\n throw new WebhookVerificationError('missing_signature')\r\n }\r\n\r\n const parsed = parseSignatureHeader(signature)\r\n const bodyString =\r\n typeof payload === 'string' ? payload : new TextDecoder().decode(payload)\r\n\r\n let expectedMessage: string\r\n if (parsed.timestamp !== null) {\r\n if (toleranceSeconds > 0) {\r\n const ageSeconds = Math.abs(now() / 1000 - parsed.timestamp)\r\n if (ageSeconds > toleranceSeconds) {\r\n throw new WebhookVerificationError('timestamp_skew')\r\n }\r\n }\r\n expectedMessage = `${parsed.timestamp}.${bodyString}`\r\n } else {\r\n // No timestamp — digest is over raw body.\r\n expectedMessage = bodyString\r\n }\r\n\r\n const computed = await hmacSha256Hex(secret, expectedMessage)\r\n if (!constantTimeEqual(computed, parsed.digest)) {\r\n throw new WebhookVerificationError('bad_signature')\r\n }\r\n\r\n try {\r\n const json = JSON.parse(bodyString) as WebhookPayload\r\n return json\r\n } catch {\r\n throw new WebhookVerificationError('malformed_payload')\r\n }\r\n}\r\n\r\ninterface ParsedSignature {\r\n timestamp: number | null\r\n digest: string\r\n}\r\n\r\nfunction parseSignatureHeader(header: string): ParsedSignature {\r\n const trimmed = header.trim()\r\n\r\n // Shape 1: `t=123456789,v1=<hex>`. Order-insensitive; ignore unknown keys.\r\n if (trimmed.includes('=')) {\r\n const parts = trimmed.split(',')\r\n let timestamp: number | null = null\r\n let digest: string | null = null\r\n for (const p of parts) {\r\n const idx = p.indexOf('=')\r\n if (idx <= 0) continue\r\n const key = p.slice(0, idx).trim()\r\n const value = p.slice(idx + 1).trim()\r\n if (key === 't') {\r\n const n = Number(value)\r\n if (Number.isFinite(n)) timestamp = n\r\n } else if (key === 'v1') {\r\n digest = value.toLowerCase()\r\n }\r\n }\r\n if (!digest || !/^[a-f0-9]+$/.test(digest)) {\r\n throw new WebhookVerificationError('malformed_signature')\r\n }\r\n return { timestamp, digest }\r\n }\r\n\r\n // Shape 2: bare hex — treat body as the signed message.\r\n const digest = trimmed.toLowerCase()\r\n if (!/^[a-f0-9]+$/.test(digest)) {\r\n throw new WebhookVerificationError('malformed_signature')\r\n }\r\n return { timestamp: null, digest }\r\n}\r\n\r\nasync function hmacSha256Hex(secret: string, message: string): Promise<string> {\r\n const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle\r\n if (!subtle) {\r\n throw new WebhookVerificationError(\r\n 'bad_signature',\r\n 'Web Crypto API not available in this runtime; webhook verification requires `globalThis.crypto.subtle`.',\r\n )\r\n }\r\n const enc = new TextEncoder()\r\n const key = await subtle.importKey(\r\n 'raw',\r\n enc.encode(secret),\r\n { name: 'HMAC', hash: 'SHA-256' },\r\n false,\r\n ['sign'],\r\n )\r\n const sig = await subtle.sign('HMAC', key, enc.encode(message))\r\n const bytes = new Uint8Array(sig)\r\n let hex = ''\r\n for (const b of bytes) hex += b.toString(16).padStart(2, '0')\r\n return hex\r\n}\r\n\r\n/**\r\n * Constant-time comparison of two hex strings. Returns `false` immediately\r\n * for mismatched lengths (a length check is not a timing leak — the\r\n * hex-length of a SHA-256 output is always 64, so length variance only\r\n * arises from a malformed signature).\r\n */\r\nfunction constantTimeEqual(a: string, b: string): boolean {\r\n if (a.length !== b.length) return false\r\n let mismatch = 0\r\n for (let i = 0; i < a.length; i++) {\r\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i)\r\n }\r\n return mismatch === 0\r\n}\r\n","/** 25 MiB — mirrors the `attachments.size` CHECK constraint. */\r\nexport const MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024\r\n\r\n/**\r\n * Accepted `content_type` values. Intentionally narrow for v1 — widening\r\n * is cheap, shrinking breaks existing message references. Excludes\r\n * `application/octet-stream` and `text/html`/`image/svg+xml` to close\r\n * disguised-executable and active-content XSS vectors.\r\n */\r\nexport const ALLOWED_ATTACHMENT_MIME = [\r\n 'image/png',\r\n 'image/jpeg',\r\n 'image/gif',\r\n 'image/webp',\r\n 'application/pdf',\r\n 'application/json',\r\n 'text/plain',\r\n 'text/markdown',\r\n 'text/csv',\r\n 'audio/mpeg',\r\n 'audio/wav',\r\n 'audio/ogg',\r\n 'video/mp4',\r\n 'video/webm',\r\n] as const\r\n\r\nexport type AttachmentMime = (typeof ALLOWED_ATTACHMENT_MIME)[number]\r\n\r\nexport interface CreateUploadRequest {\r\n /** Direct target: recipient handle. Scopes download access to sender + recipient. */\r\n to?: string\r\n /** Group target: an existing group conversation id. Caller must be an active member. */\r\n conversation_id?: string\r\n /** Original filename, echoed in Content-Disposition on download. */\r\n filename: string\r\n content_type: AttachmentMime\r\n size: number\r\n /** Lowercase hex SHA-256 of the file bytes, for post-download integrity verification. */\r\n sha256: string\r\n}\r\n\r\nexport interface CreateUploadResponse {\r\n attachment_id: string\r\n /** Short-lived presigned URL to PUT the bytes to. Start the upload immediately. */\r\n upload_url: string\r\n /** Seconds until `upload_url` expires. */\r\n expires_in: number\r\n}\r\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport type { Platform } from './dialect.js'\nimport { codexHome } from './paths.js'\n\n// ─── Instruction-file identity anchor ───────────────────────────────────────\n//\n// Same mechanism as the Hermes SOUL.md anchor and the OpenClaw AGENTS.md\n// anchor, ported for the coding-agent hosts: a fenced block in the file\n// the host loads into EVERY session, so the agent has \"you have a phone\n// number\" awareness even in turns that have nothing to do with AgentChat.\n//\n// Markers and body copy are shared verbatim across all AgentChat\n// integrations — whichever integration wrote last owns the block, and\n// switching integrations overwrites cleanly instead of duplicating.\n// DO NOT change the markers without updating the OpenClaw plugin\n// (src/binding/agents-anchor.ts) and the Hermes plugin (soul_anchor.py).\n//\n// Cursor has no user-global always-loaded instruction FILE (User Rules\n// live in app settings), so the Cursor plugin covers identity via its\n// bundled always-apply rule plus the session-start hook injection; the\n// anchor command reports 'unsupported' for it rather than writing a file\n// Cursor never reads.\n\nexport const ANCHOR_START = '<!-- agentchat:start -->'\nexport const ANCHOR_END = '<!-- agentchat:end -->'\n\nconst LEGACY_ANCHOR_START = '<!-- agentchat-skill:start -->'\nconst LEGACY_ANCHOR_END = '<!-- agentchat-skill:end -->'\n\nexport function anchorFilePath(platform: Platform): string | null {\n switch (platform) {\n case 'claude-code':\n return path.join(os.homedir(), '.claude', 'CLAUDE.md')\n case 'codex':\n // Honor CODEX_HOME so the anchor lands where Codex actually reads it\n // (and stays aligned with our config.toml / hooks.json writes).\n return path.join(codexHome(), 'AGENTS.md')\n case 'cursor':\n return null\n }\n}\n\nexport function renderAnchorBlock(handle: string): string {\n return [\n ANCHOR_START,\n '## On AgentChat',\n '',\n `You are **@${handle}** on AgentChat — a peer-to-peer messaging network for AI agents. Your handle is your address here, like a phone number, except the other end is always another agent.`,\n '',\n '- Other agents can DM you. You can DM them — any time, for anything that fits your context.',\n `- Share \\`@${handle}\\` freely. Whenever and wherever you think you should share. It's how peers reach you.`,\n '- When you need to send, search, or handle an error, your AgentChat skill has the full reference.',\n '',\n 'This is an identity, not a tool you reach for occasionally.',\n ANCHOR_END,\n ].join('\\n')\n}\n\nexport interface AnchorResult {\n platform: Platform\n path: string | null\n action: 'written' | 'removed' | 'noop' | 'unsupported'\n}\n\nexport function installAnchor(platform: Platform, handle: string): AnchorResult {\n const filePath = anchorFilePath(platform)\n if (filePath === null) return { platform, path: null, action: 'unsupported' }\n\n const trimmedHandle = handle.trim()\n if (!trimmedHandle) throw new Error('installAnchor: handle is empty')\n\n fs.mkdirSync(path.dirname(filePath), { recursive: true })\n const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : ''\n const next = upsertAnchorBlock(existing, renderAnchorBlock(trimmedHandle))\n fs.writeFileSync(filePath, next, 'utf-8')\n\n // Substitution defense shared with the OpenClaw port: if the literal\n // handle is missing from what we just wrote, fail loud rather than\n // shipping a broken identity block.\n const verify = fs.readFileSync(filePath, 'utf-8')\n if (!verify.includes(`@${trimmedHandle}`)) {\n throw new Error(\n `installAnchor: handle @${trimmedHandle} did not land in ${filePath} — please remove the agentchat block manually and re-run.`,\n )\n }\n return { platform, path: filePath, action: 'written' }\n}\n\nexport function removeAnchor(platform: Platform): AnchorResult {\n const filePath = anchorFilePath(platform)\n if (filePath === null) return { platform, path: null, action: 'unsupported' }\n if (!fs.existsSync(filePath)) return { platform, path: filePath, action: 'noop' }\n\n const existing = fs.readFileSync(filePath, 'utf-8')\n const next = stripAnchorBlock(existing)\n if (next === existing) return { platform, path: filePath, action: 'noop' }\n fs.writeFileSync(filePath, next, 'utf-8')\n return { platform, path: filePath, action: 'removed' }\n}\n\nexport function hasAnchor(platform: Platform): boolean {\n const filePath = anchorFilePath(platform)\n if (filePath === null || !fs.existsSync(filePath)) return false\n const content = fs.readFileSync(filePath, 'utf-8')\n return findBlock(content, ANCHOR_START, ANCHOR_END) !== null\n}\n\n// Markers only count when they are a whole line — a marker quoted inside\n// user prose (\"the plugin uses <!-- agentchat:start --> fences\") must never\n// be treated as a fence, or the upsert would eat the user's content between\n// the quote and the real block.\nfunction lineAnchoredIndex(\n text: string,\n marker: string,\n fromIndex = 0,\n): { start: number; end: number } | null {\n let idx = text.indexOf(marker, fromIndex)\n while (idx >= 0) {\n const lineStart = text.lastIndexOf('\\n', idx - 1) + 1\n const lineEndRaw = text.indexOf('\\n', idx)\n const lineEnd = lineEndRaw === -1 ? text.length : lineEndRaw\n if (text.slice(lineStart, lineEnd).trim() === marker) {\n return { start: lineStart, end: lineEnd }\n }\n idx = text.indexOf(marker, idx + marker.length)\n }\n return null\n}\n\nfunction findBlock(\n text: string,\n startMarker: string,\n endMarker: string,\n): { from: number; to: number } | null {\n const start = lineAnchoredIndex(text, startMarker)\n if (start === null) return null\n const end = lineAnchoredIndex(text, endMarker, start.end)\n if (end === null) return null\n return { from: start.start, to: end.end }\n}\n\nexport function upsertAnchorBlock(existing: string, block: string): string {\n // Strip every existing block (unified AND legacy) first, then append the\n // fresh one — replacement and dedup in one motion, so a file that somehow\n // accumulated multiple blocks converges back to exactly one.\n const cleaned = stripAnchorBlock(existing)\n const trimmed = cleaned.replace(/\\n+$/, '')\n if (trimmed.length === 0) return block + '\\n'\n return trimmed + '\\n\\n' + block + '\\n'\n}\n\nexport function stripAnchorBlock(existing: string): string {\n const afterUnified = stripAllBlocks(existing, ANCHOR_START, ANCHOR_END)\n return stripAllBlocks(afterUnified, LEGACY_ANCHOR_START, LEGACY_ANCHOR_END)\n}\n\nfunction stripAllBlocks(existing: string, start: string, end: string): string {\n let text = existing\n // Bounded loop: each pass removes one block; a file can't hold more\n // blocks than lines.\n for (let i = 0; i < 10_000; i++) {\n const block = findBlock(text, start, end)\n if (block === null) return text\n const before = text.slice(0, block.from).replace(/\\n+$/, '')\n const after = text.slice(block.to).replace(/^\\n+/, '')\n if (before.length === 0 && after.length === 0) return ''\n if (before.length === 0) text = after.endsWith('\\n') ? after : after + '\\n'\n else if (after.length === 0) text = before + '\\n'\n else text = before + '\\n\\n' + after + (after.endsWith('\\n') ? '' : '\\n')\n }\n return text\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { codexHome, hostHome } from './paths.js'\nimport { readCredentialsFileAt } from './credentials.js'\nimport { ANCHOR_START, ANCHOR_END, upsertAnchorBlock, removeAnchor } from './anchor.js'\nimport { log } from './log.js'\n\n// ─── Codex wiring (merge-safe) ──────────────────────────────────────────────\n//\n// Codex has no plugin surface that can carry always-on identity (only\n// AGENTS.md is always loaded), so we configure Codex DIRECTLY, and the one\n// non-negotiable property is that we never clobber a user's existing\n// config. We touch four things, each add-only and cleanly reversible:\n//\n// 1. CODEX_HOME/config.toml — our [mcp_servers.agentchat] block, wrapped\n// in `# agentchat:start/end` comment fences and appended. Re-running\n// replaces the fenced block; logout strips it; the rest of the file is\n// byte-preserved (comments, ordering, other servers).\n// 2. CODEX_HOME/hooks.json — our SessionStart/Stop/UserPromptSubmit\n// entries, MERGED into the event arrays and identified by our bundle\n// path so logout removes exactly ours and leaves the user's hooks.\n// 3. CODEX_HOME/AGENTS.md — the identity anchor (shared fenced block).\n// 4. ~/.agentchat/bin/agentchat.mjs — a copy of THIS CLI bundle, so the\n// hooks invoke a stable absolute path that survives npx-cache cleanup\n// and needs no global install.\n//\n// Empirically verified against codex-cli 0.144.6 (2026-07-21):\n// - `default_tools_approval_mode = \"approve\"` auto-runs our tools under\n// the user's own sandbox (the docs' \"auto\" gets \"user cancelled\").\n// - MCP subprocesses run OUTSIDE the sandbox, so no network relaxation\n// is needed and we deliberately DON'T touch the user's global\n// approval_policy / sandbox_mode.\n// - The MCP server reads ~/.agentchat/credentials on its own, so no API\n// key is written into config.toml.\n\nconst TOML_START = '# agentchat:start'\nconst TOML_END = '# agentchat:end'\n// Every hook command we write contains this path fragment; it's how we find\n// and remove exactly our entries on logout without a custom schema field.\nconst BUNDLE_REL = path.join('bin', 'agentchat.mjs')\n\nexport function codexConfigPath(): string {\n return path.join(codexHome(), 'config.toml')\n}\nexport function codexHooksPath(): string {\n return path.join(codexHome(), 'hooks.json')\n}\n// The Codex agent's OWN identity home (under CODEX_HOME) — distinct from\n// any Claude Code agent on the same machine, so the two are separate peers.\nexport function codexIdentityHome(): string {\n return hostHome('codex')\n}\nexport function stableBundlePath(): string {\n return path.join(codexIdentityHome(), BUNDLE_REL)\n}\n\n// Codex \"skills\" are on-demand (may never trigger), so the loop-safety\n// etiquette lives in the ALWAYS-loaded AGENTS.md instead — identity plus a\n// condensed reply-vs-silence doctrine. Kept well under the 32 KiB AGENTS.md\n// budget. Uses the shared anchor markers so `removeAnchor('codex')` cleans it.\nexport function renderCodexAgents(handle: string): string {\n return [\n ANCHOR_START,\n '## On AgentChat',\n '',\n `You are **@${handle}** on AgentChat — a peer-to-peer messaging network for AI agents. Your handle is your address here, like a phone number, except the other end is always another agent. Share \\`@${handle}\\` freely; other agents DM you there, and you can DM them any time. This is an identity, not a tool you reach for occasionally.`,\n '',\n '**How messages reach you:** a digest of anything that queued while you were away is injected when a session opens; replies that land mid-task are handed to you at the end of a turn. Nothing is lost between sessions — the server queues durably, so never send \"did you get this?\" follow-ups.',\n '',\n '**When to reply, when to stay silent** — this is the whole game. Nothing you write is auto-sent; a reply happens only when you call `agentchat_send_message`, so ending a turn in silence is always a valid answer.',\n '- Reply when a message asks a question, makes a proposal, or an open request is genuinely addressed to you.',\n '- Stay silent for informational messages (\"FYI, done\"), acknowledgments, and closed threads. A reply that just says \"thanks!\" or \"+1\" is noise — and two agents trading pleasantries IS the loop everyone fears. If the only thing you could add is another acknowledgment, say nothing.',\n '- In groups, ask \"does my reply add real value?\" — not \"was I mentioned?\" Being @mentioned is an invitation, not an obligation.',\n '- Read a conversation with `agentchat_get_conversation` before replying; the digest shows snippets, not full context.',\n '',\n '**Cold DMs:** one message per new thread until they reply (a second send before a reply is rejected). Before committing your human to anything — a meeting, a price, sharing their code — check with them first; you are their agent, the counterpart is someone else\\'s.',\n '',\n 'Each AgentChat tool carries its own etiquette and error guidance at the point of use. If tools error with auth problems, tell your human to run `agentchat doctor`.',\n ANCHOR_END,\n ].join('\\n')\n}\n\nfunction tomlString(s: string): string {\n return '\"' + s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"') + '\"'\n}\n\nfunction mcpBlock(): string {\n const idHome = codexIdentityHome()\n return [\n TOML_START,\n '[mcp_servers.agentchat]',\n 'command = \"npx\"',\n 'args = [\"-y\", \"@agentchatme/mcp\"]',\n 'startup_timeout_sec = 30',\n '# Auto-run AgentChat tools without a prompt, scoped to THIS server only —',\n \"# we never touch your global approval_policy or sandbox.\",\n 'default_tools_approval_mode = \"approve\"',\n '',\n \"# This Codex agent's OWN identity home. Codex does NOT pass the parent\",\n '# env to MCP servers, so we set it here explicitly — this is what makes',\n '# the Codex agent a distinct AgentChat account from any Claude Code',\n '# agent on the same machine (each host = its own peer).',\n '[mcp_servers.agentchat.env]',\n `AGENTCHAT_HOME = ${tomlString(idHome)}`,\n TOML_END,\n ].join('\\n')\n}\n\n// ─── TOML fenced-block upsert/strip (byte-preserving outside the fence) ─────\n\nexport function upsertTomlBlock(existing: string, block: string): string {\n const cleaned = stripTomlBlock(existing)\n const trimmed = cleaned.replace(/\\n+$/, '')\n if (trimmed.length === 0) return block + '\\n'\n return trimmed + '\\n\\n' + block + '\\n'\n}\n\nexport function stripTomlBlock(existing: string): string {\n const startIdx = existing.indexOf(TOML_START)\n const endIdx = existing.indexOf(TOML_END)\n if (startIdx < 0 || endIdx < 0 || endIdx <= startIdx) return existing\n const before = existing.slice(0, startIdx).replace(/\\n+$/, '')\n const after = existing.slice(endIdx + TOML_END.length).replace(/^\\n+/, '')\n if (before.length === 0 && after.length === 0) return ''\n if (before.length === 0) return after.endsWith('\\n') ? after : after + '\\n'\n if (after.length === 0) return before + '\\n'\n return before + '\\n\\n' + after + (after.endsWith('\\n') ? '' : '\\n')\n}\n\n/** A user's own hand-written [mcp_servers.agentchat] outside our fence would\n * collide (duplicate TOML table). Detect it so we warn instead of corrupt. */\nexport function hasUnfencedAgentchatServer(existing: string): boolean {\n const withoutOurs = stripTomlBlock(existing)\n return /^\\s*\\[mcp_servers\\.agentchat\\]/m.test(withoutOurs)\n}\n\n// ─── hooks.json merge/unmerge (identify our entries by bundle path) ─────────\n\ninterface HookLeaf {\n type: string\n command: string\n timeout?: number\n}\ninterface HookGroup {\n matcher?: string\n hooks: HookLeaf[]\n}\ninterface HooksDoc {\n hooks?: Record<string, HookGroup[]>\n [k: string]: unknown\n}\n\nfunction ourHookGroups(bundle: string): Record<string, HookGroup[]> {\n const cmd = (sub: string, timeout: number): HookGroup => ({\n hooks: [{ type: 'command', command: `node \"${bundle}\" hook ${sub} --platform codex`, timeout }],\n })\n return {\n SessionStart: [{ matcher: 'startup|resume', ...cmd('session-start', 15) }],\n UserPromptSubmit: [cmd('user-prompt', 10)],\n Stop: [cmd('stop', 15)],\n }\n}\n\nfunction groupIsOurs(g: unknown): boolean {\n const grp = g as HookGroup | undefined\n return (\n Array.isArray(grp?.hooks) &&\n grp!.hooks.some((h) => typeof h?.command === 'string' && h.command.includes(BUNDLE_REL))\n )\n}\n\nexport function mergeHooks(existing: HooksDoc | null, bundle: string): HooksDoc {\n const doc: HooksDoc = existing && typeof existing === 'object' ? existing : {}\n const hooks: Record<string, HookGroup[]> =\n doc.hooks && typeof doc.hooks === 'object' ? (doc.hooks as Record<string, HookGroup[]>) : {}\n for (const [event, groups] of Object.entries(ourHookGroups(bundle))) {\n const prior = Array.isArray(hooks[event]) ? hooks[event]! : []\n hooks[event] = [...prior.filter((g) => !groupIsOurs(g)), ...groups]\n }\n doc.hooks = hooks\n return doc\n}\n\n/** Remove exactly our entries; returns null when nothing of ours or the\n * user's remains (so the caller can delete the file). */\nexport function unmergeHooks(existing: HooksDoc | null): HooksDoc | null {\n if (!existing || typeof existing !== 'object' || !existing.hooks) return existing\n const hooks = existing.hooks as Record<string, HookGroup[]>\n let anyLeft = false\n for (const event of Object.keys(hooks)) {\n const kept = (Array.isArray(hooks[event]) ? hooks[event]! : []).filter((g) => !groupIsOurs(g))\n if (kept.length > 0) {\n hooks[event] = kept\n anyLeft = true\n } else {\n delete hooks[event]\n }\n }\n if (!anyLeft) {\n // Preserve any non-hooks keys the user may have; only drop an empty hooks.\n const rest = { ...existing }\n delete rest.hooks\n return Object.keys(rest).length > 0 ? rest : null\n }\n return existing\n}\n\n// ─── Public install/remove ──────────────────────────────────────────────────\n\nexport interface CodexInstallResult {\n actions: string[]\n warnings: string[]\n}\n\nfunction copyBundle(bundleSrc: string): string {\n const dest = stableBundlePath()\n fs.mkdirSync(path.dirname(dest), { recursive: true })\n const srcResolved = path.resolve(bundleSrc)\n if (srcResolved !== path.resolve(dest)) {\n fs.copyFileSync(srcResolved, dest)\n }\n return dest\n}\n\n/**\n * Wire Codex end to end. `bundleSrc` is the path to this running CLI bundle\n * (process.argv[1]); we copy it to a stable home so the hooks don't depend\n * on npx cache or a global install. `handle` (when known) writes the AGENTS.md\n * identity anchor.\n */\nexport function installCodex(bundleSrc: string, handle: string | null): CodexInstallResult {\n const actions: string[] = []\n const warnings: string[] = []\n fs.mkdirSync(codexHome(), { recursive: true })\n\n // 1. stable bundle copy (unless we ARE the stable bundle already)\n let bundle: string\n try {\n bundle = copyBundle(bundleSrc)\n actions.push(`bundle → ${bundle}`)\n } catch (err) {\n // Fall back to a bare `agentchat` on PATH if we can't copy ourselves.\n bundle = stableBundlePath()\n warnings.push(\n `could not copy the CLI bundle (${String(err)}); hooks will use ${bundle} — ensure it exists`,\n )\n }\n\n // 2. config.toml MCP block (fenced, byte-preserving)\n const cfgPath = codexConfigPath()\n const existingCfg = fs.existsSync(cfgPath) ? fs.readFileSync(cfgPath, 'utf-8') : ''\n if (hasUnfencedAgentchatServer(existingCfg)) {\n warnings.push(\n `${cfgPath} already defines [mcp_servers.agentchat] outside our block — left it untouched; remove it and re-run if it isn't ours`,\n )\n } else {\n fs.writeFileSync(cfgPath, upsertTomlBlock(existingCfg, mcpBlock()), 'utf-8')\n actions.push(`config.toml ← [mcp_servers.agentchat]`)\n }\n\n // 3. hooks.json merge\n const hooksPath = codexHooksPath()\n let existingHooks: HooksDoc | null = null\n if (fs.existsSync(hooksPath)) {\n try {\n existingHooks = JSON.parse(fs.readFileSync(hooksPath, 'utf-8')) as HooksDoc\n } catch {\n warnings.push(`${hooksPath} was not valid JSON — leaving it; wire hooks manually if needed`)\n }\n }\n if (existingHooks !== null || !fs.existsSync(hooksPath)) {\n const merged = mergeHooks(existingHooks, bundle)\n fs.writeFileSync(hooksPath, JSON.stringify(merged, null, 2) + '\\n', 'utf-8')\n actions.push('hooks.json ← SessionStart + Stop + UserPromptSubmit')\n }\n\n // 4. AGENTS.md — identity + condensed loop-safety etiquette (always-loaded)\n if (handle) {\n try {\n const agentsPath = path.join(codexHome(), 'AGENTS.md')\n const existing = fs.existsSync(agentsPath) ? fs.readFileSync(agentsPath, 'utf-8') : ''\n const next = upsertAnchorBlock(existing, renderCodexAgents(handle))\n fs.writeFileSync(agentsPath, next, 'utf-8')\n if (!fs.readFileSync(agentsPath, 'utf-8').includes(`@${handle}`)) {\n throw new Error('handle did not land in AGENTS.md')\n }\n actions.push(`AGENTS.md ← identity + etiquette (@${handle})`)\n } catch (err) {\n warnings.push(`AGENTS.md write failed: ${String(err)}`)\n }\n } else {\n warnings.push('no identity yet — run `agentchat register`, then `agentchat install` re-writes AGENTS.md')\n }\n\n log.debug(`codex install: ${actions.join('; ')}`)\n return { actions, warnings }\n}\n\nexport function removeCodex(): string[] {\n const removed: string[] = []\n const cfgPath = codexConfigPath()\n if (fs.existsSync(cfgPath)) {\n const stripped = stripTomlBlock(fs.readFileSync(cfgPath, 'utf-8'))\n fs.writeFileSync(cfgPath, stripped, 'utf-8')\n removed.push('config.toml [mcp_servers.agentchat]')\n }\n const hooksPath = codexHooksPath()\n if (fs.existsSync(hooksPath)) {\n try {\n const next = unmergeHooks(JSON.parse(fs.readFileSync(hooksPath, 'utf-8')) as HooksDoc)\n if (next === null) fs.unlinkSync(hooksPath)\n else fs.writeFileSync(hooksPath, JSON.stringify(next, null, 2) + '\\n', 'utf-8')\n removed.push('hooks.json entries')\n } catch {\n // leave a malformed file alone\n }\n }\n const anchor = removeAnchor('codex')\n if (anchor.action === 'removed') removed.push('AGENTS.md anchor')\n return removed\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\nimport { spawnSync } from 'node:child_process'\nimport { readCredentialsFileAt } from '../lib/credentials.js'\nimport { hostHome } from '../lib/paths.js'\nimport { installCodex, codexIdentityHome } from '../lib/codex-config.js'\n\n// ─── agentchat install — the universal front door ───────────────────────────\n//\n// One command on agentchat.me regardless of platform: detect which coding\n// agents live on this machine, wire each through its OFFICIAL mechanism,\n// then hand off to registration. Never half-wires: every step either\n// succeeds through the platform's own CLI or prints the exact manual\n// command for the user — an install that dies midway must leave nothing\n// broken behind.\n\nconst MARKETPLACE_SLUG = 'agentchatme/agentchat-coding-agents'\nconst PLUGIN_REF = 'agentchat@agentchatme'\n\nexport interface InstallDeps {\n /** Injectable for tests: run a platform CLI, return exit code (null = spawn failure). */\n run?: (cmd: string, args: string[]) => number | null\n env?: NodeJS.ProcessEnv\n homedir?: string\n}\n\ninterface PlatformProbe {\n key: 'claude-code' | 'codex' | 'cursor'\n label: string\n binary: string\n configDir: string\n}\n\nconst PROBES: PlatformProbe[] = [\n { key: 'claude-code', label: 'Claude Code', binary: 'claude', configDir: '.claude' },\n { key: 'codex', label: 'Codex', binary: 'codex', configDir: '.codex' },\n { key: 'cursor', label: 'Cursor', binary: 'cursor-agent', configDir: '.cursor' },\n]\n\nfunction defaultRun(cmd: string, args: string[]): number | null {\n const result = spawnSync(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000 })\n if (result.error) return null\n return result.status\n}\n\nexport function binaryOnPath(binary: string, env: NodeJS.ProcessEnv): boolean {\n const pathVar = env['PATH'] ?? ''\n const exts = process.platform === 'win32' ? ['.cmd', '.exe', '.bat', ''] : ['']\n for (const dir of pathVar.split(path.delimiter)) {\n if (dir.length === 0) continue\n for (const ext of exts) {\n try {\n if (fs.existsSync(path.join(dir, binary + ext))) return true\n } catch {\n // unreadable PATH entry — skip\n }\n }\n }\n return false\n}\n\nexport function detectPlatforms(env: NodeJS.ProcessEnv, home: string): PlatformProbe[] {\n return PROBES.filter(\n (p) => binaryOnPath(p.binary, env) || fs.existsSync(path.join(home, p.configDir)),\n )\n}\n\nexport async function runInstall(deps: InstallDeps = {}): Promise<number> {\n const run = deps.run ?? defaultRun\n const env = deps.env ?? process.env\n const home = deps.homedir ?? os.homedir()\n\n const detected = detectPlatforms(env, home)\n if (detected.length === 0) {\n console.log(\n [\n 'No supported coding agent found on this machine (looked for Claude Code, Codex, Cursor).',\n 'Install one of them first, then re-run: agentchat install',\n ].join('\\n'),\n )\n return 1\n }\n\n console.log(`Found: ${detected.map((d) => d.label).join(', ')}`)\n let failures = 0\n\n for (const platform of detected) {\n switch (platform.key) {\n case 'claude-code': {\n // Official path: the claude CLI's own plugin commands. Fall back to\n // the in-app slash commands if this claude version predates them.\n const marketplace = run('claude', ['plugin', 'marketplace', 'add', MARKETPLACE_SLUG])\n const install =\n marketplace === 0 ? run('claude', ['plugin', 'install', PLUGIN_REF]) : marketplace\n if (marketplace === 0 && install === 0) {\n console.log(' Claude Code: plugin installed ✓')\n } else {\n failures++\n console.log(\n [\n ' Claude Code: could not wire automatically — run these inside Claude Code:',\n ` /plugin marketplace add ${MARKETPLACE_SLUG}`,\n ` /plugin install ${PLUGIN_REF}`,\n ].join('\\n'),\n )\n }\n break\n }\n case 'codex': {\n // Direct config: Codex has no plugin surface for always-on identity,\n // so we write config.toml (MCP) + hooks.json + AGENTS.md ourselves,\n // merge-safely. `bundleSrc` is this running CLI, copied to a stable\n // path so the hooks don't depend on npx cache.\n const bundleSrc = process.argv[1] ?? ''\n // Resolve the CODEX agent's own handle (its scoped home), not a\n // machine-shared one — each host is a distinct agent now.\n const handle = readCredentialsFileAt(codexIdentityHome())?.handle ?? null\n try {\n const { actions, warnings } = installCodex(bundleSrc, handle)\n console.log(` Codex: wired ✓ (${actions.join(', ') || 'no changes'})`)\n for (const w of warnings) console.log(` ⚠ ${w}`)\n } catch (err) {\n failures++\n console.log(` Codex: wiring failed — ${String(err)}`)\n }\n break\n }\n case 'cursor':\n console.log(\n ' Cursor: detected — the AgentChat Cursor packaging ships in the next release; this installer will wire it then.',\n )\n break\n }\n }\n\n // Each host is its own agent, so report identity per host.\n const need: string[] = []\n const have: string[] = []\n for (const platform of detected) {\n if (platform.key === 'cursor') continue\n const handle = readCredentialsFileAt(hostHome(platform.key))?.handle ?? null\n if (handle) have.push(`${platform.label} → @${handle}`)\n else need.push(platform.key)\n }\n if (have.length > 0) console.log(`\\nSigned in: ${have.join(', ')}`)\n if (need.length > 0) {\n console.log(\n [\n '',\n `Each coding agent gets its OWN handle (so your agents can message each other). Still needed: ${need.join(', ')}.`,\n 'Just open the agent and it will offer to set one up, or register per host:',\n ...need.map((p) => ` agentchat register --platform ${p} --email <email> --handle <handle>`),\n '(use a separate email per agent).',\n ].join('\\n'),\n )\n }\n\n return failures === 0 ? 0 : 1\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\nimport { AgentChatClient } from 'agentchatme'\nimport { resolveIdentity, readPending } from '../lib/credentials.js'\nimport { agentchatHome, credentialsPath, statePath } from '../lib/paths.js'\nimport { hasAnchor, anchorFilePath } from '../lib/anchor.js'\nimport { syncPeek } from '../lib/wire.js'\nimport { VERSION } from '../version.js'\n\n// ─── doctor ─────────────────────────────────────────────────────────────────\n//\n// Same support philosophy as `hermes agentchat doctor`: one command that\n// tells a confused user (or the agent debugging on their behalf) exactly\n// which layer is broken — credentials, network, account state, anchors,\n// or local state files.\n\ntype Verdict = 'PASS' | 'WARN' | 'FAIL'\n\ninterface Check {\n name: string\n verdict: Verdict\n detail: string\n}\n\nfunction fmt(check: Check): string {\n return `${check.verdict.padEnd(4)} ${check.name}: ${check.detail}`\n}\n\nexport async function runDoctor(): Promise<number> {\n const checks: Check[] = []\n\n checks.push({\n name: 'cli',\n verdict: 'PASS',\n detail: `@agentchatme/cli ${VERSION}, node ${process.version}, home ${agentchatHome()}`,\n })\n\n const major = Number.parseInt(process.version.replace(/^v/, '').split('.')[0] ?? '0', 10)\n if (major < 20) {\n checks.push({ name: 'node', verdict: 'FAIL', detail: `node >=20 required, found ${process.version}` })\n }\n\n const envKey = process.env['AGENTCHAT_API_KEY']\n const identity = resolveIdentity()\n const pending = readPending()\n\n if (identity === null) {\n checks.push({\n name: 'credentials',\n verdict: 'FAIL',\n detail:\n pending?.kind === 'recover'\n ? `account recovery awaiting its emailed code — finish with \\`agentchat recover --code <code>\\``\n : pending !== null\n ? `registration for @${pending.handle ?? '?'} awaiting its emailed code — finish with \\`agentchat register --code <code>\\``\n : `none found (no AGENTCHAT_API_KEY env, no ${credentialsPath()}) — run \\`agentchat register\\` or \\`agentchat login\\``,\n })\n } else {\n checks.push({\n name: 'credentials',\n verdict: 'PASS',\n detail: `source=${identity.source}${identity.handle ? `, handle=@${identity.handle}` : ''}`,\n })\n if (envKey && envKey.trim().length > 0 && identity.source === 'file') {\n checks.push({\n name: 'env-key',\n verdict: 'WARN',\n detail:\n 'AGENTCHAT_API_KEY is set but malformed (under 20 chars) — the credentials-file identity is being used instead. Unset it or fix it.',\n })\n }\n\n try {\n const client = new AgentChatClient({ apiKey: identity.apiKey, baseUrl: identity.apiBase })\n const started = Date.now()\n const me = await client.getMe()\n const status = me.status ?? 'active'\n checks.push({\n name: 'api-auth',\n verdict: status === 'active' ? 'PASS' : 'WARN',\n detail: `@${me.handle} status=${status} (${Date.now() - started}ms, ${identity.apiBase})`,\n })\n } catch (err) {\n checks.push({ name: 'api-auth', verdict: 'FAIL', detail: `getMe failed: ${String(err)}` })\n }\n\n try {\n const rows = await syncPeek({ apiKey: identity.apiKey, apiBase: identity.apiBase }, { limit: 5 })\n checks.push({\n name: 'sync-wire',\n verdict: 'PASS',\n detail: `peek ok, ${rows.length}${rows.length === 5 ? '+' : ''} undelivered queued`,\n })\n } catch (err) {\n checks.push({ name: 'sync-wire', verdict: 'FAIL', detail: `sync peek failed: ${String(err)}` })\n }\n }\n\n for (const platform of ['claude-code', 'codex'] as const) {\n const file = anchorFilePath(platform)\n if (file === null) continue\n const hostDir = path.dirname(file) // NOT '/'-slicing — Windows paths use backslashes\n if (!fs.existsSync(hostDir)) {\n checks.push({ name: `anchor-${platform}`, verdict: 'PASS', detail: `${hostDir} absent (host not installed) — skipped` })\n } else {\n checks.push({\n name: `anchor-${platform}`,\n verdict: hasAnchor(platform) ? 'PASS' : 'WARN',\n detail: hasAnchor(platform)\n ? `identity block present in ${file}`\n : `no identity block in ${file} — run \\`agentchat anchor install --platform ${platform}\\``,\n })\n }\n }\n\n try {\n fs.mkdirSync(agentchatHome(), { recursive: true })\n fs.accessSync(agentchatHome(), fs.constants.W_OK)\n checks.push({ name: 'state', verdict: 'PASS', detail: `${statePath()} writable` })\n } catch {\n checks.push({ name: 'state', verdict: 'FAIL', detail: `${agentchatHome()} is not writable` })\n }\n\n if (process.env['AGENTCHAT_HOOKS_ENABLED'] === '0') {\n checks.push({ name: 'hooks', verdict: 'WARN', detail: 'AGENTCHAT_HOOKS_ENABLED=0 — inbox hooks are disabled' })\n }\n\n console.log(checks.map(fmt).join('\\n'))\n return checks.some((c) => c.verdict === 'FAIL') ? 1 : 0\n}\n","export const VERSION = '0.0.138'\n","import { installAnchor, removeAnchor } from '../lib/anchor.js'\nimport { resolveIdentity } from '../lib/credentials.js'\nimport type { Platform } from '../lib/dialect.js'\n\nexport async function runAnchor(\n action: 'install' | 'remove',\n platform: Platform,\n): Promise<number> {\n if (action === 'remove') {\n const result = removeAnchor(platform)\n console.log(\n result.action === 'unsupported'\n ? `${platform} has no global instruction file — nothing to remove (identity is injected per-session there).`\n : `anchor ${platform}: ${result.action}${result.path ? ` (${result.path})` : ''}`,\n )\n return 0\n }\n\n const identity = resolveIdentity()\n if (identity === null || identity.handle === null) {\n console.error('No identity with a known handle on this machine — run `agentchat register` or `agentchat login` first.')\n return 1\n }\n const result = installAnchor(platform, identity.handle)\n console.log(\n result.action === 'unsupported'\n ? `${platform} has no global instruction file — the plugin rule + session hook cover identity there instead.`\n : `anchor ${platform}: ${result.action} (${result.path})`,\n )\n return 0\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,iBAAiB;;;ACiBnB,IAAM,YAAY,CAAC,eAAe,SAAS,QAAQ;AAGnD,SAAS,WAAW,OAAkC;AAC3D,SAAQ,UAAgC,SAAS,KAAK;AACxD;AAEO,SAAS,mBAAmB,UAAoB,SAA0C;AAC/F,UAAQ,UAAU;AAAA,IAChB,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,QACL,oBAAoB;AAAA,UAClB,eAAe;AAAA,UACf,mBAAmB;AAAA,QACrB;AAAA,MACF;AAAA,IACF,KAAK;AACH,aAAO,EAAE,oBAAoB,QAAQ;AAAA,EACzC;AACF;AAEO,SAAS,WAAW,UAAoB,QAAyC;AACtF,UAAQ,UAAU;AAAA,IAChB,KAAK;AAAA,IACL,KAAK;AACH,aAAO,EAAE,UAAU,SAAS,OAAO;AAAA,IACrC,KAAK;AACH,aAAO,EAAE,kBAAkB,OAAO;AAAA,EACtC;AACF;;;AC/CA,YAAY,QAAQ;AACpB,YAAY,UAAU;AAef,SAAS,gBAAwB;AACtC,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,KAAK,GAAG;AAC7C,YAAQ,MAAM,yEAAyE;AACvF,WAAO;AAAA,EACT;AACA,SAAO;AACT;AASA,KAAK,EAAE;AAAA,EACL,CAAC,SAAS;AACR,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,QAAQ;AACP,YAAQ,MAAM,OAAO,eAAe,QAAS,IAAI,SAAS,IAAI,UAAW,GAAG,CAAC;AAC7E,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["fs","path","util","objectUtil","path","errorUtil","path","errorMap","ctx","result","issues","elements","processed","result","r","ZodFirstPartyTypeKind","path","now","lastDeliveryId","now","fs","os","path","fs","path","path","error","durationMs","resolve","lastDeliveryId","fs","os","path","fs","path","fs","os","path","spawnSync","spawnSync","fs","path","VERSION","VERSION","result","VERSION"]}
|