@keystrokehq/cli 0.0.147 → 0.0.148

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["isPlainObject","objectToString","#options","#runBeforeRequestHooks","#retry","#fetch","#consumeReturnedResponseFromBeforeRetryHook","#runAfterResponseHooks","#retryFromError","#getResponseRequest","#getNormalizedOptions","#getResponseData","#decorateResponse","#cancelResponseBody","#beforeRetryHookErrors","#retryCount","#originalRequest","#cancelBody","#normalizeSearchParams","#input","#userProvidedAbortSignal","#abortController","#createManagedSignal","#startTime","#getCurrentTime","#calculateRetryDelay","#calculateDelay","#readResponseText","#getErrorDataTimeout","#throwIfTotalTimeoutExhausted","#isJsonContentType","#parseJson","#getRemainingTotalTimeout","#assignRequest","#setResponseRequest","#returnedResponseFromBeforeRetryHook","#wrapRequestWithUploadProgress","#cachedNormalizedOptions","#responseRequests","normalizeBaseUrl","applyActiveOrganizationHeader","applyAuthHeaders","createAgentsResource","createCredentialsResource","createHealthResource","createWorkflowsResource","#hiddenStack","now","getMethod","sleep","collectSetValues"],"sources":["../src/resolve-platform-url.ts","../src/config.ts","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/KyError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/HTTPError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/NetworkError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/NonError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/ForceRetryError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/SchemaValidationError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/TimeoutError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/core/constants.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/body.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/is.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/merge.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/normalize.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/timeout.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/delay.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/options.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/is-network-error.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/type-guards.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/core/Ky.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/index.js","../../../packages/sdk/dist/index.mjs","../src/auth/credentials.ts","../../../packages/auth/dist/jwt-BVJ7dVm9.mjs","../../../packages/auth/dist/jwt-cache-4YqHn3jM.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/package.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/version.mjs","../../../node_modules/.pnpm/better-call@1.3.5_zod@4.4.3/node_modules/better-call/dist/error.mjs","../../../node_modules/.pnpm/@better-auth+core@1.6.11_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_better-cal_90e7d2cb715d3338ca39f1d23262e011/node_modules/@better-auth/core/dist/error/index.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/plugins/device-authorization/client.mjs","../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/clean-stores/index.js","../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/atom/index.js","../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/lifecycle/index.js","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/query.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/broadcast-channel.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/focus-manager.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/online-manager.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/parser.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/session-refresh.mjs","../../../node_modules/.pnpm/@better-auth+core@1.6.11_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_better-cal_90e7d2cb715d3338ca39f1d23262e011/node_modules/@better-auth/core/dist/env/env-impl.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/utils/url.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/fetch-plugins.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/session-atom.mjs","../../../node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs","../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/dist/index.js","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/config.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/utils/is-atom.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/proxy.mjs","../../../node_modules/.pnpm/@better-auth+core@1.6.11_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_better-cal_90e7d2cb715d3338ca39f1d23262e011/node_modules/@better-auth/core/dist/utils/string.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/vanilla.mjs","../../../packages/auth/dist/cli.mjs","../src/auth/jwt-cache.ts","../src/auth/resolve-cli-auth.ts","../src/client.ts","../../../packages/sdk/dist/platform/index.mjs","../src/platform-client.ts","../src/resolve-resource-ref.ts","../src/organization/active-organization.ts","../src/dev-session.ts","../src/resolve-api-target.ts","../src/target-options.ts","../src/errors/example-input.ts","../src/errors/format-api-message.ts","../src/errors/format-cli-error.ts","../src/errors/run-command.ts","../src/errors/command-input.ts","../src/resolve-project-target.ts","../src/commands/agent/list.ts","../src/commands/agent/prompt.ts","../src/commands/agent/sessions.ts","../src/commands/agent/index.ts","../src/auth/open-url.ts","../src/commands/connect/run-connect.ts","../src/commands/connect/index.ts","../src/commands/credentials/target-options.ts","../src/commands/credentials/delete.ts","../src/commands/credentials/list.ts","../src/commands/credentials/format-set-conflict-error.ts","../src/project/env-ref.ts","../src/project/resolve-project-root.ts","../src/project/load-project-env.ts","../src/commands/credentials/parse-value.ts","../src/commands/credentials/set.ts","../src/commands/credentials/update.ts","../src/commands/credentials/index.ts","../src/auth/resolve-login-targets.ts","../src/commands/auth/login.ts","../src/commands/auth/logout.ts","../src/commands/auth/status.ts","../src/commands/auth/index.ts","../src/commands/build.ts","../../../packages/storage/dist/pack-artifact.mjs","../src/project/collect-source.ts","../src/commands/deploy.ts","../src/project/runtime-child-env.ts","../src/project/bootstrap-run.ts","../src/process/run-processes.ts","../src/runtime/ensure-native-deps.ts","../src/runtime/resolve-runtime-node-modules.ts","../src/commands/dev.ts","../src/commands/project/run-project.ts","../src/commands/history/run-history.ts","../src/commands/history/index.ts","../src/commands/health.ts","../src/init/project-name.ts","../src/init/prompts.ts","../src/init/catalog-versions.ts","../src/init/copy-template.ts","../src/init/resolve-template-dir.ts","../src/init/project-files.ts","../src/skills/resolve-skills-bundle-dir.ts","../src/skills/sync-bundled-skills.ts","../src/init/scaffold-empty-src-dirs.ts","../src/init/scaffold-project-dotfiles.ts","../src/init/run-init.ts","../src/commands/init.ts","../src/commands/organization/run-organization.ts","../src/commands/organization/index.ts","../src/commands/project/index.ts","../src/commands/start.ts","../src/commands/trigger/list.ts","../src/commands/trigger/poll.ts","../src/commands/trigger/runs.ts","../src/commands/trigger/index.ts","../src/commands/workflow/list.ts","../src/commands/workflow/run.ts","../src/commands/workflow/runs.ts","../src/commands/workflow/index.ts","../src/commands/config/use-project.ts","../src/commands/config/preferences-patch.ts","../src/commands/config/preferences.ts","../src/commands/config/index.ts","../src/commands/skill/index.ts","../src/commands/skills.ts","../src/project/resolve-keystroke-config-root.ts","../src/skills/sync-skills.ts","../src/program.ts","../src/index.ts"],"sourcesContent":["import { originFromPublicUrl } from \"@keystrokehq/shared\";\n\nexport const DEFAULT_WEB_URL = \"https://app.keystroke.ai\";\nexport const DEFAULT_PLATFORM_URL = \"https://api.keystroke.ai\";\nexport const LOCAL_WEB_URL = \"http://localhost:3000\";\nexport const LOCAL_PLATFORM_URL = \"http://localhost:3002\";\n\nexport type ResolvePlatformUrlOptions = {\n platformUrl?: string;\n /** Used when webUrl does not match a known deployment. */\n fallback?: string;\n};\n\nfunction webOriginFromUrl(webUrl: string): string {\n return originFromPublicUrl(webUrl, webUrl.replace(/\\/+$/, \"\"));\n}\n\n/** Known web origins with a fixed platform API — undefined for custom/staging URLs. */\nexport function knownPlatformUrlForWebUrl(webUrl: string): string | undefined {\n const webOrigin = webOriginFromUrl(webUrl);\n\n if (webOrigin === LOCAL_WEB_URL || webOrigin === \"http://127.0.0.1:3000\") {\n return LOCAL_PLATFORM_URL;\n }\n\n if (webOrigin === DEFAULT_WEB_URL) {\n return DEFAULT_PLATFORM_URL;\n }\n\n return undefined;\n}\n\nexport function resolvePlatformUrlForWebUrl(\n webUrl: string,\n options: ResolvePlatformUrlOptions = {},\n): string {\n const explicit = options.platformUrl?.trim();\n if (explicit) {\n return explicit.replace(/\\/+$/, \"\");\n }\n\n const known = knownPlatformUrlForWebUrl(webUrl);\n if (known) {\n return known;\n }\n\n const fallback = options.fallback?.trim() || DEFAULT_PLATFORM_URL;\n return fallback.replace(/\\/+$/, \"\");\n}\n","import Conf from \"conf\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport {\n DEFAULT_PLATFORM_URL,\n DEFAULT_WEB_URL,\n knownPlatformUrlForWebUrl,\n resolvePlatformUrlForWebUrl,\n} from \"./resolve-platform-url\";\n\nexport type ApiTargetMode = \"local\" | \"platform\";\n\nexport type CliConfig = {\n serverUrl: string;\n webUrl: string;\n platformUrl: string;\n activeOrganizationId?: string;\n activeProjectId?: string;\n apiTarget?: ApiTargetMode;\n};\n\nexport function getCliConfigDir(cwd = join(homedir(), \".keystroke\")): string {\n return cwd;\n}\n\nexport function getConfigDir(config: Conf<CliConfig>): string {\n return dirname(config.path);\n}\n\nexport function getEffectiveApiTarget(config: Conf<CliConfig>): ApiTargetMode {\n const explicit = config.get(\"apiTarget\");\n if (explicit === \"local\" || explicit === \"platform\") {\n return explicit;\n }\n\n return \"local\";\n}\n\nfunction syncPlatformUrlWithWebUrl(config: Conf<CliConfig>): void {\n const webUrl = config.get(\"webUrl\");\n const known = knownPlatformUrlForWebUrl(webUrl);\n if (!known) {\n return;\n }\n\n const stored = config.get(\"platformUrl\");\n if (stored !== known) {\n config.set(\"platformUrl\", known);\n }\n}\n\nexport function createCliConfig(cwd = getCliConfigDir()): Conf<CliConfig> {\n const config = new Conf<CliConfig>({\n projectName: \"keystroke\",\n cwd,\n schema: {\n serverUrl: {\n type: \"string\",\n default: \"http://localhost:3001\",\n },\n webUrl: {\n type: \"string\",\n default: DEFAULT_WEB_URL,\n },\n platformUrl: {\n type: \"string\",\n default: DEFAULT_PLATFORM_URL,\n },\n activeOrganizationId: {\n type: \"string\",\n },\n activeProjectId: {\n type: \"string\",\n },\n apiTarget: {\n type: \"string\",\n enum: [\"local\", \"platform\"],\n },\n },\n });\n\n syncPlatformUrlWithWebUrl(config);\n return config;\n}\n\nexport function getServerUrl(config: Conf<CliConfig>): string {\n return config.get(\"serverUrl\");\n}\n\nexport function getWebUrl(config: Conf<CliConfig>): string {\n return config.get(\"webUrl\");\n}\n\nexport function getPlatformUrl(config: Conf<CliConfig>): string {\n return resolvePlatformUrlForWebUrl(getWebUrl(config), {\n fallback: config.get(\"platformUrl\"),\n });\n}\n","/**\nBase class for all Ky-specific errors. `HTTPError`, `NetworkError`, `TimeoutError`, and `ForceRetryError` extend this class.\n\nYou can use `instanceof KyError` to check if an error originated from Ky, or use the `isKyError()` type guard for cross-realm compatibility and TypeScript type narrowing.\n\nNote: `SchemaValidationError` is intentionally not considered a Ky error. `KyError` covers failures in Ky's HTTP lifecycle (bad status, timeout, retry), while schema validation errors originate from the user-provided schema, not from Ky itself.\n*/\nexport class KyError extends Error {\n name = 'KyError';\n get isKyError() {\n return true;\n }\n}\n//# sourceMappingURL=KyError.js.map","import { KyError } from './KyError.js';\n/**\nError thrown when the response has a non-2xx status code and `throwHttpErrors` is enabled.\n\nThe error has a `response` property with the `Response` object, a `request` property with the `Request` object, an `options` property with the normalized options (either passed to `ky` when creating an instance with `ky.create()` or directly when performing the request), and a `data` property with the pre-parsed response body. For JSON responses (based on `Content-Type`), the body is parsed using the `parseJson` option if set, or `JSON.parse` by default. For other content types, it is set as plain text. If the body is empty or parsing fails, `data` will be `undefined`. To avoid hanging or excessive buffering, `error.data` population is bounded by the request timeout and a 10 MiB response body size limit. The `data` property is populated before `beforeError` hooks run, so hooks can access it.\n\nThe response body is automatically consumed when populating `error.data`, so `error.response.json()` and other body methods will not work. Use `error.data` instead. The `error.response` object is still available for headers, status, etc.\n\nBe aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError` and will not contain a `response` property.\n*/\nexport class HTTPError extends KyError {\n name = 'HTTPError';\n response;\n request;\n options;\n data;\n constructor(response, request, options) {\n const code = (response.status || response.status === 0) ? response.status : '';\n const title = response.statusText ?? '';\n const status = `${code} ${title}`.trim();\n const reason = status ? `status code ${status}` : 'an unknown error';\n super(`Request failed with ${reason}: ${request.method} ${request.url}`);\n this.response = response;\n this.request = request;\n this.options = options;\n }\n}\n//# sourceMappingURL=HTTPError.js.map","import { KyError } from './KyError.js';\n/**\nError thrown when a network error occurs during the request (e.g., DNS failure, connection refused, offline). It has a `request` property with the `Request` object. The original error is available via the standard `cause` property.\n\nNetwork errors are automatically retried (for retriable methods).\n\nNote: Network errors are detected using runtime-specific heuristics. Unrecognized runtimes may produce errors that are not wrapped in `NetworkError`. Use the `shouldRetry` option to handle such cases.\n*/\nexport class NetworkError extends KyError {\n name = 'NetworkError';\n request;\n constructor(request, options) {\n super(`Request failed due to a network error: ${request.method} ${request.url}`, options);\n this.request = request;\n }\n}\n//# sourceMappingURL=NetworkError.js.map","/**\nWrapper for non-Error values that were thrown.\n\nIn JavaScript, any value can be thrown (not just Error instances). This class wraps such values to ensure consistent error handling.\n*/\nexport class NonError extends Error {\n name = 'NonError';\n value;\n constructor(value) {\n let message = 'Non-error value was thrown';\n // Intentionally minimal as this error is just an edge-case.\n try {\n if (typeof value === 'string') {\n message = value;\n }\n else if (value && typeof value === 'object' && 'message' in value && typeof value.message === 'string') {\n message = value.message;\n }\n }\n catch {\n // Use default message if accessing properties throws\n }\n super(message);\n this.value = value;\n }\n}\n//# sourceMappingURL=NonError.js.map","import { KyError } from './KyError.js';\nimport { NonError } from './NonError.js';\n/**\nError used to signal a forced retry from `afterResponse` hooks.\n\nThis is thrown when `ky.retry()` is returned from an `afterResponse` hook. It is observable in `beforeRetry` and `beforeError` hooks via the `isForceRetryError()` type guard.\n*/\nexport class ForceRetryError extends KyError {\n name = 'ForceRetryError';\n customDelay;\n code;\n customRequest;\n constructor(options) {\n // Runtime protection: wrap non-Error causes in NonError\n // TypeScript type is Error for guidance, but JS users can pass anything\n const cause = options?.cause\n ? (options.cause instanceof Error ? options.cause : new NonError(options.cause))\n : undefined;\n super(options?.code ? `Forced retry: ${options.code}` : 'Forced retry', cause ? { cause } : undefined);\n this.customDelay = options?.delay;\n this.code = options?.code;\n this.customRequest = options?.request;\n }\n}\n//# sourceMappingURL=ForceRetryError.js.map","/**\nThe error thrown when [Standard Schema](https://github.com/standard-schema/standard-schema) validation fails in `.json(schema)`. It has an `issues` property with the validation issues from the schema.\n\nThis error intentionally does not extend `KyError` because it does not represent a failure in Ky's HTTP lifecycle. The request succeeded; the user's schema rejected the data. As such, it is not matched by `isKyError()`.\n\n@example\n```\nimport ky, {SchemaValidationError} from 'ky';\nimport {z} from 'zod';\n\nconst userSchema = z.object({name: z.string()});\n\ntry {\n const user = await ky('/api/user').json(userSchema);\n console.log(user.name);\n} catch (error) {\n if (error instanceof SchemaValidationError) {\n console.error(error.issues);\n }\n}\n```\n*/\nexport class SchemaValidationError extends Error {\n name = 'SchemaValidationError';\n issues;\n constructor(issues) {\n super('Response schema validation failed');\n this.issues = issues;\n }\n}\n//# sourceMappingURL=SchemaValidationError.js.map","import { KyError } from './KyError.js';\n/**\nError thrown when the request times out. It has a `request` property with the `Request` object.\n*/\nexport class TimeoutError extends KyError {\n name = 'TimeoutError';\n request;\n constructor(request) {\n super(`Request timed out: ${request.method} ${request.url}`);\n this.request = request;\n }\n}\n//# sourceMappingURL=TimeoutError.js.map","export const supportsRequestStreams = (() => {\n let duplexAccessed = false;\n let hasContentType = false;\n const supportsReadableStream = typeof globalThis.ReadableStream === 'function';\n const supportsRequest = typeof globalThis.Request === 'function';\n if (supportsReadableStream && supportsRequest) {\n try {\n hasContentType = new globalThis.Request('https://empty.invalid', {\n body: new globalThis.ReadableStream(),\n method: 'POST',\n // @ts-expect-error - Types are outdated.\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n }\n catch (error) {\n // QQBrowser on iOS throws \"unsupported BodyInit type\" error (see issue #581)\n if (error instanceof Error && error.message === 'unsupported BodyInit type') {\n return false;\n }\n throw error;\n }\n }\n return duplexAccessed && !hasContentType;\n})();\nexport const supportsAbortController = typeof globalThis.AbortController === 'function';\nexport const supportsAbortSignal = typeof globalThis.AbortSignal === 'function' && typeof globalThis.AbortSignal.any === 'function';\nexport const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';\nexport const supportsFormData = typeof globalThis.FormData === 'function';\nexport const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];\nconst validate = () => undefined;\nvalidate();\nexport const responseTypes = {\n json: 'application/json',\n text: 'text/*',\n formData: 'multipart/form-data',\n arrayBuffer: '*/*',\n blob: '*/*',\n // Supported in modern Fetch implementations (for example, browsers and recent Node.js/undici).\n // We still feature-check at runtime before exposing the shortcut.\n bytes: '*/*',\n};\n// The maximum value of a 32bit int (see issue #117)\nexport const maxSafeTimeout = 2_147_483_647;\n// Size in bytes of a typical form boundary (e.g., '------WebKitFormBoundaryaxpyiPgbbPti10Rw'), used to help estimate upload size\nexport const usualFormBoundarySize = 40;\n/**\nSymbol that can be returned by a `beforeRetry` hook to stop retrying without throwing an error.\n*/\nexport const stop = Symbol('stop');\n/**\nMarker returned by `ky.retry()` to signal a forced retry from `afterResponse` hooks.\n*/\nexport class RetryMarker {\n options;\n constructor(options) {\n this.options = options;\n }\n}\n/**\nForce a retry from an `afterResponse` hook.\n\nThis allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`.\n\n@param options - Optional configuration for the retry.\n\n@example\n```\nimport ky, {isForceRetryError} from 'ky';\n\nconst api = ky.extend({\n hooks: {\n afterResponse: [\n async ({request, response}) => {\n // Retry based on response body content\n if (response.status === 200) {\n const data = await response.json();\n\n // Simple retry with default delay\n if (data.error?.code === 'TEMPORARY_ERROR') {\n return ky.retry();\n }\n\n // Retry with custom delay from API response\n if (data.error?.code === 'RATE_LIMIT') {\n return ky.retry({\n delay: data.error.retryAfter * 1000,\n code: 'RATE_LIMIT'\n });\n }\n\n // Retry with a modified request (e.g., fallback endpoint)\n if (data.error?.code === 'FALLBACK_TO_BACKUP') {\n return ky.retry({\n request: new Request('https://backup-api.com/endpoint', {\n method: request.method,\n headers: request.headers,\n }),\n code: 'BACKUP_ENDPOINT'\n });\n }\n\n // Retry with refreshed authentication\n if (data.error?.code === 'TOKEN_REFRESH' && data.newToken) {\n return ky.retry({\n request: new Request(request, {\n headers: {\n ...Object.fromEntries(request.headers),\n 'Authorization': `Bearer ${data.newToken}`\n }\n }),\n code: 'TOKEN_REFRESHED'\n });\n }\n\n // Retry with cause to preserve error chain\n try {\n validateResponse(data);\n } catch (error) {\n return ky.retry({\n code: 'VALIDATION_FAILED',\n cause: error\n });\n }\n }\n }\n ],\n beforeRetry: [\n ({error, retryCount}) => {\n // Observable in beforeRetry hooks\n if (isForceRetryError(error)) {\n console.log(`Forced retry #${retryCount}: ${error.message}`);\n // Example output: \"Forced retry #1: Forced retry: RATE_LIMIT\"\n }\n }\n ]\n }\n});\n\nconst response = await api.get('https://example.com/api');\n```\n*/\nexport const retry = (options) => new RetryMarker(options);\nexport const kyOptionKeys = {\n json: true,\n parseJson: true,\n stringifyJson: true,\n searchParams: true,\n baseUrl: true,\n prefix: true,\n retry: true,\n timeout: true,\n totalTimeout: true,\n hooks: true,\n throwHttpErrors: true,\n onDownloadProgress: true,\n onUploadProgress: true,\n fetch: true,\n context: true,\n};\n// Standard RequestInit options that should NOT be passed separately to fetch()\n// because they're already applied to the Request object.\n// Note: `dispatcher` and `priority` are NOT included here - they're fetch-only\n// options that the Request constructor doesn't accept, so they need to be passed\n// separately to fetch().\nexport const requestOptionsRegistry = {\n method: true,\n headers: true,\n body: true,\n mode: true,\n credentials: true,\n cache: true,\n redirect: true,\n referrer: true,\n referrerPolicy: true,\n integrity: true,\n keepalive: true,\n signal: true,\n window: true,\n duplex: true,\n};\n//# sourceMappingURL=constants.js.map","import { usualFormBoundarySize } from '../core/constants.js';\nconst encoder = new TextEncoder();\n// eslint-disable-next-line @typescript-eslint/no-restricted-types\nexport const getBodySize = (body) => {\n if (!body) {\n return 0;\n }\n if (body instanceof FormData) {\n // This is an approximation, as FormData size calculation is not straightforward\n let size = 0;\n for (const [key, value] of body) {\n size += usualFormBoundarySize;\n size += encoder.encode(`Content-Disposition: form-data; name=\"${key}\"`).byteLength;\n size += typeof value === 'string'\n ? encoder.encode(value).byteLength\n : value.size;\n }\n return size;\n }\n if (body instanceof Blob) {\n return body.size;\n }\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\n return body.byteLength;\n }\n if (typeof body === 'string') {\n return encoder.encode(body).byteLength;\n }\n if (body instanceof URLSearchParams) {\n return encoder.encode(body.toString()).byteLength;\n }\n return 0;\n};\nconst withProgress = (stream, totalBytes, onProgress) => {\n let previousChunk;\n let transferredBytes = 0;\n return stream.pipeThrough(new TransformStream({\n transform(currentChunk, controller) {\n controller.enqueue(currentChunk);\n if (previousChunk) {\n transferredBytes += previousChunk.byteLength;\n let percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;\n // Avoid reporting 100% progress before the stream is actually finished (in case totalBytes is inaccurate)\n if (percent >= 1) {\n // Epsilon is used here to get as close as possible to 100% without reaching it.\n // If we were to use 0.99 here, percent could potentially go backwards.\n percent = 1 - Number.EPSILON;\n }\n onProgress?.({ percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);\n }\n previousChunk = currentChunk;\n },\n flush() {\n if (previousChunk) {\n transferredBytes += previousChunk.byteLength;\n onProgress?.({ percent: 1, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);\n }\n },\n }));\n};\nexport const streamResponse = (response, onDownloadProgress) => {\n if (!response.body) {\n return response;\n }\n const responseInit = {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n };\n if (response.status === 204) {\n return new Response(null, responseInit);\n }\n const totalBytes = Math.max(0, Number(response.headers.get('content-length')) || 0);\n return new Response(withProgress(response.body, totalBytes, onDownloadProgress), responseInit);\n};\n// eslint-disable-next-line @typescript-eslint/no-restricted-types\nexport const streamRequest = (request, onUploadProgress, originalBody) => {\n if (!request.body) {\n return request;\n }\n // Use original body for size calculation since request.body is already a stream\n const totalBytes = getBodySize(originalBody ?? request.body);\n return new Request(request, {\n // @ts-expect-error - Types are outdated.\n duplex: 'half',\n body: withProgress(request.body, totalBytes, onUploadProgress),\n });\n};\n//# sourceMappingURL=body.js.map","// eslint-disable-next-line @typescript-eslint/no-restricted-types\nexport const isObject = (value) => value !== null && typeof value === 'object';\n//# sourceMappingURL=is.js.map","import { supportsAbortSignal } from '../core/constants.js';\nimport { isObject } from './is.js';\nconst replaceSymbol = Symbol('replaceOption');\nconst getReplaceState = (value) => isObject(value) && value[replaceSymbol] === true\n ? {\n isReplace: true,\n value: value.value,\n }\n : {\n isReplace: false,\n value,\n };\n/**\nWraps a value so that `ky.extend()` will replace the parent value instead of merging with it. Works with hooks, headers, search parameters, context, and any other deep-merged option.\n\nBy default, `.extend()` deep-merges options with the parent instance: hooks get appended, headers get merged, and search parameters get accumulated. Use `replaceOption` when you want to fully replace a merged property instead.\n\n@example\n```\nimport ky, {replaceOption} from 'ky';\n\nconst base = ky.create({\n hooks: {beforeRequest: [addAuth, addTracking]},\n});\n\n// Replaces instead of appending\nconst extended = base.extend({\n hooks: replaceOption({beforeRequest: [onlyThis]}),\n});\n// hooks.beforeRequest is now [onlyThis], not [addAuth, addTracking, onlyThis]\n```\n*/\nexport const replaceOption = (value) => {\n const markedValue = { [replaceSymbol]: true, value };\n return markedValue;\n};\nexport const validateAndMerge = (...sources) => {\n for (const source of sources) {\n if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {\n throw new TypeError('The `options` argument must be an object');\n }\n }\n return deepMerge({}, ...sources);\n};\nexport const mergeHeaders = (source1 = {}, source2 = {}) => {\n const result = new globalThis.Headers(source1);\n const isHeadersInstance = source2 instanceof globalThis.Headers;\n const source = new globalThis.Headers(source2);\n for (const [key, value] of source.entries()) {\n if ((isHeadersInstance && value === 'undefined') || value === undefined) {\n result.delete(key);\n }\n else {\n result.set(key, value);\n }\n }\n return result;\n};\nconst isPlainObject = (value) => {\n if (!isObject(value) || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\nexport const cloneShallow = (value) => {\n if (value instanceof URLSearchParams) {\n const copy = new URLSearchParams(value);\n const deleted = value[deletedParametersSymbol];\n if (deleted) {\n // Preserve internal deletion markers so init-hook cloning does not resurrect params removed during option merging.\n copy[deletedParametersSymbol] = new Set(deleted);\n }\n return copy;\n }\n if (value instanceof globalThis.Headers) {\n return new globalThis.Headers(value);\n }\n if (Array.isArray(value)) {\n return [...value];\n }\n if (isPlainObject(value)) {\n const copy = { ...value };\n return copy;\n }\n return value;\n};\nconst normalizeHeaderObject = (headers) => Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== undefined));\nconst mergeHeaderContainers = (source1, source2) => {\n if (isPlainObject(source1) && isPlainObject(source2)) {\n return normalizeHeaderObject({ ...source1, ...source2 });\n }\n return mergeHeaders(source1, source2);\n};\nfunction newHookValue(original, incoming, property) {\n return (Object.hasOwn(incoming, property) && incoming[property] === undefined)\n ? []\n : deepMerge(original[property] ?? [], incoming[property] ?? []);\n}\nexport const mergeHooks = (original = {}, incoming = {}) => ({\n init: newHookValue(original, incoming, 'init'),\n beforeRequest: newHookValue(original, incoming, 'beforeRequest'),\n beforeRetry: newHookValue(original, incoming, 'beforeRetry'),\n beforeError: newHookValue(original, incoming, 'beforeError'),\n afterResponse: newHookValue(original, incoming, 'afterResponse'),\n});\nexport const deletedParametersSymbol = Symbol('deletedParameters');\nconst appendSearchParameters = (target, source) => {\n const result = new URLSearchParams();\n const deleted = new Set();\n for (const input of [target, source]) {\n if (input === undefined) {\n continue;\n }\n if (input instanceof URLSearchParams) {\n for (const [key, value] of input.entries()) {\n result.append(key, value);\n deleted.delete(key);\n }\n const inputDeleted = input[deletedParametersSymbol];\n if (inputDeleted) {\n for (const key of inputDeleted) {\n result.delete(key);\n deleted.add(key);\n }\n }\n }\n else if (Array.isArray(input)) {\n for (const pair of input) {\n if (!Array.isArray(pair) || pair.length !== 2) {\n throw new TypeError('Array search parameters must be provided in [[key, value], ...] format');\n }\n result.append(String(pair[0]), String(pair[1]));\n deleted.delete(String(pair[0]));\n }\n }\n else if (isObject(input)) {\n for (const [key, value] of Object.entries(input)) {\n if (value === undefined) {\n result.delete(key);\n deleted.add(key);\n }\n else {\n result.append(key, String(value));\n deleted.delete(key);\n }\n }\n }\n else {\n // String\n const parameters = new URLSearchParams(input);\n for (const [key, value] of parameters.entries()) {\n result.append(key, value);\n deleted.delete(key);\n }\n }\n }\n if (deleted.size > 0) {\n result[deletedParametersSymbol] = deleted;\n }\n return result;\n};\n// TODO: Make this strongly-typed (no `any`).\nexport const deepMerge = (...sources) => {\n let returnValue = {};\n let headers = {};\n let hooks = {};\n let searchParameters;\n const signals = [];\n for (const source of sources) {\n if (Array.isArray(source)) {\n if (!Array.isArray(returnValue)) {\n returnValue = [];\n }\n returnValue = [...returnValue, ...source];\n }\n else if (isObject(source)) {\n for (let [key, value] of Object.entries(source)) {\n // Special handling for AbortSignal instances\n if (key === 'signal' && value instanceof globalThis.AbortSignal) {\n signals.push(value);\n continue;\n }\n const replaceState = getReplaceState(value);\n const { isReplace } = replaceState;\n value = replaceState.value;\n // Special handling for context - shallow merge only\n if (key === 'context') {\n if (value !== undefined && value !== null && (!isObject(value) || Array.isArray(value))) {\n throw new TypeError('The `context` option must be an object');\n }\n // Shallow merge: always create a new object to prevent mutation bugs\n returnValue = {\n ...returnValue,\n context: (value === undefined || value === null)\n ? {}\n : (isReplace\n ? { ...value }\n : { ...returnValue.context, ...value }),\n };\n continue;\n }\n // Special handling for searchParams\n if (key === 'searchParams') {\n if (value === undefined || value === null) {\n // Explicit undefined or null removes searchParams\n searchParameters = undefined;\n }\n else if (isReplace) {\n searchParameters = value;\n }\n else {\n // First source: keep as-is to preserve type (string/object/URLSearchParams)\n // Subsequent sources: merge and convert to URLSearchParams\n searchParameters = searchParameters === undefined ? value : appendSearchParameters(searchParameters, value);\n }\n continue;\n }\n if (isObject(value) && !isReplace && key in returnValue) {\n value = deepMerge(returnValue[key], value);\n }\n returnValue = { ...returnValue, [key]: value };\n }\n if (isObject(source.hooks)) {\n const { value: hookValue, isReplace } = getReplaceState(source.hooks);\n hooks = isReplace\n ? mergeHooks({}, hookValue)\n : mergeHooks(hooks, hookValue);\n returnValue.hooks = hooks;\n }\n if (isObject(source.headers)) {\n const { value: headerValue, isReplace } = getReplaceState(source.headers);\n headers = isReplace\n ? cloneShallow(headerValue)\n : mergeHeaderContainers(headers, headerValue);\n returnValue.headers = headers;\n }\n }\n }\n if (searchParameters !== undefined) {\n returnValue.searchParams = searchParameters;\n }\n if (signals.length > 0) {\n if (signals.length === 1) {\n returnValue.signal = signals[0];\n }\n else if (supportsAbortSignal) {\n returnValue.signal = AbortSignal.any(signals);\n }\n else {\n // When AbortSignal.any is not available, use the last signal\n // This maintains the previous behavior before signal merging was added\n // This can be remove when the `supportsAbortSignal` check is removed.`\n returnValue.signal = signals.at(-1);\n }\n }\n return returnValue;\n};\n//# sourceMappingURL=merge.js.map","import { requestMethods } from '../core/constants.js';\nexport const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;\nconst retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];\nconst retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];\nconst retryAfterStatusCodes = [413, 429, 503];\nconst defaultRetryOptions = {\n limit: 2,\n methods: retryMethods,\n statusCodes: retryStatusCodes,\n afterStatusCodes: retryAfterStatusCodes,\n maxRetryAfter: Number.POSITIVE_INFINITY,\n backoffLimit: Number.POSITIVE_INFINITY,\n delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,\n jitter: undefined,\n retryOnTimeout: false,\n};\nexport const normalizeRetryOptions = (retry = {}) => {\n if (typeof retry === 'number') {\n return {\n ...defaultRetryOptions,\n limit: retry,\n };\n }\n if (retry.methods && !Array.isArray(retry.methods)) {\n throw new Error('retry.methods must be an array');\n }\n if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {\n throw new Error('retry.statusCodes must be an array');\n }\n const normalizedRetry = Object.fromEntries(Object.entries({\n ...retry,\n methods: retry.methods?.map(method => method.toLowerCase()),\n }).filter(([, value]) => value !== undefined));\n return {\n ...defaultRetryOptions,\n ...normalizedRetry,\n };\n};\n//# sourceMappingURL=normalize.js.map","import { TimeoutError } from '../errors/TimeoutError.js';\n// `Promise.race()` workaround (#91)\nexport default async function timeout(request, init, abortController, options) {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n if (abortController) {\n abortController.abort();\n }\n reject(new TimeoutError(request));\n }, options.timeout);\n void options\n .fetch(request, init)\n .then(resolve)\n .catch(reject)\n .then(() => {\n clearTimeout(timeoutId);\n });\n });\n}\n//# sourceMappingURL=timeout.js.map","// https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111\nexport default async function delay(ms, { signal }) {\n return new Promise((resolve, reject) => {\n if (signal) {\n signal.throwIfAborted();\n signal.addEventListener('abort', abortHandler, { once: true });\n }\n function abortHandler() {\n clearTimeout(timeoutId);\n reject(signal.reason);\n }\n const timeoutId = setTimeout(() => {\n signal?.removeEventListener('abort', abortHandler);\n resolve();\n }, ms);\n });\n}\n//# sourceMappingURL=delay.js.map","import { kyOptionKeys, requestOptionsRegistry } from '../core/constants.js';\nimport { deletedParametersSymbol } from './merge.js';\nexport const findUnknownOptions = (options) => {\n const unknownOptions = {};\n for (const key in options) {\n // Skip inherited properties\n if (!Object.hasOwn(options, key)) {\n continue;\n }\n // Forward every non-standard, non-Ky option to fetch().\n // We intentionally do not check whether the key also exists on `Request`, because some runtimes\n // patch `Request.prototype` with fetch-only extensions. For example, Next.js adds `next`, and the\n // old `key in request` heuristic dropped it unless Ky kept a special-case allowlist.\n // Passing all non-standard keys makes that allowlist unnecessary and preserves future fetch extensions too.\n if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys)) {\n unknownOptions[key] = options[key];\n }\n }\n return unknownOptions;\n};\nexport const hasSearchParameters = (search) => {\n if (search === undefined) {\n return false;\n }\n // The `typeof array` still gives \"object\", so we need different checking for array.\n if (Array.isArray(search)) {\n return search.length > 0;\n }\n if (search instanceof URLSearchParams) {\n return search.size > 0 || Boolean(search[deletedParametersSymbol]?.size);\n }\n // Record\n if (typeof search === 'object') {\n return Object.keys(search).length > 0;\n }\n if (typeof search === 'string') {\n return search.trim().length > 0;\n }\n return Boolean(search);\n};\n//# sourceMappingURL=options.js.map","// Inlined from https://github.com/sindresorhus/is-network-error v1.3.1\nconst objectToString = Object.prototype.toString;\nconst isError = (value) => objectToString.call(value) === '[object Error]';\nconst errorMessages = new Set([\n 'network error', // Chrome\n 'NetworkError when attempting to fetch resource.', // Firefox\n 'The Internet connection appears to be offline.', // Safari 16\n 'Network request failed', // `cross-fetch`\n 'fetch failed', // Undici (Node.js)\n 'terminated', // Undici (Node.js)\n ' A network error occurred.', // Bun (WebKit) - leading space is intentional\n 'Network connection lost', // Cloudflare Workers (fetch)\n]);\nexport default function isRawNetworkError(error) {\n const isValid = error\n && isError(error)\n && error.name === 'TypeError'\n && typeof error.message === 'string';\n if (!isValid) {\n return false;\n }\n const { message, stack } = error;\n // Safari 17+ has generic message but no stack for network errors\n if (message === 'Load failed') {\n return stack === undefined\n // Sentry adds its own stack trace to the fetch error, so also check for that\n || '__sentry_captured__' in error;\n }\n // Deno network errors start with specific text\n if (message.startsWith('error sending request for url')) {\n return true;\n }\n // Chrome: exact \"Failed to fetch\" or with hostname: \"Failed to fetch (example.com)\"\n if (message === 'Failed to fetch' || (message.startsWith('Failed to fetch (') && message.endsWith(')'))) {\n return true;\n }\n // Standard network error messages\n return errorMessages.has(message);\n}\n//# sourceMappingURL=is-network-error.js.map","import { HTTPError } from '../errors/HTTPError.js';\nimport { NetworkError } from '../errors/NetworkError.js';\nimport { TimeoutError } from '../errors/TimeoutError.js';\nimport { ForceRetryError } from '../errors/ForceRetryError.js';\n// Handles cross-realm cases (e.g., iframes, different JS contexts) where `instanceof` fails.\nconst isErrorType = (error, cls) => error instanceof cls || error?.name === cls.name;\n/**\nType guard to check if an error is a `KyError`.\n\nNote: `SchemaValidationError` is intentionally not considered a Ky error. `KyError` covers failures in Ky's HTTP lifecycle (bad status, timeout, retry), while schema validation errors originate from the user-provided schema, not from Ky itself.\n\n@param error - The error to check\n@returns `true` if the error is a Ky error, `false` otherwise\n\n@example\n```\nimport ky, {isKyError} from 'ky';\ntry {\n const response = await ky.get('/api/data');\n} catch (error) {\n if (isKyError(error)) {\n // Handle Ky-specific errors\n console.log('Ky error occurred:', error.message);\n } else {\n // Handle other errors\n console.log('Unknown error:', error);\n }\n}\n```\n*/\nexport function isKyError(error) {\n return error?.isKyError === true || isHTTPError(error) || isNetworkError(error) || isTimeoutError(error) || isForceRetryError(error);\n}\n/**\nType guard to check if an error is an `HTTPError`.\n\n@param error - The error to check\n@returns `true` if the error is an `HTTPError`, `false` otherwise\n\n@example\n```\nimport ky, {isHTTPError} from 'ky';\ntry {\n const response = await ky.get('/api/data');\n} catch (error) {\n if (isHTTPError(error)) {\n console.log('HTTP error status:', error.response.status);\n }\n}\n```\n*/\nexport function isHTTPError(error) {\n return isErrorType(error, HTTPError);\n}\n/**\nType guard to check if an error is a `NetworkError`.\n\n@param error - The error to check\n@returns `true` if the error is a `NetworkError`, `false` otherwise\n\n@example\n```\nimport ky, {isNetworkError} from 'ky';\ntry {\n const response = await ky.get('/api/data');\n} catch (error) {\n if (isNetworkError(error)) {\n console.log('Network error:', error.request.url);\n }\n}\n```\n*/\nexport function isNetworkError(error) {\n return isErrorType(error, NetworkError);\n}\n/**\nType guard to check if an error is a `TimeoutError`.\n\n@param error - The error to check\n@returns `true` if the error is a `TimeoutError`, `false` otherwise\n\n@example\n```\nimport ky, {isTimeoutError} from 'ky';\ntry {\n const response = await ky.get('/api/data', { timeout: 1000 });\n} catch (error) {\n if (isTimeoutError(error)) {\n console.log('Request timed out:', error.request.url);\n }\n}\n```\n*/\nexport function isTimeoutError(error) {\n return isErrorType(error, TimeoutError);\n}\n/**\nType guard to check if an error is a `ForceRetryError`.\n\n@param error - The error to check\n@returns `true` if the error is a `ForceRetryError`, `false` otherwise\n\n@example\n```\nimport ky, {isForceRetryError} from 'ky';\n\nconst api = ky.extend({\n hooks: {\n beforeRetry: [\n ({error, retryCount}) => {\n if (isForceRetryError(error)) {\n console.log(`Forced retry #${retryCount}: ${error.code}`);\n }\n }\n ]\n }\n});\n```\n*/\nexport function isForceRetryError(error) {\n return isErrorType(error, ForceRetryError);\n}\n//# sourceMappingURL=type-guards.js.map","import { HTTPError } from '../errors/HTTPError.js';\nimport { NetworkError } from '../errors/NetworkError.js';\nimport { NonError } from '../errors/NonError.js';\nimport { ForceRetryError } from '../errors/ForceRetryError.js';\nimport { SchemaValidationError } from '../errors/SchemaValidationError.js';\nimport { TimeoutError } from '../errors/TimeoutError.js';\nimport { streamRequest, streamResponse } from '../utils/body.js';\nimport { cloneShallow, mergeHeaders, mergeHooks, deletedParametersSymbol, } from '../utils/merge.js';\nimport { normalizeRequestMethod, normalizeRetryOptions } from '../utils/normalize.js';\nimport timeout from '../utils/timeout.js';\nimport delay from '../utils/delay.js';\nimport { findUnknownOptions, hasSearchParameters } from '../utils/options.js';\nimport isRawNetworkError from '../utils/is-network-error.js';\nimport { isHTTPError, isNetworkError, isTimeoutError } from '../utils/type-guards.js';\nimport { maxSafeTimeout, responseTypes, stop, RetryMarker, supportsAbortController, supportsAbortSignal, supportsFormData, supportsResponseStreams, supportsRequestStreams, } from './constants.js';\nconst maxErrorResponseBodySize = 10 * 1024 * 1024;\nconst prefixUrlRenamedErrorMessage = 'The `prefixUrl` option has been renamed `prefix` in v2 and enhanced to allow slashes in input. See also the new `baseUrl` option for improved flexibility with standard URL resolution: https://github.com/sindresorhus/ky#baseurl';\nconst timedOutResponseData = Symbol('timedOutResponseData');\nconst createTextDecoder = (contentType) => {\n const match = /;\\s*charset\\s*=\\s*(?:\"([^\"]+)\"|([^;,\\s]+))/i.exec(contentType);\n const charset = match?.[1] ?? match?.[2];\n if (charset) {\n try {\n return new TextDecoder(charset);\n }\n catch { }\n }\n return new TextDecoder();\n};\nconst invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';\nconst cloneRetryOptions = (retry) => {\n if (typeof retry !== 'object') {\n return retry;\n }\n // Clone nested arrays too so init hooks can mutate retry config without leaking state across requests.\n return {\n ...retry,\n ...(retry.methods && { methods: [...retry.methods] }),\n ...(retry.statusCodes && { statusCodes: [...retry.statusCodes] }),\n ...(retry.afterStatusCodes && { afterStatusCodes: [...retry.afterStatusCodes] }),\n };\n};\nconst objectToString = Object.prototype.toString;\nconst isRequestInstance = (value) => value instanceof globalThis.Request || objectToString.call(value) === '[object Request]';\n// Accepted custom responses are treated as full Responses throughout Ky.\n// If a custom fetch returns one, it must behave like a Response for cloning,\n// body consumption, `json()` decoration, and any enabled stream features.\nconst isResponseInstance = (value) => value instanceof globalThis.Response || objectToString.call(value) === '[object Response]';\nconst cloneSearchParametersForInitHook = (searchParameters) => {\n if (Array.isArray(searchParameters)) {\n return searchParameters.map(parameter => [...parameter]);\n }\n return cloneShallow(searchParameters);\n};\n// Shallow-clone mutable option properties so init hook mutations don't leak across requests.\nfunction cloneInitHookOptions(options) {\n const clonedOptions = {\n ...options,\n json: cloneShallow(options.json),\n context: cloneShallow(options.context),\n headers: cloneShallow(options.headers),\n searchParams: cloneSearchParametersForInitHook(options.searchParams),\n };\n if (options.retry !== undefined) {\n clonedOptions.retry = cloneRetryOptions(options.retry);\n }\n return clonedOptions;\n}\nconst validateJsonWithSchema = async (jsonValue, schema) => {\n if ((typeof schema !== 'object'\n && typeof schema !== 'function')\n || schema === null) {\n throw new TypeError(invalidSchemaMessage);\n }\n const standardSchema = schema['~standard'];\n if (typeof standardSchema !== 'object'\n || standardSchema === null\n || typeof standardSchema.validate !== 'function') {\n throw new TypeError(invalidSchemaMessage);\n }\n const validationResult = await standardSchema.validate(jsonValue);\n if (validationResult.issues) {\n throw new SchemaValidationError(validationResult.issues);\n }\n return validationResult.value;\n};\nexport class Ky {\n static create(input, options) {\n const initHooks = options.hooks?.init ?? [];\n const initHookOptions = initHooks.length > 0 ? cloneInitHookOptions(options) : options;\n for (const hook of initHooks) {\n hook(initHookOptions);\n }\n const ky = new Ky(input, initHookOptions);\n const function_ = async () => {\n if (typeof ky.#options.timeout === 'number' && ky.#options.timeout > maxSafeTimeout) {\n throw new RangeError(`The \\`timeout\\` option cannot be greater than ${maxSafeTimeout}`);\n }\n if (typeof ky.#options.totalTimeout === 'number' && ky.#options.totalTimeout > maxSafeTimeout) {\n throw new RangeError(`The \\`totalTimeout\\` option cannot be greater than ${maxSafeTimeout}`);\n }\n // Delay the fetch so that body method shortcuts can set the Accept header\n await Promise.resolve();\n const beforeRequestResponse = await ky.#runBeforeRequestHooks();\n let response = beforeRequestResponse ?? await ky.#retry(async () => ky.#fetch());\n let responseFromHook = beforeRequestResponse !== undefined\n || ky.#consumeReturnedResponseFromBeforeRetryHook();\n for (;;) {\n // `undefined` means a hook stopped the flow without providing a response.\n // Non-native Responses still continue through Ky if they pass `isResponseInstance()`.\n if (response === undefined) {\n return response;\n }\n if (isResponseInstance(response)) {\n try {\n // eslint-disable-next-line no-await-in-loop\n response = await ky.#runAfterResponseHooks(response);\n }\n catch (error) {\n if (!(error instanceof ForceRetryError)) {\n throw error;\n }\n // eslint-disable-next-line no-await-in-loop\n const retriedResponse = await ky.#retryFromError(error, async () => ky.#fetch());\n if (retriedResponse === undefined) {\n return retriedResponse;\n }\n response = retriedResponse;\n responseFromHook = ky.#consumeReturnedResponseFromBeforeRetryHook();\n continue;\n }\n }\n const currentResponse = response;\n // Opaque responses (`response.type === 'opaque'`) from `no-cors` requests always have `status: 0` and `ok: false`, but this is not a failure - the actual status is hidden by the browser.\n if (!currentResponse.ok && currentResponse.type !== 'opaque' && (typeof ky.#options.throwHttpErrors === 'function'\n ? ky.#options.throwHttpErrors(currentResponse.status)\n : ky.#options.throwHttpErrors)) {\n // `request` must reflect the request that actually failed, but `options` stays as Ky's\n // normalized options snapshot. Replacement `Request` instances do not preserve the\n // original `BodyInit`, so trying to make `options` mirror arbitrary requests would be lossy.\n const httpError = new HTTPError(currentResponse, ky.#getResponseRequest(currentResponse), ky.#getNormalizedOptions());\n const errorToThrow = httpError;\n // eslint-disable-next-line no-await-in-loop\n httpError.data = await ky.#getResponseData(currentResponse);\n if (responseFromHook) {\n throw errorToThrow;\n }\n // eslint-disable-next-line no-await-in-loop\n const retriedResponse = await ky.#retryFromError(httpError, async () => ky.#fetch());\n if (retriedResponse === undefined) {\n return retriedResponse;\n }\n response = retriedResponse;\n responseFromHook = ky.#consumeReturnedResponseFromBeforeRetryHook();\n continue;\n }\n break;\n }\n if (!isResponseInstance(response)) {\n return response;\n }\n ky.#decorateResponse(response);\n // If `onDownloadProgress` is passed, it uses the stream API internally\n if (ky.#options.onDownloadProgress) {\n if (typeof ky.#options.onDownloadProgress !== 'function') {\n throw new TypeError('The `onDownloadProgress` option must be a function');\n }\n if (!supportsResponseStreams) {\n throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');\n }\n const progressResponse = response.clone();\n ky.#cancelResponseBody(response);\n return streamResponse(progressResponse, ky.#options.onDownloadProgress);\n }\n return response;\n };\n const result = (async () => {\n try {\n return await function_();\n }\n catch (error) {\n // Non-Error throws (e.g., thrown strings) pass through unchanged\n if (!(error instanceof Error)) {\n throw error;\n }\n // Errors thrown by beforeRetry hooks must propagate unchanged.\n if (ky.#beforeRetryHookErrors.has(error)) {\n throw error;\n }\n let processedError = error;\n for (const hook of ky.#options.hooks.beforeError) {\n // `request` is the current failing request. `options` intentionally remains the\n // stable normalized Ky options snapshot for the same reason as `HTTPError` above.\n // eslint-disable-next-line no-await-in-loop\n const hookResult = await hook({\n request: ky.request,\n options: ky.#getNormalizedOptions(),\n error: processedError,\n retryCount: ky.#retryCount,\n });\n // Only overwrite if the hook returns a valid Error instance.\n if (hookResult instanceof Error) {\n processedError = hookResult;\n }\n }\n throw processedError;\n }\n finally {\n const originalRequest = ky.#originalRequest;\n // Ignore cancellation errors from already-locked or already-consumed streams.\n ky.#cancelBody(originalRequest?.body ?? undefined);\n // Only cancel the current request body if it's distinct from the original (i.e. it was cloned for retries).\n if (ky.request !== originalRequest) {\n ky.#cancelBody(ky.request.body ?? undefined);\n }\n }\n })();\n for (const [type, mimeType] of Object.entries(responseTypes)) {\n // Only expose `.bytes()` when the environment implements it.\n if (type === 'bytes'\n && typeof globalThis.Response?.prototype?.bytes !== 'function') {\n continue;\n }\n result[type] = async (schema) => {\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);\n const response = await result;\n if (type !== 'json') {\n return response[type]();\n }\n const text = await response.text();\n if (text === '') {\n if (schema !== undefined) {\n return validateJsonWithSchema(undefined, schema);\n }\n return JSON.parse(text);\n }\n const jsonValue = initHookOptions.parseJson\n ? await initHookOptions.parseJson(text, { request: ky.#getResponseRequest(response), response })\n : JSON.parse(text);\n return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);\n };\n }\n return result;\n }\n // eslint-disable-next-line unicorn/prevent-abbreviations\n static #normalizeSearchParams(searchParams) {\n // Filter out undefined values from plain objects\n if (searchParams && typeof searchParams === 'object' && !Array.isArray(searchParams) && !(searchParams instanceof URLSearchParams)) {\n return Object.fromEntries(Object.entries(searchParams).filter(([, value]) => value !== undefined));\n }\n return searchParams;\n }\n request;\n #abortController;\n #retryCount = 0;\n // eslint-disable-next-line @typescript-eslint/prefer-readonly -- False positive: #input is reassigned on line 202\n #input;\n #options;\n #originalRequest;\n #userProvidedAbortSignal;\n #beforeRetryHookErrors = new WeakSet();\n #cachedNormalizedOptions;\n #startTime;\n #returnedResponseFromBeforeRetryHook = false;\n #responseRequests = new WeakMap();\n // eslint-disable-next-line complexity\n constructor(input, options = {}) {\n this.#input = input;\n if (Object.hasOwn(options, 'prefixUrl')) {\n throw new Error(prefixUrlRenamedErrorMessage);\n }\n this.#options = {\n ...options,\n headers: mergeHeaders(this.#input.headers, options.headers),\n hooks: mergeHooks({}, options.hooks),\n method: normalizeRequestMethod(options.method ?? this.#input.method ?? 'GET'),\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n prefix: String(options.prefix || ''),\n retry: normalizeRetryOptions(options.retry),\n throwHttpErrors: options.throwHttpErrors ?? true,\n timeout: options.timeout ?? 10_000,\n totalTimeout: options.totalTimeout ?? false,\n fetch: options.fetch ?? globalThis.fetch.bind(globalThis),\n context: options.context ?? {},\n };\n if (typeof this.#input !== 'string' && !(this.#input instanceof URL || this.#input instanceof globalThis.Request)) {\n throw new TypeError('`input` must be a string, URL, or Request');\n }\n if (typeof this.#input === 'string') {\n if (this.#options.prefix) {\n const normalizedPrefix = this.#options.prefix.replace(/\\/+$/, '');\n const normalizedInput = this.#input.replace(/^\\/+/, '');\n this.#input = `${normalizedPrefix}/${normalizedInput}`;\n }\n if (this.#options.baseUrl) {\n let absoluteInput;\n try {\n absoluteInput = new URL(this.#input);\n }\n catch { }\n if (!absoluteInput) {\n this.#input = new URL(this.#input, (new Request(this.#options.baseUrl)).url);\n }\n }\n }\n if (supportsAbortController && supportsAbortSignal) {\n this.#userProvidedAbortSignal = this.#options.signal ?? this.#input.signal;\n this.#abortController = new globalThis.AbortController();\n this.#options.signal = this.#createManagedSignal();\n }\n if (supportsRequestStreams) {\n // @ts-expect-error - Types are outdated.\n this.#options.duplex = 'half';\n }\n if (this.#options.json !== undefined) {\n this.#options.body = this.#options.stringifyJson?.(this.#options.json) ?? JSON.stringify(this.#options.json);\n this.#options.headers.set('content-type', this.#options.headers.get('content-type') ?? 'application/json');\n }\n // To provide correct form boundary, Content-Type header should be deleted when creating Request from another Request with FormData/URLSearchParams body\n // Only delete if user didn't explicitly provide a custom content-type\n const userProvidedContentType = options.headers && new globalThis.Headers(options.headers).has('content-type');\n if (this.#input instanceof globalThis.Request\n && ((supportsFormData && this.#options.body instanceof globalThis.FormData) || this.#options.body instanceof URLSearchParams)\n && !userProvidedContentType) {\n this.#options.headers.delete('content-type');\n }\n this.request = new globalThis.Request(this.#input, this.#options);\n if (hasSearchParameters(this.#options.searchParams)) {\n const url = new URL(this.request.url);\n const deleted = this.#options.searchParams?.[deletedParametersSymbol];\n if (deleted) {\n // Remove keys from the input URL first so later searchParams entries can intentionally re-add them.\n for (const key of deleted) {\n url.searchParams.delete(key);\n }\n }\n if (typeof this.#options.searchParams === 'string') {\n const stringSearchParameters = this.#options.searchParams.replace(/^\\?/, '');\n if (stringSearchParameters !== '') {\n url.search = url.search ? `${url.search}&${stringSearchParameters}` : `?${stringSearchParameters}`;\n }\n }\n else {\n const optionsSearchParameters = new URLSearchParams(Ky.#normalizeSearchParams(this.#options.searchParams));\n for (const [key, value] of optionsSearchParameters.entries()) {\n url.searchParams.append(key, value);\n }\n }\n if (this.#options.searchParams\n && typeof this.#options.searchParams === 'object'\n && !Array.isArray(this.#options.searchParams)\n && !(this.#options.searchParams instanceof URLSearchParams)) {\n for (const [key, value] of Object.entries(this.#options.searchParams)) {\n if (value === undefined) {\n url.searchParams.delete(key);\n }\n }\n }\n // Recreate request with the updated URL. We already have all options in this.#options, including duplex.\n this.request = new globalThis.Request(url, this.#options);\n }\n if (this.#options.onUploadProgress && typeof this.#options.onUploadProgress !== 'function') {\n throw new TypeError('The `onUploadProgress` option must be a function');\n }\n // `totalTimeout` starts when the request pipeline is created, so it also includes\n // Ky's internal scheduling and user hook time before the first fetch attempt.\n this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;\n }\n #calculateDelay() {\n const retryDelay = this.#options.retry.delay(this.#retryCount + 1);\n let jitteredDelay = retryDelay;\n if (this.#options.retry.jitter === true) {\n jitteredDelay = Math.random() * retryDelay;\n }\n else if (typeof this.#options.retry.jitter === 'function') {\n jitteredDelay = this.#options.retry.jitter(retryDelay);\n if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {\n jitteredDelay = retryDelay;\n }\n }\n return Math.min(this.#options.retry.backoffLimit, jitteredDelay);\n }\n async #calculateRetryDelay(error) {\n if (this.#retryCount >= this.#options.retry.limit) {\n throw error;\n }\n // Wrap non-Error throws to ensure consistent error handling\n const errorObject = error instanceof Error ? error : new NonError(error);\n // Handle forced retry from afterResponse hook - skip method check and shouldRetry\n if (errorObject instanceof ForceRetryError) {\n return errorObject.customDelay ?? this.#calculateDelay();\n }\n // Check if method is retriable for non-forced retries\n if (!this.#options.retry.methods.includes(this.request.method.toLowerCase())) {\n throw error;\n }\n // User-provided shouldRetry function takes precedence over default checks (retryOnTimeout, status codes, etc.)\n if (this.#options.retry.shouldRetry !== undefined) {\n const result = await this.#options.retry.shouldRetry({ error: errorObject, retryCount: this.#retryCount + 1 });\n // Strict boolean checking - only exact true/false are handled specially\n if (result === false) {\n throw error;\n }\n if (result === true) {\n // Force retry - skip all other validation and return delay\n return this.#calculateDelay();\n }\n // If undefined or any other value, fall through to default behavior\n }\n // Default timeout behavior\n if (isTimeoutError(error)) {\n if (!this.#options.retry.retryOnTimeout) {\n throw error;\n }\n return this.#calculateDelay();\n }\n if (isHTTPError(error)) {\n if (!this.#options.retry.statusCodes.includes(error.response.status)) {\n throw error;\n }\n const retryAfter = error.response.headers.get('Retry-After')\n ?? error.response.headers.get('RateLimit-Reset')\n ?? error.response.headers.get('X-RateLimit-Retry-After') // Symfony-based services\n ?? error.response.headers.get('X-RateLimit-Reset') // GitHub\n ?? error.response.headers.get('X-Rate-Limit-Reset'); // Twitter\n if (retryAfter && this.#options.retry.afterStatusCodes.includes(error.response.status)) {\n let after = Number(retryAfter) * 1000;\n if (Number.isNaN(after)) {\n after = Date.parse(retryAfter) - Date.now();\n }\n else if (after >= Date.parse('2024-01-01')) {\n // A large number is treated as a timestamp (fixed threshold protects against clock skew)\n after -= Date.now();\n }\n if (!Number.isFinite(after)) {\n return Math.min(this.#options.retry.maxRetryAfter, this.#calculateDelay());\n }\n after = Math.max(0, after);\n // Don't apply jitter when server provides explicit retry timing\n return Math.min(this.#options.retry.maxRetryAfter, after);\n }\n if (error.response.status === 413) {\n throw error;\n }\n return this.#calculateDelay();\n }\n // Only retry known retriable error types. Unknown errors (e.g., programming bugs) are not retried.\n if (!isNetworkError(error)) {\n throw error;\n }\n return this.#calculateDelay();\n }\n #decorateResponse(response) {\n const request = this.#getResponseRequest(response);\n if (this.#options.parseJson) {\n response.json = async () => {\n const text = await response.text();\n if (text === '') {\n return JSON.parse(text);\n }\n return this.#options.parseJson(text, { request, response });\n };\n }\n return response;\n }\n async #getResponseData(response) {\n // Even with request timeouts disabled, bound error-body reads so retries and error propagation\n // cannot be stalled indefinitely by never-ending response streams.\n const text = await this.#readResponseText(response, this.#getErrorDataTimeout());\n if (text === timedOutResponseData) {\n this.#throwIfTotalTimeoutExhausted();\n return undefined;\n }\n if (!text) {\n return undefined;\n }\n if (!this.#isJsonContentType(response.headers.get('content-type') ?? '')) {\n return text;\n }\n const data = await this.#parseJson(text, response, this.#getErrorDataTimeout(), this.#getResponseRequest(response));\n if (data === timedOutResponseData) {\n this.#throwIfTotalTimeoutExhausted();\n return undefined;\n }\n return data;\n }\n #getErrorDataTimeout() {\n const errorDataTimeout = this.#options.timeout === false ? 10_000 : this.#options.timeout;\n const remainingTotal = this.#getRemainingTotalTimeout();\n if (remainingTotal === undefined) {\n return errorDataTimeout;\n }\n if (remainingTotal <= 0) {\n throw new TimeoutError(this.request);\n }\n return Math.min(errorDataTimeout, remainingTotal);\n }\n #isJsonContentType(contentType) {\n // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.\n const mimeType = (contentType.split(';', 1)[0] ?? '').trim().toLowerCase();\n return /\\/(?:.*[.+-])?json$/.test(mimeType);\n }\n async #readResponseText(response, timeoutMs) {\n const { body } = response;\n if (!body) {\n try {\n return await response.text();\n }\n catch {\n return undefined;\n }\n }\n let reader;\n try {\n reader = body.getReader();\n }\n catch {\n // Another consumer already locked the stream.\n return undefined;\n }\n const decoder = createTextDecoder(response.headers.get('content-type') ?? '');\n const chunks = [];\n let totalBytes = 0;\n const readAll = (async () => {\n try {\n for (;;) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n totalBytes += value.byteLength;\n if (totalBytes > maxErrorResponseBodySize) {\n void reader.cancel().catch(() => undefined);\n return undefined;\n }\n chunks.push(decoder.decode(value, { stream: true }));\n }\n }\n catch {\n return undefined;\n }\n chunks.push(decoder.decode());\n return chunks.join('');\n })();\n const timeoutPromise = new Promise(resolve => {\n const timeoutId = setTimeout(() => {\n resolve(timedOutResponseData);\n }, timeoutMs);\n void readAll.finally(() => {\n clearTimeout(timeoutId);\n });\n });\n const result = await Promise.race([readAll, timeoutPromise]);\n if (result === timedOutResponseData) {\n void reader.cancel().catch(() => undefined);\n }\n return result;\n }\n async #parseJson(text, response, timeoutMs, request) {\n let timeoutId;\n try {\n return await Promise.race([\n Promise.resolve().then(() => this.#options.parseJson\n ? this.#options.parseJson(text, { request, response })\n : JSON.parse(text)),\n new Promise(resolve => {\n timeoutId = setTimeout(() => {\n resolve(timedOutResponseData);\n }, timeoutMs);\n }),\n ]);\n }\n catch {\n return undefined;\n }\n finally {\n clearTimeout(timeoutId);\n }\n }\n #cancelBody(body) {\n if (!body) {\n return;\n }\n // Ignore cancellation failures from already-locked or already-consumed streams.\n void body.cancel().catch(() => undefined);\n }\n #cancelResponseBody(response) {\n // Ignore cancellation failures from already-locked or already-consumed streams.\n this.#cancelBody(response.body ?? undefined);\n }\n #createManagedSignal() {\n return this.#userProvidedAbortSignal\n ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController.signal])\n : this.#abortController.signal;\n }\n #throwIfTotalTimeoutExhausted() {\n const remaining = this.#getRemainingTotalTimeout();\n if (remaining !== undefined && remaining <= 0) {\n throw new TimeoutError(this.request);\n }\n }\n async #runBeforeRequestHooks() {\n for (const hook of this.#options.hooks.beforeRequest) {\n // eslint-disable-next-line no-await-in-loop\n const result = await hook({\n request: this.request,\n options: this.#getNormalizedOptions(),\n retryCount: 0,\n });\n if (isRequestInstance(result)) {\n this.#assignRequest(result);\n }\n else if (isResponseInstance(result)) {\n return result;\n }\n }\n return undefined;\n }\n async #runAfterResponseHooks(response) {\n const responseRequest = this.#getResponseRequest(response);\n for (const hook of this.#options.hooks.afterResponse) {\n const hookResponse = this.#setResponseRequest(response.clone(), responseRequest);\n this.#decorateResponse(hookResponse);\n let modifiedResponse;\n try {\n // eslint-disable-next-line no-await-in-loop\n modifiedResponse = await hook({\n request: this.request,\n options: this.#getNormalizedOptions(),\n response: hookResponse,\n retryCount: this.#retryCount,\n });\n }\n catch (error) {\n // Cancel both responses to prevent memory leaks when hook throws\n if (hookResponse !== response) {\n this.#cancelResponseBody(hookResponse);\n }\n this.#cancelResponseBody(response);\n throw error;\n }\n if (modifiedResponse instanceof RetryMarker) {\n // Cancel both the cloned response passed to the hook and the current response to prevent resource leaks (especially important in Deno/Bun).\n // Do not await cancellation since hooks can clone the response, leaving extra tee branches that keep cancel promises pending per the Streams spec.\n if (hookResponse !== response) {\n this.#cancelResponseBody(hookResponse);\n }\n this.#cancelResponseBody(response);\n throw new ForceRetryError(modifiedResponse.options);\n }\n const nextResponse = isResponseInstance(modifiedResponse)\n ? this.#setResponseRequest(modifiedResponse, responseRequest)\n : response;\n // Cancel any response bodies we won't use to prevent memory leaks.\n // Uses fire-and-forget since hooks may have cloned the response, creating tee branches that block cancellation.\n // If the hook wrapped an existing body into a new Response, both Response objects can still point at the same stream.\n if (hookResponse !== response && hookResponse !== nextResponse && hookResponse.body !== nextResponse.body) {\n this.#cancelResponseBody(hookResponse);\n }\n if (response !== nextResponse && response.body !== nextResponse.body) {\n this.#cancelResponseBody(response);\n }\n response = nextResponse;\n }\n return response;\n }\n async #retry(function_) {\n try {\n return await function_();\n }\n catch (error) {\n return this.#retryFromError(error, function_);\n }\n }\n async #retryFromError(error, function_) {\n this.#returnedResponseFromBeforeRetryHook = false;\n const retryDelay = Math.min(await this.#calculateRetryDelay(error), maxSafeTimeout);\n const delayOptions = { signal: this.#userProvidedAbortSignal };\n const remainingTimeout = this.#getRemainingTotalTimeout();\n if (remainingTimeout !== undefined) {\n if (remainingTimeout <= 0) {\n throw new TimeoutError(this.request);\n }\n // If waiting would consume all remaining budget, time out without starting another request.\n if (retryDelay >= remainingTimeout) {\n await delay(remainingTimeout, delayOptions);\n throw new TimeoutError(this.request);\n }\n }\n // Only use user-provided signal for delay, not our internal abortController\n await delay(retryDelay, delayOptions);\n this.#throwIfTotalTimeoutExhausted();\n // Apply custom request from forced retry before beforeRetry hooks\n // Ensure the custom request has the correct managed signal for timeouts and user aborts\n if (error instanceof ForceRetryError && error.customRequest) {\n const customRequest = new globalThis.Request(error.customRequest, this.#options.signal ? { signal: this.#options.signal } : undefined);\n // Replacement Requests are authoritative by design. Do not rewrite headers here,\n // even for cross-origin retries. Callers using `ky.retry({request})` explicitly\n // opted into the exact Request they constructed.\n this.#assignRequest(customRequest);\n }\n for (const hook of this.#options.hooks.beforeRetry) {\n let hookResult;\n try {\n // eslint-disable-next-line no-await-in-loop\n hookResult = await hook({\n request: this.request,\n options: this.#getNormalizedOptions(),\n error: error,\n retryCount: this.#retryCount + 1,\n });\n }\n catch (hookError) {\n // Preserve the original request error path (`throw error`) so beforeError hooks can still run.\n if (hookError instanceof Error && hookError !== error) {\n this.#beforeRetryHookErrors.add(hookError);\n }\n throw hookError;\n }\n if (isRequestInstance(hookResult)) {\n // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`\n // is used as-is rather than being sanitized or otherwise rewritten by Ky.\n this.#assignRequest(hookResult);\n break;\n }\n if (isResponseInstance(hookResult)) {\n this.#returnedResponseFromBeforeRetryHook = true;\n this.#retryCount++;\n return hookResult;\n }\n // If `stop` is returned from the hook, the retry process is stopped\n if (hookResult === stop) {\n return;\n }\n }\n this.#throwIfTotalTimeoutExhausted();\n this.#retryCount++;\n return this.#retry(function_);\n }\n #consumeReturnedResponseFromBeforeRetryHook() {\n const value = this.#returnedResponseFromBeforeRetryHook;\n this.#returnedResponseFromBeforeRetryHook = false;\n return value;\n }\n async #fetch() {\n // Reset abortController if it was aborted (happens on timeout retry)\n if (this.#abortController?.signal.aborted) {\n this.#abortController = new globalThis.AbortController();\n this.#options.signal = this.#createManagedSignal();\n // Recreate request with new signal\n this.request = new globalThis.Request(this.request, { signal: this.#options.signal });\n }\n const nonRequestOptions = findUnknownOptions(this.#options);\n const retryRequest = this.#options.retry.limit > 0 ? this.request.clone() : undefined;\n const request = this.#wrapRequestWithUploadProgress(this.request, this.#options.body ?? undefined);\n // Cloning is done here to prepare in advance for retries.\n // Skip cloning when retries are disabled - cloning a streaming body calls ReadableStream#tee()\n // which buffers the entire stream in memory, causing excessive memory usage for large uploads.\n this.#originalRequest = request;\n if (retryRequest) {\n this.request = retryRequest;\n }\n try {\n const remainingTotal = this.#getRemainingTotalTimeout();\n if (remainingTotal !== undefined && remainingTotal <= 0) {\n throw new TimeoutError(this.request);\n }\n const effectiveTimeout = this.#options.timeout === false\n ? remainingTotal\n : (remainingTotal === undefined\n ? this.#options.timeout\n : Math.min(this.#options.timeout, remainingTotal));\n const response = effectiveTimeout === undefined\n ? await this.#options.fetch(request, nonRequestOptions)\n : await timeout(request, nonRequestOptions, this.#abortController, {\n timeout: effectiveTimeout,\n fetch: this.#options.fetch,\n });\n return this.#setResponseRequest(response, request);\n }\n catch (error) {\n if (isRawNetworkError(error)) {\n throw new NetworkError(this.request, { cause: error });\n }\n throw error;\n }\n }\n #getRemainingTotalTimeout() {\n if (this.#startTime === undefined) {\n return undefined;\n }\n const elapsed = this.#getCurrentTime() - this.#startTime;\n return Math.max(0, this.#options.totalTimeout - elapsed);\n }\n #getCurrentTime() {\n return globalThis.performance?.now() ?? Date.now();\n }\n #getNormalizedOptions() {\n if (!this.#cachedNormalizedOptions) {\n // Exclude Ky-specific options that are not part of `RequestInit`.\n const { hooks, json, parseJson, stringifyJson, searchParams, timeout, totalTimeout, throwHttpErrors, fetch, ...normalizedOptions } = this.#options;\n this.#cachedNormalizedOptions = Object.freeze(normalizedOptions);\n }\n return this.#cachedNormalizedOptions;\n }\n #assignRequest(request) {\n this.#cachedNormalizedOptions = undefined;\n this.request = request;\n }\n #getResponseRequest(response) {\n return this.#responseRequests.get(response) ?? this.request;\n }\n #setResponseRequest(response, request) {\n this.#responseRequests.set(response, request);\n return response;\n }\n #wrapRequestWithUploadProgress(request, originalBody) {\n if (!this.#options.onUploadProgress || !request.body || !supportsRequestStreams) {\n return request;\n }\n return streamRequest(request, this.#options.onUploadProgress, originalBody ?? this.#options.body ?? undefined);\n }\n}\n//# sourceMappingURL=Ky.js.map","/*! MIT License © Sindre Sorhus */\nimport { Ky } from './core/Ky.js';\nimport { requestMethods, stop, retry } from './core/constants.js';\nimport { validateAndMerge } from './utils/merge.js';\nconst createInstance = (defaults) => {\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));\n for (const method of requestMethods) {\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));\n }\n ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));\n ky.extend = (newDefaults) => {\n if (typeof newDefaults === 'function') {\n newDefaults = newDefaults(defaults ?? {});\n }\n return createInstance(validateAndMerge(defaults, newDefaults));\n };\n ky.stop = stop;\n ky.retry = retry;\n return ky;\n};\nconst ky = createInstance();\nexport default ky;\nexport { KyError } from './errors/KyError.js';\nexport { HTTPError } from './errors/HTTPError.js';\nexport { SchemaValidationError } from './errors/SchemaValidationError.js';\nexport { NetworkError } from './errors/NetworkError.js';\nexport { TimeoutError } from './errors/TimeoutError.js';\nexport { ForceRetryError } from './errors/ForceRetryError.js';\nexport { isKyError, isHTTPError, isNetworkError, isTimeoutError, isForceRetryError, } from './utils/type-guards.js';\nexport { replaceOption } from './utils/merge.js';\n// Intentionally not exporting this for now as it's just an implementation detail and we don't want to commit to a certain API yet at least.\n// export {NonError} from './errors/NonError.js';\n//# sourceMappingURL=index.js.map","import ky, { isHTTPError } from \"ky\";\nimport { ACTIVE_ORG_HEADER, AgentSessionDetailResponseSchema, AgentSessionListResponseSchema, ConnectAuthorizeUrlResponseSchema, ConnectProvidersResponseSchema, CreateCredentialInstanceBodySchema, CredentialInstanceListResponseSchema, CredentialInstanceRecordSchema, HealthResponseSchema, PollRunResponseSchema, PromptInputSchema, PromptResponseSchema, QueuedAgentPromptResponseSchema, QueuedRunResponseSchema, SkipResponseSchema, TriggerDetailResponseSchema, TriggerListResponseSchema, TriggerRunDetailResponseSchema, TriggerRunListResponseSchema, UpdateCredentialInstanceBodySchema, WorkflowRunDetailResponseSchema, WorkflowRunListResponseSchema, parseErrorResponse } from \"@keystrokehq/shared\";\n//#region src/auth.ts\nfunction normalizeBaseUrl(baseUrl) {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\nfunction applyActiveOrganizationHeader(request, organizationId) {\n\tif (organizationId) request.headers.set(ACTIVE_ORG_HEADER, organizationId);\n}\nfunction applyAuthHeaders(request, auth, getToken) {\n\tif (!auth || auth.type === \"none\") return;\n\tif (auth.type === \"apiKey\") {\n\t\tconst key = auth.getKey();\n\t\tif (key) request.headers.set(\"x-api-key\", key);\n\t\treturn;\n\t}\n\tif (auth.type === \"bearer\") {\n\t\tconst tokenPromise = getToken?.() ?? auth.getToken();\n\t\treturn Promise.resolve(tokenPromise).then((token) => {\n\t\t\tif (token) request.headers.set(\"Authorization\", `Bearer ${token}`);\n\t\t});\n\t}\n}\n//#endregion\n//#region src/errors.ts\nvar KeystrokeError = class extends Error {\n\tstatus;\n\tbody;\n\tconstructor(message, status, body) {\n\t\tsuper(message);\n\t\tthis.name = \"KeystrokeError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t}\n};\nasync function toKeystrokeError(error) {\n\tif (!isHTTPError(error)) return new KeystrokeError(error instanceof Error ? error.message : \"Request failed\", 0, null);\n\tconst status = error.response.status;\n\tconst body = error.data ?? null;\n\tconst parsed = parseErrorResponse(body);\n\treturn new KeystrokeError(parsed ? parsed.message ?? parsed.error : `Request failed with status ${status}`, status, body);\n}\n//#endregion\n//#region src/resources/shared.ts\nasync function readJson(response) {\n\treturn response.json();\n}\n//#endregion\n//#region src/resources/agents.ts\nfunction isQueuedAgentPromptResponse(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (\"messages\" in value) return false;\n\treturn QueuedAgentPromptResponseSchema.safeParse(value).success;\n}\nfunction listSessionsSearchParams(query) {\n\tif (!query) return {};\n\tconst params = {};\n\tif (query.limit !== void 0) params.limit = String(query.limit);\n\tif (query.cursor) params.cursor = query.cursor;\n\tif (query.status) params.status = query.status;\n\tif (query.source) params.source = query.source;\n\treturn params;\n}\nfunction detailSearchParams$2(query) {\n\tif (!query?.include) return {};\n\treturn { include: query.include };\n}\nfunction createAgentsResource(http) {\n\treturn {\n\t\tasync prompt(id, input) {\n\t\t\tconst body = PromptInputSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst response = await http.post(`agents/${id}`, { json: body });\n\t\t\t\tconst data = await readJson(response);\n\t\t\t\tif (response.status === 202) return QueuedAgentPromptResponseSchema.parse(data);\n\t\t\t\treturn PromptResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync listSessions(agentId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`agents/${agentId}/sessions`, { searchParams: listSessionsSearchParams(query) }).json();\n\t\t\t\treturn AgentSessionListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync getSession(agentId, sessionId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`agents/${agentId}/sessions/${sessionId}`, { searchParams: detailSearchParams$2(query) }).json();\n\t\t\t\treturn AgentSessionDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/resources/connect.ts\nfunction routeFromPath(path) {\n\treturn path.replace(/^\\//, \"\");\n}\nfunction createConnectResource(http) {\n\treturn {\n\t\tasync listProviders() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"connect/providers\").json();\n\t\t\t\treturn ConnectProvidersResponseSchema.parse(data).providers;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync getAuthorizeUrl(path) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(routeFromPath(path)).json();\n\t\t\t\treturn ConnectAuthorizeUrlResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/resources/credentials.ts\nfunction createCredentialsResource(http) {\n\treturn {\n\t\tasync listInstances(options) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = options?.key ? { key: options.key } : void 0;\n\t\t\t\tconst data = await http.get(\"credentials/instances\", { searchParams }).json();\n\t\t\t\treturn CredentialInstanceListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync createInstance(body) {\n\t\t\ttry {\n\t\t\t\tconst payload = CreateCredentialInstanceBodySchema.parse(body);\n\t\t\t\tconst data = await http.post(\"credentials/instances\", { json: payload }).json();\n\t\t\t\treturn CredentialInstanceRecordSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync updateInstance(id, body) {\n\t\t\ttry {\n\t\t\t\tconst payload = UpdateCredentialInstanceBodySchema.parse(body);\n\t\t\t\tconst data = await http.put(`credentials/instances/${id}`, { json: payload }).json();\n\t\t\t\treturn CredentialInstanceRecordSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync deleteInstance(id) {\n\t\t\ttry {\n\t\t\t\tawait http.delete(`credentials/instances/${id}`);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/resources/health.ts\nfunction createHealthResource(http) {\n\treturn { async check() {\n\t\ttry {\n\t\t\tconst data = await http.get(\"health\").json();\n\t\t\treturn HealthResponseSchema.parse(data);\n\t\t} catch (error) {\n\t\t\tthrow await toKeystrokeError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/resources/openapi.ts\nfunction createOpenApiResource(http) {\n\treturn { async fetch() {\n\t\ttry {\n\t\t\treturn await http.get(\"openapi.json\").json();\n\t\t} catch (error) {\n\t\t\tthrow await toKeystrokeError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/resources/triggers.ts\nfunction pollRunBody(options) {\n\tif (!options?.workflows?.length && !options?.attachments?.length) return;\n\treturn {\n\t\t...options.workflows?.length ? { workflows: options.workflows } : {},\n\t\t...options.attachments?.length ? { attachments: options.attachments } : {}\n\t};\n}\nfunction listRunsSearchParams$1(query) {\n\tif (!query) return {};\n\tconst params = {};\n\tif (query.limit !== void 0) params.limit = String(query.limit);\n\tif (query.cursor) params.cursor = query.cursor;\n\tif (query.triggerType) params.triggerType = query.triggerType;\n\treturn params;\n}\nfunction detailSearchParams$1(query) {\n\tif (!query?.include) return {};\n\treturn { include: query.include };\n}\nfunction createTriggersResource(http) {\n\treturn {\n\t\tasync list(query) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = query?.endpoint ? { endpoint: query.endpoint } : void 0;\n\t\t\t\tconst data = await http.get(\"triggers\", { searchParams }).json();\n\t\t\t\treturn TriggerListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(id) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`triggers/${id}`).json();\n\t\t\t\tconst list = TriggerListResponseSchema.safeParse(data);\n\t\t\t\tif (list.success) return list.data;\n\t\t\t\treturn TriggerDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync webhookUrl(id) {\n\t\t\tconst result = await this.get(id);\n\t\t\tconst webhookUrl = \"triggers\" in result ? result.triggers.find((entry) => entry.webhookUrl)?.webhookUrl : result.webhookUrl;\n\t\t\tif (!webhookUrl) throw new KeystrokeError(`Webhook URL not found: ${id}`, 404, { error: \"Not found\" });\n\t\t\treturn webhookUrl;\n\t\t},\n\t\tasync webhook(endpoint, body = {}, options = {}) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = options.token ? { token: options.token } : void 0;\n\t\t\t\tconst normalized = endpoint.replace(/^\\/+|\\/+$/g, \"\").replace(/^triggers\\/?/, \"\");\n\t\t\t\treturn await http.post(`triggers/${normalized}`, {\n\t\t\t\t\tjson: body,\n\t\t\t\t\tsearchParams\n\t\t\t\t}).json();\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync poll(id, options = {}) {\n\t\t\ttry {\n\t\t\t\tconst { group, ...target } = options;\n\t\t\t\tconst json = pollRunBody(target);\n\t\t\t\tconst path = group ? `triggers/polls/${id}/run` : `triggers/${id}/poll`;\n\t\t\t\tconst data = await readJson(await http.post(path, json ? { json } : void 0));\n\t\t\t\tPollRunResponseSchema.parse(data);\n\t\t\t\treturn data;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync runPollGroup(pollId, options = {}) {\n\t\t\treturn this.poll(pollId, {\n\t\t\t\t...options,\n\t\t\t\tgroup: true\n\t\t\t});\n\t\t},\n\t\tasync listRuns(attachmentId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`triggers/${attachmentId}/runs`, { searchParams: listRunsSearchParams$1(query) }).json();\n\t\t\t\treturn TriggerRunListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync getRun(attachmentId, runId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`triggers/${attachmentId}/runs/${runId}`, { searchParams: detailSearchParams$1(query) }).json();\n\t\t\t\treturn TriggerRunDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t}\n\t};\n}\nfunction isSkippedTriggerResponse(value) {\n\treturn SkipResponseSchema.safeParse(value).success;\n}\n//#endregion\n//#region src/resources/workflows.ts\nfunction isQueuedRunResponse(value) {\n\treturn QueuedRunResponseSchema.safeParse(value).success;\n}\nfunction listRunsSearchParams(query) {\n\tif (!query) return {};\n\tconst params = {};\n\tif (query.limit !== void 0) params.limit = String(query.limit);\n\tif (query.cursor) params.cursor = query.cursor;\n\tif (query.status) params.status = query.status;\n\tif (query.trigger) params.trigger = query.trigger;\n\treturn params;\n}\nfunction detailSearchParams(query) {\n\tif (!query?.include) return {};\n\treturn { include: query.include };\n}\nfunction createWorkflowsResource(http) {\n\treturn {\n\t\tasync run(id, input = {}) {\n\t\t\ttry {\n\t\t\t\tconst response = await http.post(`workflows/${id}`, { json: input });\n\t\t\t\tconst data = await readJson(response);\n\t\t\t\tif (response.status === 202) return QueuedRunResponseSchema.parse(data);\n\t\t\t\treturn data;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync listRuns(workflowId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`workflows/${workflowId}/runs`, { searchParams: listRunsSearchParams(query) }).json();\n\t\t\t\treturn WorkflowRunListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync getRun(workflowId, runId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`workflows/${workflowId}/runs/${runId}`, { searchParams: detailSearchParams(query) }).json();\n\t\t\t\treturn WorkflowRunDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/index.ts\nfunction createKeystrokeClient(options) {\n\tconst auth = options.auth ?? { type: \"none\" };\n\tconst base = normalizeBaseUrl(options.baseUrl);\n\tconst getActiveOrganizationId = options.getActiveOrganizationId;\n\tconst http = ky.create({\n\t\tprefix: base === \"\" ? void 0 : `${base}/`,\n\t\tcredentials: \"omit\",\n\t\thooks: { beforeRequest: [({ request }) => {\n\t\t\tapplyActiveOrganizationHeader(request, getActiveOrganizationId?.());\n\t\t\treturn applyAuthHeaders(request, auth);\n\t\t}] },\n\t\t...options.ky\n\t});\n\treturn {\n\t\thttp,\n\t\thealth: createHealthResource(http),\n\t\tconnect: createConnectResource(http),\n\t\tcredentials: createCredentialsResource(http),\n\t\topenapi: createOpenApiResource(http),\n\t\tagents: createAgentsResource(http),\n\t\tworkflows: createWorkflowsResource(http),\n\t\ttriggers: createTriggersResource(http)\n\t};\n}\n//#endregion\nexport { KeystrokeError, createKeystrokeClient, isQueuedAgentPromptResponse, isQueuedRunResponse, isSkippedTriggerResponse, toKeystrokeError };\n\n//# sourceMappingURL=index.mjs.map","import { Entry } from \"@napi-rs/keyring\";\n\nconst SERVICE = \"keystroke\";\n\nfunction accountForWebUrl(webUrl: string): string {\n return new URL(webUrl).hostname;\n}\n\nexport function getAccessToken(webUrl: string): string | undefined {\n const entry = new Entry(SERVICE, accountForWebUrl(webUrl));\n const password = entry.getPassword();\n return password === null ? undefined : password;\n}\n\nexport function setAccessToken(webUrl: string, token: string): void {\n const entry = new Entry(SERVICE, accountForWebUrl(webUrl));\n entry.setPassword(token);\n}\n\nexport function clearAccessToken(webUrl: string): void {\n const entry = new Entry(SERVICE, accountForWebUrl(webUrl));\n entry.deletePassword();\n}\n","import { createRemoteJWKSet, jwtVerify } from \"jose\";\n//#region src/constants.ts\n/** OAuth device-flow client id for `keystroke auth login`. */\nconst CLI_CLIENT_ID = \"keystroke-cli\";\n//#endregion\n//#region src/jwt.ts\nconst jwksCache = /* @__PURE__ */ new Map();\nfunction getRemoteJwks(jwksUrl) {\n\tconst cached = jwksCache.get(jwksUrl);\n\tif (cached) return cached;\n\tconst jwks = createRemoteJWKSet(new URL(jwksUrl));\n\tjwksCache.set(jwksUrl, jwks);\n\treturn jwks;\n}\nfunction payloadToUser(payload) {\n\tconst id = typeof payload.id === \"string\" ? payload.id : payload.sub;\n\tconst email = typeof payload.email === \"string\" ? payload.email : void 0;\n\tconst name = typeof payload.name === \"string\" && payload.name.length > 0 ? payload.name : email?.split(\"@\")[0];\n\tif (!id || !email || !name) return null;\n\treturn {\n\t\tid,\n\t\temail,\n\t\tname,\n\t\timage: typeof payload.image === \"string\" ? payload.image : null,\n\t\temailVerified: typeof payload.emailVerified === \"boolean\" ? payload.emailVerified : void 0\n\t};\n}\nfunction createJwtVerifier(options) {\n\tconst audience = options.audience ?? options.issuer;\n\tlet jwks;\n\treturn { verify: async (token) => {\n\t\ttry {\n\t\t\tjwks ??= getRemoteJwks(options.jwksUrl);\n\t\t\tconst { payload } = await jwtVerify(token, jwks, {\n\t\t\t\tissuer: options.issuer,\n\t\t\t\taudience\n\t\t\t});\n\t\t\treturn payloadToUser(payload);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t} };\n}\nfunction extractBearerToken(headers) {\n\tconst authorization = headers.get(\"authorization\");\n\tif (!authorization?.startsWith(\"Bearer \")) return null;\n\tconst token = authorization.slice(7).trim();\n\treturn token.length > 0 ? token : null;\n}\nfunction looksLikeJwt(token) {\n\treturn token.split(\".\").length === 3;\n}\nfunction userFromJwt(jwtUser) {\n\treturn {\n\t\tid: jwtUser.id,\n\t\temail: jwtUser.email,\n\t\tname: jwtUser.name,\n\t\timage: jwtUser.image ?? null,\n\t\temailVerified: jwtUser.emailVerified ?? true,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n}\nfunction sessionFromJwt(jwtUser, token) {\n\treturn {\n\t\tid: jwtUser.id,\n\t\tuserId: jwtUser.id,\n\t\ttoken,\n\t\texpiresAt: new Date(Date.now() + 900 * 1e3),\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n}\nasync function resolveRequestAuth(jwtVerifier, headers) {\n\tconst bearerToken = extractBearerToken(headers);\n\tif (!bearerToken || !jwtVerifier || !looksLikeJwt(bearerToken)) return null;\n\tconst jwtUser = await jwtVerifier.verify(bearerToken);\n\tif (!jwtUser) return null;\n\treturn {\n\t\tuser: userFromJwt(jwtUser),\n\t\tsession: sessionFromJwt(jwtUser, bearerToken)\n\t};\n}\n/** Auth API origin for JWT verification — platform URL when auth is mounted there. */\nfunction resolveAuthApiBaseUrl() {\n\treturn (process.env.PUBLIC_PLATFORM_URL ?? process.env.PUBLIC_WEB_URL ?? \"\").replace(/\\/+$/, \"\");\n}\nfunction createDefaultAuthJwtVerifier() {\n\treturn createAuthJwtVerifier(resolveAuthApiBaseUrl());\n}\nfunction createAuthJwtVerifier(authBaseUrl) {\n\tconst normalizedBaseUrl = authBaseUrl.replace(/\\/+$/, \"\");\n\tif (!normalizedBaseUrl) return;\n\treturn createJwtVerifier({\n\t\tissuer: normalizedBaseUrl,\n\t\taudience: normalizedBaseUrl,\n\t\tjwksUrl: `${normalizedBaseUrl}/api/auth/jwks`\n\t});\n}\nasync function fetchJwtWithSession(authBaseUrl, sessionCredential) {\n\tconst headers = new Headers();\n\tif (sessionCredential.cookie) headers.set(\"cookie\", sessionCredential.cookie);\n\tif (sessionCredential.bearerToken) headers.set(\"authorization\", `Bearer ${sessionCredential.bearerToken}`);\n\tconst normalizedBaseUrl = authBaseUrl.replace(/\\/+$/, \"\");\n\tconst response = await fetch(`${normalizedBaseUrl}/api/auth/token`, { headers });\n\tif (!response.ok) return null;\n\tconst body = await response.json();\n\treturn typeof body.token === \"string\" ? body.token : null;\n}\n//#endregion\nexport { fetchJwtWithSession as a, CLI_CLIENT_ID as c, extractBearerToken as i, createDefaultAuthJwtVerifier as n, resolveAuthApiBaseUrl as o, createJwtVerifier as r, resolveRequestAuth as s, createAuthJwtVerifier as t };\n\n//# sourceMappingURL=jwt-BVJ7dVm9.mjs.map","//#region src/jwt-cache.ts\nconst REFRESH_BUFFER_MS = 6e4;\nconst FALLBACK_TTL_MS = 840 * 1e3;\nfunction decodeBase64Url(value) {\n\tconst base64 = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, \"=\");\n\treturn atob(padded);\n}\nfunction decodeJwtExpiryMs(token) {\n\tconst parts = token.split(\".\");\n\tif (parts.length !== 3) return null;\n\ttry {\n\t\tconst payload = JSON.parse(decodeBase64Url(parts[1] ?? \"\"));\n\t\treturn typeof payload.exp === \"number\" ? payload.exp * 1e3 : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/** Caches JWTs minted by `mint`, refreshing shortly before expiry and deduping concurrent mints. */\nfunction createJwtTokenCache(mint) {\n\tlet cached = null;\n\tlet pending = null;\n\treturn {\n\t\tget: async (force = false) => {\n\t\t\tif (!force && cached && cached.expiresAtMs - Date.now() > REFRESH_BUFFER_MS) return cached.token;\n\t\t\tif (pending) return pending;\n\t\t\tpending = (async () => {\n\t\t\t\tconst token = await mint();\n\t\t\t\tif (!token) {\n\t\t\t\t\tcached = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcached = {\n\t\t\t\t\ttoken,\n\t\t\t\t\texpiresAtMs: decodeJwtExpiryMs(token) ?? Date.now() + FALLBACK_TTL_MS\n\t\t\t\t};\n\t\t\t\treturn token;\n\t\t\t})();\n\t\t\ttry {\n\t\t\t\treturn await pending;\n\t\t\t} finally {\n\t\t\t\tpending = null;\n\t\t\t}\n\t\t},\n\t\tclear: () => {\n\t\t\tcached = null;\n\t\t}\n\t};\n}\n//#endregion\nexport { decodeJwtExpiryMs as n, createJwtTokenCache as t };\n\n//# sourceMappingURL=jwt-cache-4YqHn3jM.mjs.map","//#region package.json\nvar version = \"1.6.11\";\n//#endregion\nexport { version };\n","import { version } from \"./package.mjs\";\n//#region src/version.ts\nconst PACKAGE_VERSION = version;\n//#endregion\nexport { PACKAGE_VERSION };\n","//#region src/error.ts\nfunction isErrorStackTraceLimitWritable() {\n\tconst desc = Object.getOwnPropertyDescriptor(Error, \"stackTraceLimit\");\n\tif (desc === void 0) return Object.isExtensible(Error);\n\treturn Object.prototype.hasOwnProperty.call(desc, \"writable\") ? desc.writable : desc.set !== void 0;\n}\n/**\n* Hide internal stack frames from the error stack trace.\n*/\nfunction hideInternalStackFrames(stack) {\n\tconst lines = stack.split(\"\\n at \");\n\tif (lines.length <= 1) return stack;\n\tlines.splice(1, 1);\n\treturn lines.join(\"\\n at \");\n}\n/**\n* Creates a custom error class that hides stack frames.\n*/\nfunction makeErrorForHideStackFrame(Base, clazz) {\n\tclass HideStackFramesError extends Base {\n\t\t#hiddenStack;\n\t\tconstructor(...args) {\n\t\t\tif (isErrorStackTraceLimitWritable()) {\n\t\t\t\tconst limit = Error.stackTraceLimit;\n\t\t\t\tError.stackTraceLimit = 0;\n\t\t\t\tsuper(...args);\n\t\t\t\tError.stackTraceLimit = limit;\n\t\t\t} else super(...args);\n\t\t\tconst stack = (/* @__PURE__ */ new Error()).stack;\n\t\t\tif (stack) this.#hiddenStack = hideInternalStackFrames(stack.replace(/^Error/, this.name));\n\t\t}\n\t\tget errorStack() {\n\t\t\treturn this.#hiddenStack;\n\t\t}\n\t}\n\tObject.defineProperty(HideStackFramesError.prototype, \"constructor\", {\n\t\tget() {\n\t\t\treturn clazz;\n\t\t},\n\t\tenumerable: false,\n\t\tconfigurable: true\n\t});\n\treturn HideStackFramesError;\n}\nconst statusCodes = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511\n};\nvar InternalAPIError = class extends Error {\n\tconstructor(status = \"INTERNAL_SERVER_ERROR\", body = void 0, headers = {}, statusCode = typeof status === \"number\" ? status : statusCodes[status]) {\n\t\tsuper(body?.message, body?.cause ? { cause: body.cause } : void 0);\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t\tthis.headers = headers;\n\t\tthis.statusCode = statusCode;\n\t\tthis.name = \"APIError\";\n\t\tthis.status = status;\n\t\tthis.headers = headers;\n\t\tthis.statusCode = statusCode;\n\t\tthis.body = body;\n\t}\n};\nvar ValidationError = class extends InternalAPIError {\n\tconstructor(message, issues) {\n\t\tsuper(400, {\n\t\t\tmessage,\n\t\t\tcode: \"VALIDATION_ERROR\"\n\t\t});\n\t\tthis.message = message;\n\t\tthis.issues = issues;\n\t\tthis.issues = issues;\n\t}\n};\nvar BetterCallError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"BetterCallError\";\n\t}\n};\nconst kAPIErrorHeaderSymbol = Symbol.for(\"better-call:api-error-headers\");\nconst APIError = makeErrorForHideStackFrame(InternalAPIError, Error);\n\n//#endregion\nexport { APIError, BetterCallError, ValidationError, hideInternalStackFrames, kAPIErrorHeaderSymbol, makeErrorForHideStackFrame, statusCodes };\n//# sourceMappingURL=error.mjs.map","import { BASE_ERROR_CODES } from \"./codes.mjs\";\nimport { APIError as APIError$1 } from \"better-call/error\";\n//#region src/error/index.ts\nvar BetterAuthError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.name = \"BetterAuthError\";\n\t\tthis.message = message;\n\t\tthis.stack = \"\";\n\t}\n};\nvar APIError = class APIError extends APIError$1 {\n\tconstructor(...args) {\n\t\tsuper(...args);\n\t}\n\tstatic fromStatus(status, body) {\n\t\treturn new APIError(status, body);\n\t}\n\tstatic from(status, error) {\n\t\treturn new APIError(status, {\n\t\t\tmessage: error.message,\n\t\t\tcode: error.code\n\t\t});\n\t}\n};\n//#endregion\nexport { APIError, BASE_ERROR_CODES, BetterAuthError };\n","import { PACKAGE_VERSION } from \"../../version.mjs\";\n//#region src/plugins/device-authorization/client.ts\nconst deviceAuthorizationClient = () => {\n\treturn {\n\t\tid: \"device-authorization\",\n\t\tversion: PACKAGE_VERSION,\n\t\t$InferServerPlugin: {},\n\t\tpathMethods: {\n\t\t\t\"/device/code\": \"POST\",\n\t\t\t\"/device/token\": \"POST\",\n\t\t\t\"/device\": \"GET\",\n\t\t\t\"/device/approve\": \"POST\",\n\t\t\t\"/device/deny\": \"POST\"\n\t\t}\n\t};\n};\n//#endregion\nexport { deviceAuthorizationClient };\n","import { cleanTasks } from '../task/index.js'\n\nexport const clean = Symbol('clean')\n\nexport const cleanStores = (...stores) => {\n if (process.env.NODE_ENV === 'production') {\n throw new Error(\n 'cleanStores() can be used only during development or tests'\n )\n }\n cleanTasks()\n for (let $store of stores) {\n if ($store) {\n if ($store.mocked) delete $store.mocked\n if ($store[clean]) $store[clean]()\n }\n }\n}\n","import { clean } from '../clean-stores/index.js'\n\nlet listenerQueue = []\nlet lqIndex = 0\nconst QUEUE_ITEMS_PER_LISTENER = 4\n// Use globalThis.nanostoresGlobal to store epoch so all module instances share\n// the same counter. This fixes issues when Nano Store is bundled separately\n// in different parts of an application (e.g., tree-shaking separates core\n// from React), causing each bundle to have its own epoch instance.\nexport const nanostoresGlobal = (globalThis.nanostoresGlobal ||= { epoch: 0 })\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const atom = initialValue => {\n let listeners = []\n let $atom = {\n get() {\n if (!$atom.lc) {\n $atom.listen(() => {})()\n }\n return $atom.value\n },\n init: initialValue,\n lc: 0,\n listen(listener) {\n $atom.lc = listeners.push(listener)\n\n return () => {\n for (\n let i = lqIndex + QUEUE_ITEMS_PER_LISTENER;\n i < listenerQueue.length;\n ) {\n if (listenerQueue[i] === listener) {\n listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER)\n } else {\n i += QUEUE_ITEMS_PER_LISTENER\n }\n }\n\n let index = listeners.indexOf(listener)\n if (~index) {\n listeners.splice(index, 1)\n if (!--$atom.lc) $atom.off()\n }\n }\n },\n notify(oldValue, changedKey) {\n nanostoresGlobal.epoch++\n let runListenerQueue = !listenerQueue.length\n for (let listener of listeners) {\n listenerQueue.push(listener, $atom.value, oldValue, changedKey)\n }\n\n if (runListenerQueue) {\n for (\n lqIndex = 0;\n lqIndex < listenerQueue.length;\n lqIndex += QUEUE_ITEMS_PER_LISTENER\n ) {\n listenerQueue[lqIndex](\n listenerQueue[lqIndex + 1],\n listenerQueue[lqIndex + 2],\n listenerQueue[lqIndex + 3]\n )\n }\n listenerQueue.length = 0\n }\n },\n /* It will be called on last listener unsubscribing.\n We will redefine it in onMount and onStop. */\n off() {},\n set(newValue) {\n let oldValue = $atom.value\n if (oldValue !== newValue) {\n $atom.value = newValue\n $atom.notify(oldValue)\n }\n },\n subscribe(listener) {\n let unbind = $atom.listen(listener)\n listener($atom.value)\n return unbind\n },\n value: initialValue\n }\n\n if (process.env.NODE_ENV !== 'production') {\n $atom[clean] = () => {\n listeners = []\n $atom.lc = 0\n $atom.off()\n }\n }\n\n return $atom\n}\n\nexport const readonlyType = store => store\n","import { clean } from '../clean-stores/index.js'\n\nconst START = 0\nconst STOP = 1\nconst SET = 2\nconst NOTIFY = 3\nconst MOUNT = 5\nconst UNMOUNT = 6\nconst REVERT_MUTATION = 10\n\nexport let on = (object, listener, eventKey, mutateStore) => {\n object.events = object.events || {}\n if (!object.events[eventKey + REVERT_MUTATION]) {\n object.events[eventKey + REVERT_MUTATION] = mutateStore(eventProps => {\n // eslint-disable-next-line no-sequences\n object.events[eventKey].reduceRight((event, l) => (l(event), event), {\n shared: {},\n ...eventProps\n })\n })\n }\n object.events[eventKey] = object.events[eventKey] || []\n object.events[eventKey].push(listener)\n return () => {\n let currentListeners = object.events[eventKey]\n let index = currentListeners.indexOf(listener)\n currentListeners.splice(index, 1)\n if (!currentListeners.length) {\n delete object.events[eventKey]\n object.events[eventKey + REVERT_MUTATION]()\n delete object.events[eventKey + REVERT_MUTATION]\n }\n }\n}\n\nexport let onStart = ($store, listener) =>\n on($store, listener, START, runListeners => {\n let originListen = $store.listen\n $store.listen = arg => {\n if (!$store.lc && !$store.starting) {\n $store.starting = true\n runListeners()\n delete $store.starting\n }\n return originListen(arg)\n }\n return () => {\n $store.listen = originListen\n }\n })\n\nexport let onStop = ($store, listener) =>\n on($store, listener, STOP, runListeners => {\n let originOff = $store.off\n $store.off = () => {\n runListeners()\n originOff()\n }\n return () => {\n $store.off = originOff\n }\n })\n\nexport let onSet = ($store, listener) =>\n on($store, listener, SET, runListeners => {\n let originSet = $store.set\n let originSetKey = $store.setKey\n if ($store.setKey) {\n $store.setKey = (changed, changedValue) => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({\n abort,\n changed,\n newValue: { ...$store.value, [changed]: changedValue }\n })\n if (!isAborted) return originSetKey(changed, changedValue)\n }\n }\n $store.set = newValue => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({ abort, newValue })\n if (!isAborted) return originSet(newValue)\n }\n return () => {\n $store.set = originSet\n $store.setKey = originSetKey\n }\n })\n\nexport let onNotify = ($store, listener) =>\n on($store, listener, NOTIFY, runListeners => {\n let originNotify = $store.notify\n $store.notify = (oldValue, changed) => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({ abort, changed, oldValue })\n if (!isAborted) return originNotify(oldValue, changed)\n }\n return () => {\n $store.notify = originNotify\n }\n })\n\nexport const STORE_UNMOUNT_DELAY = 1000\n\nexport let onMount = ($store, initialize) => {\n let listener = payload => {\n let destroy = initialize(payload)\n if (destroy) $store.events[UNMOUNT].push(destroy)\n }\n return on($store, listener, MOUNT, runListeners => {\n let originListen = $store.listen\n $store.listen = (...args) => {\n if (!$store.lc && !$store.active) {\n $store.active = true\n runListeners()\n }\n return originListen(...args)\n }\n\n let originOff = $store.off\n $store.events[UNMOUNT] = []\n $store.off = () => {\n originOff()\n setTimeout(() => {\n if ($store.active && !$store.lc) {\n $store.active = false\n for (let destroy of $store.events[UNMOUNT]) destroy()\n $store.events[UNMOUNT] = []\n }\n }, STORE_UNMOUNT_DELAY)\n }\n\n if (process.env.NODE_ENV !== 'production') {\n let originClean = $store[clean]\n $store[clean] = () => {\n for (let destroy of $store.events[UNMOUNT]) destroy()\n $store.events[UNMOUNT] = []\n $store.active = false\n originClean()\n }\n }\n\n return () => {\n $store.listen = originListen\n $store.off = originOff\n }\n })\n}\n","import { atom, onMount } from \"nanostores\";\n//#region src/client/query.ts\nconst isServer = () => typeof window === \"undefined\";\nconst useAuthQuery = (initializedAtom, path, $fetch, options) => {\n\tconst value = atom({\n\t\tdata: null,\n\t\terror: null,\n\t\tisPending: true,\n\t\tisRefetching: false,\n\t\trefetch: (queryParams) => fn(queryParams)\n\t});\n\tconst fn = async (queryParams) => {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst opts = typeof options === \"function\" ? options({\n\t\t\t\tdata: value.get().data,\n\t\t\t\terror: value.get().error,\n\t\t\t\tisPending: value.get().isPending\n\t\t\t}) : options;\n\t\t\t$fetch(path, {\n\t\t\t\t...opts,\n\t\t\t\tquery: {\n\t\t\t\t\t...opts?.query,\n\t\t\t\t\t...queryParams?.query\n\t\t\t\t},\n\t\t\t\tasync onSuccess(context) {\n\t\t\t\t\tvalue.set({\n\t\t\t\t\t\tdata: context.data,\n\t\t\t\t\t\terror: null,\n\t\t\t\t\t\tisPending: false,\n\t\t\t\t\t\tisRefetching: false,\n\t\t\t\t\t\trefetch: value.value.refetch\n\t\t\t\t\t});\n\t\t\t\t\tawait opts?.onSuccess?.(context);\n\t\t\t\t},\n\t\t\t\tasync onError(context) {\n\t\t\t\t\tconst { request } = context;\n\t\t\t\t\tconst retryAttempts = typeof request.retry === \"number\" ? request.retry : request.retry?.attempts;\n\t\t\t\t\tconst retryAttempt = request.retryAttempt || 0;\n\t\t\t\t\tif (retryAttempts && retryAttempt < retryAttempts) return;\n\t\t\t\t\tconst isUnauthorized = context.error.status === 401;\n\t\t\t\t\tvalue.set({\n\t\t\t\t\t\terror: context.error,\n\t\t\t\t\t\tdata: isUnauthorized ? null : value.get().data,\n\t\t\t\t\t\tisPending: false,\n\t\t\t\t\t\tisRefetching: false,\n\t\t\t\t\t\trefetch: value.value.refetch\n\t\t\t\t\t});\n\t\t\t\t\tawait opts?.onError?.(context);\n\t\t\t\t},\n\t\t\t\tasync onRequest(context) {\n\t\t\t\t\tconst currentValue = value.get();\n\t\t\t\t\tvalue.set({\n\t\t\t\t\t\tisPending: currentValue.data === null,\n\t\t\t\t\t\tdata: currentValue.data,\n\t\t\t\t\t\terror: null,\n\t\t\t\t\t\tisRefetching: true,\n\t\t\t\t\t\trefetch: value.value.refetch\n\t\t\t\t\t});\n\t\t\t\t\tawait opts?.onRequest?.(context);\n\t\t\t\t}\n\t\t\t}).catch((error) => {\n\t\t\t\tvalue.set({\n\t\t\t\t\terror,\n\t\t\t\t\tdata: value.get().data,\n\t\t\t\t\tisPending: false,\n\t\t\t\t\tisRefetching: false,\n\t\t\t\t\trefetch: value.value.refetch\n\t\t\t\t});\n\t\t\t}).finally(() => {\n\t\t\t\tresolve(void 0);\n\t\t\t});\n\t\t});\n\t};\n\tinitializedAtom = Array.isArray(initializedAtom) ? initializedAtom : [initializedAtom];\n\tlet isInitialized = false;\n\tfor (const initAtom of initializedAtom) initAtom.subscribe(async () => {\n\t\tif (isServer()) return;\n\t\tif (isInitialized) await fn();\n\t\telse onMount(value, () => {\n\t\t\tconst timeoutId = setTimeout(async () => {\n\t\t\t\tif (!isInitialized) {\n\t\t\t\t\tisInitialized = true;\n\t\t\t\t\tawait fn();\n\t\t\t\t}\n\t\t\t}, 0);\n\t\t\treturn () => {\n\t\t\t\tvalue.off();\n\t\t\t\tinitAtom.off();\n\t\t\t\tclearTimeout(timeoutId);\n\t\t\t};\n\t\t});\n\t});\n\treturn value;\n};\n//#endregion\nexport { useAuthQuery };\n","//#region src/client/broadcast-channel.ts\nconst kBroadcastChannel = Symbol.for(\"better-auth:broadcast-channel\");\nconst now = () => Math.floor(Date.now() / 1e3);\nvar WindowBroadcastChannel = class {\n\tlisteners = /* @__PURE__ */ new Set();\n\tname;\n\tconstructor(name = \"better-auth.message\") {\n\t\tthis.name = name;\n\t}\n\tsubscribe(listener) {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\tpost(message) {\n\t\tif (typeof window === \"undefined\") return;\n\t\ttry {\n\t\t\tlocalStorage.setItem(this.name, JSON.stringify({\n\t\t\t\t...message,\n\t\t\t\ttimestamp: now()\n\t\t\t}));\n\t\t} catch {}\n\t}\n\tsetup() {\n\t\tif (typeof window === \"undefined\" || typeof window.addEventListener === \"undefined\") return () => {};\n\t\tconst handler = (event) => {\n\t\t\tif (event.key !== this.name) return;\n\t\t\tconst message = JSON.parse(event.newValue ?? \"{}\");\n\t\t\tif (message?.event !== \"session\" || !message?.data) return;\n\t\t\tthis.listeners.forEach((listener) => listener(message));\n\t\t};\n\t\twindow.addEventListener(\"storage\", handler);\n\t\treturn () => {\n\t\t\twindow.removeEventListener(\"storage\", handler);\n\t\t};\n\t}\n};\nfunction getGlobalBroadcastChannel(name = \"better-auth.message\") {\n\tif (!globalThis[kBroadcastChannel]) globalThis[kBroadcastChannel] = new WindowBroadcastChannel(name);\n\treturn globalThis[kBroadcastChannel];\n}\n//#endregion\nexport { getGlobalBroadcastChannel, kBroadcastChannel };\n","//#region src/client/focus-manager.ts\nconst kFocusManager = Symbol.for(\"better-auth:focus-manager\");\nvar WindowFocusManager = class {\n\tlisteners = /* @__PURE__ */ new Set();\n\tsubscribe(listener) {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\tsetFocused(focused) {\n\t\tthis.listeners.forEach((listener) => listener(focused));\n\t}\n\tsetup() {\n\t\tif (typeof window === \"undefined\" || typeof document === \"undefined\" || typeof window.addEventListener === \"undefined\") return () => {};\n\t\tconst visibilityHandler = () => {\n\t\t\tif (document.visibilityState === \"visible\") this.setFocused(true);\n\t\t};\n\t\tdocument.addEventListener(\"visibilitychange\", visibilityHandler, false);\n\t\treturn () => {\n\t\t\tdocument.removeEventListener(\"visibilitychange\", visibilityHandler, false);\n\t\t};\n\t}\n};\nfunction getGlobalFocusManager() {\n\tif (!globalThis[kFocusManager]) globalThis[kFocusManager] = new WindowFocusManager();\n\treturn globalThis[kFocusManager];\n}\n//#endregion\nexport { getGlobalFocusManager, kFocusManager };\n","//#region src/client/online-manager.ts\nconst kOnlineManager = Symbol.for(\"better-auth:online-manager\");\nvar WindowOnlineManager = class {\n\tlisteners = /* @__PURE__ */ new Set();\n\tisOnline = typeof navigator !== \"undefined\" ? navigator.onLine : true;\n\tsubscribe(listener) {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\tsetOnline(online) {\n\t\tthis.isOnline = online;\n\t\tthis.listeners.forEach((listener) => listener(online));\n\t}\n\tsetup() {\n\t\tif (typeof window === \"undefined\" || typeof window.addEventListener === \"undefined\") return () => {};\n\t\tconst onOnline = () => this.setOnline(true);\n\t\tconst onOffline = () => this.setOnline(false);\n\t\twindow.addEventListener(\"online\", onOnline, false);\n\t\twindow.addEventListener(\"offline\", onOffline, false);\n\t\treturn () => {\n\t\t\twindow.removeEventListener(\"online\", onOnline, false);\n\t\t\twindow.removeEventListener(\"offline\", onOffline, false);\n\t\t};\n\t}\n};\nfunction getGlobalOnlineManager() {\n\tif (!globalThis[kOnlineManager]) globalThis[kOnlineManager] = new WindowOnlineManager();\n\treturn globalThis[kOnlineManager];\n}\n//#endregion\nexport { getGlobalOnlineManager, kOnlineManager };\n","//#region src/client/parser.ts\nconst PROTO_POLLUTION_PATTERNS = {\n\tproto: /\"(?:_|\\\\u0{2}5[Ff]){2}(?:p|\\\\u0{2}70)(?:r|\\\\u0{2}72)(?:o|\\\\u0{2}6[Ff])(?:t|\\\\u0{2}74)(?:o|\\\\u0{2}6[Ff])(?:_|\\\\u0{2}5[Ff]){2}\"\\s*:/,\n\tconstructor: /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/,\n\tprotoShort: /\"__proto__\"\\s*:/,\n\tconstructorShort: /\"constructor\"\\s*:/\n};\nconst JSON_SIGNATURE = /^\\s*[\"[{]|^\\s*-?\\d{1,16}(\\.\\d{1,17})?([Ee][+-]?\\d+)?\\s*$/;\nconst SPECIAL_VALUES = {\n\ttrue: true,\n\tfalse: false,\n\tnull: null,\n\tundefined: void 0,\n\tnan: NaN,\n\tinfinity: Number.POSITIVE_INFINITY,\n\t\"-infinity\": Number.NEGATIVE_INFINITY\n};\nconst ISO_DATE_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,7}))?(?:Z|([+-])(\\d{2}):(\\d{2}))$/;\nfunction isValidDate(date) {\n\treturn date instanceof Date && !isNaN(date.getTime());\n}\nfunction parseISODate(value) {\n\tconst match = ISO_DATE_REGEX.exec(value);\n\tif (!match) return null;\n\tconst [, year, month, day, hour, minute, second, ms, offsetSign, offsetHour, offsetMinute] = match;\n\tconst date = new Date(Date.UTC(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10), parseInt(hour, 10), parseInt(minute, 10), parseInt(second, 10), ms ? parseInt(ms.padEnd(3, \"0\"), 10) : 0));\n\tif (offsetSign) {\n\t\tconst offset = (parseInt(offsetHour, 10) * 60 + parseInt(offsetMinute, 10)) * (offsetSign === \"+\" ? -1 : 1);\n\t\tdate.setUTCMinutes(date.getUTCMinutes() + offset);\n\t}\n\treturn isValidDate(date) ? date : null;\n}\nfunction betterJSONParse(value, options = {}) {\n\tconst { strict = false, warnings = false, reviver, parseDates = true } = options;\n\tif (typeof value !== \"string\") return value;\n\tconst trimmed = value.trim();\n\tif (trimmed.length > 0 && trimmed[0] === \"\\\"\" && trimmed.endsWith(\"\\\"\") && !trimmed.slice(1, -1).includes(\"\\\"\")) return trimmed.slice(1, -1);\n\tconst lowerValue = trimmed.toLowerCase();\n\tif (lowerValue.length <= 9 && lowerValue in SPECIAL_VALUES) return SPECIAL_VALUES[lowerValue];\n\tif (!JSON_SIGNATURE.test(trimmed)) {\n\t\tif (strict) throw new SyntaxError(\"[better-json] Invalid JSON\");\n\t\treturn value;\n\t}\n\tif (Object.entries(PROTO_POLLUTION_PATTERNS).some(([key, pattern]) => {\n\t\tconst matches = pattern.test(trimmed);\n\t\tif (matches && warnings) console.warn(`[better-json] Detected potential prototype pollution attempt using ${key} pattern`);\n\t\treturn matches;\n\t}) && strict) throw new Error(\"[better-json] Potential prototype pollution attempt detected\");\n\ttry {\n\t\tconst secureReviver = (key, value) => {\n\t\t\tif (key === \"__proto__\" || key === \"constructor\" && value && typeof value === \"object\" && \"prototype\" in value) {\n\t\t\t\tif (warnings) console.warn(`[better-json] Dropping \"${key}\" key to prevent prototype pollution`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parseDates && typeof value === \"string\") {\n\t\t\t\tconst date = parseISODate(value);\n\t\t\t\tif (date) return date;\n\t\t\t}\n\t\t\treturn reviver ? reviver(key, value) : value;\n\t\t};\n\t\treturn JSON.parse(trimmed, secureReviver);\n\t} catch (error) {\n\t\tif (strict) throw error;\n\t\treturn value;\n\t}\n}\nfunction parseJSON(value, options = { strict: true }) {\n\treturn betterJSONParse(value, options);\n}\n//#endregion\nexport { parseJSON };\n","import { getGlobalBroadcastChannel } from \"./broadcast-channel.mjs\";\nimport { getGlobalFocusManager } from \"./focus-manager.mjs\";\nimport { getGlobalOnlineManager } from \"./online-manager.mjs\";\n//#region src/client/session-refresh.ts\nconst now = () => Math.floor(Date.now() / 1e3);\n/**\n* Normalize $fetch response: `throw: true` returns data directly, otherwise `{ data, error }`.\n*/\nfunction normalizeSessionResponse(res) {\n\tif (typeof res === \"object\" && res !== null && \"data\" in res && \"error\" in res) return res;\n\treturn {\n\t\tdata: res,\n\t\terror: null\n\t};\n}\n/**\n* Rate limit: don't refetch on focus if a session request was made within this many seconds\n*/\nconst FOCUS_REFETCH_RATE_LIMIT_SECONDS = 5;\nfunction createSessionRefreshManager(opts) {\n\tconst { sessionAtom, sessionSignal, $fetch, options = {} } = opts;\n\tconst refetchInterval = options.sessionOptions?.refetchInterval ?? 0;\n\tconst refetchOnWindowFocus = options.sessionOptions?.refetchOnWindowFocus ?? true;\n\tconst refetchWhenOffline = options.sessionOptions?.refetchWhenOffline ?? false;\n\tconst state = {\n\t\tlastSync: 0,\n\t\tlastSessionRequest: 0,\n\t\tcachedSession: void 0\n\t};\n\tconst shouldRefetch = () => {\n\t\treturn refetchWhenOffline || getGlobalOnlineManager().isOnline;\n\t};\n\tconst triggerRefetch = (event) => {\n\t\tif (!shouldRefetch()) return;\n\t\tif (event?.event === \"storage\") {\n\t\t\tstate.lastSync = now();\n\t\t\tsessionSignal.set(!sessionSignal.get());\n\t\t\treturn;\n\t\t}\n\t\tconst currentSession = sessionAtom.get();\n\t\tconst fetchSessionWithRefresh = () => {\n\t\t\tstate.lastSessionRequest = now();\n\t\t\t$fetch(\"/get-session\").then(async (res) => {\n\t\t\t\tlet { data, error } = normalizeSessionResponse(res);\n\t\t\t\tif (data?.needsRefresh) try {\n\t\t\t\t\tconst refreshRes = await $fetch(\"/get-session\", { method: \"POST\" });\n\t\t\t\t\t({data, error} = normalizeSessionResponse(refreshRes));\n\t\t\t\t} catch {}\n\t\t\t\tconst sessionData = data?.session && data?.user ? data : null;\n\t\t\t\tsessionAtom.set({\n\t\t\t\t\t...currentSession,\n\t\t\t\t\tdata: sessionData,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tstate.lastSync = now();\n\t\t\t\tsessionSignal.set(!sessionSignal.get());\n\t\t\t}).catch(() => {});\n\t\t};\n\t\tif (event?.event === \"poll\") {\n\t\t\tfetchSessionWithRefresh();\n\t\t\treturn;\n\t\t}\n\t\tif (event?.event === \"visibilitychange\") {\n\t\t\tif (now() - state.lastSessionRequest < FOCUS_REFETCH_RATE_LIMIT_SECONDS) return;\n\t\t\tstate.lastSessionRequest = now();\n\t\t}\n\t\tif (event?.event === \"visibilitychange\") {\n\t\t\tfetchSessionWithRefresh();\n\t\t\treturn;\n\t\t}\n\t\tif (currentSession?.data === null || currentSession?.data === void 0) {\n\t\t\tstate.lastSync = now();\n\t\t\tsessionSignal.set(!sessionSignal.get());\n\t\t}\n\t};\n\tconst broadcastSessionUpdate = (trigger) => {\n\t\tgetGlobalBroadcastChannel().post({\n\t\t\tevent: \"session\",\n\t\t\tdata: { trigger },\n\t\t\tclientId: Math.random().toString(36).substring(7)\n\t\t});\n\t};\n\tconst setupPolling = () => {\n\t\tif (refetchInterval && refetchInterval > 0) state.pollInterval = setInterval(() => {\n\t\t\tif (sessionAtom.get()?.data) triggerRefetch({ event: \"poll\" });\n\t\t}, refetchInterval * 1e3);\n\t};\n\tconst setupBroadcast = () => {\n\t\tstate.unsubscribeBroadcast = getGlobalBroadcastChannel().subscribe(() => {\n\t\t\ttriggerRefetch({ event: \"storage\" });\n\t\t});\n\t};\n\tconst setupFocusRefetch = () => {\n\t\tif (!refetchOnWindowFocus) return;\n\t\tstate.unsubscribeFocus = getGlobalFocusManager().subscribe(() => {\n\t\t\ttriggerRefetch({ event: \"visibilitychange\" });\n\t\t});\n\t};\n\tconst setupOnlineRefetch = () => {\n\t\tstate.unsubscribeOnline = getGlobalOnlineManager().subscribe((online) => {\n\t\t\tif (online) triggerRefetch({ event: \"visibilitychange\" });\n\t\t});\n\t};\n\tconst init = () => {\n\t\tsetupPolling();\n\t\tsetupBroadcast();\n\t\tsetupFocusRefetch();\n\t\tsetupOnlineRefetch();\n\t\tgetGlobalBroadcastChannel().setup();\n\t\tgetGlobalFocusManager().setup();\n\t\tgetGlobalOnlineManager().setup();\n\t};\n\tconst cleanup = () => {\n\t\tif (state.pollInterval) {\n\t\t\tclearInterval(state.pollInterval);\n\t\t\tstate.pollInterval = void 0;\n\t\t}\n\t\tif (state.unsubscribeBroadcast) {\n\t\t\tstate.unsubscribeBroadcast();\n\t\t\tstate.unsubscribeBroadcast = void 0;\n\t\t}\n\t\tif (state.unsubscribeFocus) {\n\t\t\tstate.unsubscribeFocus();\n\t\t\tstate.unsubscribeFocus = void 0;\n\t\t}\n\t\tif (state.unsubscribeOnline) {\n\t\t\tstate.unsubscribeOnline();\n\t\t\tstate.unsubscribeOnline = void 0;\n\t\t}\n\t\tstate.lastSync = 0;\n\t\tstate.lastSessionRequest = 0;\n\t\tstate.cachedSession = void 0;\n\t};\n\treturn {\n\t\tinit,\n\t\tcleanup,\n\t\ttriggerRefetch,\n\t\tbroadcastSessionUpdate\n\t};\n}\n//#endregion\nexport { createSessionRefreshManager };\n","//#region src/env/env-impl.ts\nconst _envShim = Object.create(null);\nconst _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis);\nconst env = new Proxy(_envShim, {\n\tget(_, prop) {\n\t\treturn _getEnv()[prop] ?? _envShim[prop];\n\t},\n\thas(_, prop) {\n\t\treturn prop in _getEnv() || prop in _envShim;\n\t},\n\tset(_, prop, value) {\n\t\tconst env = _getEnv(true);\n\t\tenv[prop] = value;\n\t\treturn true;\n\t},\n\tdeleteProperty(_, prop) {\n\t\tif (!prop) return false;\n\t\tconst env = _getEnv(true);\n\t\tdelete env[prop];\n\t\treturn true;\n\t},\n\townKeys() {\n\t\tconst env = _getEnv(true);\n\t\treturn Object.keys(env);\n\t}\n});\nfunction toBoolean(val) {\n\treturn val ? val !== \"false\" : false;\n}\nconst nodeENV = typeof process !== \"undefined\" && process.env && process.env.NODE_ENV || \"\";\n/** Detect if `NODE_ENV` environment variable is `production` */\nconst isProduction = nodeENV === \"production\";\n/** Detect if `NODE_ENV` environment variable is `dev` or `development` */\nconst isDevelopment = () => nodeENV === \"dev\" || nodeENV === \"development\";\n/** Detect if `NODE_ENV` environment variable is `test` */\nconst isTest = () => nodeENV === \"test\" || toBoolean(env.TEST);\n/**\n* Get environment variable with fallback\n*/\nfunction getEnvVar(key, fallback) {\n\tif (typeof process !== \"undefined\" && process.env) return process.env[key] ?? fallback;\n\tif (typeof Deno !== \"undefined\") return Deno.env.get(key) ?? fallback;\n\tif (typeof Bun !== \"undefined\") return Bun.env[key] ?? fallback;\n\treturn fallback;\n}\n/**\n* Get boolean environment variable\n*/\nfunction getBooleanEnvVar(key, fallback = true) {\n\tconst value = getEnvVar(key);\n\tif (!value) return fallback;\n\treturn value !== \"0\" && value.toLowerCase() !== \"false\" && value !== \"\";\n}\n/**\n* Common environment variables used in Better Auth\n*/\nconst ENV = Object.freeze({\n\tget BETTER_AUTH_SECRET() {\n\t\treturn getEnvVar(\"BETTER_AUTH_SECRET\");\n\t},\n\tget AUTH_SECRET() {\n\t\treturn getEnvVar(\"AUTH_SECRET\");\n\t},\n\tget BETTER_AUTH_TELEMETRY() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY\");\n\t},\n\tget BETTER_AUTH_TELEMETRY_ID() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY_ID\");\n\t},\n\tget NODE_ENV() {\n\t\treturn getEnvVar(\"NODE_ENV\", \"development\");\n\t},\n\tget PACKAGE_VERSION() {\n\t\treturn getEnvVar(\"PACKAGE_VERSION\", \"0.0.0\");\n\t},\n\tget BETTER_AUTH_TELEMETRY_ENDPOINT() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY_ENDPOINT\", \"\");\n\t}\n});\n//#endregion\nexport { ENV, env, getBooleanEnvVar, getEnvVar, isDevelopment, isProduction, isTest, nodeENV };\n","import { wildcardMatch } from \"./wildcard.mjs\";\nimport { env } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/utils/url.ts\n/**\n* Minimal loopback check for dev scheme inference only. Reachable from\n* `client/config.ts` via `getBaseURL`, so we MUST NOT import the full\n* `@better-auth/core/utils/host` classifier here: its `utils/ip` dependency\n* on zod would leak into the client bundle (see `e2e/smoke/test/vite.spec.ts`).\n*\n* Server-side SSRF/loopback checks (oauth redirect matching, trusted-origin\n* resolution, electron fetch gate) continue to use the authoritative\n* `isLoopbackHost` from `@better-auth/core/utils/host`. This helper's only\n* job is picking `http` vs `https` for dev ergonomics.\n*/\nfunction isLoopbackForDevScheme(host) {\n\tconst hostname = host.replace(/:\\d+$/, \"\").replace(/^\\[|\\]$/g, \"\").toLowerCase();\n\treturn hostname === \"localhost\" || hostname.endsWith(\".localhost\") || hostname === \"::1\" || hostname.startsWith(\"127.\");\n}\nfunction checkHasPath(url) {\n\ttry {\n\t\treturn (new URL(url).pathname.replace(/\\/+$/, \"\") || \"/\") !== \"/\";\n\t} catch {\n\t\tthrow new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`);\n\t}\n}\nfunction assertHasProtocol(url) {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\tif (parsedUrl.protocol !== \"http:\" && parsedUrl.protocol !== \"https:\") throw new BetterAuthError(`Invalid base URL: ${url}. URL must include 'http://' or 'https://'`);\n\t} catch (error) {\n\t\tif (error instanceof BetterAuthError) throw error;\n\t\tthrow new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`, { cause: error });\n\t}\n}\nfunction withPath(url, path = \"/api/auth\") {\n\tassertHasProtocol(url);\n\tif (checkHasPath(url)) return url;\n\tconst trimmedUrl = url.replace(/\\/+$/, \"\");\n\tif (!path || path === \"/\") return trimmedUrl;\n\tpath = path.startsWith(\"/\") ? path : `/${path}`;\n\treturn `${trimmedUrl}${path}`;\n}\nfunction validateProxyHeader(header, type) {\n\tif (!header || header.trim() === \"\") return false;\n\tif (type === \"proto\") return header === \"http\" || header === \"https\";\n\tif (type === \"host\") {\n\t\tif ([\n\t\t\t/\\.\\./,\n\t\t\t/\\0/,\n\t\t\t/[\\s]/,\n\t\t\t/^[.]/,\n\t\t\t/[<>'\"]/,\n\t\t\t/javascript:/i,\n\t\t\t/file:/i,\n\t\t\t/data:/i\n\t\t].some((pattern) => pattern.test(header))) return false;\n\t\treturn /^[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])?)*(:[0-9]{1,5})?$/.test(header) || /^(\\d{1,3}\\.){3}\\d{1,3}(:[0-9]{1,5})?$/.test(header) || /^\\[[0-9a-fA-F:]+\\](:[0-9]{1,5})?$/.test(header) || /^localhost(:[0-9]{1,5})?$/i.test(header);\n\t}\n\treturn false;\n}\nfunction getBaseURL(url, path, request, loadEnv, trustedProxyHeaders) {\n\tif (url) return withPath(url, path);\n\tif (loadEnv !== false) {\n\t\tconst fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== \"/\" ? env.BASE_URL : void 0);\n\t\tif (fromEnv) return withPath(fromEnv, path);\n\t}\n\tconst fromRequest = request?.headers.get(\"x-forwarded-host\");\n\tconst fromRequestProto = request?.headers.get(\"x-forwarded-proto\");\n\tif (fromRequest && fromRequestProto && trustedProxyHeaders) {\n\t\tif (validateProxyHeader(fromRequestProto, \"proto\") && validateProxyHeader(fromRequest, \"host\")) try {\n\t\t\treturn withPath(`${fromRequestProto}://${fromRequest}`, path);\n\t\t} catch (_error) {}\n\t}\n\tif (request) {\n\t\tconst url = getOrigin(request.url);\n\t\tif (!url) throw new BetterAuthError(\"Could not get origin from request. Please provide a valid base URL.\");\n\t\treturn withPath(url, path);\n\t}\n\tif (typeof window !== \"undefined\" && window.location) return withPath(window.location.origin, path);\n}\nfunction getOrigin(url) {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\treturn parsedUrl.origin === \"null\" ? null : parsedUrl.origin;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getProtocol(url) {\n\ttry {\n\t\treturn new URL(url).protocol;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getHost(url) {\n\ttry {\n\t\treturn new URL(url).host;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/**\n* Checks if the baseURL config is a dynamic config object\n*/\nfunction isDynamicBaseURLConfig(config) {\n\treturn typeof config === \"object\" && config !== null && \"allowedHosts\" in config && Array.isArray(config.allowedHosts);\n}\n/**\n* Check if a value is a `Request`\n* - `instanceof`: works for native Request instances\n* - `toString`: handles where instanceof check fails but the object is still a\n* valid Request (e.g. cross-realm, polyfills). Paired with a shape check so\n* an object that only spoofs `Symbol.toStringTag` without the real shape is\n* rejected before downstream code tries to read `.headers` / `.url`.\n*\n* @param value The value to check\n* @returns `true` if the value is a Request instance\n*/\nfunction isRequestLike(value) {\n\tif (value instanceof Request) return true;\n\tif (typeof value !== \"object\" || value === null || Object.prototype.toString.call(value) !== \"[object Request]\") return false;\n\tconst v = value;\n\treturn typeof v.url === \"string\" && typeof v.headers === \"object\" && v.headers !== null && typeof v.headers.get === \"function\";\n}\n/**\n* Extracts the host from a `Request` or `Headers`.\n* Honors `x-forwarded-host` only when `trustedProxyHeaders` is enabled,\n* then falls back to the `host` header and finally the request URL.\n*/\nfunction getHostFromSource(source, trustedProxyHeaders) {\n\tconst headers = isRequestLike(source) ? source.headers : source;\n\tif (trustedProxyHeaders) {\n\t\tconst forwardedHost = headers.get(\"x-forwarded-host\");\n\t\tif (forwardedHost && validateProxyHeader(forwardedHost, \"host\")) return forwardedHost;\n\t}\n\tconst host = headers.get(\"host\");\n\tif (host && validateProxyHeader(host, \"host\")) return host;\n\tif (isRequestLike(source)) try {\n\t\treturn new URL(source.url).host;\n\t} catch {\n\t\treturn null;\n\t}\n\treturn null;\n}\n/**\n* Extracts the protocol from a `Request` or `Headers`.\n* Honors `x-forwarded-proto` only when `trustedProxyHeaders` is enabled,\n* then falls back to the request URL, then to \"https\".\n*/\nfunction getProtocolFromSource(source, configProtocol, trustedProxyHeaders) {\n\tif (configProtocol === \"http\" || configProtocol === \"https\") return configProtocol;\n\tconst headers = isRequestLike(source) ? source.headers : source;\n\tif (trustedProxyHeaders) {\n\t\tconst forwardedProto = headers.get(\"x-forwarded-proto\");\n\t\tif (forwardedProto && validateProxyHeader(forwardedProto, \"proto\")) return forwardedProto;\n\t}\n\tif (isRequestLike(source)) try {\n\t\tconst url = new URL(source.url);\n\t\tif (url.protocol === \"http:\" || url.protocol === \"https:\") return url.protocol.slice(0, -1);\n\t} catch {}\n\tconst host = getHostFromSource(source, trustedProxyHeaders);\n\tif (host && isLoopbackForDevScheme(host)) return \"http\";\n\treturn \"https\";\n}\n/**\n* Matches a hostname against a host pattern.\n* Supports wildcard patterns like `*.vercel.app` or `preview-*.myapp.com`.\n*\n* @param host The hostname to test (e.g., \"myapp.com\", \"preview-123.vercel.app\")\n* @param pattern The host pattern (e.g., \"myapp.com\", \"*.vercel.app\")\n* @returns {boolean} true if the host matches the pattern, false otherwise.\n*\n* @example\n* ```ts\n* matchesHostPattern(\"myapp.com\", \"myapp.com\") // true\n* matchesHostPattern(\"preview-123.vercel.app\", \"*.vercel.app\") // true\n* matchesHostPattern(\"preview-123.myapp.com\", \"preview-*.myapp.com\") // true\n* matchesHostPattern(\"evil.com\", \"myapp.com\") // false\n* ```\n*/\nconst matchesHostPattern = (host, pattern) => {\n\tif (!host || !pattern) return false;\n\tconst normalizedHost = host.replace(/^https?:\\/\\//, \"\").split(\"/\")[0].toLowerCase();\n\tconst normalizedPattern = pattern.replace(/^https?:\\/\\//, \"\").split(\"/\")[0].toLowerCase();\n\tif (normalizedPattern.includes(\"*\") || normalizedPattern.includes(\"?\")) return wildcardMatch(normalizedPattern)(normalizedHost);\n\treturn normalizedHost.toLowerCase() === normalizedPattern.toLowerCase();\n};\n/**\n* Resolves the base URL from a dynamic config based on the incoming request.\n* Validates the derived host against the allowedHosts allowlist.\n*\n* @param config The dynamic base URL config\n* @param request The incoming request\n* @param basePath The base path to append\n* @returns The resolved base URL with path\n* @throws BetterAuthError if host is not in allowedHosts and no fallback is set\n*/\nfunction resolveDynamicBaseURL(config, source, basePath, trustedProxyHeaders) {\n\tconst host = getHostFromSource(source, trustedProxyHeaders);\n\tif (!host) {\n\t\tif (config.fallback) return withPath(config.fallback, basePath);\n\t\tthrow new BetterAuthError(\"Could not determine host from request headers. Please provide a fallback URL in your baseURL config.\");\n\t}\n\tif (config.allowedHosts.some((pattern) => matchesHostPattern(host, pattern))) return withPath(`${getProtocolFromSource(source, config.protocol, trustedProxyHeaders)}://${host}`, basePath);\n\tif (config.fallback) return withPath(config.fallback, basePath);\n\tthrow new BetterAuthError(`Host \"${host}\" is not in the allowed hosts list. Allowed hosts: ${config.allowedHosts.join(\", \")}. Add this host to your allowedHosts config or provide a fallback URL.`);\n}\n/**\n* Resolves the base URL from any config type (static string or dynamic object).\n* This is the main entry point for base URL resolution.\n*\n* @param config The base URL config (string or object)\n* @param basePath The base path to append\n* @param request Optional request for dynamic resolution\n* @param loadEnv Whether to load from environment variables\n* @param trustedProxyHeaders Whether to trust proxy headers (for legacy behavior)\n* @returns The resolved base URL with path\n*/\nfunction resolveBaseURL(config, basePath, source, loadEnv, trustedProxyHeaders) {\n\tif (isDynamicBaseURLConfig(config)) {\n\t\tif (source) return resolveDynamicBaseURL(config, source, basePath, trustedProxyHeaders);\n\t\tif (config.fallback) return withPath(config.fallback, basePath);\n\t\treturn getBaseURL(void 0, basePath, void 0, loadEnv, trustedProxyHeaders);\n\t}\n\tconst request = isRequestLike(source) ? source : void 0;\n\tif (typeof config === \"string\") return getBaseURL(config, basePath, request, loadEnv, trustedProxyHeaders);\n\treturn getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders);\n}\n//#endregion\nexport { getBaseURL, getHost, getHostFromSource, getOrigin, getProtocol, getProtocolFromSource, isDynamicBaseURLConfig, isRequestLike, matchesHostPattern, resolveBaseURL, resolveDynamicBaseURL };\n","//#region src/client/fetch-plugins.ts\nconst redirectPlugin = {\n\tid: \"redirect\",\n\tname: \"Redirect\",\n\thooks: { onSuccess(context) {\n\t\tif (context.data?.url && context.data?.redirect) {\n\t\t\tif (typeof window !== \"undefined\" && window.location) {\n\t\t\t\tif (window.location) try {\n\t\t\t\t\twindow.location.href = context.data.url;\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t}\n\t} }\n};\n//#endregion\nexport { redirectPlugin };\n","import { useAuthQuery } from \"./query.mjs\";\nimport { createSessionRefreshManager } from \"./session-refresh.mjs\";\nimport { atom, onMount } from \"nanostores\";\n//#region src/client/session-atom.ts\nfunction getSessionAtom($fetch, options) {\n\tconst $signal = atom(false);\n\tconst session = useAuthQuery($signal, \"/get-session\", $fetch, { method: \"GET\" });\n\tlet broadcastSessionUpdate = () => {};\n\tonMount(session, () => {\n\t\tconst refreshManager = createSessionRefreshManager({\n\t\t\tsessionAtom: session,\n\t\t\tsessionSignal: $signal,\n\t\t\t$fetch,\n\t\t\toptions\n\t\t});\n\t\trefreshManager.init();\n\t\tbroadcastSessionUpdate = refreshManager.broadcastSessionUpdate;\n\t\treturn () => {\n\t\t\trefreshManager.cleanup();\n\t\t};\n\t});\n\treturn {\n\t\tsession,\n\t\t$sessionSignal: $signal,\n\t\tbroadcastSessionUpdate: (trigger) => broadcastSessionUpdate(trigger)\n\t};\n}\n//#endregion\nexport { getSessionAtom };\n","function isPlainObject(value) {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {\n return false;\n }\n if (Symbol.iterator in value) {\n return false;\n }\n if (Symbol.toStringTag in value) {\n return Object.prototype.toString.call(value) === \"[object Module]\";\n }\n return true;\n}\n\nfunction _defu(baseObject, defaults, namespace = \".\", merger) {\n if (!isPlainObject(defaults)) {\n return _defu(baseObject, {}, namespace, merger);\n }\n const object = { ...defaults };\n for (const key of Object.keys(baseObject)) {\n if (key === \"__proto__\" || key === \"constructor\") {\n continue;\n }\n const value = baseObject[key];\n if (value === null || value === void 0) {\n continue;\n }\n if (merger && merger(object, key, value, namespace)) {\n continue;\n }\n if (Array.isArray(value) && Array.isArray(object[key])) {\n object[key] = [...value, ...object[key]];\n } else if (isPlainObject(value) && isPlainObject(object[key])) {\n object[key] = _defu(\n value,\n object[key],\n (namespace ? `${namespace}.` : \"\") + key.toString(),\n merger\n );\n } else {\n object[key] = value;\n }\n }\n return object;\n}\nfunction createDefu(merger) {\n return (...arguments_) => (\n // eslint-disable-next-line unicorn/no-array-reduce\n arguments_.reduce((p, c) => _defu(p, c, \"\", merger), {})\n );\n}\nconst defu = createDefu();\nconst defuFn = createDefu((object, key, currentValue) => {\n if (object[key] !== void 0 && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\nconst defuArrayFn = createDefu((object, key, currentValue) => {\n if (Array.isArray(object[key]) && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\n\nexport { createDefu, defu as default, defu, defuArrayFn, defuFn };\n","var __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\n\n// src/error.ts\nvar BetterFetchError = class extends Error {\n constructor(status, statusText, error) {\n super(statusText || status.toString(), {\n cause: error\n });\n this.status = status;\n this.statusText = statusText;\n this.error = error;\n Error.captureStackTrace(this, this.constructor);\n }\n};\n\n// src/plugins.ts\nvar initializePlugins = async (url, options) => {\n var _a, _b, _c, _d, _e, _f;\n let opts = options || {};\n const hooks = {\n onRequest: [options == null ? void 0 : options.onRequest],\n onResponse: [options == null ? void 0 : options.onResponse],\n onSuccess: [options == null ? void 0 : options.onSuccess],\n onError: [options == null ? void 0 : options.onError],\n onRetry: [options == null ? void 0 : options.onRetry]\n };\n if (!options || !(options == null ? void 0 : options.plugins)) {\n return {\n url,\n options: opts,\n hooks\n };\n }\n for (const plugin of (options == null ? void 0 : options.plugins) || []) {\n if (plugin.init) {\n const pluginRes = await ((_a = plugin.init) == null ? void 0 : _a.call(plugin, url.toString(), options));\n opts = pluginRes.options || opts;\n url = pluginRes.url;\n }\n hooks.onRequest.push((_b = plugin.hooks) == null ? void 0 : _b.onRequest);\n hooks.onResponse.push((_c = plugin.hooks) == null ? void 0 : _c.onResponse);\n hooks.onSuccess.push((_d = plugin.hooks) == null ? void 0 : _d.onSuccess);\n hooks.onError.push((_e = plugin.hooks) == null ? void 0 : _e.onError);\n hooks.onRetry.push((_f = plugin.hooks) == null ? void 0 : _f.onRetry);\n }\n return {\n url,\n options: opts,\n hooks\n };\n};\n\n// src/retry.ts\nvar LinearRetryStrategy = class {\n constructor(options) {\n this.options = options;\n }\n shouldAttemptRetry(attempt, response) {\n if (this.options.shouldRetry) {\n return Promise.resolve(\n attempt < this.options.attempts && this.options.shouldRetry(response)\n );\n }\n return Promise.resolve(attempt < this.options.attempts);\n }\n getDelay() {\n return this.options.delay;\n }\n};\nvar ExponentialRetryStrategy = class {\n constructor(options) {\n this.options = options;\n }\n shouldAttemptRetry(attempt, response) {\n if (this.options.shouldRetry) {\n return Promise.resolve(\n attempt < this.options.attempts && this.options.shouldRetry(response)\n );\n }\n return Promise.resolve(attempt < this.options.attempts);\n }\n getDelay(attempt) {\n const delay = Math.min(\n this.options.maxDelay,\n this.options.baseDelay * 2 ** attempt\n );\n return delay;\n }\n};\nfunction createRetryStrategy(options) {\n if (typeof options === \"number\") {\n return new LinearRetryStrategy({\n type: \"linear\",\n attempts: options,\n delay: 1e3\n });\n }\n switch (options.type) {\n case \"linear\":\n return new LinearRetryStrategy(options);\n case \"exponential\":\n return new ExponentialRetryStrategy(options);\n default:\n throw new Error(\"Invalid retry strategy\");\n }\n}\n\n// src/auth.ts\nvar getAuthHeader = async (options) => {\n const headers = {};\n const getValue = async (value) => typeof value === \"function\" ? await value() : value;\n if (options == null ? void 0 : options.auth) {\n if (options.auth.type === \"Bearer\") {\n const token = await getValue(options.auth.token);\n if (!token) {\n return headers;\n }\n headers[\"authorization\"] = `Bearer ${token}`;\n } else if (options.auth.type === \"Basic\") {\n const [username, password] = await Promise.all([\n getValue(options.auth.username),\n getValue(options.auth.password)\n ]);\n if (!username || !password) {\n return headers;\n }\n headers[\"authorization\"] = `Basic ${btoa(`${username}:${password}`)}`;\n } else if (options.auth.type === \"Custom\") {\n const [prefix, value] = await Promise.all([\n getValue(options.auth.prefix),\n getValue(options.auth.value)\n ]);\n if (!value) {\n return headers;\n }\n headers[\"authorization\"] = `${prefix != null ? prefix : \"\"} ${value}`;\n }\n }\n return headers;\n};\n\n// src/utils.ts\nvar JSON_RE = /^application\\/(?:[\\w!#$%&*.^`~-]*\\+)?json(;.+)?$/i;\nfunction detectResponseType(request) {\n const _contentType = request.headers.get(\"content-type\");\n const textTypes = /* @__PURE__ */ new Set([\n \"image/svg\",\n \"application/xml\",\n \"application/xhtml\",\n \"application/html\"\n ]);\n if (!_contentType) {\n return \"json\";\n }\n const contentType = _contentType.split(\";\").shift() || \"\";\n if (JSON_RE.test(contentType)) {\n return \"json\";\n }\n if (textTypes.has(contentType) || contentType.startsWith(\"text/\")) {\n return \"text\";\n }\n return \"blob\";\n}\nfunction isJSONParsable(value) {\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n}\nfunction isJSONSerializable(value) {\n if (value === void 0) {\n return false;\n }\n const t = typeof value;\n if (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) {\n return true;\n }\n if (t !== \"object\") {\n return false;\n }\n if (Array.isArray(value)) {\n return true;\n }\n if (value.buffer) {\n return false;\n }\n return value.constructor && value.constructor.name === \"Object\" || typeof value.toJSON === \"function\";\n}\nfunction jsonParse(text) {\n try {\n return JSON.parse(text);\n } catch (error) {\n return text;\n }\n}\nfunction isFunction(value) {\n return typeof value === \"function\";\n}\nfunction getFetch(options) {\n if (options == null ? void 0 : options.customFetchImpl) {\n return options.customFetchImpl;\n }\n if (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) {\n return globalThis.fetch;\n }\n if (typeof window !== \"undefined\" && isFunction(window.fetch)) {\n return window.fetch;\n }\n throw new Error(\"No fetch implementation found\");\n}\nfunction isPayloadMethod(method) {\n if (!method) {\n return false;\n }\n const payloadMethod = [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n return payloadMethod.includes(method.toUpperCase());\n}\nfunction isRouteMethod(method) {\n const routeMethod = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n if (!method) {\n return false;\n }\n return routeMethod.includes(method.toUpperCase());\n}\nasync function getHeaders(opts) {\n const headers = new Headers(opts == null ? void 0 : opts.headers);\n const authHeader = await getAuthHeader(opts);\n for (const [key, value] of Object.entries(authHeader || {})) {\n headers.set(key, value);\n }\n if (!headers.has(\"content-type\")) {\n const t = detectContentType(opts == null ? void 0 : opts.body);\n if (t) {\n headers.set(\"content-type\", t);\n }\n }\n return headers;\n}\nfunction getURL(url, options) {\n if (url.startsWith(\"@\")) {\n const m = url.toString().split(\"@\")[1].split(\"/\")[0];\n if (methods.includes(m)) {\n url = url.replace(`@${m}/`, \"/\");\n }\n }\n let _url;\n try {\n if (url.startsWith(\"http\")) {\n _url = url;\n } else {\n let baseURL = options == null ? void 0 : options.baseURL;\n if (baseURL && !(baseURL == null ? void 0 : baseURL.endsWith(\"/\"))) {\n baseURL = baseURL + \"/\";\n }\n if (url.startsWith(\"/\")) {\n _url = new URL(url.substring(1), baseURL);\n } else {\n _url = new URL(url, options == null ? void 0 : options.baseURL);\n }\n }\n } catch (e) {\n if (e instanceof TypeError) {\n if (!(options == null ? void 0 : options.baseURL)) {\n throw TypeError(\n `Invalid URL ${url}. Are you passing in a relative url but not setting the baseURL?`\n );\n }\n throw TypeError(\n `Invalid URL ${url}. Please validate that you are passing the correct input.`\n );\n }\n throw e;\n }\n if (options == null ? void 0 : options.params) {\n if (Array.isArray(options == null ? void 0 : options.params)) {\n const params = (options == null ? void 0 : options.params) ? Array.isArray(options.params) ? `/${options.params.join(\"/\")}` : `/${Object.values(options.params).join(\"/\")}` : \"\";\n _url = _url.toString().split(\"/:\")[0];\n _url = `${_url.toString()}${params}`;\n } else {\n for (const [key, value] of Object.entries(options == null ? void 0 : options.params)) {\n _url = _url.toString().replace(`:${key}`, String(value));\n }\n }\n }\n const __url = new URL(_url);\n const queryParams = options == null ? void 0 : options.query;\n if (queryParams) {\n for (const [key, value] of Object.entries(queryParams)) {\n __url.searchParams.append(key, String(value));\n }\n }\n return __url;\n}\nfunction detectContentType(body) {\n if (isJSONSerializable(body)) {\n return \"application/json\";\n }\n return null;\n}\nfunction getBody(options) {\n if (!(options == null ? void 0 : options.body)) {\n return null;\n }\n const headers = new Headers(options == null ? void 0 : options.headers);\n if (isJSONSerializable(options.body) && !headers.has(\"content-type\")) {\n for (const [key, value] of Object.entries(options == null ? void 0 : options.body)) {\n if (value instanceof Date) {\n options.body[key] = value.toISOString();\n }\n }\n return JSON.stringify(options.body);\n }\n if (headers.has(\"content-type\") && headers.get(\"content-type\") === \"application/x-www-form-urlencoded\") {\n if (isJSONSerializable(options.body)) {\n return new URLSearchParams(options.body).toString();\n }\n return options.body;\n }\n return options.body;\n}\nfunction getMethod(url, options) {\n var _a;\n if (options == null ? void 0 : options.method) {\n return options.method.toUpperCase();\n }\n if (url.startsWith(\"@\")) {\n const pMethod = (_a = url.split(\"@\")[1]) == null ? void 0 : _a.split(\"/\")[0];\n if (!methods.includes(pMethod)) {\n return (options == null ? void 0 : options.body) ? \"POST\" : \"GET\";\n }\n return pMethod.toUpperCase();\n }\n return (options == null ? void 0 : options.body) ? \"POST\" : \"GET\";\n}\nfunction getTimeout(options, controller) {\n let abortTimeout;\n if (!(options == null ? void 0 : options.signal) && (options == null ? void 0 : options.timeout)) {\n abortTimeout = setTimeout(() => controller == null ? void 0 : controller.abort(), options == null ? void 0 : options.timeout);\n }\n return {\n abortTimeout,\n clearTimeout: () => {\n if (abortTimeout) {\n clearTimeout(abortTimeout);\n }\n }\n };\n}\nfunction bodyParser(data, responseType) {\n if (responseType === \"json\") {\n return JSON.parse(data);\n }\n return data;\n}\nvar ValidationError = class _ValidationError extends Error {\n constructor(issues, message) {\n super(message || JSON.stringify(issues, null, 2));\n this.issues = issues;\n Object.setPrototypeOf(this, _ValidationError.prototype);\n }\n};\nasync function parseStandardSchema(schema, input) {\n const result = await schema[\"~standard\"].validate(input);\n if (result.issues) {\n throw new ValidationError(result.issues);\n }\n return result.value;\n}\n\n// src/create-fetch/schema.ts\nvar methods = [\"get\", \"post\", \"put\", \"patch\", \"delete\"];\nvar createSchema = (schema, config) => {\n return {\n schema,\n config\n };\n};\n\n// src/create-fetch/index.ts\nvar applySchemaPlugin = (config) => ({\n id: \"apply-schema\",\n name: \"Apply Schema\",\n version: \"1.0.0\",\n async init(url, options) {\n var _a, _b, _c, _d;\n const schema = ((_b = (_a = config.plugins) == null ? void 0 : _a.find(\n (plugin) => {\n var _a2;\n return ((_a2 = plugin.schema) == null ? void 0 : _a2.config) ? url.startsWith(plugin.schema.config.baseURL || \"\") || url.startsWith(plugin.schema.config.prefix || \"\") : false;\n }\n )) == null ? void 0 : _b.schema) || config.schema;\n if (schema) {\n let urlKey = url;\n if ((_c = schema.config) == null ? void 0 : _c.prefix) {\n if (urlKey.startsWith(schema.config.prefix)) {\n urlKey = urlKey.replace(schema.config.prefix, \"\");\n if (schema.config.baseURL) {\n url = url.replace(schema.config.prefix, schema.config.baseURL);\n }\n }\n }\n if ((_d = schema.config) == null ? void 0 : _d.baseURL) {\n if (urlKey.startsWith(schema.config.baseURL)) {\n urlKey = urlKey.replace(schema.config.baseURL, \"\");\n }\n }\n const keySchema = schema.schema[urlKey];\n if (keySchema) {\n let opts = __spreadProps(__spreadValues({}, options), {\n method: keySchema.method,\n output: keySchema.output\n });\n if (!(options == null ? void 0 : options.disableValidation)) {\n opts = __spreadProps(__spreadValues({}, opts), {\n body: keySchema.input ? await parseStandardSchema(keySchema.input, options == null ? void 0 : options.body) : options == null ? void 0 : options.body,\n params: keySchema.params ? await parseStandardSchema(keySchema.params, options == null ? void 0 : options.params) : options == null ? void 0 : options.params,\n query: keySchema.query ? await parseStandardSchema(keySchema.query, options == null ? void 0 : options.query) : options == null ? void 0 : options.query\n });\n }\n return {\n url,\n options: opts\n };\n }\n }\n return {\n url,\n options\n };\n }\n});\nvar createFetch = (config) => {\n async function $fetch(url, options) {\n const opts = __spreadProps(__spreadValues(__spreadValues({}, config), options), {\n plugins: [...(config == null ? void 0 : config.plugins) || [], applySchemaPlugin(config || {}), ...(options == null ? void 0 : options.plugins) || []]\n });\n if (config == null ? void 0 : config.catchAllError) {\n try {\n return await betterFetch(url, opts);\n } catch (error) {\n return {\n data: null,\n error: {\n status: 500,\n statusText: \"Fetch Error\",\n message: \"Fetch related error. Captured by catchAllError option. See error property for more details.\",\n error\n }\n };\n }\n }\n return await betterFetch(url, opts);\n }\n return $fetch;\n};\n\n// src/url.ts\nfunction getURL2(url, option) {\n const { baseURL, params, query } = option || {\n query: {},\n params: {},\n baseURL: \"\"\n };\n let basePath = url.startsWith(\"http\") ? url.split(\"/\").slice(0, 3).join(\"/\") : baseURL || \"\";\n if (url.startsWith(\"@\")) {\n const m = url.toString().split(\"@\")[1].split(\"/\")[0];\n if (methods.includes(m)) {\n url = url.replace(`@${m}/`, \"/\");\n }\n }\n if (!basePath.endsWith(\"/\")) basePath += \"/\";\n let [path, urlQuery] = url.replace(basePath, \"\").split(\"?\");\n const queryParams = new URLSearchParams(urlQuery);\n for (const [key, value] of Object.entries(query || {})) {\n if (value == null) continue;\n let serializedValue;\n if (typeof value === \"string\") {\n serializedValue = value;\n } else if (Array.isArray(value)) {\n for (const val of value) {\n queryParams.append(key, val);\n }\n continue;\n } else {\n serializedValue = JSON.stringify(value);\n }\n queryParams.set(key, serializedValue);\n }\n if (params) {\n if (Array.isArray(params)) {\n const paramPaths = path.split(\"/\").filter((p) => p.startsWith(\":\"));\n for (const [index, key] of paramPaths.entries()) {\n const value = params[index];\n path = path.replace(key, value);\n }\n } else {\n for (const [key, value] of Object.entries(params)) {\n path = path.replace(`:${key}`, String(value));\n }\n }\n }\n path = path.split(\"/\").map(encodeURIComponent).join(\"/\");\n if (path.startsWith(\"/\")) path = path.slice(1);\n let queryParamString = queryParams.toString();\n queryParamString = queryParamString.length > 0 ? `?${queryParamString}`.replace(/\\+/g, \"%20\") : \"\";\n if (!basePath.startsWith(\"http\")) {\n return `${basePath}${path}${queryParamString}`;\n }\n const _url = new URL(`${path}${queryParamString}`, basePath);\n return _url;\n}\n\n// src/fetch.ts\nvar betterFetch = async (url, options) => {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n const {\n hooks,\n url: __url,\n options: opts\n } = await initializePlugins(url, options);\n const fetch = getFetch(opts);\n const controller = new AbortController();\n const signal = (_a = opts.signal) != null ? _a : controller.signal;\n const _url = getURL2(__url, opts);\n const body = getBody(opts);\n const headers = await getHeaders(opts);\n const method = getMethod(__url, opts);\n let context = __spreadProps(__spreadValues({}, opts), {\n url: _url,\n headers,\n body,\n method,\n signal\n });\n for (const onRequest of hooks.onRequest) {\n if (onRequest) {\n const res = await onRequest(context);\n if (typeof res === \"object\" && res !== null) {\n context = res;\n }\n }\n }\n if (\"pipeTo\" in context && typeof context.pipeTo === \"function\" || typeof ((_b = options == null ? void 0 : options.body) == null ? void 0 : _b.pipe) === \"function\") {\n if (!(\"duplex\" in context)) {\n context.duplex = \"half\";\n }\n }\n const { clearTimeout: clearTimeout2 } = getTimeout(opts, controller);\n let response = await fetch(context.url, context);\n clearTimeout2();\n const responseContext = {\n response,\n request: context\n };\n for (const onResponse of hooks.onResponse) {\n if (onResponse) {\n const r = await onResponse(__spreadProps(__spreadValues({}, responseContext), {\n response: ((_c = options == null ? void 0 : options.hookOptions) == null ? void 0 : _c.cloneResponse) ? response.clone() : response\n }));\n if (r instanceof Response) {\n response = r;\n } else if (typeof r === \"object\" && r !== null) {\n response = r.response;\n }\n }\n }\n if (response.ok) {\n const hasBody = context.method !== \"HEAD\";\n if (!hasBody) {\n return {\n data: \"\",\n error: null\n };\n }\n const responseType = detectResponseType(response);\n const successContext = {\n data: null,\n response,\n request: context\n };\n if (responseType === \"json\" || responseType === \"text\") {\n const text = await response.text();\n const parser2 = (_d = context.jsonParser) != null ? _d : jsonParse;\n successContext.data = await parser2(text);\n } else {\n successContext.data = await response[responseType]();\n }\n if (context == null ? void 0 : context.output) {\n if (context.output && !context.disableValidation) {\n successContext.data = await parseStandardSchema(\n context.output,\n successContext.data\n );\n }\n }\n for (const onSuccess of hooks.onSuccess) {\n if (onSuccess) {\n await onSuccess(__spreadProps(__spreadValues({}, successContext), {\n response: ((_e = options == null ? void 0 : options.hookOptions) == null ? void 0 : _e.cloneResponse) ? response.clone() : response\n }));\n }\n }\n if (options == null ? void 0 : options.throw) {\n return successContext.data;\n }\n return {\n data: successContext.data,\n error: null\n };\n }\n const parser = (_f = options == null ? void 0 : options.jsonParser) != null ? _f : jsonParse;\n const responseText = await response.text();\n const isJSONResponse = isJSONParsable(responseText);\n const errorObject = isJSONResponse ? await parser(responseText) : null;\n const errorContext = {\n response,\n responseText,\n request: context,\n error: __spreadProps(__spreadValues({}, errorObject), {\n status: response.status,\n statusText: response.statusText\n })\n };\n for (const onError of hooks.onError) {\n if (onError) {\n await onError(__spreadProps(__spreadValues({}, errorContext), {\n response: ((_g = options == null ? void 0 : options.hookOptions) == null ? void 0 : _g.cloneResponse) ? response.clone() : response\n }));\n }\n }\n if (options == null ? void 0 : options.retry) {\n const retryStrategy = createRetryStrategy(options.retry);\n const _retryAttempt = (_h = options.retryAttempt) != null ? _h : 0;\n if (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) {\n for (const onRetry of hooks.onRetry) {\n if (onRetry) {\n await onRetry(responseContext);\n }\n }\n const delay = retryStrategy.getDelay(_retryAttempt);\n await new Promise((resolve) => setTimeout(resolve, delay));\n return await betterFetch(url, __spreadProps(__spreadValues({}, options), {\n retryAttempt: _retryAttempt + 1\n }));\n }\n }\n if (options == null ? void 0 : options.throw) {\n throw new BetterFetchError(\n response.status,\n response.statusText,\n isJSONResponse ? errorObject : responseText\n );\n }\n return {\n data: null,\n error: __spreadProps(__spreadValues({}, errorObject), {\n status: response.status,\n statusText: response.statusText\n })\n };\n};\nexport {\n BetterFetchError,\n ValidationError,\n applySchemaPlugin,\n betterFetch,\n bodyParser,\n createFetch,\n createRetryStrategy,\n createSchema,\n detectContentType,\n detectResponseType,\n getBody,\n getFetch,\n getHeaders,\n getMethod,\n getTimeout,\n getURL,\n initializePlugins,\n isFunction,\n isJSONParsable,\n isJSONSerializable,\n isPayloadMethod,\n isRouteMethod,\n jsonParse,\n methods,\n parseStandardSchema\n};\n//# sourceMappingURL=index.js.map","import { getBaseURL } from \"../utils/url.mjs\";\nimport { parseJSON } from \"./parser.mjs\";\nimport { redirectPlugin } from \"./fetch-plugins.mjs\";\nimport { getSessionAtom } from \"./session-atom.mjs\";\nimport { defu } from \"defu\";\nimport { createFetch } from \"@better-fetch/fetch\";\n//#region src/client/config.ts\nconst resolvePublicAuthUrl = (basePath) => {\n\tif (typeof process === \"undefined\") return void 0;\n\tconst path = basePath ?? \"/api/auth\";\n\tif (process.env.NEXT_PUBLIC_AUTH_URL) return process.env.NEXT_PUBLIC_AUTH_URL;\n\tif (typeof window === \"undefined\") {\n\t\tif (process.env.NEXTAUTH_URL) try {\n\t\t\treturn process.env.NEXTAUTH_URL;\n\t\t} catch {}\n\t\tif (process.env.VERCEL_URL) try {\n\t\t\tconst protocol = process.env.VERCEL_URL.startsWith(\"http\") ? \"\" : \"https://\";\n\t\t\treturn `${new URL(`${protocol}${process.env.VERCEL_URL}`).origin}${path}`;\n\t\t} catch {}\n\t}\n};\nconst getClientConfig = (options, loadEnv) => {\n\tconst isCredentialsSupported = \"credentials\" in Request.prototype;\n\tconst baseURL = getBaseURL(options?.baseURL, options?.basePath, void 0, loadEnv) ?? resolvePublicAuthUrl(options?.basePath) ?? \"/api/auth\";\n\tconst pluginsFetchPlugins = options?.plugins?.flatMap((plugin) => plugin.fetchPlugins).filter((pl) => pl !== void 0) || [];\n\tconst lifeCyclePlugin = {\n\t\tid: \"lifecycle-hooks\",\n\t\tname: \"lifecycle-hooks\",\n\t\thooks: {\n\t\t\tonSuccess: options?.fetchOptions?.onSuccess,\n\t\t\tonError: options?.fetchOptions?.onError,\n\t\t\tonRequest: options?.fetchOptions?.onRequest,\n\t\t\tonResponse: options?.fetchOptions?.onResponse\n\t\t}\n\t};\n\tconst { onSuccess: _onSuccess, onError: _onError, onRequest: _onRequest, onResponse: _onResponse, ...restOfFetchOptions } = options?.fetchOptions || {};\n\tconst $fetch = createFetch({\n\t\tbaseURL,\n\t\t...isCredentialsSupported ? { credentials: \"include\" } : {},\n\t\tmethod: \"GET\",\n\t\tjsonParser(text) {\n\t\t\tif (!text) return null;\n\t\t\treturn parseJSON(text, { strict: false });\n\t\t},\n\t\tcustomFetchImpl: fetch,\n\t\t...restOfFetchOptions,\n\t\tplugins: [\n\t\t\tlifeCyclePlugin,\n\t\t\t...restOfFetchOptions.plugins || [],\n\t\t\t...options?.disableDefaultFetchPlugins ? [] : [redirectPlugin],\n\t\t\t...pluginsFetchPlugins\n\t\t]\n\t});\n\tconst { $sessionSignal, session, broadcastSessionUpdate } = getSessionAtom($fetch, options);\n\tconst plugins = options?.plugins || [];\n\tlet pluginsActions = {};\n\tconst pluginsAtoms = {\n\t\t$sessionSignal,\n\t\tsession\n\t};\n\tconst pluginPathMethods = {\n\t\t\"/sign-out\": \"POST\",\n\t\t\"/revoke-sessions\": \"POST\",\n\t\t\"/revoke-other-sessions\": \"POST\",\n\t\t\"/delete-user\": \"POST\"\n\t};\n\tconst atomListeners = [{\n\t\tsignal: \"$sessionSignal\",\n\t\tmatcher(path) {\n\t\t\treturn path === \"/sign-out\" || path === \"/update-user\" || path === \"/update-session\" || path === \"/sign-up/email\" || path === \"/sign-in/email\" || path === \"/delete-user\" || path === \"/verify-email\" || path === \"/revoke-sessions\" || path === \"/revoke-session\" || path === \"/revoke-other-sessions\" || path === \"/change-email\" || path === \"/change-password\";\n\t\t},\n\t\tcallback(path) {\n\t\t\tif (path === \"/sign-out\") broadcastSessionUpdate(\"signout\");\n\t\t\telse if (path === \"/update-user\" || path === \"/update-session\") broadcastSessionUpdate(\"updateUser\");\n\t\t}\n\t}];\n\tfor (const plugin of plugins) {\n\t\tif (plugin.getAtoms) Object.assign(pluginsAtoms, plugin.getAtoms?.($fetch));\n\t\tif (plugin.pathMethods) Object.assign(pluginPathMethods, plugin.pathMethods);\n\t\tif (plugin.atomListeners) atomListeners.push(...plugin.atomListeners);\n\t}\n\tconst $store = {\n\t\tnotify: (signal) => {\n\t\t\tpluginsAtoms[signal].set(!pluginsAtoms[signal].get());\n\t\t},\n\t\tlisten: (signal, listener) => {\n\t\t\tpluginsAtoms[signal].subscribe(listener);\n\t\t},\n\t\tatoms: pluginsAtoms\n\t};\n\tfor (const plugin of plugins) if (plugin.getActions) pluginsActions = defu(plugin.getActions?.($fetch, $store, options) ?? {}, pluginsActions);\n\treturn {\n\t\tget baseURL() {\n\t\t\treturn baseURL;\n\t\t},\n\t\tpluginsActions,\n\t\tpluginsAtoms,\n\t\tpluginPathMethods,\n\t\tatomListeners,\n\t\t$fetch,\n\t\t$store\n\t};\n};\n//#endregion\nexport { getClientConfig };\n","//#region src/utils/is-atom.ts\nfunction isAtom(value) {\n\treturn typeof value === \"object\" && value !== null && \"get\" in value && typeof value.get === \"function\" && \"lc\" in value && typeof value.lc === \"number\";\n}\n//#endregion\nexport { isAtom };\n","import { isAtom } from \"../utils/is-atom.mjs\";\n//#region src/client/proxy.ts\nfunction getMethod(path, knownPathMethods, args) {\n\tconst method = knownPathMethods[path];\n\tconst { fetchOptions, query: _query, ...body } = args || {};\n\tif (method) return method;\n\tif (fetchOptions?.method) return fetchOptions.method;\n\tif (body && Object.keys(body).length > 0) return \"POST\";\n\treturn \"GET\";\n}\nfunction createDynamicPathProxy(routes, client, knownPathMethods, atoms, atomListeners) {\n\tfunction createProxy(path = []) {\n\t\treturn new Proxy(function() {}, {\n\t\t\tget(_, prop) {\n\t\t\t\tif (typeof prop !== \"string\") return;\n\t\t\t\tif (prop === \"then\" || prop === \"catch\" || prop === \"finally\") return;\n\t\t\t\tconst fullPath = [...path, prop];\n\t\t\t\tlet current = routes;\n\t\t\t\tfor (const segment of fullPath) if (current && typeof current === \"object\" && segment in current) current = current[segment];\n\t\t\t\telse {\n\t\t\t\t\tcurrent = void 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (typeof current === \"function\") return current;\n\t\t\t\tif (isAtom(current)) return current;\n\t\t\t\treturn createProxy(fullPath);\n\t\t\t},\n\t\t\tapply: async (_, __, args) => {\n\t\t\t\tconst routePath = \"/\" + path.map((segment) => segment.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)).join(\"/\");\n\t\t\t\tconst arg = args[0] || {};\n\t\t\t\tconst fetchOptions = args[1] || {};\n\t\t\t\tconst { query, fetchOptions: argFetchOptions, ...body } = arg;\n\t\t\t\tconst options = {\n\t\t\t\t\t...fetchOptions,\n\t\t\t\t\t...argFetchOptions\n\t\t\t\t};\n\t\t\t\tconst method = getMethod(routePath, knownPathMethods, arg);\n\t\t\t\treturn await client(routePath, {\n\t\t\t\t\t...options,\n\t\t\t\t\tbody: method === \"GET\" ? void 0 : {\n\t\t\t\t\t\t...body,\n\t\t\t\t\t\t...options?.body || {}\n\t\t\t\t\t},\n\t\t\t\t\tquery: query || options?.query,\n\t\t\t\t\tmethod,\n\t\t\t\t\tasync onSuccess(context) {\n\t\t\t\t\t\tawait options?.onSuccess?.(context);\n\t\t\t\t\t\tif (!atomListeners || options.disableSignal) return;\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t* We trigger listeners\n\t\t\t\t\t\t*/\n\t\t\t\t\t\tconst matches = atomListeners.filter((s) => s.matcher(routePath));\n\t\t\t\t\t\tif (!matches.length) return;\n\t\t\t\t\t\tconst visited = /* @__PURE__ */ new Set();\n\t\t\t\t\t\tfor (const match of matches) {\n\t\t\t\t\t\t\tconst signal = atoms[match.signal];\n\t\t\t\t\t\t\tif (!signal) return;\n\t\t\t\t\t\t\tif (visited.has(match.signal)) continue;\n\t\t\t\t\t\t\tvisited.add(match.signal);\n\t\t\t\t\t\t\t/**\n\t\t\t\t\t\t\t* To avoid race conditions we set the signal in a setTimeout\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tconst val = signal.get();\n\t\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\t\tsignal.set(!val);\n\t\t\t\t\t\t\t}, 10);\n\t\t\t\t\t\t\tmatch.callback?.(routePath);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\treturn createProxy();\n}\n//#endregion\nexport { createDynamicPathProxy };\n","//#region src/utils/string.ts\nfunction capitalizeFirstLetter(str) {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n//#endregion\nexport { capitalizeFirstLetter };\n","import { getClientConfig } from \"./config.mjs\";\nimport { createDynamicPathProxy } from \"./proxy.mjs\";\nimport { capitalizeFirstLetter } from \"@better-auth/core/utils/string\";\n//#region src/client/vanilla.ts\nfunction createAuthClient(options) {\n\tconst { pluginPathMethods, pluginsActions, pluginsAtoms, $fetch, atomListeners, $store } = getClientConfig(options);\n\tconst resolvedHooks = {};\n\tfor (const [key, value] of Object.entries(pluginsAtoms)) resolvedHooks[`use${capitalizeFirstLetter(key)}`] = value;\n\treturn createDynamicPathProxy({\n\t\t...pluginsActions,\n\t\t...resolvedHooks,\n\t\t$fetch,\n\t\t$store\n\t}, $fetch, pluginPathMethods, pluginsAtoms, atomListeners);\n}\n//#endregion\nexport { createAuthClient };\n","import { a as fetchJwtWithSession, c as CLI_CLIENT_ID } from \"./jwt-BVJ7dVm9.mjs\";\nimport { t as createJwtTokenCache } from \"./jwt-cache-4YqHn3jM.mjs\";\nimport { deviceAuthorizationClient } from \"better-auth/client/plugins\";\nimport { createAuthClient } from \"better-auth/client\";\n//#region src/cli.ts\nfunction createCliAuthClient(baseURL) {\n\treturn createAuthClient({\n\t\tbaseURL,\n\t\tplugins: [deviceAuthorizationClient()]\n\t});\n}\nfunction sleep(ms) {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\nfunction isDeviceTokenError(value) {\n\treturn typeof value === \"object\" && value !== null && \"error\" in value && typeof value.error === \"string\";\n}\nasync function runDeviceLogin(options) {\n\tconst client = createCliAuthClient(options.baseURL);\n\tconst codeResult = await client.device.code({ client_id: options.clientId });\n\tif (codeResult.error) {\n\t\tconst message = \"error_description\" in codeResult.error ? codeResult.error.error_description : \"Failed to request device code\";\n\t\tthrow new Error(message);\n\t}\n\tconst { device_code: deviceCode, user_code: userCode, verification_uri: verificationUri, verification_uri_complete: verificationUriComplete, expires_in: expiresIn, interval } = codeResult.data;\n\tif (options.onCodes) options.onCodes({\n\t\tuserCode,\n\t\tverificationUri,\n\t\tverificationUriComplete\n\t});\n\telse if (options.openUrl) {\n\t\tprocess.stderr.write(\"Opening browser to authorize…\\n\");\n\t\toptions.openUrl(verificationUriComplete);\n\t} else process.stderr.write(`Visit ${verificationUriComplete} to authorize.\\n`);\n\tconst deadline = Date.now() + expiresIn * 1e3;\n\tlet pollIntervalMs = interval * 1e3;\n\twhile (Date.now() < deadline) {\n\t\tconst tokenResult = await client.device.token({\n\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\tdevice_code: deviceCode,\n\t\t\tclient_id: options.clientId\n\t\t});\n\t\tif (!tokenResult.error) {\n\t\t\tconst token = tokenResult.data;\n\t\t\tconst organizationId = token.scope?.trim();\n\t\t\treturn {\n\t\t\t\taccessToken: token.access_token,\n\t\t\t\texpiresIn: token.expires_in,\n\t\t\t\torganizationId: organizationId || void 0\n\t\t\t};\n\t\t}\n\t\tconst errorPayload = tokenResult.error;\n\t\tconst oauthError = isDeviceTokenError(errorPayload.body) ? errorPayload.body : isDeviceTokenError(tokenResult.error) ? tokenResult.error : null;\n\t\tif (oauthError?.error === \"authorization_pending\") {\n\t\t\tawait sleep(pollIntervalMs);\n\t\t\tcontinue;\n\t\t}\n\t\tif (oauthError?.error === \"slow_down\") {\n\t\t\tpollIntervalMs += 5e3;\n\t\t\tawait sleep(pollIntervalMs);\n\t\t\tcontinue;\n\t\t}\n\t\tif (oauthError?.error === \"expired_token\") throw new Error(\"Device code expired. Run auth login again.\");\n\t\tif (oauthError?.error === \"access_denied\") throw new Error(\"Device authorization was denied.\");\n\t\tthrow new Error(oauthError?.error_description ?? errorPayload.message ?? \"Device login failed\");\n\t}\n\tthrow new Error(\"Device code expired. Run auth login again.\");\n}\nasync function getSessionWithBearer(baseURL, accessToken) {\n\tconst result = await createCliAuthClient(baseURL).getSession({ fetchOptions: { headers: { Authorization: `Bearer ${accessToken}` } } });\n\tconst user = result && \"user\" in result ? result.user : result && \"data\" in result && result.data && \"user\" in result.data ? result.data.user : void 0;\n\tif (typeof user !== \"object\" || user === null || !(\"id\" in user) || !(\"email\" in user) || !(\"name\" in user) || typeof user.id !== \"string\" || typeof user.email !== \"string\" || typeof user.name !== \"string\") return null;\n\treturn {\n\t\tid: user.id,\n\t\temail: user.email,\n\t\tname: user.name\n\t};\n}\nasync function getJwtWithBearer(baseURL, sessionToken) {\n\treturn fetchJwtWithSession(baseURL, { bearerToken: sessionToken });\n}\n//#endregion\nexport { CLI_CLIENT_ID, createCliAuthClient, createJwtTokenCache, getJwtWithBearer, getSessionWithBearer, runDeviceLogin };\n\n//# sourceMappingURL=cli.mjs.map","import { createJwtTokenCache, getJwtWithBearer, type JwtTokenCache } from \"@keystrokehq/auth/cli\";\n\nimport { getAccessToken } from \"./credentials\";\n\nconst caches = new Map<string, JwtTokenCache>();\n\nexport function clearCliJwtCache(): void {\n caches.clear();\n}\n\nexport async function getCliJwt(platformUrl: string, force = false): Promise<string | undefined> {\n if (!getAccessToken(platformUrl)) {\n caches.delete(platformUrl);\n return undefined;\n }\n\n let cache = caches.get(platformUrl);\n if (!cache) {\n cache = createJwtTokenCache(async () => {\n const sessionToken = getAccessToken(platformUrl);\n return sessionToken ? getJwtWithBearer(platformUrl, sessionToken) : null;\n });\n caches.set(platformUrl, cache);\n }\n\n return cache.get(force);\n}\n","import type { AuthStrategy } from \"@keystrokehq/sdk\";\nimport type Conf from \"conf\";\n\nimport { getAccessToken } from \"./credentials\";\nimport { getCliJwt } from \"./jwt-cache\";\nimport { getPlatformUrl, type CliConfig } from \"../config\";\n\n/** Returns JWT bearer auth when a session refresh token is stored; otherwise none. */\nexport function resolveCliAuth(config: Conf<CliConfig>): AuthStrategy {\n const platformUrl = getPlatformUrl(config);\n if (!getAccessToken(platformUrl)) {\n return { type: \"none\" };\n }\n\n return {\n type: \"bearer\",\n getToken: () => getCliJwt(platformUrl),\n };\n}\n","import { createKeystrokeClient, type KeystrokeClient } from \"@keystrokehq/sdk\";\nimport type Conf from \"conf\";\nimport { resolveCliAuth } from \"./auth/resolve-cli-auth\";\nimport type { CliConfig } from \"./config\";\n\nexport function createCliClient(\n config: Conf<CliConfig>,\n options: { baseUrl: string; platform?: boolean },\n): KeystrokeClient {\n return createKeystrokeClient({\n baseUrl: options.baseUrl,\n auth: resolveCliAuth(config),\n getActiveOrganizationId: options.platform\n ? () => config.get(\"activeOrganizationId\") ?? null\n : undefined,\n });\n}\n","import ky, { isHTTPError } from \"ky\";\nimport { ACTIVE_ORG_HEADER, AcceptOrganizationInvitationResponseSchema, ActiveOrganizationResponseSchema, AgentSummaryDetailResponseSchema, AgentSummaryListResponseSchema, CompleteProjectArtifactResponseSchema, CreateOrganizationRequestSchema, CreateOrganizationResponseSchema, CreateProjectArtifactResponseSchema, CreateProjectRequestSchema, CreateProjectResponseSchema, DEFAULT_ORGANIZATION_SIDEBAR_BRANDING, DEFAULT_USER_PREFERENCES, DeclineOrganizationInvitationResponseSchema, ErrorResponseSchema, GatewayAttachmentRecordSchema, HealthResponseSchema, HistoryRunCancelResponseSchema, HistoryRunDetailResponseSchema, HistoryRunListQuerySchema, HistoryRunListResponseSchema, InviteOrganizationMembersRequestSchema, InviteOrganizationMembersResponseSchema, ListOrganizationInvitationsResponseSchema, ListOrganizationMembersResponseSchema, ListOrganizationsResponseSchema, ListProjectDeploymentsResponseSchema, ListProjectFilesResponseSchema, ListProjectMetricsResponseSchema, ListProjectsResponseSchema, OrganizationSidebarBrandingPatchSchema, OrganizationSidebarBrandingSchema, PROJECT_REACHABILITY_REQUEST_TIMEOUT_MS, PresignOrgLogoRequestSchema, PresignOrgLogoResponseSchema, PresignProjectSourceRequestSchema, PresignProjectSourceResponseSchema, PresignUserAvatarRequestSchema, PresignUserAvatarResponseSchema, ProjectReachabilityResponseSchema, ProjectResponseSchema, ProjectSlugAvailabilityResponseSchema, RecentResourceListResponseSchema, SkillSummaryDetailResponseSchema, SkillSummaryListResponseSchema, SlugAvailabilityResponseSchema, UpdateOrganizationMemberRequestSchema, UpdateOrganizationMemberResponseSchema, UpdateOrganizationRequestSchema, UpdateProjectRequestSchema, UploadProjectSourceManifestRequestSchema, UploadProjectSourceResponseSchema, UpsertGatewayAttachmentBodySchema, UserAvatarPatchSchema, UserAvatarSchema, UserPreferencesPatchSchema, UserPreferencesSchema, WorkflowSummaryDetailResponseSchema, WorkflowSummaryListResponseSchema, mergeOrganizationSidebarBranding, mergeUserPreferences, normalizeOrganizationSidebarBranding, normalizeUserPreferences } from \"@keystrokehq/shared\";\n//#region src/platform/active-organization.ts\nconst STORAGE_KEY = \"keystroke-active-org-id\";\nfunction readActiveOrganizationId() {\n\tif (typeof localStorage === \"undefined\") return null;\n\treturn localStorage.getItem(STORAGE_KEY);\n}\nfunction writeActiveOrganizationId(organizationId) {\n\tif (typeof localStorage === \"undefined\") return;\n\tif (organizationId) {\n\t\tlocalStorage.setItem(STORAGE_KEY, organizationId);\n\t\treturn;\n\t}\n\tlocalStorage.removeItem(STORAGE_KEY);\n}\n//#endregion\n//#region src/platform/auth.ts\nfunction normalizeBaseUrl(baseUrl) {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\nfunction applyAuthHeaders(request, auth, getToken) {\n\tif (!auth || auth.type === \"none\") return;\n\tif (auth.type === \"bearer\") {\n\t\tconst tokenPromise = getToken?.() ?? auth.getToken();\n\t\treturn Promise.resolve(tokenPromise).then((token) => {\n\t\t\tif (token) request.headers.set(\"Authorization\", `Bearer ${token}`);\n\t\t});\n\t}\n}\nfunction applyActiveOrganizationHeader(request, organizationId) {\n\tif (organizationId) request.headers.set(ACTIVE_ORG_HEADER, organizationId);\n}\n/** Browser client — sends JWT bearer tokens minted from the Better Auth session cookie. */\nfunction browserAuthStrategy(getToken) {\n\treturn {\n\t\ttype: \"bearer\",\n\t\tgetToken\n\t};\n}\n//#endregion\n//#region src/platform/errors.ts\nvar PlatformError = class extends Error {\n\tstatus;\n\tbody;\n\tcode;\n\tconstructor(message, status, body, code) {\n\t\tsuper(message);\n\t\tthis.name = \"PlatformError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t\tthis.code = code;\n\t}\n};\nasync function toPlatformError(error) {\n\tif (!isHTTPError(error)) return new PlatformError(error instanceof Error ? error.message : \"Request failed\", 0, null);\n\tconst status = error.response.status;\n\tconst body = error.data ?? null;\n\tconst parsed = ErrorResponseSchema.safeParse(body);\n\treturn new PlatformError(parsed.success ? parsed.data.error : `Request failed with status ${status}`, status, body, parsed.success ? parsed.data.code : void 0);\n}\n//#endregion\n//#region src/platform/resources/artifacts.ts\nfunction createArtifactsResource(http) {\n\treturn {\n\t\tasync create(projectId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/projects/${encodeURIComponent(projectId)}/artifacts`).json();\n\t\t\t\treturn CreateProjectArtifactResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync complete(projectId, artifactId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/projects/${encodeURIComponent(projectId)}/artifacts/${encodeURIComponent(artifactId)}/complete`).json();\n\t\t\t\treturn CompleteProjectArtifactResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\t/** Ask which source blobs are missing and get presigned PUTs for them. */\n\t\tasync presignSource(projectId, artifactId, blobs) {\n\t\t\tconst body = PresignProjectSourceRequestSchema.parse({ blobs });\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/projects/${encodeURIComponent(projectId)}/artifacts/${encodeURIComponent(artifactId)}/source/presign`, { json: body }).json();\n\t\t\t\treturn PresignProjectSourceResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\t/** Finalize the deploy's source manifest (path -> hash tree + resource refs). */\n\t\tasync uploadManifest(projectId, artifactId, manifest) {\n\t\t\tconst body = UploadProjectSourceManifestRequestSchema.parse(manifest);\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/projects/${encodeURIComponent(projectId)}/artifacts/${encodeURIComponent(artifactId)}/source/manifest`, { json: body }).json();\n\t\t\t\treturn UploadProjectSourceResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/deployments.ts\nfunction createDeploymentsResource(http) {\n\treturn { async listForProject(projectId) {\n\t\ttry {\n\t\t\tconst data = await http.get(`/api/projects/${encodeURIComponent(projectId)}/deployments`).json();\n\t\t\treturn ListProjectDeploymentsResponseSchema.parse(data).deployments;\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/gateway-attachments.ts\nfunction createGatewayAttachmentsResource(http) {\n\tconst projectPrefix = (projectId) => `/api/projects/${encodeURIComponent(projectId)}/gateways/slack/attachments`;\n\treturn { async upsertSlackAttachment(projectId, channelId, body) {\n\t\tconst payload = UpsertGatewayAttachmentBodySchema.parse(body);\n\t\ttry {\n\t\t\tconst data = await http.put(`${projectPrefix(projectId)}/${encodeURIComponent(channelId)}`, { json: payload }).json();\n\t\t\treturn GatewayAttachmentRecordSchema.parse(data);\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/project-files.ts\nfunction createProjectFilesResource(http) {\n\treturn {\n\t\t/** File tree (no contents) for a project's active deploy; empty before first deploy. */\n\t\tasync listForProject(projectId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/projects/${encodeURIComponent(projectId)}/files`).json();\n\t\t\t\treturn ListProjectFilesResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\t/** Lazily fetch a single file's contents by path for a specific deploy. */\n\t\tasync getContent(projectId, artifactId, path) {\n\t\t\ttry {\n\t\t\t\treturn await http.get(`/api/projects/${encodeURIComponent(projectId)}/artifacts/${encodeURIComponent(artifactId)}/files/content`, { searchParams: { path } }).text();\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/health.ts\nfunction createHealthResource(http) {\n\treturn { async check() {\n\t\ttry {\n\t\t\tconst data = await http.get(\"/health\").json();\n\t\t\treturn HealthResponseSchema.parse(data);\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/organizations.ts\nfunction createOrganizationsResource(http, options = {}) {\n\tasync function get(organizationId) {\n\t\ttry {\n\t\t\tconst data = await http.get(`/api/organizations/${organizationId}`).json();\n\t\t\tconst organization = ActiveOrganizationResponseSchema.parse(data).organization;\n\t\t\tif (!organization) throw new Error(\"Organization was not returned\");\n\t\t\treturn organization;\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t}\n\tasync function update(input) {\n\t\tconst body = UpdateOrganizationRequestSchema.parse(input);\n\t\tconst organizationId = options.getActiveOrganizationId?.();\n\t\tif (!organizationId) throw new Error(\"No active organization\");\n\t\ttry {\n\t\t\tconst data = await http.patch(`/api/organizations/${organizationId}`, { json: body }).json();\n\t\t\tconst organization = ActiveOrganizationResponseSchema.parse(data).organization;\n\t\t\tif (!organization) throw new Error(\"Active organization was not returned\");\n\t\t\treturn organization;\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t}\n\treturn {\n\t\tasync list() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/organizations\").json();\n\t\t\t\treturn ListOrganizationsResponseSchema.parse(data).organizations;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tget,\n\t\tasync getActive() {\n\t\t\tconst organizationId = options.getActiveOrganizationId?.();\n\t\t\tif (!organizationId) return null;\n\t\t\ttry {\n\t\t\t\treturn await get(organizationId);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof PlatformError && (error.status === 401 || error.status === 403)) return null;\n\t\t\t\tif (isHTTPError(error) && (error.response.status === 401 || error.response.status === 403)) return null;\n\t\t\t\tthrow error instanceof PlatformError ? error : await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync setActive(input) {\n\t\t\tconst organizationId = input.organizationId.trim();\n\t\t\tif (!organizationId) throw new Error(\"Organization id is required\");\n\t\t\tconst membership = await get(organizationId);\n\t\t\toptions.onActiveOrganizationChange?.(organizationId);\n\t\t\treturn membership;\n\t\t},\n\t\tasync clearActive() {\n\t\t\toptions.onActiveOrganizationChange?.(null);\n\t\t},\n\t\tupdate,\n\t\tasync create(input) {\n\t\t\tconst body = CreateOrganizationRequestSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(\"/api/organizations\", { json: body }).json();\n\t\t\t\treturn CreateOrganizationResponseSchema.parse(data).organization;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync checkSlug(slug, slugOptions = {}) {\n\t\t\tconst searchParams = new URLSearchParams({ slug });\n\t\t\tif (slugOptions.excludeOrganizationId) searchParams.set(\"excludeOrganizationId\", slugOptions.excludeOrganizationId);\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/organizations/slug-available?${searchParams}`).json();\n\t\t\t\treturn SlugAvailabilityResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/projects.ts\nfunction createProjectsResource(http) {\n\treturn {\n\t\tasync list() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/projects\").json();\n\t\t\t\treturn ListProjectsResponseSchema.parse(data).projects;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync create(input) {\n\t\t\tconst body = CreateProjectRequestSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(\"/api/projects\", { json: body }).json();\n\t\t\t\treturn CreateProjectResponseSchema.parse(data).project;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(projectId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/projects/${encodeURIComponent(projectId)}`).json();\n\t\t\t\treturn ProjectResponseSchema.parse(data).project;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync update(projectId, patch) {\n\t\t\tconst body = UpdateProjectRequestSchema.parse(patch);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(`/api/projects/${encodeURIComponent(projectId)}`, { json: body }).json();\n\t\t\t\treturn ProjectResponseSchema.parse(data).project;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync delete(projectId) {\n\t\t\ttry {\n\t\t\t\tawait http.delete(`/api/projects/${encodeURIComponent(projectId)}`);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync checkReachability(projectId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/projects/${encodeURIComponent(projectId)}/reachability`, { timeout: PROJECT_REACHABILITY_REQUEST_TIMEOUT_MS }).json();\n\t\t\t\treturn ProjectReachabilityResponseSchema.parse(data).reachable;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync checkSlug(slug, options = {}) {\n\t\t\tconst searchParams = new URLSearchParams({ slug });\n\t\t\tif (options.excludeProjectId) searchParams.set(\"excludeProjectId\", options.excludeProjectId);\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/projects/slug-available?${searchParams}`).json();\n\t\t\t\treturn ProjectSlugAvailabilityResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\nfunction createProjectMetricsResource(http) {\n\treturn { async list() {\n\t\ttry {\n\t\t\tconst data = await http.get(\"/api/projects/metrics\").json();\n\t\t\treturn ListProjectMetricsResponseSchema.parse(data).metrics;\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/agents.ts\nfunction listSearchParams$2(options) {\n\tconst projectId = options?.projectId?.trim();\n\treturn projectId ? { projectId } : void 0;\n}\nfunction createAgentsResource(http) {\n\treturn {\n\t\tasync list(options) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/agents\", { searchParams: listSearchParams$2(options) }).json();\n\t\t\t\treturn AgentSummaryListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(agentId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/agents/${encodeURIComponent(agentId)}`).json();\n\t\t\t\treturn AgentSummaryDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/workflows.ts\nfunction listSearchParams$1(options) {\n\tconst projectId = options?.projectId?.trim();\n\treturn projectId ? { projectId } : void 0;\n}\nfunction createWorkflowsResource(http) {\n\treturn {\n\t\tasync list(options) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/workflows\", { searchParams: listSearchParams$1(options) }).json();\n\t\t\t\treturn WorkflowSummaryListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(workflowId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/workflows/${encodeURIComponent(workflowId)}`).json();\n\t\t\t\treturn WorkflowSummaryDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/skills.ts\nfunction listSearchParams(options) {\n\tconst projectId = options?.projectId?.trim();\n\treturn projectId ? { projectId } : void 0;\n}\nfunction createSkillsResource(http) {\n\treturn {\n\t\tasync list(options) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/skills\", { searchParams: listSearchParams(options) }).json();\n\t\t\t\treturn SkillSummaryListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(skillId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/skills/${encodeURIComponent(skillId)}`).json();\n\t\t\t\treturn SkillSummaryDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/recents.ts\nfunction createRecentsResource(http) {\n\treturn { async list() {\n\t\ttry {\n\t\t\tconst data = await http.get(\"/api/recents\").json();\n\t\t\treturn RecentResourceListResponseSchema.parse(data);\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/mock-registry.ts\nconst registry = /* @__PURE__ */ new Map();\n/**\n* Wraps a mock implementation, registering it in the manifest. The returned\n* function is the unchanged implementation — `mock()` only adds bookkeeping.\n*/\nfunction mock(entry, impl) {\n\tregistry.set(`${entry.domain}.${entry.method}`, entry);\n\treturn impl;\n}\n/** The current inventory of mocked methods. Populated once a client is created. */\nfunction mockManifest() {\n\treturn [...registry.values()];\n}\n//#endregion\n//#region src/platform/resources/mock-project-settings.ts\nconst DEFAULT_PROJECT_SETTINGS = {\n\tdescription: \"\",\n\tdefaultRole: \"editor\",\n\tinvitePermission: \"admin\"\n};\nconst MOCK_STORAGE_KEY$1 = \"keystroke:mock-project-settings:v1\";\nfunction getBrowserLocalStorage$1() {\n\tif (typeof globalThis !== \"object\") return null;\n\treturn globalThis.localStorage ?? null;\n}\nfunction normalizeDefaultRole(value) {\n\treturn value === \"admin\" ? \"admin\" : \"editor\";\n}\nfunction normalizeInvitePermission(value) {\n\treturn value === \"all\" ? \"all\" : \"admin\";\n}\nfunction normalizeProjectSettings(value) {\n\tif (!value || typeof value !== \"object\") return DEFAULT_PROJECT_SETTINGS;\n\tconst settings = value;\n\treturn {\n\t\tdescription: typeof settings.description === \"string\" ? settings.description : \"\",\n\t\tdefaultRole: normalizeDefaultRole(settings.defaultRole),\n\t\tinvitePermission: normalizeInvitePermission(settings.invitePermission)\n\t};\n}\nfunction mergeProjectSettings(current, patch) {\n\treturn normalizeProjectSettings({\n\t\t...current,\n\t\t...patch\n\t});\n}\nfunction readSettingsStore() {\n\tconst localStorage = getBrowserLocalStorage$1();\n\tif (!localStorage) return {};\n\ttry {\n\t\tconst raw = localStorage.getItem(MOCK_STORAGE_KEY$1);\n\t\tif (!raw) return {};\n\t\tconst parsed = JSON.parse(raw);\n\t\tif (!parsed || typeof parsed !== \"object\") return {};\n\t\treturn Object.fromEntries(Object.entries(parsed).map(([projectId, value]) => [projectId, normalizeProjectSettings(value)]));\n\t} catch {\n\t\treturn {};\n\t}\n}\nfunction writeSettingsStore(store) {\n\tconst localStorage = getBrowserLocalStorage$1();\n\tif (!localStorage) return;\n\ttry {\n\t\tlocalStorage.setItem(MOCK_STORAGE_KEY$1, JSON.stringify(store));\n\t} catch {}\n}\nfunction requireProjectId(projectId) {\n\tconst trimmed = projectId.trim();\n\tif (!trimmed) throw new Error(\"Project settings require a project id\");\n\treturn trimmed;\n}\nfunction createProjectSettingsResource() {\n\treturn {\n\t\tget: mock({\n\t\t\tdomain: \"projectSettings\",\n\t\t\tmethod: \"get\",\n\t\t\tplannedEndpoint: \"GET /api/projects/:id/settings\"\n\t\t}, async (projectId) => {\n\t\t\tconst id = requireProjectId(projectId);\n\t\t\treturn readSettingsStore()[id] ?? DEFAULT_PROJECT_SETTINGS;\n\t\t}),\n\t\tupdate: mock({\n\t\t\tdomain: \"projectSettings\",\n\t\t\tmethod: \"update\",\n\t\t\tplannedEndpoint: \"PATCH /api/projects/:id/settings\"\n\t\t}, async (projectId, patch) => {\n\t\t\tconst id = requireProjectId(projectId);\n\t\t\tconst store = readSettingsStore();\n\t\t\tconst next = mergeProjectSettings(store[id] ?? DEFAULT_PROJECT_SETTINGS, patch);\n\t\t\twriteSettingsStore({\n\t\t\t\t...store,\n\t\t\t\t[id]: next\n\t\t\t});\n\t\t\treturn next;\n\t\t})\n\t};\n}\n//#endregion\n//#region src/platform/resources/invitations.ts\nfunction createInvitationsResource(http) {\n\treturn {\n\t\tasync list() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/invitations\").json();\n\t\t\t\treturn ListOrganizationInvitationsResponseSchema.parse(data).invitations;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync accept(invitationId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/invitations/${encodeURIComponent(invitationId)}/accept`).json();\n\t\t\t\treturn AcceptOrganizationInvitationResponseSchema.parse(data).organization;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync decline(invitationId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/invitations/${encodeURIComponent(invitationId)}/decline`).json();\n\t\t\t\tDeclineOrganizationInvitationResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/members.ts\nfunction createMembersResource$1(http) {\n\treturn {\n\t\tasync listOrganizationMembers() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/members\").json();\n\t\t\t\treturn ListOrganizationMembersResponseSchema.parse(data).members;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync inviteOrganizationMembers(input) {\n\t\t\tconst body = InviteOrganizationMembersRequestSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(\"/api/members/invitations\", { json: body }).json();\n\t\t\t\treturn InviteOrganizationMembersResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync updateOrganizationMember(userId, input) {\n\t\t\tconst body = UpdateOrganizationMemberRequestSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(`/api/members/${encodeURIComponent(userId)}`, { json: body }).json();\n\t\t\t\treturn UpdateOrganizationMemberResponseSchema.parse(data).member;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync removeOrganizationMember(userId) {\n\t\t\ttry {\n\t\t\t\tawait http.delete(`/api/members/${encodeURIComponent(userId)}`);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/mock-seed.ts\nconst APP_CATALOG_BASE = [\n\t{\n\t\tid: \"app-gmail\",\n\t\tname: \"Gmail\",\n\t\tdescription: \"Email trigger and delivery integration.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-slack\",\n\t\tname: \"Slack\",\n\t\tdescription: \"Post messages and handle approvals via Slack channels.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-github\",\n\t\tname: \"GitHub\",\n\t\tdescription: \"React to repo events and manage pull requests.\",\n\t\tcategory: \"Development\"\n\t},\n\t{\n\t\tid: \"app-anthropic\",\n\t\tname: \"Anthropic\",\n\t\tdescription: \"Claude models for agent and workflow AI steps.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-attio\",\n\t\tname: \"Attio\",\n\t\tdescription: \"CRM operations for deals, contacts, and notes.\",\n\t\tcategory: \"CRM\"\n\t},\n\t{\n\t\tid: \"app-openai\",\n\t\tname: \"OpenAI\",\n\t\tdescription: \"GPT models and embeddings for AI-powered steps.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-airtable\",\n\t\tname: \"Airtable\",\n\t\tdescription: \"Read and write records in Airtable bases.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-google-sheets\",\n\t\tname: \"Google Sheets\",\n\t\tdescription: \"Read, update, and append rows in spreadsheets.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-google-drive\",\n\t\tname: \"Google Drive\",\n\t\tdescription: \"Find, read, and organize files across shared drives.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-google-calendar\",\n\t\tname: \"Google Calendar\",\n\t\tdescription: \"Create events, check availability, and coordinate meetings.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-notion\",\n\t\tname: \"Notion\",\n\t\tdescription: \"Query databases, create pages, and update workspace docs.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-linear\",\n\t\tname: \"Linear\",\n\t\tdescription: \"Create issues, update triage queues, and comment on work.\",\n\t\tcategory: \"Development\"\n\t},\n\t{\n\t\tid: \"app-jira\",\n\t\tname: \"Jira\",\n\t\tdescription: \"Sync issues, transitions, comments, and project fields.\",\n\t\tcategory: \"Development\"\n\t},\n\t{\n\t\tid: \"app-asana\",\n\t\tname: \"Asana\",\n\t\tdescription: \"Create tasks, update projects, and track team work.\",\n\t\tcategory: \"Project Management\"\n\t},\n\t{\n\t\tid: \"app-trello\",\n\t\tname: \"Trello\",\n\t\tdescription: \"Move cards, update boards, and automate checklist work.\",\n\t\tcategory: \"Project Management\"\n\t},\n\t{\n\t\tid: \"app-clickup\",\n\t\tname: \"ClickUp\",\n\t\tdescription: \"Manage tasks, docs, custom fields, and workspace automations.\",\n\t\tcategory: \"Project Management\"\n\t},\n\t{\n\t\tid: \"app-monday\",\n\t\tname: \"monday.com\",\n\t\tdescription: \"Automate boards, items, updates, and team workflows.\",\n\t\tcategory: \"Project Management\"\n\t},\n\t{\n\t\tid: \"app-discord\",\n\t\tname: \"Discord\",\n\t\tdescription: \"Post updates, listen for commands, and manage communities.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-microsoft-teams\",\n\t\tname: \"Microsoft Teams\",\n\t\tdescription: \"Send messages, route approvals, and coordinate team channels.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-google-chat\",\n\t\tname: \"Google Chat\",\n\t\tdescription: \"Send messages and surface agent responses in Google Chat.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-telegram\",\n\t\tname: \"Telegram\",\n\t\tdescription: \"Send bot messages and respond to chats and groups.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-whatsapp\",\n\t\tname: \"WhatsApp\",\n\t\tdescription: \"Send WhatsApp messages and respond to customer threads.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-hubspot\",\n\t\tname: \"HubSpot\",\n\t\tdescription: \"Manage contacts, companies, deals, tickets, and timelines.\",\n\t\tcategory: \"CRM\"\n\t},\n\t{\n\t\tid: \"app-salesforce\",\n\t\tname: \"Salesforce\",\n\t\tdescription: \"Read and update leads, accounts, opportunities, and cases.\",\n\t\tcategory: \"CRM\"\n\t},\n\t{\n\t\tid: \"app-pipedrive\",\n\t\tname: \"Pipedrive\",\n\t\tdescription: \"Move deals, update contacts, and automate sales pipelines.\",\n\t\tcategory: \"CRM\"\n\t},\n\t{\n\t\tid: \"app-intercom\",\n\t\tname: \"Intercom\",\n\t\tdescription: \"Route conversations, update users, and summarize support.\",\n\t\tcategory: \"Support\"\n\t},\n\t{\n\t\tid: \"app-zendesk\",\n\t\tname: \"Zendesk\",\n\t\tdescription: \"Create tickets, reply to customers, and sync support context.\",\n\t\tcategory: \"Support\"\n\t},\n\t{\n\t\tid: \"app-freshdesk\",\n\t\tname: \"Freshdesk\",\n\t\tdescription: \"Automate ticket routing, replies, and customer updates.\",\n\t\tcategory: \"Support\"\n\t},\n\t{\n\t\tid: \"app-front\",\n\t\tname: \"Front\",\n\t\tdescription: \"Manage shared inboxes, comments, tags, and customer replies.\",\n\t\tcategory: \"Support\"\n\t},\n\t{\n\t\tid: \"app-stripe\",\n\t\tname: \"Stripe\",\n\t\tdescription: \"React to payments, manage customers, and reconcile billing.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-quickbooks\",\n\t\tname: \"QuickBooks\",\n\t\tdescription: \"Create invoices, sync customers, and reconcile accounting data.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-xero\",\n\t\tname: \"Xero\",\n\t\tdescription: \"Automate invoices, contacts, bills, and accounting workflows.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-shopify\",\n\t\tname: \"Shopify\",\n\t\tdescription: \"Process orders, update products, and coordinate fulfillment.\",\n\t\tcategory: \"Commerce\"\n\t},\n\t{\n\t\tid: \"app-woocommerce\",\n\t\tname: \"WooCommerce\",\n\t\tdescription: \"Sync orders, customers, products, and storefront events.\",\n\t\tcategory: \"Commerce\"\n\t},\n\t{\n\t\tid: \"app-webflow\",\n\t\tname: \"Webflow\",\n\t\tdescription: \"Publish CMS items, update site content, and trigger workflows.\",\n\t\tcategory: \"Marketing\"\n\t},\n\t{\n\t\tid: \"app-mailchimp\",\n\t\tname: \"Mailchimp\",\n\t\tdescription: \"Manage audiences, campaigns, tags, and email automations.\",\n\t\tcategory: \"Marketing\"\n\t},\n\t{\n\t\tid: \"app-sendgrid\",\n\t\tname: \"SendGrid\",\n\t\tdescription: \"Send transactional email and react to delivery events.\",\n\t\tcategory: \"Marketing\"\n\t},\n\t{\n\t\tid: \"app-typeform\",\n\t\tname: \"Typeform\",\n\t\tdescription: \"Capture form responses and enrich follow-up workflows.\",\n\t\tcategory: \"Forms\"\n\t},\n\t{\n\t\tid: \"app-surveymonkey\",\n\t\tname: \"SurveyMonkey\",\n\t\tdescription: \"Collect survey responses and sync insights into workflows.\",\n\t\tcategory: \"Forms\"\n\t},\n\t{\n\t\tid: \"app-calendly\",\n\t\tname: \"Calendly\",\n\t\tdescription: \"React to bookings, cancellations, and scheduling updates.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-docusign\",\n\t\tname: \"DocuSign\",\n\t\tdescription: \"Send envelopes, track signatures, and file completed agreements.\",\n\t\tcategory: \"Documents\"\n\t},\n\t{\n\t\tid: \"app-dropbox\",\n\t\tname: \"Dropbox\",\n\t\tdescription: \"Read files, upload assets, and organize shared folders.\",\n\t\tcategory: \"Files\"\n\t},\n\t{\n\t\tid: \"app-box\",\n\t\tname: \"Box\",\n\t\tdescription: \"Search enterprise files, update folders, and manage documents.\",\n\t\tcategory: \"Files\"\n\t},\n\t{\n\t\tid: \"app-figma\",\n\t\tname: \"Figma\",\n\t\tdescription: \"Inspect designs, sync comments, and coordinate design handoffs.\",\n\t\tcategory: \"Design\"\n\t},\n\t{\n\t\tid: \"app-canva\",\n\t\tname: \"Canva\",\n\t\tdescription: \"Create design assets and automate content production.\",\n\t\tcategory: \"Design\"\n\t},\n\t{\n\t\tid: \"app-sentry\",\n\t\tname: \"Sentry\",\n\t\tdescription: \"Triage errors, summarize issues, and route incidents.\",\n\t\tcategory: \"Observability\"\n\t},\n\t{\n\t\tid: \"app-datadog\",\n\t\tname: \"Datadog\",\n\t\tdescription: \"Query metrics, inspect monitors, and coordinate incidents.\",\n\t\tcategory: \"Observability\"\n\t},\n\t{\n\t\tid: \"app-pagerduty\",\n\t\tname: \"PagerDuty\",\n\t\tdescription: \"Create incidents, page responders, and automate escalations.\",\n\t\tcategory: \"Observability\"\n\t},\n\t{\n\t\tid: \"app-gitlab\",\n\t\tname: \"GitLab\",\n\t\tdescription: \"Manage merge requests, issues, pipelines, and repositories.\",\n\t\tcategory: \"Development\"\n\t},\n\t{\n\t\tid: \"app-bitbucket\",\n\t\tname: \"Bitbucket\",\n\t\tdescription: \"Automate pull requests, branches, and repository workflows.\",\n\t\tcategory: \"Development\"\n\t},\n\t{\n\t\tid: \"app-vercel\",\n\t\tname: \"Vercel\",\n\t\tdescription: \"Track deployments, manage projects, and react to build events.\",\n\t\tcategory: \"Development\"\n\t},\n\t{\n\t\tid: \"app-netlify\",\n\t\tname: \"Netlify\",\n\t\tdescription: \"Automate deploys, forms, sites, and build notifications.\",\n\t\tcategory: \"Development\"\n\t},\n\t{\n\t\tid: \"app-supabase\",\n\t\tname: \"Supabase\",\n\t\tdescription: \"Query databases, manage auth, and automate backend workflows.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-postgres\",\n\t\tname: \"Postgres\",\n\t\tdescription: \"Run SQL queries and sync structured data from Postgres.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-snowflake\",\n\t\tname: \"Snowflake\",\n\t\tdescription: \"Query warehouse data and automate analytics workflows.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-databricks\",\n\t\tname: \"Databricks\",\n\t\tdescription: \"Run jobs, query lakehouse data, and coordinate pipelines.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-segment\",\n\t\tname: \"Segment\",\n\t\tdescription: \"Route customer events and enrich downstream automations.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-twilio\",\n\t\tname: \"Twilio\",\n\t\tdescription: \"Send SMS, manage calls, and coordinate customer notifications.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-zoom\",\n\t\tname: \"Zoom\",\n\t\tdescription: \"Schedule meetings, manage recordings, and notify attendees.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-loom\",\n\t\tname: \"Loom\",\n\t\tdescription: \"Create video handoffs, summarize recordings, and share updates.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-miro\",\n\t\tname: \"Miro\",\n\t\tdescription: \"Create boards, sync cards, and coordinate visual planning.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-coda\",\n\t\tname: \"Coda\",\n\t\tdescription: \"Update docs, tables, packs, and team operating workflows.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-confluence\",\n\t\tname: \"Confluence\",\n\t\tdescription: \"Search knowledge bases and create or update documentation.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-aws\",\n\t\tname: \"AWS\",\n\t\tdescription: \"Coordinate cloud resources, events, queues, and infrastructure.\",\n\t\tcategory: \"Infrastructure\"\n\t},\n\t{\n\t\tid: \"app-google-cloud\",\n\t\tname: \"Google Cloud\",\n\t\tdescription: \"Manage cloud jobs, storage, Pub/Sub, and deployment workflows.\",\n\t\tcategory: \"Infrastructure\"\n\t},\n\t{\n\t\tid: \"app-azure\",\n\t\tname: \"Azure\",\n\t\tdescription: \"Automate Azure resources, queues, deployments, and identities.\",\n\t\tcategory: \"Infrastructure\"\n\t},\n\t{\n\t\tid: \"app-cloudflare\",\n\t\tname: \"Cloudflare\",\n\t\tdescription: \"Manage DNS, Workers, Pages, queues, and edge automations.\",\n\t\tcategory: \"Infrastructure\"\n\t},\n\t{\n\t\tid: \"app-docker\",\n\t\tname: \"Docker\",\n\t\tdescription: \"Coordinate images, registries, builds, and deployment events.\",\n\t\tcategory: \"Infrastructure\"\n\t},\n\t{\n\t\tid: \"app-kubernetes\",\n\t\tname: \"Kubernetes\",\n\t\tdescription: \"Inspect clusters, trigger jobs, and automate operations.\",\n\t\tcategory: \"Infrastructure\"\n\t},\n\t{\n\t\tid: \"app-algolia\",\n\t\tname: \"Algolia\",\n\t\tdescription: \"Sync search indexes and automate content discovery workflows.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-elasticsearch\",\n\t\tname: \"Elasticsearch\",\n\t\tdescription: \"Query search clusters and automate log or document workflows.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-redis\",\n\t\tname: \"Redis\",\n\t\tdescription: \"Read cache data, coordinate queues, and manage realtime state.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-pinecone\",\n\t\tname: \"Pinecone\",\n\t\tdescription: \"Manage vector indexes and power retrieval workflows.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-plaid\",\n\t\tname: \"Plaid\",\n\t\tdescription: \"Connect financial accounts and automate banking data flows.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-brex\",\n\t\tname: \"Brex\",\n\t\tdescription: \"Sync expenses, cards, reimbursements, and finance approvals.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-mercury\",\n\t\tname: \"Mercury\",\n\t\tdescription: \"Automate banking workflows, transactions, and treasury tasks.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-elevenlabs\",\n\t\tname: \"ElevenLabs\",\n\t\tdescription: \"Generate speech, transcribe audio, and automate voice agents.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-perplexity\",\n\t\tname: \"Perplexity\",\n\t\tdescription: \"Search the web with citations and grounded AI answers.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-gemini\",\n\t\tname: \"Gemini\",\n\t\tdescription: \"Use Google AI models for generation, analysis, and reasoning.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-polymarket\",\n\t\tname: \"Polymarket\",\n\t\tdescription: \"Read market data and automate prediction-market workflows.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-blacksmith\",\n\t\tname: \"Blacksmith\",\n\t\tdescription: \"Automate CI builds, runners, and developer infrastructure.\",\n\t\tcategory: \"Development\"\n\t},\n\t{\n\t\tid: \"app-deel\",\n\t\tname: \"Deel\",\n\t\tdescription: \"Sync employee, contractor, payroll, and HR workflows.\",\n\t\tcategory: \"HR\"\n\t},\n\t{\n\t\tid: \"app-doordash\",\n\t\tname: \"DoorDash\",\n\t\tdescription: \"Coordinate delivery, merchant, and logistics workflows.\",\n\t\tcategory: \"Commerce\"\n\t},\n\t{\n\t\tid: \"app-dub\",\n\t\tname: \"Dub\",\n\t\tdescription: \"Manage short links, attribution, and campaign routing.\",\n\t\tcategory: \"Marketing\"\n\t},\n\t{\n\t\tid: \"app-exa\",\n\t\tname: \"Exa\",\n\t\tdescription: \"Search the web and retrieve AI-ready research results.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-firecrawl\",\n\t\tname: \"Firecrawl\",\n\t\tdescription: \"Crawl sites, extract structured data, and power research agents.\",\n\t\tcategory: \"Search\"\n\t},\n\t{\n\t\tid: \"app-granola\",\n\t\tname: \"Granola\",\n\t\tdescription: \"Sync meeting notes, summaries, and follow-up workflows.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-gusto\",\n\t\tname: \"Gusto\",\n\t\tdescription: \"Automate payroll, benefits, and HR operations.\",\n\t\tcategory: \"HR\"\n\t},\n\t{\n\t\tid: \"app-hex\",\n\t\tname: \"Hex\",\n\t\tdescription: \"Run analytics workflows, notebooks, and data apps.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-instacart\",\n\t\tname: \"Instacart\",\n\t\tdescription: \"Coordinate grocery commerce, orders, and fulfillment workflows.\",\n\t\tcategory: \"Commerce\"\n\t},\n\t{\n\t\tid: \"app-kalshi\",\n\t\tname: \"Kalshi\",\n\t\tdescription: \"Read event markets and automate prediction-market workflows.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-omni\",\n\t\tname: \"Omni\",\n\t\tdescription: \"Query business intelligence models and automate analytics workflows.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-parallel\",\n\t\tname: \"Parallel\",\n\t\tdescription: \"Run AI research, enrichment, and web task workflows.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-planetscale\",\n\t\tname: \"PlanetScale\",\n\t\tdescription: \"Manage MySQL databases, branches, and deploy requests.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-porter\",\n\t\tname: \"Porter\",\n\t\tdescription: \"Coordinate cloud deployments and application infrastructure.\",\n\t\tcategory: \"Development\"\n\t},\n\t{\n\t\tid: \"app-puzzle\",\n\t\tname: \"Puzzle\",\n\t\tdescription: \"Automate accounting workflows, books, and finance operations.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-pylon\",\n\t\tname: \"Pylon\",\n\t\tdescription: \"Manage B2B support conversations and customer workflows.\",\n\t\tcategory: \"Support\"\n\t},\n\t{\n\t\tid: \"app-ramp\",\n\t\tname: \"Ramp\",\n\t\tdescription: \"Sync spend, expenses, approvals, and finance workflows.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-reducto\",\n\t\tname: \"Reducto\",\n\t\tdescription: \"Extract structured data from complex documents.\",\n\t\tcategory: \"Documents\"\n\t},\n\t{\n\t\tid: \"app-resend\",\n\t\tname: \"Resend\",\n\t\tdescription: \"Send product email and react to delivery events.\",\n\t\tcategory: \"Marketing\"\n\t},\n\t{\n\t\tid: \"app-rippling\",\n\t\tname: \"Rippling\",\n\t\tdescription: \"Automate employee, device, payroll, and HR workflows.\",\n\t\tcategory: \"HR\"\n\t},\n\t{\n\t\tid: \"app-streak\",\n\t\tname: \"Streak\",\n\t\tdescription: \"Manage Gmail-native CRM pipelines and contact workflows.\",\n\t\tcategory: \"CRM\"\n\t},\n\t{\n\t\tid: \"app-warp\",\n\t\tname: \"Warp\",\n\t\tdescription: \"Coordinate terminal, developer environment, and AI coding workflows.\",\n\t\tcategory: \"Development\"\n\t},\n\t{\n\t\tid: \"app-apollo\",\n\t\tname: \"Apollo\",\n\t\tdescription: \"Sync sales intelligence, prospecting, and enrichment workflows.\",\n\t\tcategory: \"CRM\"\n\t},\n\t{\n\t\tid: \"app-cal-com\",\n\t\tname: \"Cal.com\",\n\t\tdescription: \"Automate scheduling, bookings, availability, and routing workflows.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-cerebras\",\n\t\tname: \"Cerebras\",\n\t\tdescription: \"Use fast AI inference for model-powered workflow steps.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-chargebee\",\n\t\tname: \"Chargebee\",\n\t\tdescription: \"Automate subscription billing, customers, invoices, and revenue workflows.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-deepseek\",\n\t\tname: \"DeepSeek\",\n\t\tdescription: \"Use DeepSeek models for generation, reasoning, and analysis.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-gong\",\n\t\tname: \"Gong\",\n\t\tdescription: \"Sync revenue conversations, account insights, and sales follow-up workflows.\",\n\t\tcategory: \"CRM\"\n\t},\n\t{\n\t\tid: \"app-google-contacts\",\n\t\tname: \"Google Contacts\",\n\t\tdescription: \"Read and update contact records across Google Workspace.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-google-docs\",\n\t\tname: \"Google Docs\",\n\t\tdescription: \"Create, read, and update collaborative documents.\",\n\t\tcategory: \"Documents\"\n\t},\n\t{\n\t\tid: \"app-google-forms\",\n\t\tname: \"Google Forms\",\n\t\tdescription: \"Capture form responses and turn submissions into automated work.\",\n\t\tcategory: \"Forms\"\n\t},\n\t{\n\t\tid: \"app-google-meet\",\n\t\tname: \"Google Meet\",\n\t\tdescription: \"Coordinate meetings, recordings, and video collaboration workflows.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-google-slides\",\n\t\tname: \"Google Slides\",\n\t\tdescription: \"Create and update presentations from workflow outputs.\",\n\t\tcategory: \"Documents\"\n\t},\n\t{\n\t\tid: \"app-google-tasks\",\n\t\tname: \"Google Tasks\",\n\t\tdescription: \"Create tasks, update lists, and coordinate personal work queues.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-greenhouse\",\n\t\tname: \"Greenhouse\",\n\t\tdescription: \"Automate candidate, job, and interview coordination workflows.\",\n\t\tcategory: \"HR\"\n\t},\n\t{\n\t\tid: \"app-groq\",\n\t\tname: \"Groq\",\n\t\tdescription: \"Use low-latency AI inference in agents and workflows.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-help-scout\",\n\t\tname: \"Help Scout\",\n\t\tdescription: \"Manage customer conversations, mailboxes, and support workflows.\",\n\t\tcategory: \"Support\"\n\t},\n\t{\n\t\tid: \"app-linkedin\",\n\t\tname: \"LinkedIn\",\n\t\tdescription: \"Coordinate professional network, recruiting, and social workflows.\",\n\t\tcategory: \"CRM\"\n\t},\n\t{\n\t\tid: \"app-microsoft-excel\",\n\t\tname: \"Microsoft Excel\",\n\t\tdescription: \"Read, update, and append rows in Excel workbooks.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-microsoft-onedrive\",\n\t\tname: \"Microsoft OneDrive\",\n\t\tdescription: \"Find, read, upload, and organize files in OneDrive.\",\n\t\tcategory: \"Files\"\n\t},\n\t{\n\t\tid: \"app-microsoft-outlook\",\n\t\tname: \"Microsoft Outlook\",\n\t\tdescription: \"Send email, read messages, and coordinate calendar workflows.\",\n\t\tcategory: \"Communication\"\n\t},\n\t{\n\t\tid: \"app-microsoft-planner\",\n\t\tname: \"Microsoft Planner\",\n\t\tdescription: \"Create tasks, update plans, and coordinate project work.\",\n\t\tcategory: \"Project Management\"\n\t},\n\t{\n\t\tid: \"app-microsoft-sharepoint\",\n\t\tname: \"Microsoft SharePoint\",\n\t\tdescription: \"Search sites, update lists, and manage shared documents.\",\n\t\tcategory: \"Documents\"\n\t},\n\t{\n\t\tid: \"app-mistral\",\n\t\tname: \"Mistral\",\n\t\tdescription: \"Use Mistral models for generation, analysis, and AI workflow steps.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-posthog\",\n\t\tname: \"PostHog\",\n\t\tdescription: \"Query product analytics, feature flags, and user behavior signals.\",\n\t\tcategory: \"Data\"\n\t},\n\t{\n\t\tid: \"app-reddit\",\n\t\tname: \"Reddit\",\n\t\tdescription: \"Monitor communities, posts, and discussion-driven workflows.\",\n\t\tcategory: \"Marketing\"\n\t},\n\t{\n\t\tid: \"app-square\",\n\t\tname: \"Square\",\n\t\tdescription: \"Automate payments, customers, catalog, and point-of-sale workflows.\",\n\t\tcategory: \"Finance\"\n\t},\n\t{\n\t\tid: \"app-todoist\",\n\t\tname: \"Todoist\",\n\t\tdescription: \"Create tasks, update projects, and automate personal work queues.\",\n\t\tcategory: \"Productivity\"\n\t},\n\t{\n\t\tid: \"app-wordpress\",\n\t\tname: \"WordPress\",\n\t\tdescription: \"Publish posts, update pages, and automate site content workflows.\",\n\t\tcategory: \"Marketing\"\n\t},\n\t{\n\t\tid: \"app-x-twitter\",\n\t\tname: \"X / Twitter\",\n\t\tdescription: \"Monitor posts, publish updates, and coordinate social workflows.\",\n\t\tcategory: \"Marketing\"\n\t},\n\t{\n\t\tid: \"app-xai\",\n\t\tname: \"xAI\",\n\t\tdescription: \"Use xAI models for generation, analysis, and reasoning steps.\",\n\t\tcategory: \"AI\"\n\t},\n\t{\n\t\tid: \"app-youtube\",\n\t\tname: \"YouTube\",\n\t\tdescription: \"Manage videos, channels, comments, and creator workflows.\",\n\t\tcategory: \"Marketing\"\n\t}\n];\nconst APP_INTEGRATION_DESCRIPTIONS = {\n\t\"app-gmail\": \"Connect Gmail so agents can read, draft, send, and organize email as part of a workflow. Use it for customer follow-ups, approval threads, inbound request triage, or any automation where the next step happens in an inbox.\",\n\t\"app-slack\": \"Connect Slack so agents can post updates, request approvals, and keep work moving from channel conversations. Use it for deployment approvals, triage alerts, support handoffs, or workflows that need a human decision in chat.\",\n\t\"app-github\": \"Connect GitHub so agents can react to issues, pull requests, commits, and repository events. Use it to automate review follow-ups, update project state, open PRs, or summarize engineering activity without leaving Keystroke.\",\n\t\"app-anthropic\": \"Connect Anthropic to give workflows and agents access to Claude for reasoning, writing, analysis, and structured generation. Use it when an automation needs judgment, summarization, code understanding, or a safer model step.\",\n\t\"app-attio\": \"Connect Attio so agents can look up customer context, update CRM records, and keep deal activity current. Use it to enrich leads, prepare account briefs, or write notes back to the relationship record after work happens elsewhere.\",\n\t\"app-openai\": \"Connect OpenAI to use GPT models, embeddings, and multimodal generation inside agents and workflows. Use it for classification, drafting, extraction, retrieval, and AI steps that need fast general-purpose model coverage.\",\n\t\"app-airtable\": \"Connect Airtable so workflows can read, create, and update records in the bases your team already uses. Use it for lightweight operations dashboards, intake queues, content calendars, or any structured data that lives outside the product database.\",\n\t\"app-google-sheets\": \"Connect Google Sheets so agents can inspect spreadsheets, append rows, and keep tabular data up to date. Use it for operational reports, lead lists, reconciliation sheets, or simple automations that still run through a spreadsheet.\",\n\t\"app-google-drive\": \"Connect Google Drive so agents can find, read, create, and organize files across shared folders. Use it when workflows need source documents, generated exports, meeting artifacts, or project files stored in Drive.\",\n\t\"app-google-calendar\": \"Connect Google Calendar so agents can check availability, create events, and coordinate schedule changes. Use it for booking follow-ups, launch calendars, interview loops, or workflows that need to reserve time with the right people.\",\n\t\"app-notion\": \"Connect Notion so agents can search workspace knowledge, update databases, and create pages from completed work. Use it to turn conversations into docs, keep project trackers current, or pull context from team operating notes.\",\n\t\"app-linear\": \"Connect Linear so agents can create issues, update triage queues, and comment on engineering work. Use it to turn chat decisions into tickets, keep statuses current, or route follow-up tasks to the right project.\",\n\t\"app-jira\": \"Connect Jira so agents can sync issues, transitions, comments, and project fields with the rest of your automation. Use it for sprint hygiene, release coordination, support escalations, or workflows that need to move work through Jira states.\",\n\t\"app-asana\": \"Connect Asana so workflows can create tasks, update projects, and keep team work visible. Use it for campaign checklists, launch plans, cross-functional handoffs, or automations that turn decisions into assigned tasks.\",\n\t\"app-trello\": \"Connect Trello so agents can move cards, update boards, and manage checklist work. Use it for lightweight pipelines, editorial boards, personal task flows, or team processes that are organized around cards.\",\n\t\"app-clickup\": \"Connect ClickUp so agents can manage tasks, docs, custom fields, and workspace automations. Use it to update complex workspaces, coordinate owners, or keep custom project metadata in sync with the rest of your tools.\",\n\t\"app-monday\": \"Connect monday.com so agents can update boards, create items, and automate team workflow changes. Use it for operations trackers, handoff boards, campaign production, or any process your team runs through monday.com.\",\n\t\"app-discord\": \"Connect Discord so agents can post updates, listen for commands, and respond inside communities or private servers. Use it for developer communities, customer groups, incident rooms, or lightweight command-driven workflows.\",\n\t\"app-microsoft-teams\": \"Connect Microsoft Teams so agents can send messages, coordinate approvals, and keep work moving in team channels. Use it for enterprise handoffs, meeting follow-ups, internal notifications, or workflows that need to meet users where they collaborate.\",\n\t\"app-google-chat\": \"Connect Google Chat so agents can send updates and surface workflow responses in spaces or direct messages. Use it for Workspace-native notifications, team approvals, status pings, or lightweight chat commands.\",\n\t\"app-telegram\": \"Connect Telegram so agents can send bot messages and respond to chats or groups. Use it for community operations, alerts, personal workflows, or automations that need fast mobile-friendly messaging.\",\n\t\"app-whatsapp\": \"Connect WhatsApp so agents can send customer messages and respond to conversation threads. Use it for support follow-ups, appointment reminders, sales handoffs, or any workflow where customers already expect WhatsApp updates.\",\n\t\"app-hubspot\": \"Connect HubSpot so agents can manage contacts, companies, deals, tickets, and timelines. Use it to enrich CRM records, log customer activity, trigger sales follow-ups, or keep marketing and success workflows aligned.\",\n\t\"app-salesforce\": \"Connect Salesforce so workflows can read and update leads, accounts, opportunities, and cases. Use it for account research, sales operations, support escalation, or automations that need Salesforce to remain the source of truth.\",\n\t\"app-pipedrive\": \"Connect Pipedrive so agents can move deals, update contacts, and automate sales pipeline work. Use it for lead routing, next-step reminders, pipeline cleanup, or follow-ups triggered by activity in other systems.\",\n\t\"app-intercom\": \"Connect Intercom so agents can route conversations, update users, and summarize support context. Use it to triage inbound messages, draft replies, escalate issues, or connect customer conversations to product and engineering workflows.\",\n\t\"app-zendesk\": \"Connect Zendesk so agents can create tickets, reply to customers, and keep support context in sync. Use it for ticket triage, SLA follow-ups, escalation summaries, or workflows that turn support signals into action.\",\n\t\"app-freshdesk\": \"Connect Freshdesk so workflows can route tickets, draft replies, and update customer records. Use it to automate support queues, enrich tickets with external context, or make sure resolution steps are captured consistently.\",\n\t\"app-front\": \"Connect Front so agents can work with shared inboxes, internal comments, tags, and customer replies. Use it for support or success teams that coordinate from email but need automation to keep the thread moving.\",\n\t\"app-stripe\": \"Connect Stripe so agents can react to payments, manage customers, and reconcile billing events. Use it for revenue alerts, failed payment follow-ups, invoice workflows, or customer lifecycle automation tied to billing state.\",\n\t\"app-quickbooks\": \"Connect QuickBooks so workflows can create invoices, sync customers, and reconcile accounting data. Use it for finance handoffs, bookkeeping follow-ups, payment checks, or automations that keep operational data aligned with accounting.\",\n\t\"app-xero\": \"Connect Xero so agents can automate invoices, contacts, bills, and accounting workflows. Use it for finance reviews, customer billing updates, payable tracking, or recurring accounting tasks that should not require manual entry.\",\n\t\"app-shopify\": \"Connect Shopify so agents can process orders, update products, and coordinate fulfillment work. Use it for ecommerce support, inventory checks, fulfillment exceptions, or automations triggered by store events.\",\n\t\"app-woocommerce\": \"Connect WooCommerce so workflows can sync orders, customers, products, and storefront events. Use it for store operations, fulfillment coordination, customer follow-ups, or reporting across commerce and support tools.\",\n\t\"app-webflow\": \"Connect Webflow so agents can publish CMS items, update site content, and react to site events. Use it for marketing pages, content operations, launch checklists, or workflows that turn approved content into live updates.\",\n\t\"app-mailchimp\": \"Connect Mailchimp so agents can manage audiences, campaigns, tags, and email automations. Use it for lifecycle marketing, list hygiene, campaign follow-ups, or workflows that connect product events to audience segments.\",\n\t\"app-sendgrid\": \"Connect SendGrid so workflows can send transactional email and react to delivery events. Use it for notifications, receipts, onboarding messages, or automations that need reliable email delivery and bounce handling.\",\n\t\"app-typeform\": \"Connect Typeform so agents can capture submissions and turn responses into follow-up work. Use it for intake forms, lead qualification, research surveys, or workflows that start when someone submits structured answers.\",\n\t\"app-surveymonkey\": \"Connect SurveyMonkey so agents can collect responses and move survey insights into the right workflow. Use it for customer research, feedback analysis, NPS follow-up, or reporting loops that begin with survey data.\",\n\t\"app-calendly\": \"Connect Calendly so agents can react to bookings, cancellations, and scheduling updates. Use it for sales handoffs, interview coordination, onboarding calls, or workflows that need to prepare before or follow up after a meeting.\",\n\t\"app-docusign\": \"Connect DocuSign so workflows can send envelopes, track signatures, and file completed agreements. Use it for contracts, approvals, onboarding packets, or any process where a signed document should trigger the next step.\",\n\t\"app-dropbox\": \"Connect Dropbox so agents can read files, upload assets, and organize shared folders. Use it for document intake, generated exports, client deliverables, or workflows that need to move files between teams and systems.\",\n\t\"app-box\": \"Connect Box so agents can search enterprise files, update folders, and manage documents securely. Use it for governed document workflows, legal handoffs, knowledge retrieval, or file operations that need enterprise storage controls.\",\n\t\"app-figma\": \"Connect Figma so agents can inspect designs, sync comments, and coordinate design handoffs. Use it to pull design context into implementation work, track feedback, or turn approved mockups into downstream tasks.\",\n\t\"app-canva\": \"Connect Canva so agents can help create design assets and automate content production. Use it for campaign graphics, social templates, brand asset updates, or workflows where creative requests need repeatable output.\",\n\t\"app-sentry\": \"Connect Sentry so agents can triage errors, summarize issues, and route incidents from production signals. Use it to turn crash reports into engineering tasks, prepare context for responders, or close the loop after a fix.\",\n\t\"app-datadog\": \"Connect Datadog so workflows can query metrics, inspect monitors, and coordinate incidents. Use it for alert triage, deployment checks, operational summaries, or automations that need observability context before taking action.\",\n\t\"app-pagerduty\": \"Connect PagerDuty so agents can create incidents, page responders, and automate escalation steps. Use it for on-call workflows, incident updates, postmortem prep, or routing urgent operational work to the right person.\",\n\t\"app-gitlab\": \"Connect GitLab so agents can manage merge requests, issues, pipelines, and repositories. Use it for CI follow-ups, release coordination, code review automation, or engineering workflows centered on GitLab projects.\",\n\t\"app-bitbucket\": \"Connect Bitbucket so workflows can automate pull requests, branches, and repository activity. Use it for review routing, branch hygiene, deployment handoffs, or teams whose source control lives in Atlassian.\",\n\t\"app-vercel\": \"Connect Vercel so agents can track deployments, inspect projects, and react to build events. Use it for preview checks, release notifications, failed build triage, or workflows that connect product changes to deployment state.\",\n\t\"app-netlify\": \"Connect Netlify so agents can automate deploys, forms, sites, and build notifications. Use it for static site releases, form-driven workflows, build triage, or marketing site operations tied to deployment events.\",\n\t\"app-supabase\": \"Connect Supabase so agents can query databases, manage auth context, and automate backend workflows. Use it for operational data checks, admin tasks, user support lookups, or workflows that depend on app data stored in Supabase.\",\n\t\"app-postgres\": \"Connect Postgres so workflows can run SQL queries and sync structured data from your database. Use it for reports, back-office operations, data enrichment, or automations that need direct access to relational data.\",\n\t\"app-snowflake\": \"Connect Snowflake so agents can query warehouse data and automate analytics workflows. Use it for reporting, customer segmentation, anomaly checks, or workflows that need trusted business data before acting.\",\n\t\"app-databricks\": \"Connect Databricks so workflows can run jobs, query lakehouse data, and coordinate data pipelines. Use it for analytics operations, model-adjacent workflows, data quality checks, or pipeline handoffs between teams.\",\n\t\"app-segment\": \"Connect Segment so agents can route customer events and enrich downstream automations. Use it for lifecycle triggers, audience syncs, event QA, or workflows that begin when product behavior changes.\",\n\t\"app-twilio\": \"Connect Twilio so agents can send SMS, manage calls, and coordinate customer notifications. Use it for reminders, verification flows, support callbacks, or automations that need to reach people outside email and chat.\",\n\t\"app-zoom\": \"Connect Zoom so agents can schedule meetings, manage recordings, and notify attendees. Use it for meeting prep, transcript follow-ups, customer call workflows, or automations that turn live conversations into next steps.\",\n\t\"app-loom\": \"Connect Loom so agents can create video handoffs, summarize recordings, and share updates. Use it for async status reports, customer walkthroughs, product feedback, or workflows where a short video carries the context.\",\n\t\"app-miro\": \"Connect Miro so agents can create boards, sync cards, and coordinate visual planning. Use it for workshops, roadmap sessions, research synthesis, or workflows that move structured work into a shared canvas.\",\n\t\"app-coda\": \"Connect Coda so workflows can update docs, tables, packs, and team operating systems. Use it for custom trackers, lightweight apps, planning docs, or automations that need to keep Coda tables current.\",\n\t\"app-confluence\": \"Connect Confluence so agents can search knowledge bases and create or update documentation. Use it for runbooks, implementation notes, release docs, or workflows that should leave behind durable team knowledge.\",\n\t\"app-aws\": \"Connect AWS so agents can coordinate cloud resources, events, queues, and infrastructure tasks. Use it for operational checks, deployment handoffs, queue monitoring, or workflows that need cloud state before acting.\",\n\t\"app-google-cloud\": \"Connect Google Cloud so workflows can manage cloud jobs, storage, Pub/Sub, and deployment work. Use it for infrastructure automation, data pipeline coordination, operational checks, or alerts tied to Google Cloud services.\",\n\t\"app-azure\": \"Connect Azure so agents can automate resources, queues, deployments, and identity-related tasks. Use it for enterprise cloud operations, release workflows, infrastructure checks, or automations in Microsoft-backed environments.\",\n\t\"app-cloudflare\": \"Connect Cloudflare so agents can manage DNS, Workers, Pages, queues, and edge automations. Use it for site operations, edge deployments, incident response, or workflows that need to change traffic and infrastructure at the edge.\",\n\t\"app-docker\": \"Connect Docker so agents can coordinate images, registries, builds, and deployment events. Use it for release preparation, image promotion, environment checks, or workflows that need container metadata.\",\n\t\"app-kubernetes\": \"Connect Kubernetes so agents can inspect clusters, trigger jobs, and automate operational tasks. Use it for rollout checks, incident triage, job coordination, or workflows that need live cluster context.\",\n\t\"app-algolia\": \"Connect Algolia so workflows can sync search indexes and automate content discovery tasks. Use it for search freshness, indexing checks, merchandising updates, or workflows that need searchable content to stay current.\",\n\t\"app-elasticsearch\": \"Connect Elasticsearch so agents can query search clusters and automate log or document workflows. Use it for operational investigations, search-backed features, document indexing, or workflows that depend on fast text retrieval.\",\n\t\"app-redis\": \"Connect Redis so workflows can read cache data, coordinate queues, and manage realtime state. Use it for operational checks, queue insight, temporary state lookups, or automations that need fast key-value context.\",\n\t\"app-pinecone\": \"Connect Pinecone so agents can manage vector indexes and power retrieval workflows. Use it for semantic search, memory, recommendation, or knowledge retrieval steps that need embeddings-backed context.\",\n\t\"app-plaid\": \"Connect Plaid so agents can work with financial account data and banking flows. Use it for transaction enrichment, onboarding checks, financial reporting, or workflows that depend on verified account activity.\",\n\t\"app-brex\": \"Connect Brex so workflows can sync expenses, cards, reimbursements, and finance approvals. Use it for spend review, receipt follow-up, budget alerts, or automations that connect finance operations to team workflows.\",\n\t\"app-mercury\": \"Connect Mercury so agents can automate banking workflows, transactions, and treasury tasks. Use it for finance operations, cash movement checks, approval routing, or workflows triggered by account activity.\",\n\t\"app-elevenlabs\": \"Connect ElevenLabs so agents can generate speech, transcribe audio, and build voice-enabled workflows. Use it for narrated updates, voice agents, call summaries, or automations that need natural-sounding audio output.\",\n\t\"app-perplexity\": \"Connect Perplexity so agents can search the web with citations and grounded answers. Use it for research, competitive monitoring, fact gathering, or workflows that need fresh external context before making a recommendation.\",\n\t\"app-gemini\": \"Connect Gemini so agents can use Google AI models for generation, analysis, and reasoning. Use it for multimodal understanding, document analysis, content generation, or workflows that benefit from Google model coverage.\",\n\t\"app-polymarket\": \"Connect Polymarket so agents can read market data and automate prediction-market workflows. Use it for market monitoring, research context, probability tracking, or automations that react to changing public forecasts.\",\n\t\"app-blacksmith\": \"Connect Blacksmith so agents can inspect CI runs, coordinate build infrastructure, and react to developer workflow events. Use it for failed build triage, runner capacity checks, deployment gates, or automations that keep engineering pipelines moving.\",\n\t\"app-deel\": \"Connect Deel so agents can work with contractor, employee, payroll, and compliance workflows. Use it to prepare onboarding tasks, follow up on HR operations, reconcile workforce data, or route people ops requests to the right system.\",\n\t\"app-doordash\": \"Connect DoorDash so agents can coordinate delivery, merchant, and logistics workflows. Use it for order exception handling, fulfillment updates, operational alerts, or automations where real-world delivery status needs to trigger follow-up work.\",\n\t\"app-dub\": \"Connect Dub so agents can manage short links, attribution, and campaign routing. Use it to create tracked links, monitor conversion signals, clean up campaign metadata, or connect marketing activity to downstream reporting.\",\n\t\"app-exa\": \"Connect Exa so agents can search the web and retrieve AI-ready research results. Use it for market scans, company enrichment, competitive research, or workflows that need fresh external context before drafting or deciding.\",\n\t\"app-firecrawl\": \"Connect Firecrawl so agents can crawl sites, extract structured data, and turn webpages into workflow-ready inputs. Use it for lead enrichment, documentation ingestion, content monitoring, or research tasks that start from public web pages.\",\n\t\"app-granola\": \"Connect Granola so agents can use meeting notes, summaries, and follow-up context in your workflows. Use it to turn calls into tasks, update account records, prepare recap messages, or make meeting outcomes available to other automations.\",\n\t\"app-gusto\": \"Connect Gusto so agents can coordinate payroll, benefits, and HR operations. Use it for onboarding checklists, payroll review reminders, people ops follow-ups, or workflows that need employee and compensation context.\",\n\t\"app-hex\": \"Connect Hex so agents can run analytics workflows, query notebooks, and coordinate data app outputs. Use it for metric investigations, recurring analysis, stakeholder reports, or automations that need trusted analytical context.\",\n\t\"app-instacart\": \"Connect Instacart so agents can coordinate grocery commerce, orders, and fulfillment workflows. Use it for delivery exceptions, merchant operations, catalog checks, or automations that depend on order and shopper activity.\",\n\t\"app-kalshi\": \"Connect Kalshi so agents can read event markets and automate prediction-market workflows. Use it for market monitoring, probability snapshots, research briefs, or automations that react to changing expectations around real-world events.\",\n\t\"app-omni\": \"Connect Omni so agents can query business intelligence models and automate analytics workflows. Use it to answer operational questions, refresh stakeholder summaries, investigate metric movement, or bring governed BI context into agent work.\",\n\t\"app-parallel\": \"Connect Parallel so agents can run AI research, enrichment, and web task workflows. Use it for background research, lead enrichment, competitive monitoring, or automations that delegate broad information-gathering tasks.\",\n\t\"app-planetscale\": \"Connect PlanetScale so agents can manage database branches, deploy requests, and MySQL-backed workflows. Use it for schema review reminders, release coordination, operational data checks, or automations tied to database changes.\",\n\t\"app-porter\": \"Connect Porter so agents can coordinate cloud deployments and application infrastructure. Use it for rollout checks, failed deploy triage, environment updates, or workflows that keep application operations moving.\",\n\t\"app-puzzle\": \"Connect Puzzle so agents can automate accounting workflows, books, and finance operations. Use it for close checklists, transaction review, finance handoffs, or workflows that keep bookkeeping context current.\",\n\t\"app-pylon\": \"Connect Pylon so agents can manage B2B support conversations and customer workflows. Use it to triage customer issues, summarize account context, route engineering follow-ups, or keep support signals connected to product work.\",\n\t\"app-ramp\": \"Connect Ramp so agents can sync spend, expenses, approvals, and finance workflows. Use it for receipt follow-ups, budget alerts, approval routing, or automations that connect company spend to operational context.\",\n\t\"app-reducto\": \"Connect Reducto so agents can extract structured data from complex documents. Use it for document intake, contract review prep, invoice parsing, or workflows where PDFs and files need to become reliable structured inputs.\",\n\t\"app-resend\": \"Connect Resend so agents can send product email and react to delivery events. Use it for onboarding messages, transactional notifications, bounce handling, or workflows that need reliable email delivery from product systems.\",\n\t\"app-rippling\": \"Connect Rippling so agents can coordinate employee, device, payroll, and HR workflows from one place. Use it for onboarding and offboarding checklists, access changes, equipment follow-ups, or automations that need workforce context before acting.\",\n\t\"app-streak\": \"Connect Streak so agents can manage Gmail-native CRM pipelines and contact workflows. Use it for deal follow-ups, inbox-driven sales activity, contact updates, or workflows where relationship context lives directly inside Gmail.\",\n\t\"app-warp\": \"Connect Warp so agents can coordinate terminal, developer environment, and AI coding workflows. Use it for developer setup tasks, command-driven runbooks, environment checks, or workflows that bridge local engineering activity with team operations.\",\n\t\"app-apollo\": \"Connect Apollo so agents can use sales intelligence, prospecting data, and enrichment workflows. Use it to qualify leads, enrich accounts, prepare outbound context, or route sales follow-ups based on fresh prospect data.\",\n\t\"app-cal-com\": \"Connect Cal.com so agents can automate scheduling, bookings, availability, and routing workflows. Use it for handoff scheduling, round-robin booking, interview coordination, or follow-ups that should happen before or after a meeting.\",\n\t\"app-cerebras\": \"Connect Cerebras so agents can use fast AI inference inside workflows and tools. Use it for low-latency generation, classification, extraction, or model-powered steps that need quick responses at scale.\",\n\t\"app-chargebee\": \"Connect Chargebee so agents can automate subscription billing, customers, invoices, and revenue workflows. Use it for renewal alerts, billing support, failed payment follow-ups, or automations tied to subscription lifecycle changes.\",\n\t\"app-deepseek\": \"Connect DeepSeek so agents can use DeepSeek models for generation, reasoning, and analysis. Use it for coding assistance, structured extraction, summarization, or AI steps that benefit from an additional model provider.\",\n\t\"app-gong\": \"Connect Gong so agents can use revenue conversations, account insights, and sales activity. Use it to summarize calls, extract next steps, update CRM context, or trigger follow-ups from customer conversations.\",\n\t\"app-google-contacts\": \"Connect Google Contacts so agents can read and update contact records across Google Workspace. Use it to enrich communication workflows, keep people data current, or resolve the right recipient before sending follow-ups.\",\n\t\"app-google-docs\": \"Connect Google Docs so agents can create, read, and update collaborative documents. Use it for drafting briefs, maintaining runbooks, turning conversations into docs, or updating shared plans after workflow activity.\",\n\t\"app-google-forms\": \"Connect Google Forms so agents can capture submissions and turn responses into follow-up work. Use it for intake flows, lightweight surveys, internal requests, or automations that begin when someone submits structured information.\",\n\t\"app-google-meet\": \"Connect Google Meet so agents can coordinate meetings, recordings, and video collaboration workflows. Use it for meeting prep, attendee updates, recording follow-ups, or automations that turn live conversations into next steps.\",\n\t\"app-google-slides\": \"Connect Google Slides so agents can create and update presentations from workflow outputs. Use it for status decks, customer recaps, board updates, or automations that turn approved content and data into slides.\",\n\t\"app-google-tasks\": \"Connect Google Tasks so agents can create tasks, update lists, and coordinate personal work queues. Use it for lightweight reminders, follow-up capture, personal task routing, or workflows that should land in a simple to-do list.\",\n\t\"app-greenhouse\": \"Connect Greenhouse so agents can automate candidate, job, and interview coordination workflows. Use it for recruiting follow-ups, interview loop prep, candidate summaries, or workflows that keep hiring processes current.\",\n\t\"app-groq\": \"Connect Groq so agents can use low-latency AI inference in workflows. Use it for fast classification, summarization, extraction, or interactive agent steps where response speed matters.\",\n\t\"app-help-scout\": \"Connect Help Scout so agents can manage customer conversations, mailboxes, and support workflows. Use it to triage inbound requests, draft replies, summarize customer context, or route support signals into product and engineering work.\",\n\t\"app-linkedin\": \"Connect LinkedIn so agents can coordinate professional network, recruiting, and social workflows. Use it for prospect research, hiring context, relationship prep, or automations that connect professional profiles to your operating data.\",\n\t\"app-microsoft-excel\": \"Connect Microsoft Excel so agents can read, update, and append rows in workbooks. Use it for operational reports, finance trackers, reconciliation sheets, or workflows that need to work with spreadsheets stored in Microsoft 365.\",\n\t\"app-microsoft-onedrive\": \"Connect Microsoft OneDrive so agents can find, read, upload, and organize files. Use it for document intake, generated exports, shared artifacts, or workflows that need source material from Microsoft cloud storage.\",\n\t\"app-microsoft-outlook\": \"Connect Microsoft Outlook so agents can send email, read messages, and coordinate calendar workflows. Use it for customer follow-ups, scheduling handoffs, inbox triage, or automations that need to operate inside Microsoft 365.\",\n\t\"app-microsoft-planner\": \"Connect Microsoft Planner so agents can create tasks, update plans, and coordinate project work. Use it for team checklists, project handoffs, status updates, or workflows that should create visible work items for Microsoft 365 teams.\",\n\t\"app-microsoft-sharepoint\": \"Connect Microsoft SharePoint so agents can search sites, update lists, and manage shared documents. Use it for governed document workflows, internal knowledge retrieval, approval tracking, or automations that depend on SharePoint content.\",\n\t\"app-mistral\": \"Connect Mistral so agents can use Mistral models for generation, analysis, and reasoning. Use it for multilingual tasks, structured extraction, summarization, or AI workflow steps that need another model option.\",\n\t\"app-posthog\": \"Connect PostHog so agents can query product analytics, feature flags, and user behavior signals. Use it for growth investigations, experiment follow-ups, customer debugging, or workflows triggered by product usage patterns.\",\n\t\"app-reddit\": \"Connect Reddit so agents can monitor communities, posts, and discussion-driven workflows. Use it for audience research, brand monitoring, support signal discovery, or automations that react to public community conversations.\",\n\t\"app-square\": \"Connect Square so agents can automate payments, customers, catalog, and point-of-sale workflows. Use it for transaction follow-ups, customer updates, sales reporting, or operational workflows tied to in-person and online commerce.\",\n\t\"app-todoist\": \"Connect Todoist so agents can create tasks, update projects, and automate personal work queues. Use it for lightweight reminders, follow-up capture, recurring checklists, or workflows that should become personal tasks.\",\n\t\"app-wordpress\": \"Connect WordPress so agents can publish posts, update pages, and automate site content workflows. Use it for editorial operations, release notes, content refreshes, or workflows that turn approved drafts into live site updates.\",\n\t\"app-x-twitter\": \"Connect X / Twitter so agents can monitor posts, publish updates, and coordinate social workflows. Use it for launch announcements, brand monitoring, support escalation, or automations that react to public conversation.\",\n\t\"app-xai\": \"Connect xAI so agents can use xAI models for generation, analysis, and reasoning. Use it for drafting, summarization, classification, or AI workflow steps that benefit from another model provider.\",\n\t\"app-youtube\": \"Connect YouTube so agents can manage videos, channels, comments, and creator workflows. Use it for publishing checklists, comment triage, content reporting, or automations that connect video activity to the rest of your workspace.\"\n};\nconst CATEGORY_INTEGRATION_USE_CASES = {\n\tAI: \"add model calls, embeddings, structured generation, and reasoning steps to agents or workflows\",\n\tCommerce: \"keep storefront, order, product, and fulfillment workflows moving without manual handoffs\",\n\tCommunication: \"send updates, listen for replies, route approvals, and keep conversations tied to the work they affect\",\n\tCRM: \"sync customer context, update records, and keep sales or success workflows current\",\n\tData: \"query, enrich, sync, and transform structured data as part of automated workflows\",\n\tDesign: \"pull design context into implementation work and keep creative handoffs coordinated\",\n\tDevelopment: \"react to engineering events, update project metadata, and connect code activity to agent workflows\",\n\tDocuments: \"send, track, organize, and file documents as part of repeatable business processes\",\n\tFiles: \"find, read, upload, and organize files so workflows can work with the right source material\",\n\tFinance: \"reconcile billing, accounting, customer, and transaction data across finance workflows\",\n\tForms: \"capture submissions, enrich responses, and trigger follow-up work from collected data\",\n\tHR: \"coordinate onboarding, payroll, and people operations without leaving the workspace\",\n\tInfrastructure: \"coordinate cloud resources, deployments, queues, and operational tasks from one workspace\",\n\tMarketing: \"manage campaigns, audiences, content, and delivery events from automated growth workflows\",\n\tObservability: \"triage incidents, summarize operational context, and route alerts to the right responders\",\n\tProductivity: \"coordinate calendars, docs, tasks, files, and team knowledge without leaving the workspace\",\n\t\"Project Management\": \"create tasks, update project state, and keep work queues aligned with agent-driven execution\",\n\tSearch: \"retrieve fresh external context, crawl sources, and ground workflows in real-time results\",\n\tSupport: \"triage customer conversations, update tickets, and move support context into the right workflow\"\n};\nfunction buildIntegrationDescription(app) {\n\tconst explicit = APP_INTEGRATION_DESCRIPTIONS[app.id];\n\tif (explicit) return explicit;\n\tconst categoryUseCase = CATEGORY_INTEGRATION_USE_CASES[app.category] ?? \"connect external context, events, and actions to your automated workflows\";\n\treturn `Connect ${app.name} to Keystroke so the workflows and AI agents you build can use it as a live ${app.category.toLowerCase()} system. ${app.description} Once connected, those automations can ${categoryUseCase}.`;\n}\nconst DEFAULT_OAUTH_SCOPE_DESCRIPTIONS = {\n\temail: \"View the email address associated with the connected account.\",\n\tprofile: \"View basic profile information for the connected account.\"\n};\nconst OAUTH_SCOPE_CATALOG_BY_APP_ID = {\n\t\"app-slack\": [\n\t\t{\n\t\t\tname: \"channels:history\",\n\t\t\tdescription: \"View messages and other content in public channels that the Slack Bot has been added to.\"\n\t\t},\n\t\t{\n\t\t\tname: \"channels:read\",\n\t\t\tdescription: \"View basic information about public channels in Slack.\"\n\t\t},\n\t\t{\n\t\t\tname: \"chat:write\",\n\t\t\tdescription: \"Send messages as the Keystroke Slack Bot.\"\n\t\t},\n\t\t{\n\t\t\tname: \"commands\",\n\t\t\tdescription: \"Add shortcuts and slash commands that start Keystroke actions.\"\n\t\t},\n\t\t{\n\t\t\tname: \"users:read\",\n\t\t\tdescription: \"View people in the Slack workspace.\"\n\t\t},\n\t\t{\n\t\t\tname: \"groups:read\",\n\t\t\tdescription: \"View basic information about private channels.\"\n\t\t},\n\t\t{\n\t\t\tname: \"im:read\",\n\t\t\tdescription: \"View basic information about direct messages.\"\n\t\t},\n\t\t{\n\t\t\tname: \"mpim:read\",\n\t\t\tdescription: \"View basic information about group direct messages.\"\n\t\t},\n\t\t{\n\t\t\tname: \"reactions:read\",\n\t\t\tdescription: \"View emoji reactions in conversations.\"\n\t\t},\n\t\t{\n\t\t\tname: \"team:read\",\n\t\t\tdescription: \"View basic information about the Slack workspace.\"\n\t\t},\n\t\t{\n\t\t\tname: \"files:read\",\n\t\t\tdescription: \"View files shared in Slack conversations.\"\n\t\t},\n\t\t{\n\t\t\tname: \"users.profile:read\",\n\t\t\tdescription: \"View profile fields for people in the workspace.\"\n\t\t},\n\t\t{\n\t\t\tname: \"channels:join\",\n\t\t\tdescription: \"Join public channels in the workspace.\"\n\t\t},\n\t\t{\n\t\t\tname: \"chat:write.public\",\n\t\t\tdescription: \"Send messages to public channels the bot is not a member of.\"\n\t\t},\n\t\t{\n\t\t\tname: \"groups:history\",\n\t\t\tdescription: \"View messages in private channels the bot has been added to.\"\n\t\t},\n\t\t{\n\t\t\tname: \"im:history\",\n\t\t\tdescription: \"View messages in direct message conversations.\"\n\t\t},\n\t\t{\n\t\t\tname: \"mpim:history\",\n\t\t\tdescription: \"View messages in group direct message conversations.\"\n\t\t},\n\t\t{\n\t\t\tname: \"reactions:write\",\n\t\t\tdescription: \"Add emoji reactions to Slack messages.\"\n\t\t},\n\t\t{\n\t\t\tname: \"files:write\",\n\t\t\tdescription: \"Upload and manage files in Slack conversations.\"\n\t\t}\n\t],\n\t\"app-gmail\": [\n\t\t{\n\t\t\tname: \"gmail.readonly\",\n\t\t\tdescription: \"View Gmail messages and metadata.\"\n\t\t},\n\t\t{\n\t\t\tname: \"gmail.send\",\n\t\t\tdescription: \"Send email from the connected Gmail account.\"\n\t\t},\n\t\t{\n\t\t\tname: \"gmail.modify\",\n\t\t\tdescription: \"Read, label, archive, and delete Gmail messages.\"\n\t\t},\n\t\t{\n\t\t\tname: \"gmail.labels\",\n\t\t\tdescription: \"Create, read, update, and delete Gmail labels.\"\n\t\t},\n\t\t{\n\t\t\tname: \"gmail.compose\",\n\t\t\tdescription: \"Create and manage draft email messages.\"\n\t\t},\n\t\t{\n\t\t\tname: \"profile\",\n\t\t\tdescription: DEFAULT_OAUTH_SCOPE_DESCRIPTIONS.profile\n\t\t},\n\t\t{\n\t\t\tname: \"email\",\n\t\t\tdescription: DEFAULT_OAUTH_SCOPE_DESCRIPTIONS.email\n\t\t}\n\t],\n\t\"app-github\": [\n\t\t{\n\t\t\tname: \"repo\",\n\t\t\tdescription: \"Read and write code, pull requests, issues, and repository metadata.\"\n\t\t},\n\t\t{\n\t\t\tname: \"read:org\",\n\t\t\tdescription: \"Read organization membership and team information.\"\n\t\t},\n\t\t{\n\t\t\tname: \"workflow\",\n\t\t\tdescription: \"Update GitHub Actions workflow files.\"\n\t\t},\n\t\t{\n\t\t\tname: \"admin:repo_hook\",\n\t\t\tdescription: \"Create and manage repository webhooks.\"\n\t\t},\n\t\t{\n\t\t\tname: \"read:user\",\n\t\t\tdescription: \"Read the connected GitHub user profile.\"\n\t\t},\n\t\t{\n\t\t\tname: \"user:email\",\n\t\t\tdescription: \"Read the connected GitHub user email addresses.\"\n\t\t}\n\t],\n\t\"app-stripe\": [\n\t\t{\n\t\t\tname: \"charges:read\",\n\t\t\tdescription: \"View charges, payment status, and dispute details.\"\n\t\t},\n\t\t{\n\t\t\tname: \"customers:read\",\n\t\t\tdescription: \"View customers and saved billing details.\"\n\t\t},\n\t\t{\n\t\t\tname: \"customers:write\",\n\t\t\tdescription: \"Create and update customer records.\"\n\t\t},\n\t\t{\n\t\t\tname: \"invoices:read\",\n\t\t\tdescription: \"View invoices, invoice items, and payment attempts.\"\n\t\t},\n\t\t{\n\t\t\tname: \"invoices:write\",\n\t\t\tdescription: \"Create, finalize, and update invoices.\"\n\t\t},\n\t\t{\n\t\t\tname: \"subscriptions:read\",\n\t\t\tdescription: \"View subscription plans, items, and billing schedules.\"\n\t\t},\n\t\t{\n\t\t\tname: \"webhook_endpoints:write\",\n\t\t\tdescription: \"Create and manage webhook endpoints for Stripe events.\"\n\t\t}\n\t]\n};\nfunction buildAppCatalogEntry(app) {\n\treturn {\n\t\t...app,\n\t\tintegrationDescription: buildIntegrationDescription(app),\n\t\toauthScopes: OAUTH_SCOPE_CATALOG_BY_APP_ID[app.id] ?? []\n\t};\n}\n/**\n* The supported-app catalog shown in the \"Connect an app\" picker. Mirrors the\n* curated integration list from keystroke-mockups. No connected/available flag:\n* \"connected\" is not a property of an app, it's whether a credential exists.\n*/\nconst appCatalogSeed = APP_CATALOG_BASE.map(buildAppCatalogEntry);\nconst GMAIL_SCOPES = [\n\t\"gmail.readonly\",\n\t\"gmail.send\",\n\t\"profile\",\n\t\"email\"\n];\nconst SLACK_SCOPES = [\n\t\"channels:history\",\n\t\"channels:read\",\n\t\"chat:write\",\n\t\"commands\",\n\t\"users:read\",\n\t\"groups:read\",\n\t\"im:read\",\n\t\"mpim:read\",\n\t\"reactions:read\",\n\t\"team:read\",\n\t\"files:read\",\n\t\"users.profile:read\"\n];\n/**\n* Credential records the signed-in user can see, spanning the three scopes\n* (organization, project, user) and both connection kinds (oauth, manual) so\n* the table's pre-built views and the detail page all have data to render.\n*/\nconst credentialSeed = [\n\t{\n\t\tid: \"cred-gmail-org-1\",\n\t\tappId: \"app-gmail\",\n\t\tappName: \"Gmail\",\n\t\tlabel: \"Company Gmail\",\n\t\tscope: \"organization\",\n\t\tisDefault: true,\n\t\tstatus: \"Active\",\n\t\tconnectionKind: \"oauth\",\n\t\tcreatedAt: \"2026-02-10T14:00:00Z\",\n\t\tlastUsedAt: \"2026-04-20T15:44:00Z\",\n\t\tlastRefreshedAt: \"2026-04-20T15:44:00Z\",\n\t\texpiresAt: \"2026-05-20T15:44:00Z\",\n\t\tgrantedScopes: GMAIL_SCOPES,\n\t\townerUserId: \"org-member-nate\",\n\t\townerName: \"Nate Wells\"\n\t},\n\t{\n\t\tid: \"cred-gmail-proj-marketing\",\n\t\tappId: \"app-gmail\",\n\t\tappName: \"Gmail\",\n\t\tlabel: \"Marketing Gmail\",\n\t\tscope: \"project\",\n\t\tprojectId: \"project_gtm_engineering\",\n\t\tprojectName: \"GTM Engineering\",\n\t\tisDefault: false,\n\t\tstatus: \"Active\",\n\t\tconnectionKind: \"oauth\",\n\t\tcreatedAt: \"2026-03-10T09:00:00Z\",\n\t\tlastUsedAt: \"2026-04-19T11:20:00Z\",\n\t\tlastRefreshedAt: \"2026-04-19T11:20:00Z\",\n\t\texpiresAt: \"2026-05-19T11:20:00Z\",\n\t\tgrantedScopes: GMAIL_SCOPES,\n\t\townerUserId: \"org-member-nate\",\n\t\townerName: \"Nate Wells\"\n\t},\n\t{\n\t\tid: \"cred-gmail-proj-support\",\n\t\tappId: \"app-gmail\",\n\t\tappName: \"Gmail\",\n\t\tlabel: \"Support Gmail\",\n\t\tscope: \"project\",\n\t\tprojectId: \"project_gtm_engineering\",\n\t\tprojectName: \"GTM Engineering\",\n\t\tisDefault: false,\n\t\tstatus: \"Expired\",\n\t\tconnectionKind: \"oauth\",\n\t\tcreatedAt: \"2026-03-15T10:30:00Z\",\n\t\tlastUsedAt: \"2026-04-18T16:05:00Z\",\n\t\tlastRefreshedAt: \"2026-04-18T16:05:00Z\",\n\t\texpiresAt: \"2026-04-18T16:05:00Z\",\n\t\tgrantedScopes: [\n\t\t\t\"gmail.readonly\",\n\t\t\t\"profile\",\n\t\t\t\"email\"\n\t\t],\n\t\townerUserId: \"org-member-dallin\",\n\t\townerName: \"Dallin Bentley\"\n\t},\n\t{\n\t\tid: \"cred-gmail-user-blake\",\n\t\tappId: \"app-gmail\",\n\t\tappName: \"Gmail\",\n\t\tlabel: \"Blake's Gmail\",\n\t\tscope: \"user\",\n\t\tisDefault: false,\n\t\tstatus: \"Active\",\n\t\tconnectionKind: \"oauth\",\n\t\tcreatedAt: \"2026-03-20T08:15:00Z\",\n\t\tlastUsedAt: \"2026-04-20T09:18:00Z\",\n\t\tlastRefreshedAt: \"2026-04-20T09:18:00Z\",\n\t\texpiresAt: \"2026-05-20T09:18:00Z\",\n\t\tgrantedScopes: GMAIL_SCOPES,\n\t\townerUserId: \"user_blake_rouse\",\n\t\townerName: \"Blake Rouse\"\n\t},\n\t{\n\t\tid: \"cred-slack-org-1\",\n\t\tappId: \"app-slack\",\n\t\tappName: \"Slack\",\n\t\tlabel: \"Keystroke Slack\",\n\t\tscope: \"organization\",\n\t\tisDefault: true,\n\t\tstatus: \"Active\",\n\t\tconnectionKind: \"oauth\",\n\t\tcreatedAt: \"2026-02-12T11:00:00Z\",\n\t\tlastUsedAt: \"2026-04-20T14:21:00Z\",\n\t\tlastRefreshedAt: \"2026-04-20T14:21:00Z\",\n\t\texpiresAt: \"2026-05-20T14:21:00Z\",\n\t\tgrantedScopes: SLACK_SCOPES,\n\t\townerUserId: \"org-member-wells\",\n\t\townerName: \"Wells Riley\"\n\t},\n\t{\n\t\tid: \"cred-slack-user-nate\",\n\t\tappId: \"app-slack\",\n\t\tappName: \"Slack\",\n\t\tlabel: \"Nate's Slack\",\n\t\tscope: \"user\",\n\t\tisDefault: false,\n\t\tstatus: \"Needs Reauth\",\n\t\tconnectionKind: \"oauth\",\n\t\tcreatedAt: \"2026-03-22T15:45:00Z\",\n\t\tlastUsedAt: \"2026-04-20T12:05:00Z\",\n\t\tlastRefreshedAt: \"2026-04-20T12:05:00Z\",\n\t\texpiresAt: \"2026-04-20T12:05:00Z\",\n\t\tgrantedScopes: SLACK_SCOPES,\n\t\townerUserId: \"org-member-nate\",\n\t\townerName: \"Nate Wells\"\n\t},\n\t{\n\t\tid: \"cred-github-org-1\",\n\t\tappId: \"app-github\",\n\t\tappName: \"GitHub\",\n\t\tlabel: \"Keystroke GitHub\",\n\t\tscope: \"organization\",\n\t\tisDefault: true,\n\t\tstatus: \"Active\",\n\t\tconnectionKind: \"oauth\",\n\t\tcreatedAt: \"2026-02-08T09:30:00Z\",\n\t\tlastUsedAt: \"2026-04-20T13:02:00Z\",\n\t\tlastRefreshedAt: \"2026-04-20T13:02:00Z\",\n\t\texpiresAt: \"2026-05-20T13:02:00Z\",\n\t\tgrantedScopes: [\n\t\t\t\"repo\",\n\t\t\t\"read:org\",\n\t\t\t\"workflow\"\n\t\t],\n\t\townerUserId: \"org-member-dallin\",\n\t\townerName: \"Dallin Bentley\"\n\t},\n\t{\n\t\tid: \"cred-github-proj-personal\",\n\t\tappId: \"app-github\",\n\t\tappName: \"GitHub\",\n\t\tlabel: \"Personal Repo GitHub\",\n\t\tscope: \"project\",\n\t\tprojectId: \"project_personal_repo\",\n\t\tprojectName: \"Blake's Project\",\n\t\tisDefault: false,\n\t\tstatus: \"Active\",\n\t\tconnectionKind: \"oauth\",\n\t\tcreatedAt: \"2026-03-01T16:00:00Z\",\n\t\tlastUsedAt: \"2026-04-19T19:41:00Z\",\n\t\tlastRefreshedAt: \"2026-04-19T19:41:00Z\",\n\t\texpiresAt: \"2026-05-19T19:41:00Z\",\n\t\tgrantedScopes: [\"repo\", \"workflow\"],\n\t\townerUserId: \"user_blake_rouse\",\n\t\townerName: \"Blake Rouse\"\n\t},\n\t{\n\t\tid: \"cred-anthropic-org-1\",\n\t\tappId: \"app-anthropic\",\n\t\tappName: \"Anthropic\",\n\t\tlabel: \"Anthropic API\",\n\t\tscope: \"organization\",\n\t\tisDefault: true,\n\t\tstatus: \"Active\",\n\t\tconnectionKind: \"manual\",\n\t\tcreatedAt: \"2026-02-20T13:00:00Z\",\n\t\tlastUsedAt: \"2026-04-19T09:40:00Z\",\n\t\tlastRefreshedAt: \"2026-04-19T09:40:00Z\",\n\t\tcredentialKeys: [\"ANTHROPIC_API_KEY\"],\n\t\tkeyPreviews: { ANTHROPIC_API_KEY: \"••••••••••••••••••M5f\" },\n\t\townerUserId: \"org-member-nate\",\n\t\townerName: \"Nate Wells\"\n\t}\n];\n/** Review personas for mocked project members and API key authors (not org membership). */\nconst mockPersonaSeed = [\n\t{\n\t\tid: \"user_blake_rouse\",\n\t\tname: \"Blake Rouse\",\n\t\temail: \"blake@keystroke.ai\",\n\t\tavatarUrl: \"/icons/avatars/blake-rouse.png\",\n\t\tjoinedAt: \"2026-01-12T18:00:00Z\",\n\t\tlastActiveAt: \"2026-05-31T18:00:00Z\"\n\t},\n\t{\n\t\tid: \"org-member-nate\",\n\t\tname: \"Nate Wells\",\n\t\temail: \"nate@keystroke.ai\",\n\t\tavatarUrl: \"/icons/avatars/nate-kelley.png\",\n\t\tjoinedAt: \"2026-02-03T18:00:00Z\",\n\t\tlastActiveAt: \"2026-05-31T16:00:00Z\"\n\t},\n\t{\n\t\tid: \"org-member-dallin\",\n\t\tname: \"Dallin Bentley\",\n\t\temail: \"dallin@keystroke.ai\",\n\t\tavatarUrl: \"/icons/avatars/dallin-bentley.png\",\n\t\tjoinedAt: \"2026-03-18T18:00:00Z\",\n\t\tlastActiveAt: \"2026-05-30T16:00:00Z\"\n\t},\n\t{\n\t\tid: \"org-member-wells\",\n\t\tname: \"Wells Riley\",\n\t\temail: \"wells@keystroke.ai\",\n\t\tavatarUrl: \"/icons/avatars/wells-bunker.png\",\n\t\tjoinedAt: \"2026-04-09T18:00:00Z\",\n\t\tlastActiveAt: \"2026-05-20T16:00:00Z\"\n\t}\n];\nconst projectMemberSeed = mockPersonaSeed.map((member, index) => ({\n\tid: `project-member-${member.id}`,\n\tprojectId: \"project_personal_repo\",\n\tname: member.name,\n\temail: member.email,\n\trole: index <= 1 ? \"admin\" : \"editor\",\n\tstatus: \"active\",\n\tavatarUrl: member.avatarUrl,\n\tjoinedAt: member.joinedAt,\n\tlastActiveAt: member.lastActiveAt,\n\tisCurrentUser: member.id === \"user_blake_rouse\"\n}));\nconst apiKeySeed = [\n\t{\n\t\tid: \"api-key-local-dev\",\n\t\tname: \"LOCAL_DEV_BLAKE\",\n\t\tkeyPreview: \"******J7Pt\",\n\t\tcreatedAt: \"2026-04-20T15:44:00Z\",\n\t\tcreatedBy: mockPersonaSeed[0],\n\t\tisCreatedByCurrentUser: true\n\t},\n\t{\n\t\tid: \"api-key-ci-deploy\",\n\t\tname: \"CI deploy\",\n\t\tkeyPreview: \"******TJb7\",\n\t\tcreatedAt: \"2026-03-08T15:44:00Z\",\n\t\tcreatedBy: mockPersonaSeed[1],\n\t\tisCreatedByCurrentUser: false\n\t},\n\t{\n\t\tid: \"api-key-partner-webhooks\",\n\t\tname: \"partner_webhooks\",\n\t\tkeyPreview: \"******9Qzc\",\n\t\tcreatedAt: \"2026-02-18T15:44:00Z\",\n\t\tcreatedBy: mockPersonaSeed[2],\n\t\tisCreatedByCurrentUser: false\n\t}\n];\n//#endregion\n//#region src/platform/resources/mock-resources.ts\nlet credentialRecords = [...credentialSeed];\nfunction createMockApiKeySecret() {\n\tconst secret = `sk_${`${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`}`;\n\treturn {\n\t\tsecret,\n\t\tkeyPreview: `******${secret.slice(-4)}`\n\t};\n}\nfunction createAppsResource() {\n\treturn { listCatalog: mock({\n\t\tdomain: \"apps\",\n\t\tmethod: \"listCatalog\",\n\t\tplannedEndpoint: \"GET /api/apps\"\n\t}, async () => appCatalogSeed) };\n}\nfunction createCredentialsResource() {\n\treturn {\n\t\tlist: mock({\n\t\t\tdomain: \"credentials\",\n\t\t\tmethod: \"list\",\n\t\t\tplannedEndpoint: \"GET /api/credentials\"\n\t\t}, async () => credentialRecords),\n\t\tget: mock({\n\t\t\tdomain: \"credentials\",\n\t\t\tmethod: \"get\",\n\t\t\tplannedEndpoint: \"GET /api/credentials/:id\"\n\t\t}, async (credentialId) => credentialRecords.find((credential) => credential.id === credentialId) ?? null),\n\t\tstartOAuthConnection: mock({\n\t\t\tdomain: \"credentials\",\n\t\t\tmethod: \"startOAuthConnection\",\n\t\t\tplannedEndpoint: \"GET /oauth/:key/authorize-url\"\n\t\t}, async (input) => {\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 900));\n\t\t\treturn {\n\t\t\t\tstatus: \"connected\",\n\t\t\t\tauthorizeUrl: null\n\t\t\t};\n\t\t}),\n\t\tcreate: mock({\n\t\t\tdomain: \"credentials\",\n\t\t\tmethod: \"create\",\n\t\t\tplannedEndpoint: \"POST /api/credentials\"\n\t\t}, async (input) => {\n\t\t\tconst app = appCatalogSeed.find((entry) => entry.id === input.appId);\n\t\t\tconst now = (/* @__PURE__ */ new Date()).toISOString();\n\t\t\tconst keyName = `${(app?.name ?? \"APP\").toUpperCase().replace(/\\W+/g, \"_\")}_API_KEY`;\n\t\t\tconst base = {\n\t\t\t\tappId: input.appId,\n\t\t\t\tappName: app?.name,\n\t\t\t\tstatus: \"Active\",\n\t\t\t\tconnectionKind: input.connectionKind,\n\t\t\t\tcreatedAt: now,\n\t\t\t\tlastRefreshedAt: now,\n\t\t\t\tlastUsedAt: null,\n\t\t\t\tisDefault: false,\n\t\t\t\tgrantedScopes: input.scopes,\n\t\t\t\tcredentialKeys: input.apiKey ? [keyName] : void 0,\n\t\t\t\tkeyPreviews: input.apiKey ? { [keyName]: maskSecretPreview(input.apiKey) } : void 0,\n\t\t\t\townerUserId: \"user_blake_rouse\",\n\t\t\t\townerName: \"Blake Rouse\"\n\t\t\t};\n\t\t\tconst created = [\n\t\t\t\t...input.projectIds.map((projectId) => ({\n\t\t\t\t\t...base,\n\t\t\t\t\tid: `cred-${input.appId}-${projectId}-${Date.now().toString(36)}`,\n\t\t\t\t\tlabel: `${app?.name ?? input.appId} project credential`,\n\t\t\t\t\tscope: \"project\",\n\t\t\t\t\tprojectId\n\t\t\t\t})),\n\t\t\t\t...input.createOrganizationCredential ? [{\n\t\t\t\t\t...base,\n\t\t\t\t\tid: `cred-${input.appId}-org-${Date.now().toString(36)}`,\n\t\t\t\t\tlabel: `${app?.name ?? input.appId} organization credential`,\n\t\t\t\t\tscope: \"organization\"\n\t\t\t\t}] : [],\n\t\t\t\t...input.createUserProvidedCredential ? [{\n\t\t\t\t\t...base,\n\t\t\t\t\tid: `cred-${input.appId}-user-${Date.now().toString(36)}`,\n\t\t\t\t\tlabel: `${app?.name ?? input.appId} personal credential`,\n\t\t\t\t\tscope: \"user\"\n\t\t\t\t}] : []\n\t\t\t];\n\t\t\tcredentialRecords = [...created, ...credentialRecords];\n\t\t\treturn created;\n\t\t}),\n\t\tupdate: mock({\n\t\t\tdomain: \"credentials\",\n\t\t\tmethod: \"update\",\n\t\t\tplannedEndpoint: \"PATCH /api/credentials/:id\"\n\t\t}, async (credentialId, patch) => {\n\t\t\tconst target = credentialRecords.find((credential) => credential.id === credentialId);\n\t\t\tif (!target) return null;\n\t\t\tconst settingDefault = patch.isDefault === true;\n\t\t\tcredentialRecords = credentialRecords.map((credential) => {\n\t\t\t\tif (credential.id === credentialId) return {\n\t\t\t\t\t...credential,\n\t\t\t\t\t...patch.label !== void 0 ? { label: patch.label } : {},\n\t\t\t\t\t...patch.isDefault !== void 0 ? { isDefault: patch.isDefault } : {}\n\t\t\t\t};\n\t\t\t\tif (settingDefault && credential.appId === target.appId && credential.scope === target.scope) return {\n\t\t\t\t\t...credential,\n\t\t\t\t\tisDefault: false\n\t\t\t\t};\n\t\t\t\treturn credential;\n\t\t\t});\n\t\t\treturn credentialRecords.find((credential) => credential.id === credentialId) ?? null;\n\t\t})\n\t};\n}\n/** Masked preview of a secret — last 4 chars revealed, the rest masked. */\nfunction maskSecretPreview(value) {\n\tconst trimmed = value.trim();\n\tif (trimmed.length <= 4) return \"•\".repeat(Math.max(trimmed.length, 4));\n\treturn `${\"•\".repeat(Math.min(trimmed.length - 4, 20))}${trimmed.slice(-4)}`;\n}\nconst projectMembersStore = /* @__PURE__ */ new Map();\nfunction getProjectMembers(projectId) {\n\tlet members = projectMembersStore.get(projectId);\n\tif (!members) {\n\t\tmembers = projectMemberSeed.map((member) => ({\n\t\t\t...member,\n\t\t\tprojectId\n\t\t}));\n\t\tprojectMembersStore.set(projectId, members);\n\t}\n\treturn members;\n}\n/** Derive a best-effort display name from an email local part. */\nfunction displayNameFromEmail(email) {\n\treturn (email.split(\"@\")[0] ?? email).split(/[._-]+/).filter((part) => part.length > 0).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(\" \");\n}\nfunction createMembersResource(http) {\n\treturn {\n\t\t...createMembersResource$1(http),\n\t\tlistForProject: mock({\n\t\t\tdomain: \"members\",\n\t\t\tmethod: \"listForProject\",\n\t\t\tplannedEndpoint: \"GET /api/projects/:id/members\"\n\t\t}, async (projectId) => [...getProjectMembers(projectId)]),\n\t\tinviteToProject: mock({\n\t\t\tdomain: \"members\",\n\t\t\tmethod: \"inviteToProject\",\n\t\t\tplannedEndpoint: \"POST /api/projects/:id/members/invitations\"\n\t\t}, async (input) => {\n\t\t\tconst members = getProjectMembers(input.projectId);\n\t\t\tconst pendingOrgEmails = new Set((input.pendingOrgEmails ?? []).map((email) => email.toLowerCase()));\n\t\t\tconst seen = new Set(members.map((member) => member.email.toLowerCase()));\n\t\t\tconst invited = [];\n\t\t\tinput.emails.forEach((email, index) => {\n\t\t\t\tconst key = email.toLowerCase();\n\t\t\t\tif (seen.has(key)) return;\n\t\t\t\tseen.add(key);\n\t\t\t\tinvited.push({\n\t\t\t\t\tid: `project-member-invite-${Date.now().toString(36)}-${index}`,\n\t\t\t\t\tprojectId: input.projectId,\n\t\t\t\t\tname: displayNameFromEmail(email),\n\t\t\t\t\temail,\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: pendingOrgEmails.has(key) ? \"invited\" : \"active\",\n\t\t\t\t\tjoinedAt: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\t\t\tlastActiveAt: null\n\t\t\t\t});\n\t\t\t});\n\t\t\tif (invited.length > 0) projectMembersStore.set(input.projectId, [...members, ...invited]);\n\t\t\treturn { invited };\n\t\t})\n\t};\n}\nlet apiKeyRecords = [...apiKeySeed];\nfunction createApiKeysResource() {\n\treturn {\n\t\tlist: mock({\n\t\t\tdomain: \"apiKeys\",\n\t\t\tmethod: \"list\",\n\t\t\tplannedEndpoint: \"GET /api/api-keys\"\n\t\t}, async () => apiKeyRecords),\n\t\tcreate: mock({\n\t\t\tdomain: \"apiKeys\",\n\t\t\tmethod: \"create\",\n\t\t\tplannedEndpoint: \"POST /api/api-keys\"\n\t\t}, async (input) => {\n\t\t\tconst { secret, keyPreview } = createMockApiKeySecret();\n\t\t\tconst created = {\n\t\t\t\tid: `api-key-${Date.now().toString(36)}`,\n\t\t\t\tname: input.name,\n\t\t\t\tkeyPreview,\n\t\t\t\tcreatedAt: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\t\tcreatedBy: mockPersonaSeed[0],\n\t\t\t\tisCreatedByCurrentUser: true\n\t\t\t};\n\t\t\tapiKeyRecords = [created, ...apiKeyRecords];\n\t\t\treturn {\n\t\t\t\t...created,\n\t\t\t\tsecret\n\t\t\t};\n\t\t}),\n\t\trevoke: mock({\n\t\t\tdomain: \"apiKeys\",\n\t\t\tmethod: \"revoke\",\n\t\t\tplannedEndpoint: \"DELETE /api/api-keys/:id\"\n\t\t}, async (apiKeyId) => {\n\t\t\tapiKeyRecords = apiKeyRecords.filter((apiKey) => apiKey.id !== apiKeyId);\n\t\t})\n\t};\n}\n//#endregion\n//#region src/platform/resources/history.ts\nfunction createHistoryResource(http) {\n\treturn {\n\t\t/** Runs across projects the current user can access in the active org. */\n\t\tasync list(filters) {\n\t\t\ttry {\n\t\t\t\tconst parsedFilters = filters ? HistoryRunListQuerySchema.parse(filters) : void 0;\n\t\t\t\tconst searchParams = new URLSearchParams();\n\t\t\t\tif (parsedFilters?.project) searchParams.set(\"project\", parsedFilters.project);\n\t\t\t\tif (parsedFilters?.status) searchParams.set(\"status\", parsedFilters.status);\n\t\t\t\tif (parsedFilters?.kind) searchParams.set(\"kind\", parsedFilters.kind);\n\t\t\t\tconst query = searchParams.toString();\n\t\t\t\tconst data = await http.get(query ? `api/history?${query}` : \"api/history\").json();\n\t\t\t\treturn HistoryRunListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(runId) {\n\t\t\ttry {\n\t\t\t\tconst response = await http.get(`api/history/${encodeURIComponent(runId)}`);\n\t\t\t\tif (response.status === 404) return null;\n\t\t\t\tconst data = await response.json();\n\t\t\t\treturn HistoryRunDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync cancel(runId) {\n\t\t\ttry {\n\t\t\t\tconst response = await http.post(`api/history/${encodeURIComponent(runId)}/cancel`);\n\t\t\t\tif (response.status === 404) return null;\n\t\t\t\tconst data = await response.json();\n\t\t\t\treturn HistoryRunCancelResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/presign-upload.ts\nasync function presignPutAndFinalize(input) {\n\tconst contentType = input.file.type?.trim() || \"application/octet-stream\";\n\tconst uploadFailedMessage = input.uploadFailedMessage ?? \"Upload failed\";\n\ttry {\n\t\tconst { uploadUrl, storageKey } = await input.presign(contentType);\n\t\tif (!(await fetch(uploadUrl, {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: input.file,\n\t\t\theaders: { \"Content-Type\": contentType }\n\t\t})).ok) throw new Error(uploadFailedMessage);\n\t\treturn await input.finalize(storageKey);\n\t} catch (error) {\n\t\tif (error instanceof Error && error.message === uploadFailedMessage) throw error;\n\t\tthrow await input.toPlatformError(error);\n\t}\n}\n//#endregion\n//#region src/platform/resources/organization-sidebar-branding.ts\nfunction createOrganizationSidebarBrandingResource(http, options = {}) {\n\tfunction brandingPath() {\n\t\tconst organizationId = options.getActiveOrganizationId?.();\n\t\tif (!organizationId) throw new Error(\"No active organization\");\n\t\treturn `/api/organizations/${organizationId}/branding`;\n\t}\n\tasync function presignLogoUpload(variant, contentType) {\n\t\tconst body = PresignOrgLogoRequestSchema.parse({\n\t\t\tvariant,\n\t\t\tcontentType\n\t\t});\n\t\tconst data = await http.post(`${brandingPath()}/logo/presign`, { json: body }).json();\n\t\treturn PresignOrgLogoResponseSchema.parse(data);\n\t}\n\treturn {\n\t\tasync get() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(brandingPath()).json();\n\t\t\t\treturn OrganizationSidebarBrandingSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync uploadLogo(file, variant) {\n\t\t\tconst storageKeyField = variant === \"light\" ? \"logoLightStorageKey\" : \"logoDarkStorageKey\";\n\t\t\treturn presignPutAndFinalize({\n\t\t\t\tfile,\n\t\t\t\tpresign: (contentType) => presignLogoUpload(variant, contentType),\n\t\t\t\tfinalize: (storageKey) => this.update({\n\t\t\t\t\t[storageKeyField]: storageKey,\n\t\t\t\t\tcustomLogoEnabled: true,\n\t\t\t\t\tcustomLogoExplicitlyDisabled: false\n\t\t\t\t}),\n\t\t\t\tuploadFailedMessage: \"Logo upload failed\",\n\t\t\t\ttoPlatformError\n\t\t\t});\n\t\t},\n\t\tasync removeLogo(variant) {\n\t\t\tconst storageKeyField = variant === \"light\" ? \"logoLightStorageKey\" : \"logoDarkStorageKey\";\n\t\t\treturn this.update({ [storageKeyField]: null });\n\t\t},\n\t\tasync update(patch) {\n\t\t\tconst body = OrganizationSidebarBrandingPatchSchema.parse(patch);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(brandingPath(), { json: body }).json();\n\t\t\t\treturn OrganizationSidebarBrandingSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/user-preferences.ts\nconst USER_PREFERENCES_PATH = \"/api/users/me/preferences\";\nfunction createUserPreferencesResource(http) {\n\treturn {\n\t\tasync get() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(USER_PREFERENCES_PATH).json();\n\t\t\t\treturn UserPreferencesSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync update(patch) {\n\t\t\tconst body = UserPreferencesPatchSchema.parse(patch);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(USER_PREFERENCES_PATH, { json: body }).json();\n\t\t\t\treturn UserPreferencesSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/user-avatar.ts\nconst DEFAULT_USER_AVATAR = { url: null };\nfunction createUserAvatarResource(http) {\n\tasync function presignUpload(contentType) {\n\t\tconst body = PresignUserAvatarRequestSchema.parse({ contentType });\n\t\tconst data = await http.post(\"/api/users/me/avatar/presign\", { json: body }).json();\n\t\treturn PresignUserAvatarResponseSchema.parse(data);\n\t}\n\treturn {\n\t\tasync get() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/users/me/avatar\").json();\n\t\t\t\treturn UserAvatarSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync upload(file) {\n\t\t\treturn presignPutAndFinalize({\n\t\t\t\tfile,\n\t\t\t\tpresign: presignUpload,\n\t\t\t\tfinalize: (storageKey) => this.update({ storageKey }),\n\t\t\t\tuploadFailedMessage: \"Avatar upload failed\",\n\t\t\t\ttoPlatformError\n\t\t\t});\n\t\t},\n\t\tasync remove() {\n\t\t\treturn this.update({ storageKey: null });\n\t\t},\n\t\tasync update(patch) {\n\t\t\tconst body = UserAvatarPatchSchema.parse(patch);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(\"/api/users/me/avatar\", { json: body }).json();\n\t\t\t\treturn UserAvatarSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/mock-channels.ts\nconst CHANNEL_PLATFORMS = [\n\t{\n\t\tkey: \"slack\",\n\t\tname: \"Slack\",\n\t\tappLogoId: \"slack\",\n\t\tfallbackDomain: \"slack.com\",\n\t\tdescription: \"Connect a Slack workspace so this agent can respond in channels, threads, and DMs.\",\n\t\ttagline: \"Respond in channels, threads, and DMs.\",\n\t\tauthKind: \"oauth\",\n\t\tcredentialFields: [],\n\t\tcapabilities: {\n\t\t\tmentions: true,\n\t\t\treactions: \"full\",\n\t\t\tcards: \"full\",\n\t\t\tmodals: true,\n\t\t\tstreaming: \"native\",\n\t\t\tdms: true\n\t\t},\n\t\tsupportedModes: [\n\t\t\t\"mention\",\n\t\t\t\"all\",\n\t\t\t\"dm\"\n\t\t],\n\t\tresourceNoun: {\n\t\t\tsingular: \"channel\",\n\t\t\tplural: \"channels\"\n\t\t},\n\t\twebhookPathHint: \"/gateways/slack\",\n\t\tsupportsChannelDirectory: true,\n\t\tdocsUrl: \"https://chat-sdk.dev/adapters/official/slack\"\n\t},\n\t{\n\t\tkey: \"discord\",\n\t\tname: \"Discord\",\n\t\tappLogoId: \"discord\",\n\t\tfallbackDomain: \"discord.com\",\n\t\tdescription: \"Connect a Discord application so this agent can respond in servers and channels.\",\n\t\ttagline: \"Respond in servers and channels.\",\n\t\tauthKind: \"credentials\",\n\t\tcredentialFields: [\n\t\t\t{\n\t\t\t\tkey: \"botToken\",\n\t\t\t\tlabel: \"Bot token\",\n\t\t\t\tplaceholder: \"Bot token from the Discord developer portal\",\n\t\t\t\thelpText: \"Bot → Reset Token. Shown only once.\",\n\t\t\t\ttype: \"password\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\t{\n\t\t\t\tkey: \"applicationId\",\n\t\t\t\tlabel: \"Application ID\",\n\t\t\t\tplaceholder: \"Application ID\",\n\t\t\t\ttype: \"text\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\t{\n\t\t\t\tkey: \"publicKey\",\n\t\t\t\tlabel: \"Public key\",\n\t\t\t\tplaceholder: \"Public key\",\n\t\t\t\thelpText: \"General Information → Public Key, used to verify interactions.\",\n\t\t\t\ttype: \"text\",\n\t\t\t\trequired: true\n\t\t\t}\n\t\t],\n\t\tcapabilities: {\n\t\t\tmentions: true,\n\t\t\treactions: \"full\",\n\t\t\tcards: \"full\",\n\t\t\tmodals: false,\n\t\t\tstreaming: \"post-edit\",\n\t\t\tdms: true\n\t\t},\n\t\tsupportedModes: [\n\t\t\t\"mention\",\n\t\t\t\"all\",\n\t\t\t\"dm\"\n\t\t],\n\t\tresourceNoun: {\n\t\t\tsingular: \"channel\",\n\t\t\tplural: \"channels\"\n\t\t},\n\t\twebhookPathHint: \"/gateways/discord\",\n\t\tsupportsChannelDirectory: true,\n\t\tdocsUrl: \"https://chat-sdk.dev/adapters/official/discord\"\n\t},\n\t{\n\t\tkey: \"telegram\",\n\t\tname: \"Telegram\",\n\t\tappLogoId: \"telegram\",\n\t\tfallbackDomain: \"telegram.org\",\n\t\tdescription: \"Connect a Telegram bot so this agent can respond in chats and groups.\",\n\t\ttagline: \"Respond in chats and groups.\",\n\t\tauthKind: \"bot-token\",\n\t\tcredentialFields: [{\n\t\t\tkey: \"botToken\",\n\t\t\tlabel: \"Bot token\",\n\t\t\tplaceholder: \"123456:ABC-DEF…\",\n\t\t\thelpText: \"Create a bot with @BotFather and paste its token.\",\n\t\t\ttype: \"password\",\n\t\t\trequired: true\n\t\t}, {\n\t\t\tkey: \"botUsername\",\n\t\t\tlabel: \"Bot username\",\n\t\t\tplaceholder: \"my_agent_bot\",\n\t\t\ttype: \"text\",\n\t\t\trequired: false,\n\t\t\tprefix: \"@\"\n\t\t}],\n\t\tcapabilities: {\n\t\t\tmentions: true,\n\t\t\treactions: \"full\",\n\t\t\tcards: \"partial\",\n\t\t\tmodals: false,\n\t\t\tstreaming: \"drafts\",\n\t\t\tdms: true\n\t\t},\n\t\tsupportedModes: [\n\t\t\t\"mention\",\n\t\t\t\"all\",\n\t\t\t\"dm\"\n\t\t],\n\t\tresourceNoun: {\n\t\t\tsingular: \"chat\",\n\t\t\tplural: \"chats\"\n\t\t},\n\t\twebhookPathHint: \"/gateways/telegram\",\n\t\tsupportsChannelDirectory: false,\n\t\tdocsUrl: \"https://chat-sdk.dev/adapters/official/telegram\"\n\t},\n\t{\n\t\tkey: \"microsoft-teams\",\n\t\tname: \"Microsoft Teams\",\n\t\tappLogoId: \"microsoft-teams\",\n\t\tfallbackDomain: \"teams.microsoft.com\",\n\t\tdescription: \"Connect a Microsoft Teams app so this agent can respond in channels and chats.\",\n\t\ttagline: \"Respond in channels and chats.\",\n\t\tauthKind: \"credentials\",\n\t\tcredentialFields: [\n\t\t\t{\n\t\t\t\tkey: \"appId\",\n\t\t\t\tlabel: \"App ID\",\n\t\t\t\tplaceholder: \"Azure AD application (client) ID\",\n\t\t\t\ttype: \"text\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\t{\n\t\t\t\tkey: \"appPassword\",\n\t\t\t\tlabel: \"App password\",\n\t\t\t\tplaceholder: \"Client secret\",\n\t\t\t\ttype: \"password\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\t{\n\t\t\t\tkey: \"tenantId\",\n\t\t\t\tlabel: \"Tenant ID\",\n\t\t\t\tplaceholder: \"Azure AD tenant ID\",\n\t\t\t\ttype: \"text\",\n\t\t\t\trequired: true\n\t\t\t}\n\t\t],\n\t\tcapabilities: {\n\t\t\tmentions: true,\n\t\t\treactions: \"read-only\",\n\t\t\tcards: \"full\",\n\t\t\tmodals: true,\n\t\t\tstreaming: \"buffered\",\n\t\t\tdms: true\n\t\t},\n\t\tsupportedModes: [\n\t\t\t\"mention\",\n\t\t\t\"all\",\n\t\t\t\"dm\"\n\t\t],\n\t\tresourceNoun: {\n\t\t\tsingular: \"channel\",\n\t\t\tplural: \"channels\"\n\t\t},\n\t\twebhookPathHint: \"/gateways/teams\",\n\t\tsupportsChannelDirectory: true,\n\t\tdocsUrl: \"https://chat-sdk.dev/adapters/official/teams\"\n\t},\n\t{\n\t\tkey: \"google-chat\",\n\t\tname: \"Google Chat\",\n\t\tappLogoId: \"google-chat\",\n\t\tfallbackDomain: \"chat.google.com\",\n\t\tdescription: \"Connect a Google Chat app so this agent can respond in spaces and direct messages.\",\n\t\ttagline: \"Respond in spaces and DMs.\",\n\t\tauthKind: \"credentials\",\n\t\tcredentialFields: [{\n\t\t\tkey: \"serviceAccountJson\",\n\t\t\tlabel: \"Service account JSON\",\n\t\t\tplaceholder: \"Paste the service account key JSON\",\n\t\t\thelpText: \"IAM → Service Accounts → Keys → Add key → JSON.\",\n\t\t\ttype: \"textarea\",\n\t\t\trequired: true\n\t\t}, {\n\t\t\tkey: \"projectNumber\",\n\t\t\tlabel: \"GCP project number\",\n\t\t\tplaceholder: \"Project number used to verify webhooks\",\n\t\t\ttype: \"text\",\n\t\t\trequired: true\n\t\t}],\n\t\tcapabilities: {\n\t\t\tmentions: true,\n\t\t\treactions: \"full\",\n\t\t\tcards: \"full\",\n\t\t\tmodals: false,\n\t\t\tstreaming: \"post-edit\",\n\t\t\tdms: true\n\t\t},\n\t\tsupportedModes: [\n\t\t\t\"mention\",\n\t\t\t\"all\",\n\t\t\t\"dm\"\n\t\t],\n\t\tresourceNoun: {\n\t\t\tsingular: \"space\",\n\t\t\tplural: \"spaces\"\n\t\t},\n\t\twebhookPathHint: \"/gateways/gchat\",\n\t\tsupportsChannelDirectory: true,\n\t\tdocsUrl: \"https://chat-sdk.dev/adapters/official/google-chat\"\n\t}\n];\nfunction getChannelPlatform(key) {\n\treturn CHANNEL_PLATFORMS.find((platform) => platform.key === key);\n}\nconst CHANNEL_DIRECTORY = {\n\tslack: [\n\t\t{\n\t\t\tid: \"C0SUPPORT\",\n\t\t\tname: \"support\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 48\n\t\t},\n\t\t{\n\t\t\tid: \"C0GENERAL\",\n\t\t\tname: \"general\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 132\n\t\t},\n\t\t{\n\t\t\tid: \"C0ENG\",\n\t\t\tname: \"engineering\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 27\n\t\t},\n\t\t{\n\t\t\tid: \"C0INCIDENTS\",\n\t\t\tname: \"incidents\",\n\t\t\tkind: \"private\",\n\t\t\tmemberCount: 12\n\t\t},\n\t\t{\n\t\t\tid: \"C0RANDOM\",\n\t\t\tname: \"random\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 118\n\t\t},\n\t\t{\n\t\t\tid: \"C0ARCHIVE\",\n\t\t\tname: \"launch-2025\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 9,\n\t\t\tisArchived: true\n\t\t}\n\t],\n\tdiscord: [\n\t\t{\n\t\t\tid: \"d-general\",\n\t\t\tname: \"general\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 540\n\t\t},\n\t\t{\n\t\t\tid: \"d-help\",\n\t\t\tname: \"help\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 312\n\t\t},\n\t\t{\n\t\t\tid: \"d-dev\",\n\t\t\tname: \"dev\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 76\n\t\t},\n\t\t{\n\t\t\tid: \"d-staff\",\n\t\t\tname: \"staff\",\n\t\t\tkind: \"private\",\n\t\t\tmemberCount: 8\n\t\t}\n\t],\n\ttelegram: [],\n\t\"microsoft-teams\": [\n\t\t{\n\t\t\tid: \"t-general\",\n\t\t\tname: \"General\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 64\n\t\t},\n\t\t{\n\t\t\tid: \"t-support\",\n\t\t\tname: \"Customer Support\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 22\n\t\t},\n\t\t{\n\t\t\tid: \"t-leads\",\n\t\t\tname: \"Leadership\",\n\t\t\tkind: \"private\",\n\t\t\tmemberCount: 6\n\t\t}\n\t],\n\t\"google-chat\": [\n\t\t{\n\t\t\tid: \"spaces/AAA-support\",\n\t\t\tname: \"Support\",\n\t\t\tkind: \"space\",\n\t\t\tmemberCount: 31\n\t\t},\n\t\t{\n\t\t\tid: \"spaces/AAA-eng\",\n\t\t\tname: \"Engineering\",\n\t\t\tkind: \"space\",\n\t\t\tmemberCount: 44\n\t\t},\n\t\t{\n\t\t\tid: \"spaces/AAA-ops\",\n\t\t\tname: \"Ops On-call\",\n\t\t\tkind: \"space\",\n\t\t\tmemberCount: 10\n\t\t}\n\t]\n};\nconst MOCK_STORAGE_KEY = \"keystroke:mock-channels:v1\";\nfunction getBrowserLocalStorage() {\n\tif (typeof globalThis !== \"object\") return null;\n\treturn globalThis.localStorage ?? null;\n}\n/** A connected Slack workspace with two bindings, so the panel is reviewable. */\nfunction seedStore() {\n\treturn { \"agent-support\": [{\n\t\tid: \"chan-conn-slack-support\",\n\t\tplatform: \"slack\",\n\t\tagentId: \"agent-support\",\n\t\taccountLabel: \"Keystroke HQ\",\n\t\taccountId: \"T0KEYSTROKE\",\n\t\tconnectedAt: \"2026-05-28T15:30:00Z\",\n\t\tbindings: [{\n\t\t\tid: \"chan-bind-support\",\n\t\t\tchannelId: \"C0SUPPORT\",\n\t\t\tchannelName: \"support\",\n\t\t\tchannelKind: \"public\",\n\t\t\tmode: \"all\",\n\t\t\tsubscribeOnMention: true,\n\t\t\tcreatedAt: \"2026-05-28T15:31:00Z\",\n\t\t\tupdatedAt: \"2026-05-28T15:31:00Z\"\n\t\t}, {\n\t\t\tid: \"chan-bind-incidents\",\n\t\t\tchannelId: \"C0INCIDENTS\",\n\t\t\tchannelName: \"incidents\",\n\t\t\tchannelKind: \"private\",\n\t\t\tmode: \"mention\",\n\t\t\tsubscribeOnMention: true,\n\t\t\tcreatedAt: \"2026-05-29T09:05:00Z\",\n\t\t\tupdatedAt: \"2026-05-29T09:05:00Z\"\n\t\t}]\n\t}] };\n}\nfunction readStore() {\n\tconst localStorage = getBrowserLocalStorage();\n\tif (!localStorage) return seedStore();\n\ttry {\n\t\tconst raw = localStorage.getItem(MOCK_STORAGE_KEY);\n\t\tif (!raw) {\n\t\t\tconst seeded = seedStore();\n\t\t\tlocalStorage.setItem(MOCK_STORAGE_KEY, JSON.stringify(seeded));\n\t\t\treturn seeded;\n\t\t}\n\t\tconst parsed = JSON.parse(raw);\n\t\tif (!parsed || typeof parsed !== \"object\") return {};\n\t\treturn parsed;\n\t} catch {\n\t\treturn {};\n\t}\n}\nfunction writeStore(store) {\n\tconst localStorage = getBrowserLocalStorage();\n\tif (!localStorage) return;\n\ttry {\n\t\tlocalStorage.setItem(MOCK_STORAGE_KEY, JSON.stringify(store));\n\t} catch {}\n}\nfunction newId(prefix) {\n\tconst cryptoRef = globalThis.crypto;\n\tif (cryptoRef?.randomUUID) return `${prefix}-${cryptoRef.randomUUID()}`;\n\treturn `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n}\nfunction requireAgentId(agentId) {\n\tconst trimmed = agentId.trim();\n\tif (!trimmed) throw new Error(\"Channels require an agent id\");\n\treturn trimmed;\n}\nfunction clone(value) {\n\treturn JSON.parse(JSON.stringify(value));\n}\nfunction defaultAccountLabel(platform) {\n\tconst meta = getChannelPlatform(platform);\n\treturn meta ? `${meta.name} workspace` : platform;\n}\nfunction findConnection(connections, connectionId) {\n\tconst connection = connections.find((entry) => entry.id === connectionId);\n\tif (!connection) throw new Error(`Channel connection not found: ${connectionId}`);\n\treturn connection;\n}\nfunction toBinding(input, now) {\n\treturn {\n\t\tid: newId(\"chan-bind\"),\n\t\tchannelId: input.channelId,\n\t\tchannelName: input.channelName,\n\t\tchannelKind: input.channelKind ?? \"public\",\n\t\tmode: input.mode ?? \"mention\",\n\t\tsubscribeOnMention: input.subscribeOnMention ?? true,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t};\n}\nfunction createChannelsResource() {\n\treturn {\n\t\t/** The supported-platform catalog (static; backend may derive from the adapter registry). */\n\t\tlistPlatforms: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"listPlatforms\",\n\t\t\tplannedEndpoint: \"GET /api/channels/platforms\"\n\t\t}, async () => clone(CHANNEL_PLATFORMS)),\n\t\t/** Connections (with their channel bindings) for one agent. */\n\t\tlistForAgent: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"listForAgent\",\n\t\t\tplannedEndpoint: \"GET /api/agents/:agentId/channels\"\n\t\t}, async (agentId) => {\n\t\t\tconst id = requireAgentId(agentId);\n\t\t\treturn clone(readStore()[id] ?? []);\n\t\t}),\n\t\t/**\n\t\t* Channel directory for a platform — the picker source. NET-NEW vs. the\n\t\t* current backend (no channel-list endpoint exists). The runtime team needs\n\t\t* to expose this (e.g. Slack `conversations.list`) for a real picker.\n\t\t*/\n\t\tlistChannels: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"listChannels\",\n\t\t\tplannedEndpoint: \"GET /api/channels/:platform/directory\"\n\t\t}, async (platform) => clone(CHANNEL_DIRECTORY[platform] ?? [])),\n\t\t/** Connect a platform for an agent (OAuth install or credential entry), optionally with a first binding. */\n\t\tconnect: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"connect\",\n\t\t\tplannedEndpoint: \"POST /api/agents/:agentId/channels\"\n\t\t}, async (input) => {\n\t\t\tconst agentId = requireAgentId(input.agentId);\n\t\t\tconst store = readStore();\n\t\t\tconst now = (/* @__PURE__ */ new Date()).toISOString();\n\t\t\tconst connection = {\n\t\t\t\tid: newId(\"chan-conn\"),\n\t\t\t\tplatform: input.platform,\n\t\t\t\tagentId,\n\t\t\t\taccountLabel: input.accountLabel ?? defaultAccountLabel(input.platform),\n\t\t\t\taccountId: newId(\"acct\").toUpperCase(),\n\t\t\t\tconnectedAt: now,\n\t\t\t\tbindings: input.initialBinding ? [toBinding(input.initialBinding, now)] : []\n\t\t\t};\n\t\t\twriteStore({\n\t\t\t\t...store,\n\t\t\t\t[agentId]: [...store[agentId] ?? [], connection]\n\t\t\t});\n\t\t\treturn clone(connection);\n\t\t}),\n\t\t/** Add a channel binding to an existing connection. */\n\t\taddBinding: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"addBinding\",\n\t\t\tplannedEndpoint: \"PUT /gateways/:platform/attachments/:channelId\"\n\t\t}, async (input) => {\n\t\t\tconst agentId = requireAgentId(input.agentId);\n\t\t\tconst store = readStore();\n\t\t\tconst connections = store[agentId] ?? [];\n\t\t\tconst connection = findConnection(connections, input.connectionId);\n\t\t\tconst now = (/* @__PURE__ */ new Date()).toISOString();\n\t\t\tconnection.bindings = [...connection.bindings, toBinding(input.binding, now)];\n\t\t\twriteStore({\n\t\t\t\t...store,\n\t\t\t\t[agentId]: connections\n\t\t\t});\n\t\t\treturn clone(connection);\n\t\t}),\n\t\t/** Update a binding's listen mode / subscribe flag. */\n\t\tupdateBinding: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"updateBinding\",\n\t\t\tplannedEndpoint: \"PUT /gateways/:platform/attachments/:channelId\"\n\t\t}, async (input) => {\n\t\t\tconst agentId = requireAgentId(input.agentId);\n\t\t\tconst store = readStore();\n\t\t\tconst connections = store[agentId] ?? [];\n\t\t\tconst connection = findConnection(connections, input.connectionId);\n\t\t\tconst binding = connection.bindings.find((entry) => entry.id === input.bindingId);\n\t\t\tif (!binding) throw new Error(`Channel binding not found: ${input.bindingId}`);\n\t\t\tif (input.patch.mode !== void 0) binding.mode = input.patch.mode;\n\t\t\tif (input.patch.subscribeOnMention !== void 0) binding.subscribeOnMention = input.patch.subscribeOnMention;\n\t\t\tbinding.updatedAt = (/* @__PURE__ */ new Date()).toISOString();\n\t\t\twriteStore({\n\t\t\t\t...store,\n\t\t\t\t[agentId]: connections\n\t\t\t});\n\t\t\treturn clone(connection);\n\t\t}),\n\t\t/** Remove a channel binding. */\n\t\tremoveBinding: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"removeBinding\",\n\t\t\tplannedEndpoint: \"DELETE /gateways/:platform/attachments/:channelId\"\n\t\t}, async (input) => {\n\t\t\tconst agentId = requireAgentId(input.agentId);\n\t\t\tconst store = readStore();\n\t\t\tconst connections = store[agentId] ?? [];\n\t\t\tconst connection = findConnection(connections, input.connectionId);\n\t\t\tconnection.bindings = connection.bindings.filter((entry) => entry.id !== input.bindingId);\n\t\t\twriteStore({\n\t\t\t\t...store,\n\t\t\t\t[agentId]: connections\n\t\t\t});\n\t\t\treturn clone(connection);\n\t\t}),\n\t\t/** Disconnect the agent from a platform (removes the connection + its bindings). */\n\t\tdisconnect: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"disconnect\",\n\t\t\tplannedEndpoint: \"DELETE /api/agents/:agentId/channels/:connectionId\"\n\t\t}, async (input) => {\n\t\t\tconst agentId = requireAgentId(input.agentId);\n\t\t\tconst store = readStore();\n\t\t\tconst next = (store[agentId] ?? []).filter((entry) => entry.id !== input.connectionId);\n\t\t\twriteStore({\n\t\t\t\t...store,\n\t\t\t\t[agentId]: next\n\t\t\t});\n\t\t})\n\t};\n}\n//#endregion\n//#region src/platform/index.ts\nconst JWT_RETRY_HEADER = \"x-keystroke-jwt-retry\";\nfunction createPlatformClient(options) {\n\tconst auth = options.auth ?? { type: \"none\" };\n\tconst base = normalizeBaseUrl(options.baseUrl);\n\tlet activeOrganizationId = options.getActiveOrganizationId?.() ?? null;\n\tconst setActiveOrganizationId = (organizationId) => {\n\t\tactiveOrganizationId = organizationId;\n\t\toptions.onActiveOrganizationChange?.(organizationId);\n\t};\n\tconst http = ky.create({\n\t\tprefix: base === \"\" ? void 0 : `${base}/`,\n\t\tcredentials: \"omit\",\n\t\thooks: {\n\t\t\tbeforeRequest: [({ request }) => {\n\t\t\t\tapplyActiveOrganizationHeader(request, activeOrganizationId);\n\t\t\t\treturn applyAuthHeaders(request, auth);\n\t\t\t}],\n\t\t\tafterResponse: [async ({ request, response, retryCount }) => {\n\t\t\t\tif (response.status !== 401 || auth.type !== \"bearer\" || !options.refreshBearerToken || retryCount > 0 || request.headers.get(JWT_RETRY_HEADER) === \"1\") return;\n\t\t\t\tconst refreshed = await options.refreshBearerToken();\n\t\t\t\tif (!refreshed) return;\n\t\t\t\tconst retryHeaders = new Headers(request.headers);\n\t\t\t\tretryHeaders.set(\"Authorization\", `Bearer ${refreshed}`);\n\t\t\t\tretryHeaders.set(JWT_RETRY_HEADER, \"1\");\n\t\t\t\treturn ky.retry({\n\t\t\t\t\trequest: new Request(request, { headers: retryHeaders }),\n\t\t\t\t\tcode: \"JWT_REFRESHED\"\n\t\t\t\t});\n\t\t\t}]\n\t\t},\n\t\t...options.ky\n\t});\n\treturn {\n\t\thttp,\n\t\thealth: createHealthResource(http),\n\t\torganizations: createOrganizationsResource(http, {\n\t\t\tonActiveOrganizationChange: setActiveOrganizationId,\n\t\t\tgetActiveOrganizationId: () => activeOrganizationId\n\t\t}),\n\t\tprojects: createProjectsResource(http),\n\t\tartifacts: createArtifactsResource(http),\n\t\tprojectSettings: createProjectSettingsResource(),\n\t\tagents: createAgentsResource(http),\n\t\tworkflows: createWorkflowsResource(http),\n\t\tskills: createSkillsResource(http),\n\t\tapps: createAppsResource(),\n\t\tcredentials: createCredentialsResource(),\n\t\thistory: createHistoryResource(http),\n\t\tdeployments: createDeploymentsResource(http),\n\t\tgatewayAttachments: createGatewayAttachmentsResource(http),\n\t\tprojectMetrics: createProjectMetricsResource(http),\n\t\tprojectFiles: createProjectFilesResource(http),\n\t\tchannels: createChannelsResource(),\n\t\tmembers: createMembersResource(http),\n\t\tinvitations: createInvitationsResource(http),\n\t\tapiKeys: createApiKeysResource(),\n\t\trecents: createRecentsResource(http),\n\t\tuserPreferences: createUserPreferencesResource(http),\n\t\tuserAvatar: createUserAvatarResource(http),\n\t\torganizationSidebarBranding: createOrganizationSidebarBrandingResource(http, { getActiveOrganizationId: () => activeOrganizationId }),\n\t\tgetActiveOrganizationId: () => activeOrganizationId,\n\t\tsetActiveOrganizationId\n\t};\n}\n/** Browser client for apps using JWT bearer auth minted from Better Auth sessions. */\nfunction createBrowserPlatformClient(options) {\n\treturn createPlatformClient({\n\t\t...options,\n\t\tbaseUrl: options.baseUrl ?? \"\",\n\t\tauth: browserAuthStrategy(options.getToken),\n\t\trefreshBearerToken: options.refreshBearerToken,\n\t\tgetActiveOrganizationId: readActiveOrganizationId,\n\t\tonActiveOrganizationChange: writeActiveOrganizationId\n\t});\n}\n//#endregion\nexport { CHANNEL_PLATFORMS, DEFAULT_ORGANIZATION_SIDEBAR_BRANDING, DEFAULT_PROJECT_SETTINGS, DEFAULT_USER_AVATAR, DEFAULT_USER_PREFERENCES, PlatformError, browserAuthStrategy, createBrowserPlatformClient, createPlatformClient, getChannelPlatform, mergeOrganizationSidebarBranding, mergeProjectSettings, mergeUserPreferences, mockManifest, normalizeBaseUrl, normalizeOrganizationSidebarBranding, normalizeProjectSettings, normalizeUserPreferences, readActiveOrganizationId, toPlatformError, writeActiveOrganizationId };\n\n//# sourceMappingURL=index.mjs.map","import {\n createPlatformClient,\n type AuthStrategy as PlatformAuthStrategy,\n type PlatformClient,\n} from \"@keystrokehq/sdk/platform\";\nimport type { AuthStrategy as CliAuthStrategy } from \"@keystrokehq/sdk\";\nimport type Conf from \"conf\";\n\nimport { resolveCliAuth } from \"./auth/resolve-cli-auth\";\nimport { getCliJwt } from \"./auth/jwt-cache\";\nimport { getPlatformUrl, type CliConfig } from \"./config\";\n\nfunction toPlatformAuth(auth: CliAuthStrategy): PlatformAuthStrategy {\n if (auth.type === \"bearer\") {\n return auth;\n }\n\n if (auth.type === \"apiKey\") {\n return {\n type: \"bearer\",\n getToken: async () => auth.getKey(),\n };\n }\n\n return { type: \"none\" };\n}\n\nexport function createCliPlatformClient(config: Conf<CliConfig>): PlatformClient {\n const platformUrl = getPlatformUrl(config);\n return createPlatformClient({\n baseUrl: platformUrl,\n auth: toPlatformAuth(resolveCliAuth(config)),\n refreshBearerToken: () => getCliJwt(platformUrl, true),\n getActiveOrganizationId: () => config.get(\"activeOrganizationId\") ?? null,\n onActiveOrganizationChange: (organizationId) => {\n if (organizationId) {\n config.set(\"activeOrganizationId\", organizationId);\n } else {\n config.delete(\"activeOrganizationId\");\n }\n },\n });\n}\n","import type { PlatformClient } from \"@keystrokehq/sdk/platform\";\nimport { PlatformError } from \"@keystrokehq/sdk/platform\";\nimport type { Project, UserOrganization } from \"@keystrokehq/shared\";\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport function looksLikeUuid(value: string): boolean {\n return UUID_PATTERN.test(value);\n}\n\nexport function formatProjectLabel(project: Pick<Project, \"slug\">): string {\n return project.slug;\n}\n\nexport async function resolveProjectRef(platform: PlatformClient, ref: string): Promise<Project> {\n if (looksLikeUuid(ref)) {\n try {\n return await platform.projects.get(ref);\n } catch (error) {\n if (error instanceof PlatformError && error.status === 404) {\n throw new Error(\n `Project ${ref} not found in the active organization. Run \\`keystroke project list\\`, then \\`keystroke config use project <slug>\\`.`,\n );\n }\n throw error;\n }\n }\n\n const projects = await platform.projects.list();\n const match = projects.find((project) => project.slug === ref);\n if (!match) {\n throw new Error(\n `Project \"${ref}\" not found in the active organization. Run \\`keystroke project list\\`.`,\n );\n }\n\n return match;\n}\n\nexport function resolveOrganizationRef(\n organizations: UserOrganization[],\n ref: string,\n): UserOrganization {\n const byId = organizations.find((entry) => entry.organization.id === ref);\n if (byId) {\n return byId;\n }\n\n const bySlug = organizations.find((entry) => entry.organization.slug === ref);\n if (bySlug) {\n return bySlug;\n }\n\n throw new Error(`Organization \"${ref}\" was not found or you do not have access`);\n}\n","import { select } from \"@inquirer/prompts\";\nimport type Conf from \"conf\";\nimport type { UserOrganization } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"../config\";\nimport { getWebUrl } from \"../config\";\nimport { createCliPlatformClient } from \"../platform-client\";\nimport { resolveOrganizationRef } from \"../resolve-resource-ref\";\n\nexport type ActivateOrganizationOptions = {\n organizationId?: string;\n organizationRef?: string;\n /** Organization active in the browser when device auth was approved. */\n deviceOrganizationId?: string;\n /** Last active organization stored in CLI config. */\n storedOrganizationId?: string;\n};\n\nfunction formatOrganization(membership: UserOrganization): string {\n return `${membership.organization.name} (${membership.role})`;\n}\n\nexport async function listOrganizations(config: Conf<CliConfig>): Promise<UserOrganization[]> {\n const platform = createCliPlatformClient(config);\n return platform.organizations.list();\n}\n\nexport async function activateOrganization(\n config: Conf<CliConfig>,\n organizationId: string,\n): Promise<UserOrganization> {\n const platform = createCliPlatformClient(config);\n const membership = await platform.organizations.setActive({ organizationId });\n platform.setActiveOrganizationId(membership.organization.id);\n return membership;\n}\n\nexport function resolveOrganizationIdForLogin(\n organizations: UserOrganization[],\n options: ActivateOrganizationOptions = {},\n): string {\n if (options.organizationRef ?? options.organizationId) {\n return resolveOrganizationRef(organizations, options.organizationRef ?? options.organizationId!)\n .organization.id;\n }\n\n for (const candidateId of [options.deviceOrganizationId, options.storedOrganizationId]) {\n const organizationId = candidateId?.trim();\n if (organizationId && organizations.some((entry) => entry.organization.id === organizationId)) {\n return organizationId;\n }\n }\n\n if (organizations.length === 1) {\n return organizations[0]!.organization.id;\n }\n\n return [...organizations].sort((left, right) =>\n left.organization.slug.localeCompare(right.organization.slug),\n )[0]!.organization.id;\n}\n\nasync function pickOrganization(\n config: Conf<CliConfig>,\n organizations: UserOrganization[],\n organizationRef?: string,\n): Promise<UserOrganization> {\n if (organizationRef) {\n const membership = resolveOrganizationRef(organizations, organizationRef);\n return activateOrganization(config, membership.organization.id);\n }\n\n if (!process.stdin.isTTY) {\n const names = organizations.map((entry) => entry.organization.slug).join(\", \");\n throw new Error(\n `Multiple organizations found. Run \\`keystroke config use org <slug>\\`. Options: ${names}`,\n );\n }\n\n const selectedId = await select({\n message: \"Select an organization\",\n choices: organizations.map((entry) => ({\n name: formatOrganization(entry),\n value: entry.organization.id,\n })),\n });\n\n return activateOrganization(config, selectedId);\n}\n\nexport async function selectActiveOrganization(\n config: Conf<CliConfig>,\n options: ActivateOrganizationOptions = {},\n): Promise<UserOrganization> {\n const organizations = await listOrganizations(config);\n\n if (organizations.length === 0) {\n throw new Error(`No organization found — create one at ${getWebUrl(config)}`);\n }\n\n if (organizations.length === 1) {\n return activateOrganization(config, organizations[0]!.organization.id);\n }\n\n return pickOrganization(config, organizations, options.organizationRef ?? options.organizationId);\n}\n\nexport async function syncActiveOrganizationAfterLogin(\n config: Conf<CliConfig>,\n options: ActivateOrganizationOptions = {},\n): Promise<UserOrganization> {\n const organizations = await listOrganizations(config);\n\n if (organizations.length === 0) {\n throw new Error(`No organization found — create one at ${getWebUrl(config)}`);\n }\n\n const organizationId = resolveOrganizationIdForLogin(organizations, {\n organizationRef: options.organizationRef,\n organizationId: options.organizationId,\n deviceOrganizationId: options.deviceOrganizationId,\n storedOrganizationId: config.get(\"activeOrganizationId\"),\n });\n\n return activateOrganization(config, organizationId);\n}\n\nexport async function ensureActiveOrganization(config: Conf<CliConfig>): Promise<void> {\n const organizations = await listOrganizations(config);\n\n if (organizations.length === 0) {\n throw new Error(\n \"No organization found. Run `keystroke auth login` after creating one in the dashboard.\",\n );\n }\n\n const storedId = config.get(\"activeOrganizationId\");\n if (storedId && organizations.some((entry) => entry.organization.id === storedId)) {\n await activateOrganization(config, storedId);\n return;\n }\n\n if (organizations.length === 1) {\n await activateOrganization(config, organizations[0]!.organization.id);\n return;\n }\n\n throw new Error(\n \"No active organization. Run `keystroke auth login` or `keystroke config use org`.\",\n );\n}\n","import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nimport { getCliConfigDir } from \"./config\";\n\nexport type DevSession = {\n pid: number;\n port: number;\n root: string;\n serverUrl: string;\n};\n\nexport function getDevSessionPath(configDir = getCliConfigDir()): string {\n return join(configDir, \"dev-session.json\");\n}\n\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function writeDevSession(session: DevSession, configDir = getCliConfigDir()): void {\n const path = getDevSessionPath(configDir);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(session)}\\n`, \"utf8\");\n}\n\nexport function clearDevSession(configDir = getCliConfigDir()): void {\n const path = getDevSessionPath(configDir);\n if (existsSync(path)) {\n unlinkSync(path);\n }\n}\n\nexport function readDevSession(configDir = getCliConfigDir()): DevSession | undefined {\n const path = getDevSessionPath(configDir);\n if (!existsSync(path)) {\n return undefined;\n }\n\n try {\n const session = JSON.parse(readFileSync(path, \"utf8\")) as DevSession;\n if (!isProcessAlive(session.pid)) {\n clearDevSession(configDir);\n return undefined;\n }\n return session;\n } catch {\n clearDevSession(configDir);\n return undefined;\n }\n}\n","import type Conf from \"conf\";\n\nimport {\n getConfigDir,\n getEffectiveApiTarget,\n getPlatformUrl,\n getServerUrl,\n type CliConfig,\n} from \"./config\";\nimport { readDevSession } from \"./dev-session\";\nimport { createCliPlatformClient } from \"./platform-client\";\nimport { formatProjectLabel, resolveProjectRef } from \"./resolve-resource-ref\";\n\nexport type ApiTargetOptions = {\n projectId?: string;\n local?: boolean;\n /** Route to `/api/projects/:id` and require a project id. Default false. */\n projectScoped?: boolean;\n /** Org-level platform API; ignores `--project` and activeProjectId. */\n orgScoped?: boolean;\n};\n\nexport const projectScopedTarget: ApiTargetOptions = { projectScoped: true };\n\nexport type ResolvedApiTarget = {\n baseUrl: string;\n projectId?: string;\n mode: \"local\" | \"platform\";\n};\n\nfunction resolveLocalTarget(config: Conf<CliConfig>): ResolvedApiTarget {\n return {\n baseUrl: getServerUrl(config),\n mode: \"local\",\n };\n}\n\nfunction resolveOrgPlatformTarget(config: Conf<CliConfig>): ResolvedApiTarget {\n return {\n baseUrl: `${getPlatformUrl(config).replace(/\\/+$/, \"\")}/api`,\n mode: \"platform\",\n };\n}\n\nasync function resolvePlatformTarget(\n config: Conf<CliConfig>,\n projectRef: string,\n): Promise<ResolvedApiTarget> {\n const platform = createCliPlatformClient(config);\n let project;\n try {\n project = await resolveProjectRef(platform, projectRef);\n } catch (error) {\n if (error instanceof Error) {\n throw error;\n }\n throw error;\n }\n if (project.status !== \"active\") {\n throw new Error(`Project ${formatProjectLabel(project)} is not active (${project.status})`);\n }\n\n const platformUrl = getPlatformUrl(config).replace(/\\/+$/, \"\");\n return {\n baseUrl: `${platformUrl}/api/projects/${encodeURIComponent(project.id)}`,\n projectId: project.id,\n mode: \"platform\",\n };\n}\n\nexport async function resolveApiTarget(\n config: Conf<CliConfig>,\n options: ApiTargetOptions = {},\n): Promise<ResolvedApiTarget> {\n if (options.local) {\n return resolveLocalTarget(config);\n }\n\n const devSession = readDevSession(getConfigDir(config));\n if (devSession && getEffectiveApiTarget(config) !== \"platform\") {\n return {\n baseUrl: devSession.serverUrl,\n mode: \"local\",\n };\n }\n\n if (options.orgScoped || options.projectScoped === false) {\n if (getEffectiveApiTarget(config) === \"local\") {\n return resolveLocalTarget(config);\n }\n return resolveOrgPlatformTarget(config);\n }\n\n if (options.projectId) {\n return resolvePlatformTarget(config, options.projectId);\n }\n\n if (getEffectiveApiTarget(config) === \"local\") {\n return resolveLocalTarget(config);\n }\n\n if (!options.projectScoped) {\n return resolveOrgPlatformTarget(config);\n }\n\n const projectRef = options.projectId ?? config.get(\"activeProjectId\");\n if (!projectRef) {\n throw new Error(\n \"No project selected. Pass `--project <slug>` or run `keystroke config use project <slug>`.\",\n );\n }\n\n return resolvePlatformTarget(config, projectRef);\n}\n","import type { ApiTargetOptions } from \"./resolve-api-target\";\n\nlet targetOptions: ApiTargetOptions = {};\n\nexport function setCliTargetOptions(options: ApiTargetOptions): void {\n targetOptions = options;\n}\n\nexport function getCliTargetOptions(): ApiTargetOptions {\n return targetOptions;\n}\n","import type { ValidationErrorDetail } from \"@keystrokehq/shared\";\n\nfunction exampleValueFromValidationMessage(message: string): unknown {\n if (/expected number/i.test(message)) {\n return 0;\n }\n if (/expected string/i.test(message)) {\n return \"\";\n }\n if (/expected boolean/i.test(message)) {\n return false;\n }\n if (/expected array/i.test(message)) {\n return [];\n }\n if (/expected object/i.test(message)) {\n return {};\n }\n\n const enumMatch = message.match(/expected one of (.+)/i);\n if (enumMatch) {\n const firstOption = enumMatch[1]?.match(/\"([^\"]+)\"/);\n if (firstOption?.[1]) {\n return firstOption[1];\n }\n }\n\n return null;\n}\n\nfunction setNestedExampleValue(input: Record<string, unknown>, path: string, value: unknown): void {\n const parts = path.split(\".\").filter(Boolean);\n if (parts.length === 0) {\n return;\n }\n\n let current: Record<string, unknown> = input;\n for (let index = 0; index < parts.length - 1; index += 1) {\n const key = parts[index]!;\n const next = current[key];\n if (typeof next !== \"object\" || next === null || Array.isArray(next)) {\n current[key] = {};\n }\n current = current[key] as Record<string, unknown>;\n }\n\n current[parts[parts.length - 1]!] = value;\n}\n\nexport function exampleInputFromValidationDetails(\n details: ValidationErrorDetail[],\n): Record<string, unknown> {\n const input: Record<string, unknown> = {};\n\n for (const detail of details) {\n if (!detail.path) {\n continue;\n }\n setNestedExampleValue(input, detail.path, exampleValueFromValidationMessage(detail.message));\n }\n\n return input;\n}\n","import type { ErrorResponse } from \"@keystrokehq/shared\";\nimport { exampleInputFromValidationDetails } from \"./example-input\";\nimport type { CliUsageHint } from \"./types\";\n\n/** Turn a parsed API error body into terminal output. */\nexport function formatApiErrorMessage(\n response: ErrorResponse,\n fallback: string,\n options?: CliUsageHint,\n): string {\n const summary = response.message ?? response.error ?? fallback;\n\n if (!response.details?.length) {\n return summary;\n }\n\n const lines = response.details.map((detail) => {\n const field = detail.path || \"(root)\";\n return ` • ${field}: ${detail.message}`;\n });\n let message = `${summary}:\\n${lines.join(\"\\n\")}`;\n\n if (options?.usage) {\n const example = JSON.stringify(exampleInputFromValidationDetails(response.details));\n const flag = options.usage.flag ?? \"--input\";\n message += `\\n\\nTry: ${options.usage.command} ${flag} '${example}'`;\n }\n\n return message;\n}\n","import { parseErrorResponse } from \"@keystrokehq/shared\";\nimport { KeystrokeError } from \"@keystrokehq/sdk\";\nimport { PlatformError } from \"@keystrokehq/sdk/platform\";\nimport { getAccessToken } from \"../auth/credentials\";\nimport { resolvePlatformUrlForWebUrl } from \"../resolve-platform-url\";\nimport type { CliErrorContext } from \"./types\";\nimport { formatApiErrorMessage } from \"./format-api-message\";\n\nfunction isUnreachableServerError(error: Error): boolean {\n return (\n error.message.includes(\"network error\") ||\n error.message.includes(\"ECONNREFUSED\") ||\n error.message.includes(\"ENOTFOUND\") ||\n error.message.includes(\"fetch failed\")\n );\n}\n\nfunction unreachableTarget(context?: CliErrorContext): string | undefined {\n return context?.serverUrl ?? context?.webUrl;\n}\n\nfunction unreachableServerMessage(targetUrl?: string): string {\n const target = targetUrl ?? \"the keystroke server\";\n return `Could not reach ${target}. Is the server running? (keystroke dev or keystroke start)`;\n}\n\ntype HttpClientError = {\n status: number;\n body: unknown;\n message: string;\n};\n\nfunction authApiOrigin(context?: CliErrorContext): string | undefined {\n if (context?.platformUrl) {\n return context.platformUrl;\n }\n\n if (context?.webUrl) {\n return resolvePlatformUrlForWebUrl(context.webUrl, {});\n }\n\n return undefined;\n}\n\nfunction formatHttpClientError(error: HttpClientError, context?: CliErrorContext): string {\n if (error.status === 401) {\n const origin = authApiOrigin(context);\n if (origin && !getAccessToken(origin)) {\n return \"Not logged in. Run `keystroke auth login` first.\";\n }\n return \"Authentication failed. Run `keystroke auth login` again.\";\n }\n\n if (error.status === 0) {\n return unreachableServerMessage(unreachableTarget(context));\n }\n\n const parsed = parseErrorResponse(error.body);\n if (parsed) {\n return formatApiErrorMessage(parsed, error.message, context);\n }\n\n return error.message;\n}\n\nexport function formatCliError(\n error: unknown,\n fallback: string,\n context?: CliErrorContext,\n): string {\n if (error instanceof KeystrokeError || error instanceof PlatformError) {\n return formatHttpClientError(error, context);\n }\n\n if (error instanceof Error) {\n if (isUnreachableServerError(error)) {\n return unreachableServerMessage(unreachableTarget(context));\n }\n return error.message;\n }\n\n return fallback;\n}\n","import { createCliClient } from \"../client\";\nimport { createCliConfig, getWebUrl } from \"../config\";\nimport { ensureActiveOrganization } from \"../organization/active-organization\";\nimport {\n projectScopedTarget,\n resolveApiTarget,\n type ApiTargetOptions,\n} from \"../resolve-api-target\";\nimport { getCliTargetOptions } from \"../target-options\";\nimport type { CliContext, CliErrorContext } from \"./types\";\nimport { formatCliError } from \"./format-cli-error\";\n\nexport async function runProjectCliCommand(\n fallback: string,\n fn: (ctx: CliContext) => Promise<void>,\n errorContext?: CliErrorContext,\n targetOptions: ApiTargetOptions = {},\n): Promise<void> {\n return runCliCommand(fallback, fn, errorContext, {\n ...projectScopedTarget,\n ...targetOptions,\n });\n}\n\nexport async function runCliCommand(\n fallback: string,\n fn: (ctx: CliContext) => Promise<void>,\n errorContext?: CliErrorContext,\n targetOptions: ApiTargetOptions = {},\n): Promise<void> {\n const config = createCliConfig();\n const target = await resolveApiTarget(config, {\n ...getCliTargetOptions(),\n ...targetOptions,\n });\n\n if (target.mode === \"platform\") {\n await ensureActiveOrganization(config);\n }\n\n const ctx: CliContext = {\n config,\n client: createCliClient(config, {\n baseUrl: target.baseUrl,\n platform: target.mode === \"platform\",\n }),\n serverUrl: target.baseUrl,\n webUrl: getWebUrl(config),\n apiTarget: target,\n };\n\n try {\n await fn(ctx);\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, fallback, {\n ...errorContext,\n serverUrl: ctx.serverUrl,\n webUrl: ctx.webUrl,\n })}\\n`,\n );\n process.exitCode = 1;\n }\n}\n","/**\n * Binary name to show in help text and \"Try: ...\" hints. Always the published\n * `keystroke`, or the `keystroke-dev` wrapper (which sets KEYSTROKE_DEV) so\n * examples stay copy-pasteable while developing on keystroke itself.\n */\nexport function cliBinaryName(): string {\n return process.env.KEYSTROKE_DEV ? \"keystroke-dev\" : \"keystroke\";\n}\n\n/** Parse a JSON CLI flag; throws a readable error on invalid input. */\nexport function parseJsonOption(value: string, flag: string): unknown {\n try {\n return JSON.parse(value) as unknown;\n } catch {\n throw new Error(`Invalid ${flag} JSON`);\n }\n}\n","import type Conf from \"conf\";\nimport type { PlatformClient } from \"@keystrokehq/sdk/platform\";\nimport type { Project } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"./config\";\nimport { createCliPlatformClient } from \"./platform-client\";\nimport { looksLikeUuid, resolveProjectRef } from \"./resolve-resource-ref\";\nimport { getCliTargetOptions } from \"./target-options\";\n\nexport async function resolveActiveProject(\n config: Conf<CliConfig>,\n platform?: PlatformClient,\n): Promise<Project | undefined> {\n const ref = getCliTargetOptions().projectId ?? config.get(\"activeProjectId\");\n if (!ref) {\n return undefined;\n }\n\n const client = platform ?? createCliPlatformClient(config);\n const fromFlag = getCliTargetOptions().projectId;\n\n if (!fromFlag && looksLikeUuid(ref)) {\n return resolveProjectRef(client, ref);\n }\n\n return resolveProjectRef(client, ref);\n}\n\nexport async function resolveActiveProjectId(config: Conf<CliConfig>): Promise<string | undefined> {\n const project = await resolveActiveProject(config);\n return project?.id;\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../../config\";\nimport { runCliCommand } from \"../../errors\";\nimport { ensureActiveOrganization } from \"../../organization/active-organization\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { resolveActiveProjectId } from \"../../resolve-project-target\";\n\nexport function registerAgentListCommand(agent: Command): void {\n agent\n .command(\"list\")\n .description(\"List agents in the active organization\")\n .action(() =>\n runCliCommand(\n \"List agents failed\",\n async () => {\n const config = createCliConfig();\n const client = createCliPlatformClient(config);\n await ensureActiveOrganization(config);\n const projectId = await resolveActiveProjectId(config);\n const result = await client.agents.list(projectId ? { projectId } : undefined);\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n },\n undefined,\n { orgScoped: true },\n ),\n );\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nexport function registerAgentPromptCommand(agent: Command): void {\n agent\n .command(\"prompt\")\n .description(\"Send a message to an agent (or follow up in an existing session)\")\n .argument(\"<agentId>\", \"Agent key / route id\")\n .requiredOption(\"--message <text>\", \"Message to send\")\n .option(\"--session-id <id>\", \"Existing session id for follow-up\")\n .action((agentId: string, options: { message: string; sessionId?: string }) =>\n runProjectCliCommand(\"Agent prompt failed\", async ({ client }) => {\n const result = await client.agents.prompt(agentId, {\n message: options.message,\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nexport function registerAgentSessionsCommand(agent: Command): void {\n const sessions = agent.command(\"sessions\").description(\"List and inspect agent sessions\");\n\n sessions\n .command(\"list\")\n .description(\"List sessions for an agent\")\n .argument(\"<agentId>\", \"Agent key / route id\")\n .option(\"--limit <n>\", \"Page size (1–100)\", \"20\")\n .option(\"--cursor <cursor>\", \"Pagination cursor from a previous page\")\n .option(\"--status <status>\", \"Filter by status (running, completed, failed)\")\n .option(\"--source <source>\", \"Filter by source (api, gateway)\")\n .action((agentId: string, options: Record<string, string | undefined>) =>\n runProjectCliCommand(\"List agent sessions failed\", async ({ client }) => {\n const result = await client.agents.listSessions(agentId, {\n limit: Number(options.limit),\n ...(options.cursor ? { cursor: options.cursor } : {}),\n ...(options.status\n ? { status: options.status as \"running\" | \"completed\" | \"failed\" }\n : {}),\n ...(options.source ? { source: options.source as \"api\" | \"gateway\" } : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n\n sessions\n .command(\"get\")\n .description(\"Get full details for an agent session\")\n .argument(\"<agentId>\", \"Agent key / route id\")\n .argument(\"<sessionId>\", \"Agent session id\")\n .option(\"--include <parts>\", \"Comma-separated: gateway, messages, events, trace\")\n .action((agentId: string, sessionId: string, options: { include?: string }) =>\n runProjectCliCommand(\"Get agent session failed\", async ({ client }) => {\n const result = await client.agents.getSession(agentId, sessionId, {\n include: options.include,\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { registerAgentListCommand } from \"./list\";\nimport { registerAgentPromptCommand } from \"./prompt\";\nimport { registerAgentSessionsCommand } from \"./sessions\";\n\nexport function registerAgentCommand(program: Command): void {\n const agent = program.command(\"agent\").description(\"Invoke and inspect agents\");\n\n registerAgentListCommand(agent);\n registerAgentPromptCommand(agent);\n registerAgentSessionsCommand(agent);\n}\n","import { spawn } from \"node:child_process\";\n\nexport function openUrl(url: string): void {\n const platform = process.platform;\n const command = platform === \"darwin\" ? \"open\" : platform === \"win32\" ? \"start\" : \"xdg-open\";\n\n spawn(command, [url], {\n detached: true,\n stdio: \"ignore\",\n }).unref();\n}\n","import type { ConnectProvider } from \"@keystrokehq/shared\";\nimport type { KeystrokeClient } from \"@keystrokehq/sdk\";\nimport { openUrl } from \"../../auth/open-url\";\n\nfunction providerLabel(key: string): string {\n return key.charAt(0).toUpperCase() + key.slice(1);\n}\n\nexport async function runConnect(options: {\n client: KeystrokeClient;\n provider: ConnectProvider;\n serverUrl: string;\n printUrl?: boolean;\n}): Promise<void> {\n const { client, provider, serverUrl, printUrl } = options;\n const label = providerLabel(provider.key);\n\n if (provider.mode === \"browser-redirect\") {\n const url = `${serverUrl}${provider.path}`;\n\n if (printUrl) {\n process.stdout.write(`${url}\\n`);\n return;\n }\n\n openUrl(url);\n process.stdout.write(`Complete ${label} sign-in in your browser.\\n`);\n return;\n }\n\n const payload = await client.connect.getAuthorizeUrl(provider.path);\n\n const authorizeUrl = new URL(payload.url);\n const scopes = authorizeUrl.searchParams.get(\"scope\")?.split(\" \").filter(Boolean) ?? [];\n\n if (scopes.length > 0) {\n process.stdout.write(\"Requested scopes:\\n\");\n for (const scope of scopes) {\n process.stdout.write(` - ${scope}\\n`);\n }\n process.stdout.write(\"\\n\");\n }\n\n if (printUrl) {\n process.stdout.write(`${payload.url}\\n`);\n return;\n }\n\n openUrl(payload.url);\n process.stdout.write(`Complete ${label} sign-in in your browser.\\n`);\n}\n","import type { Command } from \"commander\";\nimport { runCliCommand } from \"../../errors\";\nimport { getCliTargetOptions } from \"../../target-options\";\nimport type { ApiTargetOptions } from \"../../resolve-api-target\";\nimport { runConnect } from \"./run-connect\";\n\nfunction resolveConnectTargetOptions(): ApiTargetOptions {\n const { local } = getCliTargetOptions();\n if (local) {\n return { local: true };\n }\n return { orgScoped: true };\n}\n\nexport function registerConnectCommand(program: Command): void {\n program\n .command(\"connect [provider]\")\n .description(\"Connect third-party accounts (uses apiTarget; --local for local server)\")\n .option(\"--print-url\", \"Print the authorize URL and exit without opening the browser\")\n .action((provider: string | undefined, options: { printUrl?: boolean }) =>\n runCliCommand(\n \"Could not fetch connect providers\",\n async (ctx) => {\n const providers = await ctx.client.connect.listProviders();\n\n if (!provider) {\n if (providers.length === 0) {\n process.stdout.write(\"No connect providers available on this server.\\n\");\n return;\n }\n\n process.stdout.write(\"Available providers:\\n\");\n for (const entry of providers) {\n process.stdout.write(` ${entry.key}\\n`);\n }\n return;\n }\n\n const match = providers.find((entry) => entry.key === provider);\n if (!match) {\n const available = providers.map((entry) => entry.key).join(\", \") || \"(none)\";\n throw new Error(`Unknown provider \"${provider}\". Available: ${available}`);\n }\n\n await runConnect({\n client: ctx.client,\n provider: match,\n serverUrl: ctx.serverUrl,\n printUrl: options.printUrl,\n });\n },\n undefined,\n resolveConnectTargetOptions(),\n ),\n );\n}\n","import type { CredentialScopeType } from \"@keystrokehq/shared\";\nimport type { ApiTargetOptions } from \"../../resolve-api-target\";\nimport { projectScopedTarget } from \"../../resolve-api-target\";\n\nexport function resolveCredentialsTargetOptions(\n options: {\n scopeType?: CredentialScopeType;\n projectId?: string;\n } = {},\n): ApiTargetOptions {\n if (options.scopeType === \"project\") {\n return {\n ...projectScopedTarget,\n projectId: options.projectId,\n };\n }\n\n return { orgScoped: true };\n}\n","import type { Command } from \"commander\";\nimport { runCliCommand } from \"../../errors\";\nimport { resolveCredentialsTargetOptions } from \"./target-options\";\n\nexport function registerCredentialsDeleteCommand(credentials: Command): void {\n credentials\n .command(\"delete\")\n .description(\"Delete an api_key credential instance\")\n .argument(\"<id>\", \"Credential instance id\")\n .action((id: string) =>\n runCliCommand(\n \"Delete credential failed\",\n async ({ client }) => {\n await client.credentials.deleteInstance(id);\n },\n undefined,\n resolveCredentialsTargetOptions(),\n ),\n );\n}\n","import type { Command } from \"commander\";\nimport { runCliCommand } from \"../../errors\";\nimport { resolveCredentialsTargetOptions } from \"./target-options\";\n\nexport function registerCredentialsListCommand(credentials: Command): void {\n credentials\n .command(\"list\")\n .description(\"List stored credential instances\")\n .option(\"--key <key>\", \"Filter by credential key\")\n .action((options: { key?: string }) =>\n runCliCommand(\n \"List credential instances failed\",\n async ({ client }) => {\n const result = await client.credentials.listInstances(\n options.key ? { key: options.key } : undefined,\n );\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n },\n undefined,\n resolveCredentialsTargetOptions(),\n ),\n );\n}\n","import type { CredentialScopeType } from \"@keystrokehq/shared\";\nimport type { KeystrokeClient } from \"@keystrokehq/sdk\";\nimport { cliBinaryName } from \"../../errors\";\n\ntype ConflictInstance = {\n id: string;\n label: string | null;\n isDefault: boolean;\n};\n\nfunction describeInstance(instance: ConflictInstance): string {\n const defaultStatus = instance.isDefault ? \"default\" : \"not default\";\n const labelStatus = instance.label ? `label: ${instance.label}` : \"no label\";\n return `id: ${instance.id}, ${defaultStatus}, ${labelStatus}`;\n}\n\nfunction formatSetFields(setFields: string[]): string {\n return setFields.map((field) => `--set ${field}`).join(\" \");\n}\n\nfunction formatSetConflictError(args: {\n key: string;\n scope: string;\n setFields: string[];\n matching: ConflictInstance[];\n}): string {\n const binary = cliBinaryName();\n const setArgs = formatSetFields(args.setFields);\n const listCmd = `${binary} credentials list --key ${args.key}`;\n const addSecondCmd = `${binary} credentials set ${args.key} --scope ${args.scope} --label <name> ${setArgs}`;\n\n if (args.matching.length === 1) {\n const instance = args.matching[0]!;\n const updateCmd = `${binary} credentials update ${instance.id} ${setArgs}`;\n\n return [\n `An ${args.key} credential already exists in ${args.scope} scope (${describeInstance(instance)}).`,\n \"credentials set creates a new instance — it does not update an existing one.\",\n \"To update the existing credential:\",\n ` ${updateCmd}`,\n \"To add a second credential in the same scope:\",\n ` ${addSecondCmd}`,\n `List instances: ${listCmd}`,\n ].join(\"\\n\");\n }\n\n const instanceLines = args.matching.map((instance) => ` • ${describeInstance(instance)}`);\n\n return [\n `Multiple ${args.key} credentials already exist in ${args.scope} scope. --label is required to add another:`,\n ...instanceLines,\n \"To add another credential in the same scope:\",\n ` ${addSecondCmd}`,\n `List instances: ${listCmd}`,\n ].join(\"\\n\");\n}\n\nexport async function assertNoSetConflict(\n client: KeystrokeClient,\n args: {\n key: string;\n scope: string;\n scopeType: CredentialScopeType;\n projectId?: string;\n label?: string;\n setFields: string[];\n },\n): Promise<void> {\n if (args.label) {\n return;\n }\n\n const { instances } = await client.credentials.listInstances({ key: args.key });\n const matching = instances.filter(\n (instance) =>\n instance.scopeType === args.scopeType &&\n (args.scopeType !== \"project\" || instance.scopeId === args.projectId),\n );\n\n if (matching.length === 0) {\n return;\n }\n\n throw new Error(\n formatSetConflictError({\n key: args.key,\n scope: args.scope,\n setFields: args.setFields,\n matching,\n }),\n );\n}\n","export const ENV_REF_PREFIX = \"@env:\";\n\nexport function isEnvRef(raw: string): boolean {\n return raw.startsWith(ENV_REF_PREFIX);\n}\n\nexport function envRefName(raw: string): string {\n return raw.slice(ENV_REF_PREFIX.length);\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\n\nfunction hasProjectLayout(dir: string): boolean {\n return existsSync(join(dir, \"package.json\")) && existsSync(join(dir, \"src\", \"agents\"));\n}\n\nexport function resolveProjectRoot(fromDir = process.cwd()): string {\n let dir = resolve(fromDir);\n\n while (dir !== dirname(dir)) {\n if (hasProjectLayout(dir)) {\n return dir;\n }\n\n dir = dirname(dir);\n }\n\n if (hasProjectLayout(dir)) {\n return dir;\n }\n\n throw new Error(\"Could not find keystroke project root (expected package.json and src/agents/)\");\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { resolveProjectRoot } from \"./resolve-project-root\";\n\nlet loaded = false;\n\nexport function parseEnvFile(contents: string): Record<string, string> {\n const values: Record<string, string> = {};\n\n for (const line of contents.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n\n const key = trimmed.slice(0, eq).trim();\n let value = trimmed.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n\n values[key] = value;\n }\n\n return values;\n}\n\nexport function loadProjectEnv(fromDir = process.cwd()): void {\n if (loaded) {\n return;\n }\n\n loaded = true;\n\n let envPath: string;\n try {\n envPath = join(resolveProjectRoot(fromDir), \".env\");\n } catch {\n return;\n }\n\n if (!existsSync(envPath)) {\n return;\n }\n\n for (const [key, value] of Object.entries(parseEnvFile(readFileSync(envPath, \"utf8\")))) {\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n}\n\nexport function resetProjectEnvLoadedForTests(): void {\n loaded = false;\n}\n","import { envRefName, isEnvRef } from \"../../project/env-ref\";\nimport { loadProjectEnv } from \"../../project/load-project-env\";\n\nexport function parseCredentialValueFields(fields: string[]): Record<string, string> {\n const value: Record<string, string> = {};\n\n for (const field of fields) {\n const separatorIndex = field.indexOf(\"=\");\n if (separatorIndex <= 0) {\n throw new Error(`Invalid --set value: ${field}`);\n }\n\n const key = field.slice(0, separatorIndex);\n let rawValue = field.slice(separatorIndex + 1);\n\n if (isEnvRef(rawValue)) {\n const envName = envRefName(rawValue);\n if (process.env[envName] === undefined) {\n loadProjectEnv();\n }\n rawValue = process.env[envName] ?? \"\";\n if (!rawValue) {\n throw new Error(`Environment variable ${envName} is not set`);\n }\n }\n\n value[key] = rawValue;\n }\n\n if (Object.keys(value).length === 0) {\n throw new Error(\"At least one --set field is required\");\n }\n\n return value;\n}\n\nexport function scopeTypeFromCli(scope: string): \"organization\" | \"user\" | \"project\" | \"global\" {\n switch (scope) {\n case \"org\":\n return \"organization\";\n case \"user\":\n return \"user\";\n case \"project\":\n return \"project\";\n case \"global\":\n return \"global\";\n default:\n throw new Error(`Unknown scope \"${scope}\". Expected org, user, project, or global.`);\n }\n}\n","import type { Command } from \"commander\";\nimport { runCliCommand } from \"../../errors\";\nimport { assertNoSetConflict } from \"./format-set-conflict-error\";\nimport { parseCredentialValueFields, scopeTypeFromCli } from \"./parse-value\";\nimport { resolveCredentialsTargetOptions } from \"./target-options\";\n\nexport function registerCredentialsSetCommand(credentials: Command): void {\n credentials\n .command(\"set\")\n .description(\"Create a new api_key credential instance\")\n .argument(\"<key>\", \"Credential key, e.g. exa\")\n .requiredOption(\"--scope <scope>\", \"org, user, project, or global\")\n .option(\"--project-id <id>\", \"Project id when scope is project\")\n .option(\"--label <label>\", \"Human-readable label within the scope\")\n .option(\"--default\", \"Mark as default for this scope\")\n .option(\n \"--set <field>\",\n \"Credential field as key=value or key=@env:VAR (falls back to project .env when unset in shell)\",\n collectSetValues,\n [],\n )\n .action(\n (\n key: string,\n options: {\n scope: string;\n projectId?: string;\n label?: string;\n default?: boolean;\n set: string[];\n },\n ) =>\n runCliCommand(\n \"Set credential failed\",\n async ({ client }) => {\n const value = parseCredentialValueFields(options.set);\n const scopeType = scopeTypeFromCli(options.scope);\n\n if (scopeType === \"project\" && !options.projectId) {\n throw new Error(\"--project-id is required when scope is project\");\n }\n\n await assertNoSetConflict(client, {\n key,\n scope: options.scope,\n scopeType,\n projectId: options.projectId,\n label: options.label,\n setFields: options.set,\n });\n\n const result = await client.credentials.createInstance({\n key,\n scopeType,\n scopeId: scopeType === \"project\" ? options.projectId! : undefined,\n label: options.label,\n isDefault: options.default,\n value,\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n },\n undefined,\n resolveCredentialsTargetOptions({\n scopeType: scopeTypeFromCli(options.scope),\n projectId: options.projectId,\n }),\n ),\n );\n}\n\nfunction collectSetValues(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n","import type { Command } from \"commander\";\nimport { runCliCommand } from \"../../errors\";\nimport { parseCredentialValueFields } from \"./parse-value\";\nimport { resolveCredentialsTargetOptions } from \"./target-options\";\n\nexport function registerCredentialsUpdateCommand(credentials: Command): void {\n credentials\n .command(\"update\")\n .description(\"Update an api_key credential instance\")\n .argument(\"<id>\", \"Credential instance id\")\n .option(\"--label <label>\", \"Human-readable label within the scope\")\n .option(\"--default\", \"Mark as default for this scope\")\n .option(\"--set <field>\", \"Credential field as key=value or key=@env:VAR\", collectSetValues, [])\n .action(\n (\n id: string,\n options: {\n label?: string;\n default?: boolean;\n set: string[];\n },\n ) =>\n runCliCommand(\n \"Update credential failed\",\n async ({ client }) => {\n const value =\n options.set.length > 0 ? parseCredentialValueFields(options.set) : undefined;\n\n const result = await client.credentials.updateInstance(id, {\n ...(options.label !== undefined ? { label: options.label } : {}),\n ...(options.default !== undefined ? { isDefault: options.default } : {}),\n ...(value ? { value } : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n },\n undefined,\n resolveCredentialsTargetOptions(),\n ),\n );\n}\n\nfunction collectSetValues(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n","import type { Command } from \"commander\";\nimport { registerCredentialsDeleteCommand } from \"./delete\";\nimport { registerCredentialsListCommand } from \"./list\";\nimport { registerCredentialsSetCommand } from \"./set\";\nimport { registerCredentialsUpdateCommand } from \"./update\";\n\nexport function registerCredentialsCommand(program: Command): void {\n const credentials = program\n .command(\"credentials\")\n .description(\"Manage stored api_key credential instances\");\n\n registerCredentialsListCommand(credentials);\n registerCredentialsSetCommand(credentials);\n registerCredentialsUpdateCommand(credentials);\n registerCredentialsDeleteCommand(credentials);\n}\n","import type Conf from \"conf\";\nimport type { CliConfig } from \"../config\";\nimport { getPlatformUrl } from \"../config\";\nimport {\n DEFAULT_PLATFORM_URL,\n DEFAULT_WEB_URL,\n resolvePlatformUrlForWebUrl,\n} from \"../resolve-platform-url\";\n\nexport type AuthLoginTargetOptions = {\n webUrl?: string;\n platformUrl?: string;\n};\n\nexport function resolveAuthLoginTargets(\n options: AuthLoginTargetOptions,\n config: Conf<CliConfig>,\n): { webUrl: string; platformUrl: string } {\n const webUrl = options.webUrl ?? DEFAULT_WEB_URL;\n const platformUrl = resolvePlatformUrlForWebUrl(webUrl, {\n platformUrl: options.platformUrl,\n fallback: options.webUrl ? getPlatformUrl(config) : DEFAULT_PLATFORM_URL,\n });\n\n return { webUrl, platformUrl };\n}\n","import type { Command } from \"commander\";\nimport { CLI_CLIENT_ID, getSessionWithBearer, runDeviceLogin } from \"@keystrokehq/auth/cli\";\nimport { setAccessToken } from \"../../auth/credentials\";\nimport { openUrl } from \"../../auth/open-url\";\nimport { resolveAuthLoginTargets } from \"../../auth/resolve-login-targets\";\nimport { createCliConfig } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { syncActiveOrganizationAfterLogin } from \"../../organization/active-organization\";\n\ntype LoginOptions = {\n webUrl?: string;\n platformUrl?: string;\n org?: string;\n};\n\nexport function registerAuthLoginCommand(auth: Command): void {\n auth\n .command(\"login\")\n .description(\"Authenticate via browser device flow\")\n .option(\n \"--web-url <url>\",\n \"Web dashboard origin (omit to use production defaults; local dev: http://localhost:3000)\",\n )\n .option(\"--platform-url <url>\", \"Platform API origin (derived from web URL when omitted)\")\n .option(\"--org <slug>\", \"Active organization slug (overrides browser default)\")\n .action(async (options: LoginOptions) => {\n const config = createCliConfig();\n const { webUrl, platformUrl } = resolveAuthLoginTargets(options, config);\n\n config.set(\"webUrl\", webUrl);\n config.set(\"platformUrl\", platformUrl);\n\n try {\n const result = await runDeviceLogin({\n baseURL: platformUrl,\n clientId: CLI_CLIENT_ID,\n openUrl,\n });\n\n setAccessToken(platformUrl, result.accessToken);\n\n const user = await getSessionWithBearer(platformUrl, result.accessToken);\n const membership = await syncActiveOrganizationAfterLogin(config, {\n organizationRef: options.org,\n deviceOrganizationId: result.organizationId,\n });\n\n if (user) {\n process.stdout.write(\n `Logged in as ${user.name} (${user.email}) — organization ${membership.organization.name}\\n`,\n );\n } else {\n process.stdout.write(\n `Logged in to ${webUrl} — organization ${membership.organization.name}\\n`,\n );\n }\n } catch (error) {\n process.stderr.write(`${formatCliError(error, \"Login failed\", { webUrl, platformUrl })}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { clearAccessToken } from \"../../auth/credentials\";\nimport { createCliConfig, getPlatformUrl, getWebUrl } from \"../../config\";\n\ntype LogoutOptions = {\n webUrl?: string;\n};\n\nexport function registerAuthLogoutCommand(auth: Command): void {\n auth\n .command(\"logout\")\n .description(\"Clear stored credentials\")\n .option(\"--web-url <url>\", \"Web dashboard origin (default from config)\")\n .action((options: LogoutOptions) => {\n const config = createCliConfig();\n const webUrl = options.webUrl ?? getWebUrl(config);\n const platformUrl = getPlatformUrl(config);\n clearAccessToken(platformUrl);\n process.stdout.write(`${JSON.stringify({ authenticated: false, webUrl, platformUrl })}\\n`);\n });\n}\n","import { getSessionWithBearer } from \"@keystrokehq/auth/cli\";\nimport type { Command } from \"commander\";\nimport { getAccessToken } from \"../../auth/credentials\";\nimport { createCliConfig, getPlatformUrl, getWebUrl } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { listOrganizations } from \"../../organization/active-organization\";\n\ntype StatusOptions = {\n webUrl?: string;\n};\n\nexport function registerAuthStatusCommand(auth: Command): void {\n auth\n .command(\"status\")\n .description(\"Show authentication status\")\n .option(\"--web-url <url>\", \"Web dashboard origin (default from config)\")\n .action(async (options: StatusOptions) => {\n const config = createCliConfig();\n const webUrl = options.webUrl ?? getWebUrl(config);\n const platformUrl = getPlatformUrl(config);\n const token = getAccessToken(platformUrl);\n\n if (!token) {\n process.stdout.write(`${JSON.stringify({ authenticated: false, webUrl, platformUrl })}\\n`);\n return;\n }\n\n try {\n const user = await getSessionWithBearer(platformUrl, token);\n const organizations = user ? await listOrganizations(config).catch(() => []) : [];\n const activeOrganizationId = config.get(\"activeOrganizationId\");\n const activeOrganization = activeOrganizationId\n ? organizations.find((entry) => entry.organization.id === activeOrganizationId)\n : undefined;\n\n process.stdout.write(\n `${JSON.stringify({\n authenticated: user !== null,\n webUrl,\n user,\n activeOrganizationId: activeOrganizationId ?? null,\n activeOrganization: activeOrganization?.organization.name ?? null,\n })}\\n`,\n );\n\n if (!user) {\n process.exitCode = 1;\n }\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Status check failed\", { webUrl, platformUrl })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { registerAuthLoginCommand } from \"./login\";\nimport { registerAuthLogoutCommand } from \"./logout\";\nimport { registerAuthStatusCommand } from \"./status\";\n\nexport function registerAuthCommand(program: Command): void {\n const auth = program.command(\"auth\").description(\"Authenticate with an keystroke deployment\");\n\n registerAuthLoginCommand(auth);\n registerAuthLogoutCommand(auth);\n registerAuthStatusCommand(auth);\n}\n","import type { Command } from \"commander\";\nimport { resolveProjectRoot } from \"../project/resolve-project-root\";\n\nexport function registerBuildCommand(program: Command): void {\n program\n .command(\"build\")\n .description(\"Build the keystroke project for production\")\n .option(\"--dir <path>\", \"Project directory\", process.cwd())\n .action(async (options) => {\n try {\n const root = resolveProjectRoot(options.dir);\n const { buildApp } = await import(\"@keystrokehq/build\");\n await buildApp({ root });\n process.stdout.write(`Built ${root}\\n`);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Build failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import { spawnSync } from \"node:child_process\";\nimport { existsSync, mkdtempSync, readFileSync, rmSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n//#region src/pack-artifact.ts\n/** Pack `dist/` into a gzip tarball suitable for `/app` extraction in the project server image. */\nfunction packProjectArtifact(projectRoot) {\n\tif (!existsSync(join(projectRoot, \"dist\"))) throw new Error(\"dist/ not found — run keystroke build first\");\n\tconst tempDir = mkdtempSync(join(tmpdir(), \"keystroke-artifact-\"));\n\tconst archivePath = join(tempDir, \"artifact.tgz\");\n\ttry {\n\t\tconst result = spawnSync(\"tar\", [\n\t\t\t\"-czf\",\n\t\t\tarchivePath,\n\t\t\t\"--exclude=._*\",\n\t\t\t\"--exclude=.DS_Store\",\n\t\t\t\"-C\",\n\t\t\tprojectRoot,\n\t\t\t\"dist\"\n\t\t], {\n\t\t\tencoding: \"utf8\",\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\tCOPYFILE_DISABLE: \"1\"\n\t\t\t}\n\t\t});\n\t\tif (result.status !== 0) throw new Error(result.stderr?.trim() || \"Failed to pack project artifact\");\n\t\treturn readFileSync(archivePath);\n\t} finally {\n\t\trmSync(tempDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\nexport { packProjectArtifact };\n\n//# sourceMappingURL=pack-artifact.mjs.map","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { walkProject } from \"@keystrokehq/build/walk\";\nimport type { ProjectSourceFile } from \"@keystrokehq/shared\";\nimport { ROUTE_MANIFEST_REL_PATH } from \"@keystrokehq/shared\";\n\nexport type CollectedProjectSource = {\n files: ProjectSourceFile[];\n};\n\n/** Collect deploy source files via the shared project walk (for `--skip-build`). */\nexport function collectProjectSource(root: string): CollectedProjectSource {\n const manifestPath = join(root, ROUTE_MANIFEST_REL_PATH);\n if (!existsSync(manifestPath)) {\n throw new Error(\n `Route manifest missing at ${ROUTE_MANIFEST_REL_PATH}. Run keystroke build before deploy --skip-build.`,\n );\n }\n\n return { files: walkProject(root, { collectSources: true }).sourceFiles };\n}\n","import type { PlatformClient } from \"@keystrokehq/sdk/platform\";\nimport { packProjectArtifact } from \"@keystrokehq/storage/pack-artifact\";\nimport type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../config\";\nimport { selectActiveOrganization } from \"../organization/active-organization\";\nimport { createCliPlatformClient } from \"../platform-client\";\nimport { collectProjectSource, type CollectedProjectSource } from \"../project/collect-source\";\nimport { resolveProjectRoot } from \"../project/resolve-project-root\";\nimport { resolveActiveProjectId } from \"../resolve-project-target\";\n\nconst POLL_INTERVAL_MS = 2_000;\nconst DEPLOY_TIMEOUT_MS = 120_000;\nconst SOURCE_BLOB_CONTENT_TYPE = \"text/plain; charset=utf-8\";\n\n/**\n * Upload the project's source so the dashboard can render a read-only file\n * view. Content-addressed: only blobs the platform reports missing are PUT, so\n * unchanged files are never re-uploaded. The manifest (path -> hash) is sent\n * last and marks the snapshot complete.\n */\nasync function uploadProjectSourceSnapshot(\n client: PlatformClient,\n projectId: string,\n artifactId: string,\n source: CollectedProjectSource,\n): Promise<void> {\n const contentsByHash = new Map<string, string>();\n const blobsByHash = new Map<string, { hash: string; size: number }>();\n for (const file of source.files) {\n contentsByHash.set(file.hash, file.contents);\n if (!blobsByHash.has(file.hash)) {\n blobsByHash.set(file.hash, { hash: file.hash, size: Buffer.byteLength(file.contents) });\n }\n }\n\n const { uploads } = await client.artifacts.presignSource(projectId, artifactId, [\n ...blobsByHash.values(),\n ]);\n\n await Promise.all(\n uploads.map(async (upload) => {\n const contents = contentsByHash.get(upload.hash);\n if (contents === undefined) {\n return;\n }\n const response = await fetch(upload.url, {\n method: \"PUT\",\n body: contents,\n headers: { \"Content-Type\": SOURCE_BLOB_CONTENT_TYPE },\n });\n if (!response.ok) {\n throw new Error(`Source blob upload failed (${response.status})`);\n }\n }),\n );\n\n await client.artifacts.uploadManifest(projectId, artifactId, {\n files: source.files.map((file) => ({ path: file.path, hash: file.hash })),\n });\n}\n\ntype DeployOptions = {\n dir: string;\n projectId: string;\n skipBuild?: boolean;\n};\n\nasync function sleep(ms: number): Promise<void> {\n await new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport async function runDeploy(options: DeployOptions): Promise<void> {\n const root = resolveProjectRoot(options.dir);\n const config = createCliConfig();\n const client = createCliPlatformClient(config);\n\n let source: CollectedProjectSource;\n if (!options.skipBuild) {\n const { buildApp } = await import(\"@keystrokehq/build\");\n const result = await buildApp({ root, collectSources: true, emitManifest: true });\n source = { files: result.sourceFiles };\n } else {\n source = collectProjectSource(root);\n }\n\n const archive = packProjectArtifact(root);\n\n let active = await client.organizations.getActive();\n if (!active) {\n active = await selectActiveOrganization(config);\n }\n\n client.setActiveOrganizationId(active.organization.id);\n\n const project = await client.projects.get(options.projectId);\n\n const created = await client.artifacts.create(project.id);\n\n // Upload the runtime tarball and the source snapshot in parallel. Source\n // powers the dashboard's read-only file views; a failure there must not block\n // the deploy, so it only warns.\n const uploadPromise = fetch(created.uploadUrl, {\n method: \"PUT\",\n body: archive,\n headers: {\n \"Content-Type\": \"application/gzip\",\n },\n });\n const sourcePromise = uploadProjectSourceSnapshot(\n client,\n project.id,\n created.artifact.id,\n source,\n ).catch((error: unknown) => {\n const message = error instanceof Error ? error.message : \"unknown error\";\n process.stderr.write(`Warning: failed to upload project source files: ${message}\\n`);\n });\n\n const upload = await uploadPromise;\n await sourcePromise;\n\n if (!upload.ok) {\n throw new Error(`Artifact upload failed (${upload.status})`);\n }\n\n const completed = await client.artifacts.complete(project.id, created.artifact.id);\n process.stdout.write(`Deploy ${completed.artifact.id} uploaded\\n`);\n\n const deadline = Date.now() + DEPLOY_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const current = await client.projects.get(project.id);\n if (current.status === \"active\") {\n config.set(\"activeProjectId\", project.id);\n config.set(\"apiTarget\", \"platform\");\n process.stdout.write(`Project active${current.baseUrl ? `: ${current.baseUrl}` : \"\"}\\n`);\n return;\n }\n\n if (current.status === \"failed\") {\n throw new Error(current.lastError ?? \"Project runtime failed\");\n }\n\n await sleep(POLL_INTERVAL_MS);\n }\n\n throw new Error(\"Timed out waiting for project to become active\");\n}\n\nexport function registerDeployCommand(program: Command): void {\n program\n .command(\"deploy\")\n .description(\"Build, upload, and deploy the project to the platform\")\n .option(\"--dir <path>\", \"Project directory\", process.cwd())\n .option(\"--skip-build\", \"Upload the existing dist/ without rebuilding\")\n .action(async (options) => {\n try {\n const config = createCliConfig();\n const projectId = await resolveActiveProjectId(config);\n if (!projectId) {\n throw new Error(\"Usage: keystroke deploy --project <slug>\");\n }\n\n await runDeploy({\n dir: options.dir,\n projectId,\n skipBuild: options.skipBuild,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Deploy failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","/** Strip dev-only Node flags so the API child loads built `dist/`, not package `src/`. */\nexport function runtimeChildNodeOptions(nodeOptions: string | undefined): string | undefined {\n if (!nodeOptions?.trim()) {\n return undefined;\n }\n\n const parts = nodeOptions.trim().split(/\\s+/);\n const cleaned: string[] = [];\n\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index]!;\n if (part === \"--conditions=development\") {\n continue;\n }\n if (part === \"--conditions\" && parts[index + 1] === \"development\") {\n index++;\n continue;\n }\n cleaned.push(part);\n }\n\n const result = cleaned.join(\" \").trim();\n return result || undefined;\n}\n\nexport function runtimeChildEnv(\n parentEnv: NodeJS.ProcessEnv,\n overrides: Record<string, string>,\n): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...parentEnv, ...overrides };\n delete env.KEYSTROKE_DEV;\n\n const nodeOptions = runtimeChildNodeOptions(env.NODE_OPTIONS);\n if (nodeOptions) {\n env.NODE_OPTIONS = nodeOptions;\n } else {\n delete env.NODE_OPTIONS;\n }\n\n // Local project API — sqlite only; Infisical POSTGRES_* is for platform/orchestrator.\n for (const key of [\n \"POSTGRES_HOST\",\n \"POSTGRES_PORT\",\n \"POSTGRES_DB\",\n \"POSTGRES_USER\",\n \"POSTGRES_PASSWORD\",\n \"DATABASE_SEARCH_PATH\",\n ]) {\n delete env[key];\n }\n if (!env.DATABASE_URL?.trim()) {\n env.DATABASE_URL = \"file:./data/dev.db\";\n }\n\n return env;\n}\n","import { pathToFileURL } from \"node:url\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { listenPortFromPublicUrl } from \"@keystrokehq/shared\";\nimport { runtimeChildEnv } from \"./runtime-child-env\";\n\nexport type BootstrapRunOptions = {\n root: string;\n runtimeNodeModules: string;\n apiPort: number;\n};\n\nexport type BootstrapRun = {\n cwd: string;\n args: string[];\n env: NodeJS.ProcessEnv;\n};\n\n/** Node args + env for `@keystrokehq/build` bootstrap (shared by start + dev). */\nexport async function resolveBootstrapRun(options: BootstrapRunOptions): Promise<BootstrapRun> {\n const { resolveRuntimeBuildArtifact } = await import(\"@keystrokehq/build\");\n const loader = pathToFileURL(\n resolveRuntimeBuildArtifact(options.runtimeNodeModules, \"dist/runtime-loader.mjs\"),\n ).href;\n const bootstrap = resolveRuntimeBuildArtifact(options.runtimeNodeModules, \"dist/bootstrap.mjs\");\n\n const args: string[] = [`--import=${loader}`];\n const envFile = join(options.root, \".env\");\n\n if (existsSync(envFile)) {\n args.push(`--env-file=${envFile}`);\n }\n\n args.push(bootstrap);\n\n const childEnv = runtimeChildEnv(process.env, {\n KEYSTROKE_ROOT: options.root,\n KEYSTROKE_RUNTIME_NODE_MODULES: options.runtimeNodeModules,\n PROJECT_ID: process.env.PROJECT_ID ?? \"default\",\n });\n childEnv.PORT = String(listenPortFromPublicUrl(childEnv.PUBLIC_SERVER_URL, options.apiPort));\n\n return {\n cwd: options.root,\n args,\n env: childEnv,\n };\n}\n","import { spawn, type ChildProcess } from \"node:child_process\";\n\nexport type ManagedProcess = {\n name: string;\n child: ChildProcess;\n};\n\nexport function waitForExit(child: ChildProcess): Promise<number | null> {\n return new Promise((resolve) => {\n child.on(\"exit\", (code) => resolve(code ?? null));\n });\n}\n\nexport async function runUntilExit(processes: ManagedProcess[]): Promise<number | null> {\n const shutdown = (signal: NodeJS.Signals = \"SIGTERM\") => {\n for (const { child } of processes) {\n if (!child.killed && child.pid !== undefined) {\n child.kill(signal);\n }\n }\n };\n\n const onSignal = () => {\n shutdown(\"SIGINT\");\n process.exit(0);\n };\n\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n\n try {\n const results = await Promise.race(\n processes.map(async ({ name, child }) => {\n const code = await waitForExit(child);\n return { name, code };\n }),\n );\n\n if (results.code !== 0 && results.code !== null) {\n shutdown();\n throw new Error(`${results.name} exited with status ${results.code}`);\n }\n\n shutdown();\n return results.code;\n } finally {\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n }\n}\n\nexport function spawnNodeScript(options: {\n cwd: string;\n args: string[];\n env: NodeJS.ProcessEnv;\n}): ChildProcess {\n return spawn(\"node\", options.args, {\n cwd: options.cwd,\n env: options.env,\n stdio: \"inherit\",\n });\n}\n","import { spawnSync } from \"node:child_process\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\n\nconst NATIVE_PACKAGES = [\"better-sqlite3\"] as const;\n\nfunction isMissingBindingsError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(\"Could not locate the bindings file\");\n}\n\nfunction rebuildNativePackage(require: NodeRequire, pkg: string): void {\n const pkgDir = dirname(require.resolve(`${pkg}/package.json`));\n const npm = process.platform === \"win32\" ? \"npm.cmd\" : \"npm\";\n const result = spawnSync(npm, [\"run\", \"install\"], { cwd: pkgDir, stdio: \"inherit\" });\n\n if (result.status !== 0) {\n throw new Error(`Failed to build ${pkg} native bindings. Try: pnpm rebuild -g ${pkg}`);\n }\n}\n\n/** Compile native addons when pnpm skipped dependency install scripts (common on global install). */\nexport function ensureNativeDeps(nodeModulesRoot: string): void {\n const anchor = join(nodeModulesRoot, \"@keystrokehq\", \"server\", \"package.json\");\n const require = createRequire(anchor);\n\n for (const pkg of NATIVE_PACKAGES) {\n try {\n require(pkg);\n } catch (error) {\n if (!isMissingBindingsError(error)) {\n throw error;\n }\n\n process.stderr.write(`Building ${pkg} native bindings…\\n`);\n rebuildNativePackage(require, pkg);\n require(pkg);\n }\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Directory whose `node_modules/@keystrokehq/server` ships with the CLI pack. */\nexport function resolveCliRuntimeNodeModules(cliRoot: string): string {\n let dir = cliRoot;\n\n while (dir !== dirname(dir)) {\n const nodeModules = join(dir, \"node_modules\");\n if (existsSync(join(nodeModules, \"@keystrokehq\", \"server\"))) {\n return nodeModules;\n }\n dir = dirname(dir);\n }\n\n throw new Error(\n \"Keystroke runtime packages are missing. Reinstall or repack the CLI (expected @keystrokehq/server in node_modules).\",\n );\n}\n","/**\n * `keystroke dev` — watch-build + API restart.\n *\n * NOT true hot reload. On src/ changes tsdown rebuilds dist/, then we stop and\n * boot the API again so route discovery picks up new agents/workflows/triggers.\n */\nimport type { Command } from \"commander\";\nimport type { ChildProcess } from \"node:child_process\";\nimport { createCliConfig, getConfigDir, getServerUrl } from \"../config\";\nimport { clearDevSession, writeDevSession } from \"../dev-session\";\nimport { resolveBootstrapRun } from \"../project/bootstrap-run\";\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\nimport { resolveProjectRoot } from \"../project/resolve-project-root\";\nimport { spawnNodeScript } from \"../process/run-processes\";\nimport { ensureNativeDeps } from \"../runtime/ensure-native-deps\";\nimport { resolveCliRuntimeNodeModules } from \"../runtime/resolve-runtime-node-modules\";\n\nconst DEV_BANNER = \"keystroke dev: watch rebuilds dist/ and restarts the API — not hot reload.\\n\";\n\ntype DevOptions = {\n dir: string;\n port?: number;\n};\n\nfunction stopChild(child: ChildProcess | undefined): void {\n if (child && !child.killed && child.pid !== undefined) {\n child.kill(\"SIGTERM\");\n }\n}\n\nfunction resolveDevServerUrl(\n config: ReturnType<typeof createCliConfig>,\n portOverride?: number,\n): string {\n const url = new URL(getServerUrl(config));\n if (portOverride !== undefined) {\n url.port = String(portOverride);\n }\n return url.origin;\n}\n\nexport async function runDev(options: DevOptions): Promise<void> {\n const root = resolveProjectRoot(options.dir);\n\n const runtimeNodeModules = resolveCliRuntimeNodeModules(resolveCliRoot(import.meta.url));\n ensureNativeDeps(runtimeNodeModules);\n\n const cliConfig = createCliConfig();\n const configDir = getConfigDir(cliConfig);\n\n process.stdout.write(DEV_BANNER);\n\n const serverUrl = resolveDevServerUrl(cliConfig, options.port);\n const apiPort = Number(new URL(serverUrl).port || 80);\n\n writeDevSession(\n {\n pid: process.pid,\n port: apiPort,\n root,\n serverUrl,\n },\n configDir,\n );\n\n let apiChild: ChildProcess | undefined;\n let restarting = false;\n let firstBoot = true;\n\n const restartApi = async () => {\n if (restarting) {\n return;\n }\n\n restarting = true;\n stopChild(apiChild);\n const bootstrap = await resolveBootstrapRun({\n root,\n runtimeNodeModules,\n apiPort,\n });\n apiChild = spawnNodeScript(bootstrap);\n\n if (firstBoot) {\n firstBoot = false;\n process.stdout.write(`API: ${serverUrl}\\n`);\n } else {\n process.stdout.write(\"API restarted after dist rebuild (not hot reload).\\n\");\n }\n\n restarting = false;\n };\n\n const shutdown = () => {\n clearDevSession(configDir);\n stopChild(apiChild);\n process.exit(0);\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n try {\n const { watchApp } = await import(\"@keystrokehq/build\");\n await watchApp({\n root,\n clean: false,\n onRebuild: restartApi,\n });\n } finally {\n process.off(\"SIGINT\", shutdown);\n process.off(\"SIGTERM\", shutdown);\n clearDevSession(configDir);\n stopChild(apiChild);\n }\n}\n\nexport function registerDevCommand(program: Command): void {\n program\n .command(\"dev\")\n .description(\"Watch src/, rebuild dist/, and restart the API (not true hot reload)\")\n .option(\"--dir <path>\", \"Project directory\", process.cwd())\n .option(\"--port <number>\", \"API port\", (value) => Number(value))\n .action(async (options) => {\n try {\n await runDev({\n dir: options.dir,\n port: options.port,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Dev failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import type Conf from \"conf\";\nimport type { PlatformClient } from \"@keystrokehq/sdk/platform\";\nimport type { CreateProjectRequest, Project, UpdateProjectRequest } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"../../config\";\nimport { cliBinaryName } from \"../../errors/command-input\";\nimport { selectActiveOrganization } from \"../../organization/active-organization\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { formatProjectLabel } from \"../../resolve-resource-ref\";\nimport { resolveProjectRef } from \"../../resolve-resource-ref\";\n\nexport async function withActivePlatformClient(\n config: Conf<CliConfig>,\n fn: (platform: PlatformClient) => Promise<void>,\n): Promise<void> {\n const platform = createCliPlatformClient(config);\n let active = await platform.organizations.getActive();\n if (!active) {\n active = await selectActiveOrganization(config);\n }\n\n platform.setActiveOrganizationId(active.organization.id);\n await fn(platform);\n}\n\nfunction writeInactiveDeployHints(projects: Pick<Project, \"slug\" | \"status\">[]): void {\n const bin = cliBinaryName();\n for (const project of projects) {\n if (project.status !== \"inactive\") {\n continue;\n }\n\n process.stderr.write(\n `Project ${formatProjectLabel(project)} is inactive. Deploy with: ${bin} deploy --project ${formatProjectLabel(project)}\\n`,\n );\n }\n}\n\nexport async function runProjectList(config: Conf<CliConfig>): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const projects = await platform.projects.list();\n process.stdout.write(`${JSON.stringify({ projects }, null, 2)}\\n`);\n\n if (projects.length === 0) {\n const bin = cliBinaryName();\n process.stderr.write(\n `No projects yet. Create one with: ${bin} project create --name \"My project\"\\n`,\n );\n return;\n }\n\n writeInactiveDeployHints(projects);\n });\n}\n\nexport async function runProjectMetrics(\n config: Conf<CliConfig>,\n options: { projectRef?: string },\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const metrics = await platform.projectMetrics.list();\n if (options.projectRef === undefined) {\n process.stdout.write(`${JSON.stringify(metrics, null, 2)}\\n`);\n return;\n }\n\n const project = await resolveProjectRef(platform, options.projectRef);\n const output = Object.fromEntries(\n Object.entries(metrics).filter(([projectId]) => projectId === project.id),\n );\n process.stdout.write(`${JSON.stringify(output, null, 2)}\\n`);\n });\n}\n\nexport async function runProjectDeploymentsList(\n config: Conf<CliConfig>,\n options: { projectRef: string },\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const project = await resolveProjectRef(platform, options.projectRef);\n const deployments = await platform.deployments.listForProject(project.id);\n process.stdout.write(`${JSON.stringify({ deployments }, null, 2)}\\n`);\n });\n}\n\nexport async function runProjectCreate(\n config: Conf<CliConfig>,\n input: CreateProjectRequest,\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const project = await platform.projects.create(input);\n process.stdout.write(`${JSON.stringify({ project }, null, 2)}\\n`);\n writeInactiveDeployHints([project]);\n });\n}\n\nexport type UpdateProjectCommandInput = {\n projectId: string;\n} & UpdateProjectRequest;\n\nexport async function runProjectUpdate(\n config: Conf<CliConfig>,\n input: UpdateProjectCommandInput,\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const { projectId, ...patch } = input;\n const project = await platform.projects.update(projectId, patch);\n process.stdout.write(`${JSON.stringify({ project }, null, 2)}\\n`);\n });\n}\n\nexport async function runProjectDelete(config: Conf<CliConfig>, projectId: string): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n await platform.projects.delete(projectId);\n process.stdout.write(`${JSON.stringify({ deleted: projectId }, null, 2)}\\n`);\n });\n}\n","import type Conf from \"conf\";\nimport type { HistoryRunListQuery } from \"@keystrokehq/sdk/platform\";\n\nimport type { CliConfig } from \"../../config\";\nimport { withActivePlatformClient } from \"../project/run-project\";\n\nexport async function runHistoryList(\n config: Conf<CliConfig>,\n filters?: HistoryRunListQuery,\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const runs = await platform.history.list(filters);\n process.stdout.write(`${JSON.stringify(runs, null, 2)}\\n`);\n });\n}\n\nexport async function runHistoryGet(config: Conf<CliConfig>, runId: string): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const run = await platform.history.get(runId);\n process.stdout.write(`${JSON.stringify(run, null, 2)}\\n`);\n });\n}\n\nexport async function runHistoryCancel(config: Conf<CliConfig>, runId: string): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const run = await platform.history.cancel(runId);\n process.stdout.write(`${JSON.stringify(run, null, 2)}\\n`);\n });\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { getPlatformUrl, getWebUrl } from \"../../config\";\nimport { runHistoryCancel, runHistoryGet, runHistoryList } from \"./run-history\";\n\nexport function registerHistoryCommand(program: Command): void {\n const history = program\n .command(\"history\")\n .description(\"List, inspect, and cancel platform run history\");\n\n history\n .command(\"list\")\n .description(\"List runs across projects in the active organization\")\n .option(\"--project <id>\", \"Filter by project id\")\n .option(\n \"--status <status>\",\n \"Filter by status (pending, running, sleeping, waiting_hook, completed, failed, canceled)\",\n )\n .option(\"--kind <kind>\", \"Filter by kind (workflow or agent)\")\n .action(async (options: { project?: string; status?: string; kind?: string }) => {\n const config = createCliConfig();\n try {\n await runHistoryList(config, {\n ...(options.project ? { project: options.project } : {}),\n ...(options.status\n ? {\n status: options.status as\n | \"pending\"\n | \"running\"\n | \"sleeping\"\n | \"waiting_hook\"\n | \"completed\"\n | \"failed\"\n | \"canceled\",\n }\n : {}),\n ...(options.kind ? { kind: options.kind as \"workflow\" | \"agent\" } : {}),\n });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"List history failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n history\n .command(\"get\")\n .description(\"Get run details\")\n .argument(\"<runId>\", \"Run id\")\n .action(async (runId: string) => {\n const config = createCliConfig();\n try {\n await runHistoryGet(config, runId);\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Get history run failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n history\n .command(\"cancel\")\n .description(\"Cancel a pending workflow run\")\n .argument(\"<runId>\", \"Run id\")\n .action(async (runId: string) => {\n const config = createCliConfig();\n try {\n await runHistoryCancel(config, runId);\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Cancel history run failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { runCliCommand } from \"../errors\";\n\nexport function registerHealthCommand(program: Command): void {\n program\n .command(\"health\")\n .description(\"Check connectivity to the keystroke API\")\n .action(() =>\n runCliCommand(\"Health check failed\", async ({ client }) => {\n const result = await client.health.check();\n process.stdout.write(`${JSON.stringify(result)}\\n`);\n }),\n );\n}\n","const KEBAB_CASE = /^[a-z][a-z0-9-]*$/;\nconst HAS_EMOJI = /\\p{Extended_Pictographic}/u;\nconst HAS_UPPERCASE = /[A-Z]/;\nconst HAS_WHITESPACE = /\\s/;\nconst HAS_UNDERSCORE = /_/;\n\nconst EXAMPLE = \"my-keystroke\";\nconst RULES = \"Use lowercase letters, numbers, and hyphens only\";\n\nfunction projectNameValidationError(name: string): string {\n if (HAS_UPPERCASE.test(name)) {\n return `Project name must be lowercase (${RULES}; e.g. ${EXAMPLE})`;\n }\n if (HAS_WHITESPACE.test(name)) {\n return `Project name cannot contain spaces (${RULES}; e.g. ${EXAMPLE})`;\n }\n if (HAS_UNDERSCORE.test(name)) {\n return `Project name cannot contain underscores (${RULES}; e.g. ${EXAMPLE})`;\n }\n if (HAS_EMOJI.test(name)) {\n return `Project name cannot contain emojis (${RULES}; e.g. ${EXAMPLE})`;\n }\n if (/[^a-z0-9-]/.test(name)) {\n return `Project name cannot contain special characters (${RULES}; e.g. ${EXAMPLE})`;\n }\n if (!/^[a-z]/.test(name)) {\n return `Project name must start with a lowercase letter (e.g. ${EXAMPLE})`;\n }\n return `Project name must be kebab-case (${RULES}; e.g. ${EXAMPLE})`;\n}\n\nexport function assertProjectName(name: string): string {\n const trimmed = name.trim();\n if (!trimmed) {\n throw new Error(\"Project name is required\");\n }\n\n if (!KEBAB_CASE.test(trimmed)) {\n throw new Error(projectNameValidationError(trimmed));\n }\n\n return trimmed;\n}\n\nexport function projectNameFromDirectory(directory: string): string {\n const base = directory.split(/[/\\\\]/).filter(Boolean).at(-1) ?? directory;\n return assertProjectName(base);\n}\n","import { confirm, input } from \"@inquirer/prompts\";\nimport { resolve } from \"node:path\";\nimport { assertProjectName, projectNameFromDirectory } from \"./project-name\";\nimport type { InitOptions } from \"./types\";\n\nexport type InitPromptResult = {\n projectName: string;\n targetDir: string;\n};\n\nexport async function promptInitOptions(options: InitOptions): Promise<InitPromptResult> {\n const defaultName =\n options.name ??\n (options.directory ? projectNameFromDirectory(options.directory) : \"my-keystroke\");\n\n const projectName = assertProjectName(\n options.name ??\n (await input({\n message: \"Project name\",\n default: defaultName,\n validate: (value) => {\n try {\n assertProjectName(value);\n return true;\n } catch (error) {\n return error instanceof Error ? error.message : \"Invalid project name\";\n }\n },\n })),\n );\n\n const targetDir = resolve(\n options.directory ??\n (await input({\n message: \"Project directory\",\n default: `./${projectName}`,\n })),\n );\n\n return { projectName, targetDir };\n}\n\nexport async function confirmTargetDir(targetDir: string): Promise<boolean> {\n return confirm({\n message: `Directory \"${targetDir}\" is not empty. Continue and merge files?`,\n default: false,\n });\n}\n","// Generated by scripts/generate-catalog-versions.ts — do not edit.\n// Baked when @keystrokehq/cli is built and bundled into the published CLI; keystroke init\n// substitutes {{catalog:*}} from this map without reading the monorepo pnpm-workspace.yaml.\nexport const INIT_CATALOG_DEPS = [\"zod\", \"oxlint\", \"typescript\", \"vitest\", \"@types/node\"] as const;\n\nexport const INIT_CATALOG_VERSIONS = {\n zod: \"^4.4.3\",\n oxlint: \"^1.66.0\",\n typescript: \"^6.0.3\",\n vitest: \"^4.1.7\",\n \"@types/node\": \"^25.9.1\",\n} as const satisfies Record<(typeof INIT_CATALOG_DEPS)[number], string>;\n","import { readdir, readFile, stat, writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { INIT_CATALOG_VERSIONS } from \"./catalog-versions\";\n\nexport type TemplateVariables = {\n projectName: string;\n version: string;\n};\n\nfunction renderTemplate(content: string, variables: TemplateVariables): string {\n let rendered = content\n .replaceAll(\"{{projectName}}\", variables.projectName)\n .replaceAll(\"{{version}}\", variables.version);\n\n for (const [dep, version] of Object.entries(INIT_CATALOG_VERSIONS)) {\n rendered = rendered.replaceAll(`{{catalog:${dep}}}`, version);\n }\n\n return rendered;\n}\n\nasync function copyEntry(\n sourcePath: string,\n targetPath: string,\n variables: TemplateVariables,\n): Promise<void> {\n const info = await stat(sourcePath);\n\n if (info.isDirectory()) {\n await mkdir(targetPath, { recursive: true });\n const entries = await readdir(sourcePath);\n\n for (const entry of entries) {\n await copyEntry(join(sourcePath, entry), join(targetPath, entry), variables);\n }\n\n return;\n }\n\n await mkdir(dirname(targetPath), { recursive: true });\n const content = await readFile(sourcePath, \"utf8\");\n await writeFile(targetPath, renderTemplate(content, variables));\n}\n\nexport async function copyTemplate(\n templateDir: string,\n targetDir: string,\n variables: TemplateVariables,\n): Promise<void> {\n await copyEntry(templateDir, targetDir, variables);\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\n\nexport function resolveTemplateDir(templateName: string, fromModuleUrl = import.meta.url): string {\n const cliRoot = resolveCliRoot(fromModuleUrl);\n // Check source first so contributors editing `templates/` see their changes\n // without rebuilding the CLI. End users don't have `templates/` (only `dist/`\n // ships), so the fallback is what they hit.\n const candidates = [\n join(cliRoot, \"templates\", templateName),\n join(cliRoot, \"dist\", \"templates\", templateName),\n ];\n\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n\n throw new Error(`Template \"${templateName}\" not found`);\n}\n","import { readFile, unlink, writeFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport { INIT_CATALOG_VERSIONS } from \"./catalog-versions\";\n\nexport const PROJECT_NPMRC = `@keystrokehq:registry=https://registry.npmjs.org\n`;\n\nexport const PROJECT_GITIGNORE = `node_modules/\ndist/\ndata/\ncoverage/\n.env\n.agent/\n`;\n\nfunction linkSpec(fromDir: string, toDir: string): string {\n const path = relative(fromDir, toDir);\n return `link:${path.startsWith(\".\") ? path : `./${path}`}`;\n}\n\n/** Monorepo playground only (`KEYSTROKE_DEV` + `playground/`). Distributed init uses copyTemplate. */\nfunction buildPlaygroundPackageJson(\n projectName: string,\n targetDir: string,\n monorepoRoot: string,\n): string {\n return `${JSON.stringify(\n {\n name: projectName,\n version: \"0.0.0\",\n private: true,\n type: \"module\",\n scripts: {\n dev: \"keystroke dev\",\n build: \"keystroke build\",\n start: \"keystroke start\",\n lint: \"oxlint .\",\n typecheck: \"tsc --noEmit\",\n \"test:unit\": \"vitest run --project unit\",\n \"test:int\": \"vitest run --project integration\",\n },\n dependencies: {\n \"@keystrokehq/action\": linkSpec(targetDir, join(monorepoRoot, \"packages/action\")),\n \"@keystrokehq/agent\": linkSpec(targetDir, join(monorepoRoot, \"packages/agent\")),\n \"@keystrokehq/config\": linkSpec(targetDir, join(monorepoRoot, \"packages/config\")),\n \"@keystrokehq/google\": linkSpec(\n targetDir,\n join(monorepoRoot, \"packages/integrations/google\"),\n ),\n \"@keystrokehq/slack\": linkSpec(\n targetDir,\n join(monorepoRoot, \"packages/integrations/slack\"),\n ),\n \"@keystrokehq/workflow\": linkSpec(targetDir, join(monorepoRoot, \"packages/workflow\")),\n zod: INIT_CATALOG_VERSIONS.zod,\n },\n devDependencies: {\n \"@keystrokehq/cli\": linkSpec(targetDir, join(monorepoRoot, \"apps/cli\")),\n \"@keystrokehq/tsconfig\": linkSpec(targetDir, join(monorepoRoot, \"packages/tsconfig\")),\n \"@types/node\": INIT_CATALOG_VERSIONS[\"@types/node\"],\n oxlint: INIT_CATALOG_VERSIONS.oxlint,\n typescript: INIT_CATALOG_VERSIONS.typescript,\n vitest: INIT_CATALOG_VERSIONS.vitest,\n },\n },\n null,\n 2,\n )}\\n`;\n}\n\n/** Patch hello-world scaffold for monorepo playground/ (link deps, no GitHub Packages). */\nexport async function applyPlaygroundManifest(\n targetDir: string,\n projectName: string,\n monorepoRoot: string,\n): Promise<void> {\n await writeFile(\n join(targetDir, \"package.json\"),\n buildPlaygroundPackageJson(projectName, targetDir, monorepoRoot),\n );\n\n try {\n await unlink(join(targetDir, \".npmrc\"));\n } catch {\n // Existing dirs may have a consumer .npmrc from an earlier scaffold.\n }\n\n const tsconfigPath = join(targetDir, \"tsconfig.json\");\n const tsconfig = JSON.parse(await readFile(tsconfigPath, \"utf8\")) as {\n include?: string[];\n compilerOptions?: { rootDir?: string };\n };\n tsconfig.include = [\"src\", \"keystroke.config.ts\"];\n if (tsconfig.compilerOptions) {\n tsconfig.compilerOptions.rootDir = \".\";\n }\n await writeFile(tsconfigPath, `${JSON.stringify(tsconfig, null, 2)}\\n`);\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\n\nconst SKILLS_BUNDLE = \"skills-bundle\";\n\nexport function resolveSkillsBundleDir(fromModuleUrl = import.meta.url): string {\n const cliRoot = resolveCliRoot(fromModuleUrl);\n // The real skills source lives in `packages/skills/`. Check it first so\n // contributor edits are picked up without rebuilding the CLI. End users\n // don't have those paths — they get the bundled copy under `dist/`.\n const candidates = [\n join(cliRoot, \"..\", \"..\", \"packages\", \"skills\", \"bundled\"),\n join(cliRoot, \"..\", \"..\", \"packages\", \"skills\", \"dist\"),\n join(cliRoot, \"dist\", SKILLS_BUNDLE),\n join(cliRoot, SKILLS_BUNDLE),\n ];\n\n for (const candidate of candidates) {\n if (existsSync(join(candidate, \"_AGENTS.md\"))) {\n return candidate;\n }\n }\n\n throw new Error(\n \"Bundled keystroke skills not found — run `pnpm --filter @keystrokehq/cli build`\",\n );\n}\n","import { cp, lstat, mkdir, readFile, rm, symlink, writeFile } from \"node:fs/promises\";\nimport { platform } from \"node:os\";\nimport { dirname, join, relative } from \"node:path\";\nimport { readCliVersion } from \"../version\";\nimport { resolveSkillsBundleDir } from \"./resolve-skills-bundle-dir\";\n\nexport const BUNDLE_VERSION_FILENAME = \".bundle-version\";\n\nexport function agentsSkillsDir(projectRoot: string): string {\n return join(projectRoot, \".agents\", \"skills\");\n}\n\nexport function bundleVersionPath(projectRoot: string): string {\n return join(agentsSkillsDir(projectRoot), BUNDLE_VERSION_FILENAME);\n}\n\nexport async function readBundleVersion(projectRoot: string): Promise<string | null> {\n try {\n return (await readFile(bundleVersionPath(projectRoot), \"utf8\")).trim();\n } catch {\n return null;\n }\n}\n\nasync function ensureSymlink(\n target: string,\n linkPath: string,\n kind: \"dir\" | \"file\",\n): Promise<void> {\n await mkdir(dirname(linkPath), { recursive: true });\n await rm(linkPath, { recursive: true, force: true });\n const type = platform() === \"win32\" && kind === \"dir\" ? \"junction\" : kind;\n await symlink(target, linkPath, type);\n}\n\n/** Overwrites `.agents/skills/`, AGENTS.md, and recreates `.claude` symlinks from the CLI bundle. */\nexport async function syncBundledSkills(\n projectRoot: string,\n fromModuleUrl = import.meta.url,\n): Promise<void> {\n const bundleDir = resolveSkillsBundleDir(fromModuleUrl);\n const skillsDir = agentsSkillsDir(projectRoot);\n const agentsMdPath = join(projectRoot, \"AGENTS.md\");\n\n await mkdir(join(projectRoot, \".agents\"), { recursive: true });\n\n const skillsStat = await lstat(skillsDir).catch(() => null);\n if (skillsStat?.isSymbolicLink()) {\n await rm(skillsDir, { force: true });\n await cp(join(bundleDir, \"skills\"), skillsDir, { recursive: true });\n } else {\n await mkdir(skillsDir, { recursive: true });\n await cp(join(bundleDir, \"skills\"), skillsDir, { recursive: true, force: true });\n }\n\n const agentsStat = await lstat(agentsMdPath).catch(() => null);\n if (agentsStat?.isSymbolicLink()) {\n await rm(agentsMdPath, { force: true });\n }\n // Overwrite AGENTS.md from the bundle — bundled agent docs are the source of truth for now.\n await writeFile(agentsMdPath, await readFile(join(bundleDir, \"_AGENTS.md\"), \"utf8\"));\n\n await ensureSymlink(\n relative(dirname(join(projectRoot, \".claude\", \"skills\")), skillsDir),\n join(projectRoot, \".claude\", \"skills\"),\n \"dir\",\n );\n await ensureSymlink(\n relative(dirname(join(projectRoot, \"CLAUDE.md\")), agentsMdPath),\n join(projectRoot, \"CLAUDE.md\"),\n \"file\",\n );\n\n await writeFile(bundleVersionPath(projectRoot), `${readCliVersion()}\\n`);\n}\n","import { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nconst EMPTY_SRC_DIRS = [\"files\", \"skills\", \"triggers\"] as const;\n\n/** Ensure standard empty `src/` folders exist (git does not track empty directories). */\nexport async function scaffoldEmptySrcDirs(targetDir: string): Promise<void> {\n await Promise.all(\n EMPTY_SRC_DIRS.map((dir) => mkdir(join(targetDir, \"src\", dir), { recursive: true })),\n );\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { PROJECT_GITIGNORE, PROJECT_NPMRC } from \"./project-files\";\n\n/** Write dotfiles npm/pnpm deploy omits from bundled templates. */\nexport async function scaffoldProjectDotfiles(targetDir: string): Promise<void> {\n await writeFile(join(targetDir, \".npmrc\"), PROJECT_NPMRC);\n await writeFile(join(targetDir, \".gitignore\"), PROJECT_GITIGNORE);\n}\n","import { existsSync } from \"node:fs\";\nimport { access, copyFile, readdir } from \"node:fs/promises\";\nimport { basename, isAbsolute, join, relative, resolve } from \"node:path\";\nimport {\n buildPlaygroundWorkspace,\n installDependencies,\n installPlaygroundDependencies,\n resolvePackageManager,\n} from \"./package-manager\";\nimport { assertProjectName, projectNameFromDirectory } from \"./project-name\";\nimport { confirmTargetDir, promptInitOptions } from \"./prompts\";\nimport { copyTemplate } from \"./copy-template\";\nimport { resolveTemplateDir } from \"./resolve-template-dir\";\nimport { applyPlaygroundManifest } from \"./project-files\";\nimport { syncBundledSkills } from \"../skills/sync-bundled-skills\";\nimport { scaffoldEmptySrcDirs } from \"./scaffold-empty-src-dirs\";\nimport { scaffoldProjectDotfiles } from \"./scaffold-project-dotfiles\";\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\nimport type { InitOptions } from \"./types\";\n\nexport type RunInitOptions = InitOptions & {\n version: string;\n};\n\nfunction monorepoRoot(): string | null {\n const root = join(resolveCliRoot(import.meta.url), \"..\", \"..\");\n return existsSync(join(root, \"pnpm-workspace.yaml\")) ? root : null;\n}\n\nfunction resolvePlaygroundRoot(targetDir: string): string | null {\n if (process.env.KEYSTROKE_DEV !== \"1\") {\n return null;\n }\n\n const root = monorepoRoot();\n if (!root) {\n return null;\n }\n\n const rel = relative(join(root, \"playground\"), resolve(targetDir));\n return rel.length > 0 && !rel.startsWith(\"..\") && !isAbsolute(rel) ? root : null;\n}\n\nasync function directoryExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function directoryIsEmpty(path: string): Promise<boolean> {\n if (!(await directoryExists(path))) {\n return true;\n }\n\n const entries = await readdir(path);\n return entries.length === 0;\n}\n\nfunction resolveHeadlessOptions(options: RunInitOptions): {\n projectName: string;\n targetDir: string;\n} {\n const targetDir = resolve(options.directory ?? options.name ?? \"my-keystroke\");\n const projectName = assertProjectName(\n options.name ?? projectNameFromDirectory(basename(targetDir)),\n );\n\n return { projectName, targetDir };\n}\n\nexport async function runInit(\n options: RunInitOptions,\n): Promise<{ targetDir: string; projectName: string }> {\n const interactive = !options.yes && process.stdin.isTTY;\n const resolved = interactive ? await promptInitOptions(options) : resolveHeadlessOptions(options);\n const { projectName, targetDir } = resolved;\n const playgroundRoot = resolvePlaygroundRoot(targetDir);\n\n if (!(await directoryIsEmpty(targetDir))) {\n if (interactive) {\n const ok = await confirmTargetDir(targetDir);\n if (!ok) {\n throw new Error(\"Init cancelled\");\n }\n } else if (!options.yes) {\n throw new Error(\n `Directory \"${targetDir}\" is not empty. Pass --yes to merge or choose an empty directory.`,\n );\n }\n }\n\n await copyTemplate(resolveTemplateDir(options.template ?? \"hello-world\"), targetDir, {\n projectName,\n version: options.version,\n });\n await scaffoldEmptySrcDirs(targetDir);\n\n if (playgroundRoot) {\n await applyPlaygroundManifest(targetDir, projectName, playgroundRoot);\n } else {\n await scaffoldProjectDotfiles(targetDir);\n }\n\n await syncBundledSkills(targetDir);\n await copyFile(join(targetDir, \".env.example\"), join(targetDir, \".env\"));\n\n if (!options.skipInstall) {\n if (playgroundRoot) {\n installPlaygroundDependencies(targetDir);\n // `link:` deps consume each package's built dist/; build so `keystroke dev`\n // works immediately instead of failing with ERR_MODULE_NOT_FOUND.\n buildPlaygroundWorkspace(playgroundRoot);\n } else {\n const manager = resolvePackageManager(options.packageManager);\n installDependencies(targetDir, manager);\n }\n }\n\n return { targetDir, projectName };\n}\n","import type { Command } from \"commander\";\nimport { runInit } from \"../init/run-init\";\nimport { readCliVersion } from \"../version\";\n\nexport function registerInitCommand(program: Command): void {\n program\n .command(\"init\")\n .description(\"Create a new keystroke project from a template\")\n .argument(\"[directory]\", \"Directory to create the project in\")\n .option(\"--name <name>\", \"Project name (kebab-case)\")\n .option(\"--template <name>\", \"Template to use\", \"hello-world\")\n .option(\"-y, --yes\", \"Skip prompts (headless mode for scripts and AI agents)\")\n .option(\"--skip-install\", \"Skip dependency installation\")\n .option(\"--pm <manager>\", \"Package manager: npm, pnpm, yarn, or bun\")\n .action(async (directory: string | undefined, options) => {\n try {\n const result = await runInit({\n directory,\n name: options.name,\n template: options.template,\n yes: options.yes,\n skipInstall: options.skipInstall,\n packageManager: options.pm,\n version: readCliVersion(),\n });\n\n process.stdout.write(\n `Created keystroke project \"${result.projectName}\" at ${result.targetDir}\\n`,\n );\n process.stdout.write(\"\\nNext steps:\\n\");\n process.stdout.write(` cd ${result.targetDir}\\n`);\n process.stdout.write(\" # set ANTHROPIC_API_KEY and integration keys in .env\\n\");\n process.stdout.write(\" keystroke dev\\n\");\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Init failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import type Conf from \"conf\";\nimport type { UpdateOrganizationRequest } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"../../config\";\nimport { withActivePlatformClient } from \"../project/run-project\";\n\nexport async function runOrganizationUpdate(\n config: Conf<CliConfig>,\n input: Pick<UpdateOrganizationRequest, \"name\">,\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const organization = await platform.organizations.update(input);\n process.stdout.write(`${JSON.stringify({ organization }, null, 2)}\\n`);\n });\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig, getPlatformUrl, getWebUrl } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { runOrganizationUpdate } from \"./run-organization\";\n\nexport function registerOrganizationCommand(program: Command): void {\n const organization = program\n .command(\"organization\")\n .description(\"Manage the active organization\");\n\n organization\n .command(\"update\")\n .description(\"Update the active organization's display name\")\n .requiredOption(\"--name <name>\", \"Organization display name\")\n .action(async (options: { name: string }) => {\n const config = createCliConfig();\n try {\n await runOrganizationUpdate(config, { name: options.name });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Update organization failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig, getPlatformUrl, getWebUrl } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { resolveActiveProjectId } from \"../../resolve-project-target\";\nimport { getCliTargetOptions } from \"../../target-options\";\nimport {\n runProjectCreate,\n runProjectList,\n runProjectMetrics,\n runProjectDeploymentsList,\n runProjectUpdate,\n runProjectDelete,\n} from \"./run-project\";\n\nexport function registerProjectCommand(program: Command): void {\n const project = program\n .command(\"project\")\n .description(\"List, create, update, and delete platform projects\");\n\n project\n .command(\"list\")\n .description(\"List projects in the active organization\")\n .action(async () => {\n const config = createCliConfig();\n try {\n await runProjectList(config);\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"List projects failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n project\n .command(\"metrics\")\n .description(\"List rollup metrics for projects in the active organization\")\n .option(\"--project <slug>\", \"Return metrics for a single project\")\n .action(async (options: { project?: string }) => {\n const config = createCliConfig();\n try {\n await runProjectMetrics(config, {\n ...(options.project ? { projectRef: options.project } : {}),\n });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"List project metrics failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n const deployments = project\n .command(\"deployments\")\n .description(\"View deployment history for platform projects\");\n\n deployments\n .command(\"list\")\n .description(\"List deployment history for a project\")\n .option(\"--project <slug>\", \"Project slug\")\n .action(async (options: { project?: string }) => {\n const config = createCliConfig();\n try {\n const projectRef =\n options.project ?? getCliTargetOptions().projectId ?? config.get(\"activeProjectId\");\n if (!projectRef) {\n throw new Error(\"Usage: keystroke project deployments list --project <slug>\");\n }\n\n await runProjectDeploymentsList(config, { projectRef });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"List deployments failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n project\n .command(\"create\")\n .description(\"Create a platform project in the active organization\")\n .requiredOption(\"--name <name>\", \"Project name\")\n .option(\"--description <description>\", \"Project description\")\n .action(async (options: { name: string; description?: string }) => {\n const config = createCliConfig();\n try {\n await runProjectCreate(config, {\n name: options.name,\n ...(options.description ? { description: options.description } : {}),\n });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Create project failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n project\n .command(\"update\")\n .description(\"Update a platform project's name and/or description\")\n .option(\"--name <name>\", \"Project name\")\n .option(\"--description <description>\", \"Project description\")\n .action(async (options: { name?: string; description?: string }) => {\n const config = createCliConfig();\n try {\n const projectId = await resolveActiveProjectId(config);\n if (!projectId) {\n throw new Error(\"Usage: keystroke --project <slug> project update --name <name>\");\n }\n\n if (!options.name && options.description === undefined) {\n throw new Error(\"At least one of --name or --description is required\");\n }\n\n await runProjectUpdate(config, {\n projectId,\n ...(options.name ? { name: options.name } : {}),\n ...(options.description !== undefined ? { description: options.description } : {}),\n });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Update project failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n project\n .command(\"delete\")\n .description(\"Delete a platform project\")\n .option(\"-y, --yes\", \"Skip confirmation prompt\")\n .action(async (options: { yes?: boolean }) => {\n const config = createCliConfig();\n try {\n const projectId = await resolveActiveProjectId(config);\n if (!projectId) {\n throw new Error(\"Usage: keystroke --project <slug> project delete\");\n }\n\n if (!options.yes) {\n throw new Error(\"Pass --yes to confirm project deletion\");\n }\n\n await runProjectDelete(config, projectId);\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Delete project failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { createCliConfig, getServerUrl } from \"../config\";\nimport { resolveBootstrapRun } from \"../project/bootstrap-run\";\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\nimport { resolveProjectRoot } from \"../project/resolve-project-root\";\nimport { runUntilExit, spawnNodeScript, type ManagedProcess } from \"../process/run-processes\";\nimport { ensureNativeDeps } from \"../runtime/ensure-native-deps\";\nimport { resolveCliRuntimeNodeModules } from \"../runtime/resolve-runtime-node-modules\";\n\ntype StartOptions = {\n dir: string;\n port?: number;\n};\n\nfunction resolveStartServerUrl(portOverride?: number): string {\n const url = new URL(getServerUrl(createCliConfig()));\n if (portOverride !== undefined) {\n url.port = String(portOverride);\n }\n return url.origin;\n}\n\nexport async function runStart(options: StartOptions): Promise<void> {\n const root = resolveProjectRoot(options.dir);\n const serverUrl = resolveStartServerUrl(options.port);\n const apiPort = Number(new URL(serverUrl).port || 80);\n\n const runtimeNodeModules = resolveCliRuntimeNodeModules(resolveCliRoot(import.meta.url));\n ensureNativeDeps(runtimeNodeModules);\n const { buildApp } = await import(\"@keystrokehq/build\");\n await buildApp({ root, clean: false });\n\n const bootstrap = await resolveBootstrapRun({\n root,\n runtimeNodeModules,\n apiPort,\n });\n\n const processes: ManagedProcess[] = [\n {\n name: \"api\",\n child: spawnNodeScript(bootstrap),\n },\n ];\n\n process.stdout.write(`API: ${serverUrl}\\n`);\n\n await runUntilExit(processes);\n}\n\nexport function registerStartCommand(program: Command): void {\n program\n .command(\"start\")\n .description(\"Build and run the API server\")\n .option(\"--dir <path>\", \"Project directory\", process.cwd())\n .option(\"--port <number>\", \"API port\", (value) => Number(value))\n .action(async (options) => {\n try {\n await runStart({\n dir: options.dir,\n port: options.port,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Start failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nexport function registerTriggerListCommand(trigger: Command): void {\n trigger\n .command(\"list\")\n .description(\"List discovered triggers\")\n .option(\"--endpoint <endpoint>\", \"Only webhook triggers on this shared endpoint\")\n .action((options: { endpoint?: string }) =>\n runProjectCliCommand(\"List triggers failed\", async ({ client }) => {\n const result = await client.triggers.list(\n options.endpoint ? { endpoint: options.endpoint } : undefined,\n );\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n\nexport function registerTriggerGetCommand(trigger: Command): void {\n trigger\n .command(\"get\")\n .description(\"Get a trigger by key, or all webhook triggers on a shared endpoint\")\n .argument(\"<id>\", \"Trigger key or shared webhook endpoint\")\n .action((id: string) =>\n runProjectCliCommand(\"Get trigger failed\", async ({ client }) => {\n const result = await client.triggers.get(id);\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n\nexport function registerTriggerUrlCommand(trigger: Command): void {\n trigger\n .command(\"url\")\n .description(\"Print the webhook URL for a trigger\")\n .argument(\"<id>\", \"Attachment key or webhook route\")\n .action((id: string) =>\n runProjectCliCommand(\"Resolve webhook URL failed\", async ({ client }) => {\n const url = await client.triggers.webhookUrl(id);\n process.stdout.write(`${url}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nexport function registerTriggerPollCommand(trigger: Command): void {\n trigger\n .command(\"poll\")\n .description(\"Run a poll trigger on demand\")\n .argument(\"<id>\", \"Poll attachment key, or poll source id with --group\")\n .option(\"--group\", \"Run all attachments that share this poll source id\")\n .option(\"--workflow <key>\", \"Only trigger this workflow (repeatable)\", collect, [])\n .option(\"--attachment <key>\", \"Only trigger this attachment (repeatable)\", collect, [])\n .action((id: string, options: { group?: boolean; workflow: string[]; attachment: string[] }) =>\n runProjectCliCommand(\"Poll trigger failed\", async ({ client }) => {\n const result = await client.triggers.poll(id, {\n ...(options.group ? { group: true } : {}),\n ...(options.workflow.length > 0 ? { workflows: options.workflow } : {}),\n ...(options.attachment.length > 0 ? { attachments: options.attachment } : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nexport function registerTriggerRunsCommand(trigger: Command): void {\n const runs = trigger.command(\"runs\").description(\"List and inspect trigger runs\");\n\n runs\n .command(\"list\")\n .description(\"List runs for a trigger attachment\")\n .argument(\"<attachmentId>\", \"Trigger attachment key\")\n .option(\"--limit <n>\", \"Page size (1–100)\", \"20\")\n .option(\"--cursor <cursor>\", \"Pagination cursor from a previous page\")\n .option(\"--trigger-type <type>\", \"Filter by trigger type (cron, webhook, poll)\")\n .action((attachmentId: string, options: Record<string, string | undefined>) =>\n runProjectCliCommand(\"List trigger runs failed\", async ({ client }) => {\n const result = await client.triggers.listRuns(attachmentId, {\n limit: Number(options.limit),\n ...(options.cursor ? { cursor: options.cursor } : {}),\n ...(options.triggerType\n ? { triggerType: options.triggerType as \"cron\" | \"webhook\" | \"poll\" }\n : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n\n runs\n .command(\"get\")\n .description(\"Get full details for a trigger run\")\n .argument(\"<attachmentId>\", \"Trigger attachment key\")\n .argument(\"<runId>\", \"Trigger run id\")\n .option(\"--include <parts>\", \"Comma-separated: workflows, trace\")\n .action((attachmentId: string, runId: string, options: { include?: string }) =>\n runProjectCliCommand(\"Get trigger run failed\", async ({ client }) => {\n const result = await client.triggers.getRun(attachmentId, runId, {\n include: options.include,\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport {\n registerTriggerGetCommand,\n registerTriggerListCommand,\n registerTriggerUrlCommand,\n} from \"./list\";\nimport { registerTriggerPollCommand } from \"./poll\";\nimport { registerTriggerRunsCommand } from \"./runs\";\n\nexport function registerTriggerCommand(program: Command): void {\n const trigger = program.command(\"trigger\").description(\"Invoke and inspect triggers\");\n\n registerTriggerListCommand(trigger);\n registerTriggerGetCommand(trigger);\n registerTriggerUrlCommand(trigger);\n registerTriggerPollCommand(trigger);\n registerTriggerRunsCommand(trigger);\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../../config\";\nimport { runCliCommand } from \"../../errors\";\nimport { ensureActiveOrganization } from \"../../organization/active-organization\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { resolveActiveProjectId } from \"../../resolve-project-target\";\n\nexport function registerWorkflowListCommand(workflow: Command): void {\n workflow\n .command(\"list\")\n .description(\"List workflows in the active organization\")\n .action(() =>\n runCliCommand(\n \"List workflows failed\",\n async () => {\n const config = createCliConfig();\n const client = createCliPlatformClient(config);\n await ensureActiveOrganization(config);\n const projectId = await resolveActiveProjectId(config);\n const result = await client.workflows.list(projectId ? { projectId } : undefined);\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n },\n undefined,\n { orgScoped: true },\n ),\n );\n}\n","import { isQueuedRunResponse } from \"@keystrokehq/sdk\";\nimport type { Command } from \"commander\";\nimport { cliBinaryName, parseJsonOption, runProjectCliCommand } from \"../../errors\";\n\nexport function registerWorkflowRunCommand(workflow: Command): void {\n workflow\n .command(\"run\")\n .description(\"Invoke a workflow\")\n .argument(\"<workflowId>\", \"Workflow key / route id\")\n .option(\"--input <json>\", \"JSON request body (defaults to {})\", \"{}\")\n .addHelpText(\n \"after\",\n `\nExamples:\n ${cliBinaryName()} workflow run math --input '{\"first\":1,\"second\":2}'\n ${cliBinaryName()} workflow run incoming-message --input '{\"message\":\"Hi\",\"sender\":\"you\"}'\n`,\n )\n .action((workflowId: string, options: { input: string }) =>\n runProjectCliCommand(\n \"Workflow run failed\",\n async ({ client }) => {\n const input = parseJsonOption(options.input, \"--input\");\n const result = await client.workflows.run(workflowId, input);\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n\n if (isQueuedRunResponse(result)) {\n process.stderr.write(\n `Run queued. Track progress:\\n` +\n ` ${cliBinaryName()} workflow runs get ${workflowId} ${result.runId} --include steps,trace\\n`,\n );\n }\n },\n {\n usage: {\n command: `${cliBinaryName()} workflow run ${workflowId}`,\n flag: \"--input\",\n },\n },\n ),\n );\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nexport function registerWorkflowRunsCommand(workflow: Command): void {\n const runs = workflow.command(\"runs\").description(\"List and inspect workflow runs\");\n\n runs\n .command(\"list\")\n .description(\"List runs for a workflow\")\n .argument(\"<workflowId>\", \"Workflow key / route id\")\n .option(\"--limit <n>\", \"Page size (1–100)\", \"20\")\n .option(\"--cursor <cursor>\", \"Pagination cursor from a previous page\")\n .option(\"--status <status>\", \"Filter by status\")\n .option(\"--trigger <trigger>\", \"Filter by trigger kind\")\n .action((workflowId: string, options: Record<string, string | undefined>) =>\n runProjectCliCommand(\"List workflow runs failed\", async ({ client }) => {\n const result = await client.workflows.listRuns(workflowId, {\n limit: Number(options.limit),\n ...(options.cursor ? { cursor: options.cursor } : {}),\n ...(options.status\n ? { status: options.status as \"pending\" | \"running\" | \"completed\" | \"failed\" }\n : {}),\n ...(options.trigger\n ? { trigger: options.trigger as \"api\" | \"cron\" | \"webhook\" | \"poll\" | \"retry\" }\n : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n\n runs\n .command(\"get\")\n .description(\"Get full details for a workflow run\")\n .argument(\"<workflowId>\", \"Workflow key / route id\")\n .argument(\"<runId>\", \"Workflow run id\")\n .option(\"--include <parts>\", \"Comma-separated: trigger, steps, trace\")\n .action((workflowId: string, runId: string, options: { include?: string }) =>\n runProjectCliCommand(\"Get workflow run failed\", async ({ client }) => {\n const result = await client.workflows.getRun(workflowId, runId, {\n include: options.include,\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { registerWorkflowListCommand } from \"./list\";\nimport { registerWorkflowRunCommand } from \"./run\";\nimport { registerWorkflowRunsCommand } from \"./runs\";\n\nexport function registerWorkflowCommand(program: Command): void {\n const workflow = program.command(\"workflow\").description(\"Invoke and inspect workflows\");\n\n registerWorkflowListCommand(workflow);\n registerWorkflowRunCommand(workflow);\n registerWorkflowRunsCommand(workflow);\n}\n","import type Conf from \"conf\";\nimport type { Project } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"../../config\";\nimport { cliBinaryName } from \"../../errors/command-input\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { formatProjectLabel, resolveProjectRef } from \"../../resolve-resource-ref\";\n\nexport type ConfigUseProjectResult = {\n stdout: string;\n stderr?: string;\n};\n\nasync function fetchProjectInOrg(config: Conf<CliConfig>, projectRef: string): Promise<Project> {\n const platform = createCliPlatformClient(config);\n return resolveProjectRef(platform, projectRef);\n}\n\nfunction assertProjectReadyForConfig(project: Project): void {\n const label = formatProjectLabel(project);\n\n if (project.status === \"failed\") {\n throw new Error(\n project.lastError\n ? `Project ${label} deploy failed: ${project.lastError}`\n : `Project ${label} deploy failed`,\n );\n }\n\n if (project.status === \"starting\") {\n throw new Error(\n `Project ${label} is still starting. Wait for deploy to finish, then run \\`keystroke config use project ${label}\\`.`,\n );\n }\n}\n\nexport async function runConfigUseProject(\n config: Conf<CliConfig>,\n projectRef: string,\n): Promise<ConfigUseProjectResult> {\n const project = await fetchProjectInOrg(config, projectRef);\n assertProjectReadyForConfig(project);\n\n config.set(\"activeProjectId\", project.id);\n config.set(\"apiTarget\", \"platform\");\n\n const label = formatProjectLabel(project);\n const stdout =\n project.status === \"active\"\n ? `Using platform project ${label}\\n`\n : `Using platform project ${label} (${project.status})\\n`;\n\n const stderr =\n project.status === \"inactive\"\n ? `Project is not active yet. Deploy with: ${cliBinaryName()} deploy --project ${label}\\n`\n : undefined;\n\n return { stdout, stderr };\n}\n","import { UserPreferencesPatchSchema, type UserPreferencesPatch } from \"@keystrokehq/shared\";\n\nexport function parsePreferenceValue(rawValue: string): unknown {\n try {\n return JSON.parse(rawValue);\n } catch {\n return rawValue;\n }\n}\n\nexport function buildPreferencesPatchFromKeyValue(\n key: string,\n rawValue: string,\n): UserPreferencesPatch {\n const trimmedKey = key.trim();\n if (!trimmedKey) {\n throw new Error(\"Preference key is required\");\n }\n\n const value = parsePreferenceValue(rawValue);\n const segments = trimmedKey.split(\".\").filter(Boolean);\n if (segments.length === 0) {\n throw new Error(\"Preference key is required\");\n }\n\n let patch: Record<string, unknown> = { [segments.at(-1)!]: value };\n\n for (let index = segments.length - 2; index >= 0; index -= 1) {\n patch = { [segments[index]!]: patch };\n }\n\n const parsed = UserPreferencesPatchSchema.safeParse(patch);\n if (!parsed.success) {\n const message = parsed.error.issues[0]?.message ?? \"invalid value\";\n throw new Error(`Invalid preference ${trimmedKey}: ${message}`);\n }\n\n return parsed.data;\n}\n","import type { Command } from \"commander\";\nimport type { PlatformClient } from \"@keystrokehq/sdk/platform\";\n\nimport { createCliConfig } from \"../../config\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { buildPreferencesPatchFromKeyValue } from \"./preferences-patch\";\n\nexport async function runConfigPreferencesGet(platform: PlatformClient): Promise<string> {\n const preferences = await platform.userPreferences.get();\n return `${JSON.stringify(preferences, null, 2)}\\n`;\n}\n\nexport async function runConfigPreferencesSet(\n platform: PlatformClient,\n key: string,\n value: string,\n): Promise<string> {\n const patch = buildPreferencesPatchFromKeyValue(key, value);\n const preferences = await platform.userPreferences.update(patch);\n return `${JSON.stringify(preferences, null, 2)}\\n`;\n}\n\nexport function registerConfigPreferencesCommand(config: Command): void {\n const preferences = config.command(\"preferences\").description(\"Manage user preferences\");\n\n preferences\n .command(\"get\")\n .description(\"Show current user preferences as JSON\")\n .action(async () => {\n const cliConfig = createCliConfig();\n const platform = createCliPlatformClient(cliConfig);\n process.stdout.write(await runConfigPreferencesGet(platform));\n });\n\n preferences\n .command(\"set\")\n .description(\"Update a user preference by dot-path key\")\n .argument(\"<key>\", \"Preference key, e.g. interfaceTheme or sidebar.navIconVisibility\")\n .argument(\"<value>\", \"Preference value (JSON or plain string)\")\n .action(async (key: string, value: string) => {\n const cliConfig = createCliConfig();\n const platform = createCliPlatformClient(cliConfig);\n process.stdout.write(await runConfigPreferencesSet(platform, key, value));\n });\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig, getConfigDir, getEffectiveApiTarget, getPlatformUrl } from \"../../config\";\nimport { readDevSession } from \"../../dev-session\";\nimport {\n listOrganizations,\n selectActiveOrganization,\n} from \"../../organization/active-organization\";\nimport { runConfigUseProject } from \"./use-project\";\nimport { registerConfigPreferencesCommand } from \"./preferences\";\n\nexport function registerConfigCommand(program: Command): void {\n const config = program.command(\"config\").description(\"Manage CLI configuration\");\n\n registerConfigPreferencesCommand(config);\n\n config\n .command(\"show\")\n .description(\"Show CLI configuration\")\n .action(() => {\n const cliConfig = createCliConfig();\n const configDir = getConfigDir(cliConfig);\n process.stdout.write(\n `${JSON.stringify(\n {\n serverUrl: cliConfig.get(\"serverUrl\"),\n webUrl: cliConfig.get(\"webUrl\"),\n platformUrl: getPlatformUrl(cliConfig),\n activeOrganizationId: cliConfig.get(\"activeOrganizationId\"),\n activeProjectId: cliConfig.get(\"activeProjectId\"),\n apiTarget: getEffectiveApiTarget(cliConfig),\n devSession: readDevSession(configDir) ?? null,\n },\n null,\n 2,\n )}\\n`,\n );\n });\n\n config\n .command(\"use\")\n .description(\"Switch API target (local/cloud/project) or active organization\")\n .argument(\"[mode]\", \"local, cloud, project, or org\")\n .argument(\"[id]\", \"Project or organization id when switching cloud target or org\")\n .action(async (mode?: string, id?: string) => {\n const cliConfig = createCliConfig();\n\n if (!mode || mode === \"local\") {\n cliConfig.set(\"apiTarget\", \"local\");\n const activeProjectId = cliConfig.get(\"activeProjectId\");\n process.stdout.write(\n activeProjectId\n ? `Using local keystroke server (cloud project ${activeProjectId} unchanged)\\n`\n : \"Using local keystroke server\\n\",\n );\n return;\n }\n\n if (mode === \"org\") {\n const membership = await selectActiveOrganization(cliConfig, { organizationRef: id });\n process.stdout.write(`Using organization ${membership.organization.name}\\n`);\n return;\n }\n\n if (mode === \"cloud\") {\n cliConfig.set(\"apiTarget\", \"platform\");\n const activeProjectId = cliConfig.get(\"activeProjectId\");\n process.stdout.write(\n activeProjectId\n ? `Using platform API (default project ${activeProjectId} for project-scoped commands)\\n`\n : \"Using platform API\\n\",\n );\n return;\n }\n\n if (mode !== \"project\") {\n throw new Error(\"Usage: keystroke config use [local|cloud|project [slug]|org [slug]]\");\n }\n\n const targetProjectId = id ?? cliConfig.get(\"activeProjectId\");\n if (!targetProjectId) {\n throw new Error(\"Usage: keystroke config use project <slug>\");\n }\n\n const result = await runConfigUseProject(cliConfig, targetProjectId);\n process.stdout.write(result.stdout);\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n });\n\n config\n .command(\"org\")\n .description(\"List organizations you belong to\")\n .action(async () => {\n const cliConfig = createCliConfig();\n const organizations = await listOrganizations(cliConfig);\n process.stdout.write(`${JSON.stringify({ organizations }, null, 2)}\\n`);\n });\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../../config\";\nimport { runCliCommand } from \"../../errors\";\nimport { ensureActiveOrganization } from \"../../organization/active-organization\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { resolveActiveProjectId } from \"../../resolve-project-target\";\n\nexport function registerSkillCommand(program: Command): void {\n const skill = program.command(\"skill\").description(\"Inspect platform skills\");\n\n skill\n .command(\"list\")\n .description(\"List skills in the active organization\")\n .action(() =>\n runCliCommand(\n \"List skills failed\",\n async () => {\n const config = createCliConfig();\n const client = createCliPlatformClient(config);\n await ensureActiveOrganization(config);\n const projectId = await resolveActiveProjectId(config);\n const result = await client.skills.list(projectId ? { projectId } : undefined);\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n },\n undefined,\n { orgScoped: true },\n ),\n );\n}\n","import type { Command } from \"commander\";\nimport { resolveProjectRoot } from \"../project/resolve-project-root\";\nimport { syncBundledSkills } from \"../skills/sync-bundled-skills\";\n\nexport function registerSkillsCommand(program: Command): void {\n const skills = program.command(\"skills\").description(\"Manage bundled agent skills\");\n\n skills\n .command(\"sync\")\n .description(\"Overwrite bundled skills and AGENTS.md with the CLI version\")\n .option(\"--dir <path>\", \"Project directory\", process.cwd())\n .action(async (options) => {\n try {\n const root = resolveProjectRoot(options.dir);\n await syncBundledSkills(root);\n process.stdout.write(`Synced bundled skills at ${root}\\n`);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Skills sync failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\n\nconst KEYSTROKE_CONFIG = \"keystroke.config.ts\";\n\n/** Walk up from `fromDir` and return the directory containing `keystroke.config.ts`, if any. */\nexport function resolveKeystrokeConfigRoot(fromDir = process.cwd()): string | null {\n let dir = resolve(fromDir);\n\n while (dir !== dirname(dir)) {\n if (existsSync(join(dir, KEYSTROKE_CONFIG))) {\n return dir;\n }\n\n dir = dirname(dir);\n }\n\n if (existsSync(join(dir, KEYSTROKE_CONFIG))) {\n return dir;\n }\n\n return null;\n}\n","import { existsSync, lstatSync } from \"node:fs\";\nimport type { Command } from \"commander\";\nimport { resolveKeystrokeConfigRoot } from \"../project/resolve-keystroke-config-root\";\nimport { readCliVersion } from \"../version\";\nimport { agentsSkillsDir, readBundleVersion, syncBundledSkills } from \"./sync-bundled-skills\";\n\nfunction commandPath(command: Command): string[] {\n const names: string[] = [];\n\n for (let current: Command | null = command; current; current = current.parent) {\n const name = current.name();\n if (name && name !== \"keystroke\") {\n names.unshift(name);\n }\n }\n\n return names;\n}\n\nfunction shouldSkipAutoSync(command: Command): boolean {\n if (process.env.CI === \"true\" || process.env.CI === \"1\") {\n return true;\n }\n\n const path = commandPath(command);\n if (path[0] === \"init\") {\n return true;\n }\n\n if (path[0] === \"skills\") {\n return true;\n }\n\n return false;\n}\n\nfunction resolveAutoSyncRoot(command: Command): string | null {\n const opts = command.opts<{ dir?: string }>();\n return resolveKeystrokeConfigRoot(opts.dir ?? process.cwd());\n}\n\n/** Sync bundled skills when stale; no-op when not in a project or already up to date. */\nexport async function syncSkills(command: Command): Promise<void> {\n if (shouldSkipAutoSync(command)) {\n return;\n }\n\n const projectRoot = resolveAutoSyncRoot(command);\n if (!projectRoot) {\n return;\n }\n\n const skillsDir = agentsSkillsDir(projectRoot);\n if (!existsSync(skillsDir)) {\n return;\n }\n\n // Monorepo example projects symlink bundled skills for live edits — skip auto-sync.\n if (lstatSync(skillsDir).isSymbolicLink()) {\n return;\n }\n\n const currentVersion = readCliVersion();\n const bundledVersion = await readBundleVersion(projectRoot);\n if (bundledVersion === currentVersion) {\n return;\n }\n\n await syncBundledSkills(projectRoot);\n process.stderr.write(`Synced bundled skills to ${currentVersion}\\n`);\n}\n","import { Command } from \"commander\";\nimport { registerAgentCommand } from \"./commands/agent\";\nimport { registerConnectCommand } from \"./commands/connect\";\nimport { registerCredentialsCommand } from \"./commands/credentials\";\nimport { registerAuthCommand } from \"./commands/auth\";\nimport { registerBuildCommand } from \"./commands/build\";\nimport { registerDeployCommand } from \"./commands/deploy\";\nimport { registerDevCommand } from \"./commands/dev\";\nimport { registerHistoryCommand } from \"./commands/history\";\nimport { registerHealthCommand } from \"./commands/health\";\nimport { registerInitCommand } from \"./commands/init\";\nimport { registerOrganizationCommand } from \"./commands/organization\";\nimport { registerProjectCommand } from \"./commands/project\";\nimport { registerStartCommand } from \"./commands/start\";\nimport { registerTriggerCommand } from \"./commands/trigger\";\nimport { registerWorkflowCommand } from \"./commands/workflow\";\nimport { registerConfigCommand } from \"./commands/config\";\nimport { registerSkillCommand } from \"./commands/skill\";\nimport { registerSkillsCommand } from \"./commands/skills\";\nimport { syncSkills } from \"./skills/sync-skills\";\nimport { readCliVersion } from \"./version\";\nimport { setCliTargetOptions } from \"./target-options\";\n\nexport function createProgram(): Command {\n const program = new Command()\n .name(\"keystroke\")\n .description(\"Build, run, and manage keystroke projects\")\n .version(readCliVersion())\n .option(\"--project <slug>\", \"Platform project slug (deploy target or one-off API target)\")\n .option(\"--local\", \"Force local keystroke server URL\")\n .hook(\"preAction\", async (thisCommand, actionCommand) => {\n const opts = thisCommand.opts<{ project?: string; local?: boolean }>();\n setCliTargetOptions({\n projectId: opts.project,\n local: opts.local,\n });\n await syncSkills(actionCommand);\n });\n\n registerAuthCommand(program);\n registerConnectCommand(program);\n registerConfigCommand(program);\n registerOrganizationCommand(program);\n registerProjectCommand(program);\n registerHistoryCommand(program);\n registerCredentialsCommand(program);\n registerHealthCommand(program);\n registerInitCommand(program);\n registerSkillsCommand(program);\n registerSkillCommand(program);\n registerBuildCommand(program);\n registerDeployCommand(program);\n registerDevCommand(program);\n registerStartCommand(program);\n registerAgentCommand(program);\n registerWorkflowCommand(program);\n registerTriggerCommand(program);\n return program;\n}\n\nexport async function runCli(argv: string[]): Promise<void> {\n const { maybeAutoUpdate } = await import(\"./update/maybe-auto-update\");\n await maybeAutoUpdate(argv);\n createProgram().parse(argv);\n}\n","import { runCli } from \"./program\";\n\nawait runCli(process.argv);\n"],"x_google_ignoreList":[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49],"mappings":";;;;;;;;;;;;;;;;AAEA,MAAa,kBAAkB;AAC/B,MAAa,uBAAuB;AAEpC,MAAa,qBAAqB;AAQlC,SAAS,iBAAiB,QAAwB;CAChD,OAAO,oBAAoB,QAAQ,OAAO,QAAQ,QAAQ,EAAE,CAAC;AAC/D;;AAGA,SAAgB,0BAA0B,QAAoC;CAC5E,MAAM,YAAY,iBAAiB,MAAM;CAEzC,IAAI,cAAA,2BAA+B,cAAc,yBAC/C,OAAO;CAGT,IAAI,cAAA,4BACF,OAAO;AAIX;AAEA,SAAgB,4BACd,QACA,UAAqC,CAAC,GAC9B;CACR,MAAM,WAAW,QAAQ,aAAa,KAAK;CAC3C,IAAI,UACF,OAAO,SAAS,QAAQ,QAAQ,EAAE;CAGpC,MAAM,QAAQ,0BAA0B,MAAM;CAC9C,IAAI,OACF,OAAO;CAIT,QADiB,QAAQ,UAAU,KAAK,KAAA,4BACxB,QAAQ,QAAQ,EAA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AU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,aAAa;EACb,UAAU;CACX;CACA;EACC,IAAI;EACJ,MAAM;EACN,a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gB;AACzN;AACA,MAAM,mCAAmC;CACxC,OAAO;CACP,SAAS;AACV;AACA,MAAM,gCAAgC;CACrC,aAAa;EACZ;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;CACD;CACA,aAAa;EACZ;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa,iCAAiC;EAC/C;EACA;GACC,MAAM;GACN,aAAa,iCAAiC;EAC/C;CACD;CACA,cAAc;EACb;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;CACD;CACA,cAAc;EACb;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;EACA;GACC,MAAM;GACN,aAAa;EACd;CACD;AACD;AACA,SAAS,qBAAqB,KAAK;CAClC,OAAO;EACN,GAAG;EACH,wBAAwB,4BAA4B,GAAG;EACvD,aAAa,8BAA8B,IAAI,OAAO,CAAC;CACxD;AACD;;;;;;AAMA,MAAM,iBAAiB,iBAAiB,IAAI,oBAAoB;AAChE,MAAM,eAAe;CACpB;CACA;CACA;CACA;AACD;AACA,MAAM,eAAe;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAMA,MAAM,iBAAiB;CACtB;EACC,IAAI;EACJ,OAAO;EACP,SAAS;EACT,OAAO;EACP,OAAO;EACP,WAAW;EACX,QAAQ;EACR,gBAAgB;EAChB,WAAW;EACX,YAAY;EACZ,iBAAiB;EACjB,WAAW;EACX,eAAe;EACf,aAAa;EACb,WAAW;CACZ;CACA;EACC,IAAI;EACJ,OAAO;EACP,SAAS;EACT,OAAO;EACP,OAAO;EACP,WAAW;EACX,aAAa;EACb,WAAW;EACX,QAAQ;EACR,gBAAgB;EAChB,WAAW;EACX,YAAY;EACZ,iBAAiB;EACjB,WAAW;EACX,eAAe;EACf,aAAa;EACb,WAAW;CACZ;CACA;EACC,IAAI;EACJ,OAAO;EACP,SAAS;EACT,OAAO;EACP,OAAO;EACP,WAAW;EACX,aAAa;EACb,WAAW;EACX,QAAQ;EACR,gBAAgB;EAChB,WAAW;EACX,YAAY;EACZ,iBAAiB;EACjB,WAAW;EACX,eAAe;GACd;GACA;GACA;EACD;EACA,aAAa;EACb,WAAW;CACZ;CACA;EACC,IAAI;EACJ,OAAO;EACP,SAAS;EACT,OAAO;EACP,OAAO;EACP,WAAW;EACX,QAAQ;EACR,gBAAgB;EAChB,WAAW;EACX,YAAY;EACZ,iBAAiB;E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,KAAK,MAAM,wBAAwB,EAAE,MAAM,KAAK,CAAC,EAAE,KAAK;IAC3E,OAAO,iBAAiB,MAAM,IAAI;GACnC,SAAS,OAAO;IACf,MAAM,MAAM,gBAAgB,KAAK;GAClC;EACD;CACD;AACD;AAGA,MAAM,oBAAoB;CACzB;EACC,KAAK;EACL,MAAM;EACN,WAAW;EACX,gBAAgB;EAChB,aAAa;EACb,SAAS;EACT,UAAU;EACV,kBAAkB,CAAC;EACnB,cAAc;GACb,UAAU;GACV,WAAW;GACX,OAAO;GACP,QAAQ;GACR,WAAW;GACX,KAAK;EACN;EACA,gBAAgB;GACf;GACA;GACA;EACD;EACA,cAAc;GACb,UAAU;GACV,QAAQ;EACT;EACA,iBAAiB;EACjB,0BAA0B;EAC1B,SAAS;CACV;CACA;EACC,KAAK;EACL,MAAM;EACN,WAAW;EACX,gBAAgB;EAChB,aAAa;EACb,SAAS;EACT,UAAU;EACV,kBAAkB;GACjB;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,UAAU;IACV,MAAM;IACN,UAAU;GACX;GACA;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,MAAM;IACN,UAAU;GACX;GACA;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,UAAU;IACV,MAAM;IACN,UAAU;GACX;EACD;EACA,cAAc;GACb,UAAU;GACV,WAAW;GACX,OAAO;GACP,QAAQ;GACR,WAAW;GACX,KAAK;EACN;EACA,gBAAgB;GACf;GACA;GACA;EACD;EACA,cAAc;GACb,UAAU;GACV,QAAQ;EACT;EACA,iBAAiB;EACjB,0BAA0B;EAC1B,SAAS;CACV;CACA;EACC,KAAK;EACL,MAAM;EACN,WAAW;EACX,gBAAgB;EAChB,aAAa;EACb,SAAS;EACT,UAAU;EACV,kBAAkB,CAAC;GAClB,KAAK;GACL,OAAO;GACP,aAAa;GACb,UAAU;GACV,MAAM;GACN,UAAU;EACX,GAAG;GACF,KAAK;GACL,OAAO;GACP,aAAa;GACb,MAAM;GACN,UAAU;GACV,QAAQ;EACT,CAAC;EACD,cAAc;GACb,UAAU;GACV,WAAW;GACX,OAAO;GACP,QAAQ;GACR,WAAW;GACX,KAAK;EACN;EACA,gBAAgB;GACf;GACA;GACA;EACD;EACA,cAAc;GACb,UAAU;GACV,QAAQ;EACT;EACA,iBAAiB;EACjB,0BAA0B;EAC1B,SAAS;CACV;CACA;EACC,KAAK;EACL,MAAM;EACN,WAAW;EACX,gBAAgB;EAChB,aAAa;EACb,SAAS;EACT,UAAU;EACV,kBAAkB;GACjB;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,MAAM;IACN,UAAU;GACX;GACA;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,MAAM;IACN,UAAU;GACX;GACA;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,MAAM;IACN,UAAU;GACX;EACD;EACA,cAAc;GACb,UAAU;GACV,WAAW;GACX,OAAO;GACP,QAAQ;GACR,WAAW;GACX,KAAK;EACN;EACA,gBAAgB;GACf;GACA;GACA;EACD;EACA,cAAc;GACb,UAAU;GACV,QAAQ;EACT;EACA,iBAAiB;EACjB,0BAA0B;EAC1B,SAAS;CACV;CACA;EACC,KAAK;EACL,MAAM;EACN,WAAW;EACX,gBAAgB;EAChB,aAAa;EACb,SAAS;EACT,UAAU;EACV,kBAAkB,CAAC;GAClB,KAAK;GACL,OAAO;GACP,aAAa;GACb,UAAU;GACV,MAAM;GACN,UAAU;EACX,GAAG;GACF,KAAK;GACL,OAAO;GACP,aAAa;GACb,MAAM;GACN,UAAU;EACX,CAAC;EACD,cAAc;GACb,UAAU;GACV,WAAW;GACX,OAAO;GACP,QAAQ;GACR,WAAW;GACX,KAAK;EACN;EACA,gBAAgB;GACf;GACA;GACA;EACD;EACA,cAAc;GACb,UAAU;GACV,QAAQ;EACT;EACA,iBAAiB;EACjB,0BAA0B;EAC1B,SAAS;CACV;AACD;AACA,SAAS,mBAAmB,KAAK;CAChC,OAAO,kBAAkB,MAAM,aAAa,SAAS,Q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AO;AACT;AAEA,eAAsB,OAAO,MAA+B;CAC1D,MAAM,EAAE,oBAAoB,MAAM,OAAO;CACzC,MAAM,gBAAgB,IAAI;CAC1B,cAAc,EAAE,MAAM,IAAI;AAC5B;;;AC9DA,MAAM,OAAO,QAAQ,IAAI"}
1
+ {"version":3,"file":"index.mjs","names":["isPlainObject","objectToString","#options","#runBeforeRequestHooks","#retry","#fetch","#consumeReturnedResponseFromBeforeRetryHook","#runAfterResponseHooks","#retryFromError","#getResponseRequest","#getNormalizedOptions","#getResponseData","#decorateResponse","#cancelResponseBody","#beforeRetryHookErrors","#retryCount","#originalRequest","#cancelBody","#normalizeSearchParams","#input","#userProvidedAbortSignal","#abortController","#createManagedSignal","#startTime","#getCurrentTime","#calculateRetryDelay","#calculateDelay","#readResponseText","#getErrorDataTimeout","#throwIfTotalTimeoutExhausted","#isJsonContentType","#parseJson","#getRemainingTotalTimeout","#assignRequest","#setResponseRequest","#returnedResponseFromBeforeRetryHook","#wrapRequestWithUploadProgress","#cachedNormalizedOptions","#responseRequests","normalizeBaseUrl","applyActiveOrganizationHeader","applyAuthHeaders","createAgentsResource","createCredentialsResource","createHealthResource","createWorkflowsResource","#hiddenStack","now","getMethod","sleep","withActivePlatformClient","collectSetValues","collectSetValues"],"sources":["../src/resolve-platform-url.ts","../src/config.ts","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/KyError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/HTTPError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/NetworkError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/NonError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/ForceRetryError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/SchemaValidationError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/errors/TimeoutError.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/core/constants.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/body.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/is.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/merge.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/normalize.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/timeout.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/delay.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/options.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/is-network-error.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/utils/type-guards.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/core/Ky.js","../../../node_modules/.pnpm/ky@2.0.2/node_modules/ky/distribution/index.js","../../../packages/sdk/dist/index.mjs","../src/auth/credentials.ts","../../../packages/auth/dist/jwt-BVJ7dVm9.mjs","../../../packages/auth/dist/jwt-cache-4YqHn3jM.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/package.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/version.mjs","../../../node_modules/.pnpm/better-call@1.3.5_zod@4.4.3/node_modules/better-call/dist/error.mjs","../../../node_modules/.pnpm/@better-auth+core@1.6.11_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_better-cal_90e7d2cb715d3338ca39f1d23262e011/node_modules/@better-auth/core/dist/error/index.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/plugins/device-authorization/client.mjs","../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/clean-stores/index.js","../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/atom/index.js","../../../node_modules/.pnpm/nanostores@1.3.0/node_modules/nanostores/lifecycle/index.js","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/query.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/broadcast-channel.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/focus-manager.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/online-manager.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/parser.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/session-refresh.mjs","../../../node_modules/.pnpm/@better-auth+core@1.6.11_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_better-cal_90e7d2cb715d3338ca39f1d23262e011/node_modules/@better-auth/core/dist/env/env-impl.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/utils/url.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/fetch-plugins.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/session-atom.mjs","../../../node_modules/.pnpm/defu@6.1.7/node_modules/defu/dist/defu.mjs","../../../node_modules/.pnpm/@better-fetch+fetch@1.1.21/node_modules/@better-fetch/fetch/dist/index.js","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/config.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/utils/is-atom.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/proxy.mjs","../../../node_modules/.pnpm/@better-auth+core@1.6.11_@better-auth+utils@0.4.0_@better-fetch+fetch@1.1.21_better-cal_90e7d2cb715d3338ca39f1d23262e011/node_modules/@better-auth/core/dist/utils/string.mjs","../../../node_modules/.pnpm/better-auth@1.6.11_@tanstack+react-start@1.168.25_crossws@0.4.5_srvx@0.11.15__react-dom_58475d05a96f62cc1b6c1cd2acbead1f/node_modules/better-auth/dist/client/vanilla.mjs","../../../packages/auth/dist/cli.mjs","../src/auth/jwt-cache.ts","../src/auth/resolve-cli-auth.ts","../src/client.ts","../../../packages/sdk/dist/platform/index.mjs","../src/platform-client.ts","../src/resolve-resource-ref.ts","../src/organization/active-organization.ts","../src/dev-session.ts","../src/resolve-api-target.ts","../src/target-options.ts","../src/errors/example-input.ts","../src/errors/format-api-message.ts","../src/errors/format-cli-error.ts","../src/errors/run-command.ts","../src/errors/command-input.ts","../src/resolve-project-target.ts","../src/commands/agent/list.ts","../src/commands/agent/prompt.ts","../src/commands/agent/sessions.ts","../src/commands/agent/index.ts","../src/commands/app/run-app-list.ts","../src/commands/app/list.ts","../src/commands/app/index.ts","../src/commands/connect/parse-connect-scopes.ts","../src/auth/open-url.ts","../src/commands/connect/run-connect.ts","../src/commands/connect/index.ts","../src/commands/credentials/target-options.ts","../src/commands/credentials/run-credentials.ts","../src/commands/credentials/delete.ts","../src/commands/credentials/get.ts","../src/commands/credentials/list.ts","../src/project/env-ref.ts","../src/project/resolve-project-root.ts","../src/project/load-project-env.ts","../src/commands/credentials/parse-value.ts","../src/commands/credentials/rotate-key.ts","../src/commands/credentials/format-set-conflict-error.ts","../src/commands/credentials/set.ts","../src/commands/credentials/update.ts","../src/commands/credentials/index.ts","../src/auth/resolve-login-targets.ts","../src/commands/auth/login.ts","../src/commands/auth/logout.ts","../src/commands/auth/status.ts","../src/commands/auth/index.ts","../src/commands/build.ts","../../../packages/storage/dist/pack-artifact.mjs","../src/project/collect-source.ts","../src/commands/deploy.ts","../src/project/runtime-child-env.ts","../src/project/bootstrap-run.ts","../src/process/run-processes.ts","../src/runtime/ensure-native-deps.ts","../src/runtime/resolve-runtime-node-modules.ts","../src/commands/dev.ts","../src/commands/project/run-project.ts","../src/commands/history/run-history.ts","../src/commands/history/index.ts","../src/commands/health.ts","../src/init/project-name.ts","../src/init/prompts.ts","../src/init/catalog-versions.ts","../src/init/copy-template.ts","../src/init/resolve-template-dir.ts","../src/init/project-files.ts","../src/skills/resolve-skills-bundle-dir.ts","../src/skills/sync-bundled-skills.ts","../src/init/scaffold-empty-src-dirs.ts","../src/init/scaffold-project-dotfiles.ts","../src/init/run-init.ts","../src/commands/init.ts","../src/commands/organization/run-organization.ts","../src/commands/organization/index.ts","../src/commands/project/index.ts","../src/commands/start.ts","../src/commands/trigger/list.ts","../src/commands/trigger/poll.ts","../src/commands/trigger/runs.ts","../src/commands/trigger/index.ts","../src/commands/workflow/list.ts","../src/commands/workflow/run.ts","../src/commands/workflow/runs.ts","../src/commands/workflow/index.ts","../src/commands/config/use-project.ts","../src/commands/config/preferences-patch.ts","../src/commands/config/preferences.ts","../src/commands/config/index.ts","../src/commands/skill/index.ts","../src/commands/skills.ts","../src/project/resolve-keystroke-config-root.ts","../src/skills/sync-skills.ts","../src/program.ts","../src/index.ts"],"sourcesContent":["import { originFromPublicUrl } from \"@keystrokehq/shared\";\n\nexport const DEFAULT_WEB_URL = \"https://app.keystroke.ai\";\nexport const DEFAULT_PLATFORM_URL = \"https://api.keystroke.ai\";\nexport const LOCAL_WEB_URL = \"http://localhost:3000\";\nexport const LOCAL_PLATFORM_URL = \"http://localhost:3002\";\n\nexport type ResolvePlatformUrlOptions = {\n platformUrl?: string;\n /** Used when webUrl does not match a known deployment. */\n fallback?: string;\n};\n\nfunction webOriginFromUrl(webUrl: string): string {\n return originFromPublicUrl(webUrl, webUrl.replace(/\\/+$/, \"\"));\n}\n\n/** Known web origins with a fixed platform API — undefined for custom/staging URLs. */\nexport function knownPlatformUrlForWebUrl(webUrl: string): string | undefined {\n const webOrigin = webOriginFromUrl(webUrl);\n\n if (webOrigin === LOCAL_WEB_URL || webOrigin === \"http://127.0.0.1:3000\") {\n return LOCAL_PLATFORM_URL;\n }\n\n if (webOrigin === DEFAULT_WEB_URL) {\n return DEFAULT_PLATFORM_URL;\n }\n\n return undefined;\n}\n\nexport function resolvePlatformUrlForWebUrl(\n webUrl: string,\n options: ResolvePlatformUrlOptions = {},\n): string {\n const explicit = options.platformUrl?.trim();\n if (explicit) {\n return explicit.replace(/\\/+$/, \"\");\n }\n\n const known = knownPlatformUrlForWebUrl(webUrl);\n if (known) {\n return known;\n }\n\n const fallback = options.fallback?.trim() || DEFAULT_PLATFORM_URL;\n return fallback.replace(/\\/+$/, \"\");\n}\n","import Conf from \"conf\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport {\n DEFAULT_PLATFORM_URL,\n DEFAULT_WEB_URL,\n knownPlatformUrlForWebUrl,\n resolvePlatformUrlForWebUrl,\n} from \"./resolve-platform-url\";\n\nexport type ApiTargetMode = \"local\" | \"platform\";\n\nexport type CliConfig = {\n serverUrl: string;\n webUrl: string;\n platformUrl: string;\n activeOrganizationId?: string;\n activeProjectId?: string;\n apiTarget?: ApiTargetMode;\n};\n\nexport function getCliConfigDir(cwd = join(homedir(), \".keystroke\")): string {\n return cwd;\n}\n\nexport function getConfigDir(config: Conf<CliConfig>): string {\n return dirname(config.path);\n}\n\nexport function getEffectiveApiTarget(config: Conf<CliConfig>): ApiTargetMode {\n const explicit = config.get(\"apiTarget\");\n if (explicit === \"local\" || explicit === \"platform\") {\n return explicit;\n }\n\n return \"local\";\n}\n\nfunction syncPlatformUrlWithWebUrl(config: Conf<CliConfig>): void {\n const webUrl = config.get(\"webUrl\");\n const known = knownPlatformUrlForWebUrl(webUrl);\n if (!known) {\n return;\n }\n\n const stored = config.get(\"platformUrl\");\n if (stored !== known) {\n config.set(\"platformUrl\", known);\n }\n}\n\nexport function createCliConfig(cwd = getCliConfigDir()): Conf<CliConfig> {\n const config = new Conf<CliConfig>({\n projectName: \"keystroke\",\n cwd,\n schema: {\n serverUrl: {\n type: \"string\",\n default: \"http://localhost:3001\",\n },\n webUrl: {\n type: \"string\",\n default: DEFAULT_WEB_URL,\n },\n platformUrl: {\n type: \"string\",\n default: DEFAULT_PLATFORM_URL,\n },\n activeOrganizationId: {\n type: \"string\",\n },\n activeProjectId: {\n type: \"string\",\n },\n apiTarget: {\n type: \"string\",\n enum: [\"local\", \"platform\"],\n },\n },\n });\n\n syncPlatformUrlWithWebUrl(config);\n return config;\n}\n\nexport function getServerUrl(config: Conf<CliConfig>): string {\n return config.get(\"serverUrl\");\n}\n\nexport function getWebUrl(config: Conf<CliConfig>): string {\n return config.get(\"webUrl\");\n}\n\nexport function getPlatformUrl(config: Conf<CliConfig>): string {\n return resolvePlatformUrlForWebUrl(getWebUrl(config), {\n fallback: config.get(\"platformUrl\"),\n });\n}\n","/**\nBase class for all Ky-specific errors. `HTTPError`, `NetworkError`, `TimeoutError`, and `ForceRetryError` extend this class.\n\nYou can use `instanceof KyError` to check if an error originated from Ky, or use the `isKyError()` type guard for cross-realm compatibility and TypeScript type narrowing.\n\nNote: `SchemaValidationError` is intentionally not considered a Ky error. `KyError` covers failures in Ky's HTTP lifecycle (bad status, timeout, retry), while schema validation errors originate from the user-provided schema, not from Ky itself.\n*/\nexport class KyError extends Error {\n name = 'KyError';\n get isKyError() {\n return true;\n }\n}\n//# sourceMappingURL=KyError.js.map","import { KyError } from './KyError.js';\n/**\nError thrown when the response has a non-2xx status code and `throwHttpErrors` is enabled.\n\nThe error has a `response` property with the `Response` object, a `request` property with the `Request` object, an `options` property with the normalized options (either passed to `ky` when creating an instance with `ky.create()` or directly when performing the request), and a `data` property with the pre-parsed response body. For JSON responses (based on `Content-Type`), the body is parsed using the `parseJson` option if set, or `JSON.parse` by default. For other content types, it is set as plain text. If the body is empty or parsing fails, `data` will be `undefined`. To avoid hanging or excessive buffering, `error.data` population is bounded by the request timeout and a 10 MiB response body size limit. The `data` property is populated before `beforeError` hooks run, so hooks can access it.\n\nThe response body is automatically consumed when populating `error.data`, so `error.response.json()` and other body methods will not work. Use `error.data` instead. The `error.response` object is still available for headers, status, etc.\n\nBe aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will be an instance of `NetworkError` instead of `HTTPError` and will not contain a `response` property.\n*/\nexport class HTTPError extends KyError {\n name = 'HTTPError';\n response;\n request;\n options;\n data;\n constructor(response, request, options) {\n const code = (response.status || response.status === 0) ? response.status : '';\n const title = response.statusText ?? '';\n const status = `${code} ${title}`.trim();\n const reason = status ? `status code ${status}` : 'an unknown error';\n super(`Request failed with ${reason}: ${request.method} ${request.url}`);\n this.response = response;\n this.request = request;\n this.options = options;\n }\n}\n//# sourceMappingURL=HTTPError.js.map","import { KyError } from './KyError.js';\n/**\nError thrown when a network error occurs during the request (e.g., DNS failure, connection refused, offline). It has a `request` property with the `Request` object. The original error is available via the standard `cause` property.\n\nNetwork errors are automatically retried (for retriable methods).\n\nNote: Network errors are detected using runtime-specific heuristics. Unrecognized runtimes may produce errors that are not wrapped in `NetworkError`. Use the `shouldRetry` option to handle such cases.\n*/\nexport class NetworkError extends KyError {\n name = 'NetworkError';\n request;\n constructor(request, options) {\n super(`Request failed due to a network error: ${request.method} ${request.url}`, options);\n this.request = request;\n }\n}\n//# sourceMappingURL=NetworkError.js.map","/**\nWrapper for non-Error values that were thrown.\n\nIn JavaScript, any value can be thrown (not just Error instances). This class wraps such values to ensure consistent error handling.\n*/\nexport class NonError extends Error {\n name = 'NonError';\n value;\n constructor(value) {\n let message = 'Non-error value was thrown';\n // Intentionally minimal as this error is just an edge-case.\n try {\n if (typeof value === 'string') {\n message = value;\n }\n else if (value && typeof value === 'object' && 'message' in value && typeof value.message === 'string') {\n message = value.message;\n }\n }\n catch {\n // Use default message if accessing properties throws\n }\n super(message);\n this.value = value;\n }\n}\n//# sourceMappingURL=NonError.js.map","import { KyError } from './KyError.js';\nimport { NonError } from './NonError.js';\n/**\nError used to signal a forced retry from `afterResponse` hooks.\n\nThis is thrown when `ky.retry()` is returned from an `afterResponse` hook. It is observable in `beforeRetry` and `beforeError` hooks via the `isForceRetryError()` type guard.\n*/\nexport class ForceRetryError extends KyError {\n name = 'ForceRetryError';\n customDelay;\n code;\n customRequest;\n constructor(options) {\n // Runtime protection: wrap non-Error causes in NonError\n // TypeScript type is Error for guidance, but JS users can pass anything\n const cause = options?.cause\n ? (options.cause instanceof Error ? options.cause : new NonError(options.cause))\n : undefined;\n super(options?.code ? `Forced retry: ${options.code}` : 'Forced retry', cause ? { cause } : undefined);\n this.customDelay = options?.delay;\n this.code = options?.code;\n this.customRequest = options?.request;\n }\n}\n//# sourceMappingURL=ForceRetryError.js.map","/**\nThe error thrown when [Standard Schema](https://github.com/standard-schema/standard-schema) validation fails in `.json(schema)`. It has an `issues` property with the validation issues from the schema.\n\nThis error intentionally does not extend `KyError` because it does not represent a failure in Ky's HTTP lifecycle. The request succeeded; the user's schema rejected the data. As such, it is not matched by `isKyError()`.\n\n@example\n```\nimport ky, {SchemaValidationError} from 'ky';\nimport {z} from 'zod';\n\nconst userSchema = z.object({name: z.string()});\n\ntry {\n const user = await ky('/api/user').json(userSchema);\n console.log(user.name);\n} catch (error) {\n if (error instanceof SchemaValidationError) {\n console.error(error.issues);\n }\n}\n```\n*/\nexport class SchemaValidationError extends Error {\n name = 'SchemaValidationError';\n issues;\n constructor(issues) {\n super('Response schema validation failed');\n this.issues = issues;\n }\n}\n//# sourceMappingURL=SchemaValidationError.js.map","import { KyError } from './KyError.js';\n/**\nError thrown when the request times out. It has a `request` property with the `Request` object.\n*/\nexport class TimeoutError extends KyError {\n name = 'TimeoutError';\n request;\n constructor(request) {\n super(`Request timed out: ${request.method} ${request.url}`);\n this.request = request;\n }\n}\n//# sourceMappingURL=TimeoutError.js.map","export const supportsRequestStreams = (() => {\n let duplexAccessed = false;\n let hasContentType = false;\n const supportsReadableStream = typeof globalThis.ReadableStream === 'function';\n const supportsRequest = typeof globalThis.Request === 'function';\n if (supportsReadableStream && supportsRequest) {\n try {\n hasContentType = new globalThis.Request('https://empty.invalid', {\n body: new globalThis.ReadableStream(),\n method: 'POST',\n // @ts-expect-error - Types are outdated.\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n }\n catch (error) {\n // QQBrowser on iOS throws \"unsupported BodyInit type\" error (see issue #581)\n if (error instanceof Error && error.message === 'unsupported BodyInit type') {\n return false;\n }\n throw error;\n }\n }\n return duplexAccessed && !hasContentType;\n})();\nexport const supportsAbortController = typeof globalThis.AbortController === 'function';\nexport const supportsAbortSignal = typeof globalThis.AbortSignal === 'function' && typeof globalThis.AbortSignal.any === 'function';\nexport const supportsResponseStreams = typeof globalThis.ReadableStream === 'function';\nexport const supportsFormData = typeof globalThis.FormData === 'function';\nexport const requestMethods = ['get', 'post', 'put', 'patch', 'head', 'delete'];\nconst validate = () => undefined;\nvalidate();\nexport const responseTypes = {\n json: 'application/json',\n text: 'text/*',\n formData: 'multipart/form-data',\n arrayBuffer: '*/*',\n blob: '*/*',\n // Supported in modern Fetch implementations (for example, browsers and recent Node.js/undici).\n // We still feature-check at runtime before exposing the shortcut.\n bytes: '*/*',\n};\n// The maximum value of a 32bit int (see issue #117)\nexport const maxSafeTimeout = 2_147_483_647;\n// Size in bytes of a typical form boundary (e.g., '------WebKitFormBoundaryaxpyiPgbbPti10Rw'), used to help estimate upload size\nexport const usualFormBoundarySize = 40;\n/**\nSymbol that can be returned by a `beforeRetry` hook to stop retrying without throwing an error.\n*/\nexport const stop = Symbol('stop');\n/**\nMarker returned by `ky.retry()` to signal a forced retry from `afterResponse` hooks.\n*/\nexport class RetryMarker {\n options;\n constructor(options) {\n this.options = options;\n }\n}\n/**\nForce a retry from an `afterResponse` hook.\n\nThis allows you to retry a request based on the response content, even if the response has a successful status code. The retry will respect the `retry.limit` option and skip the `shouldRetry` check. The forced retry is observable in `beforeRetry` hooks, where the error will be a `ForceRetryError`.\n\n@param options - Optional configuration for the retry.\n\n@example\n```\nimport ky, {isForceRetryError} from 'ky';\n\nconst api = ky.extend({\n hooks: {\n afterResponse: [\n async ({request, response}) => {\n // Retry based on response body content\n if (response.status === 200) {\n const data = await response.json();\n\n // Simple retry with default delay\n if (data.error?.code === 'TEMPORARY_ERROR') {\n return ky.retry();\n }\n\n // Retry with custom delay from API response\n if (data.error?.code === 'RATE_LIMIT') {\n return ky.retry({\n delay: data.error.retryAfter * 1000,\n code: 'RATE_LIMIT'\n });\n }\n\n // Retry with a modified request (e.g., fallback endpoint)\n if (data.error?.code === 'FALLBACK_TO_BACKUP') {\n return ky.retry({\n request: new Request('https://backup-api.com/endpoint', {\n method: request.method,\n headers: request.headers,\n }),\n code: 'BACKUP_ENDPOINT'\n });\n }\n\n // Retry with refreshed authentication\n if (data.error?.code === 'TOKEN_REFRESH' && data.newToken) {\n return ky.retry({\n request: new Request(request, {\n headers: {\n ...Object.fromEntries(request.headers),\n 'Authorization': `Bearer ${data.newToken}`\n }\n }),\n code: 'TOKEN_REFRESHED'\n });\n }\n\n // Retry with cause to preserve error chain\n try {\n validateResponse(data);\n } catch (error) {\n return ky.retry({\n code: 'VALIDATION_FAILED',\n cause: error\n });\n }\n }\n }\n ],\n beforeRetry: [\n ({error, retryCount}) => {\n // Observable in beforeRetry hooks\n if (isForceRetryError(error)) {\n console.log(`Forced retry #${retryCount}: ${error.message}`);\n // Example output: \"Forced retry #1: Forced retry: RATE_LIMIT\"\n }\n }\n ]\n }\n});\n\nconst response = await api.get('https://example.com/api');\n```\n*/\nexport const retry = (options) => new RetryMarker(options);\nexport const kyOptionKeys = {\n json: true,\n parseJson: true,\n stringifyJson: true,\n searchParams: true,\n baseUrl: true,\n prefix: true,\n retry: true,\n timeout: true,\n totalTimeout: true,\n hooks: true,\n throwHttpErrors: true,\n onDownloadProgress: true,\n onUploadProgress: true,\n fetch: true,\n context: true,\n};\n// Standard RequestInit options that should NOT be passed separately to fetch()\n// because they're already applied to the Request object.\n// Note: `dispatcher` and `priority` are NOT included here - they're fetch-only\n// options that the Request constructor doesn't accept, so they need to be passed\n// separately to fetch().\nexport const requestOptionsRegistry = {\n method: true,\n headers: true,\n body: true,\n mode: true,\n credentials: true,\n cache: true,\n redirect: true,\n referrer: true,\n referrerPolicy: true,\n integrity: true,\n keepalive: true,\n signal: true,\n window: true,\n duplex: true,\n};\n//# sourceMappingURL=constants.js.map","import { usualFormBoundarySize } from '../core/constants.js';\nconst encoder = new TextEncoder();\n// eslint-disable-next-line @typescript-eslint/no-restricted-types\nexport const getBodySize = (body) => {\n if (!body) {\n return 0;\n }\n if (body instanceof FormData) {\n // This is an approximation, as FormData size calculation is not straightforward\n let size = 0;\n for (const [key, value] of body) {\n size += usualFormBoundarySize;\n size += encoder.encode(`Content-Disposition: form-data; name=\"${key}\"`).byteLength;\n size += typeof value === 'string'\n ? encoder.encode(value).byteLength\n : value.size;\n }\n return size;\n }\n if (body instanceof Blob) {\n return body.size;\n }\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\n return body.byteLength;\n }\n if (typeof body === 'string') {\n return encoder.encode(body).byteLength;\n }\n if (body instanceof URLSearchParams) {\n return encoder.encode(body.toString()).byteLength;\n }\n return 0;\n};\nconst withProgress = (stream, totalBytes, onProgress) => {\n let previousChunk;\n let transferredBytes = 0;\n return stream.pipeThrough(new TransformStream({\n transform(currentChunk, controller) {\n controller.enqueue(currentChunk);\n if (previousChunk) {\n transferredBytes += previousChunk.byteLength;\n let percent = totalBytes === 0 ? 0 : transferredBytes / totalBytes;\n // Avoid reporting 100% progress before the stream is actually finished (in case totalBytes is inaccurate)\n if (percent >= 1) {\n // Epsilon is used here to get as close as possible to 100% without reaching it.\n // If we were to use 0.99 here, percent could potentially go backwards.\n percent = 1 - Number.EPSILON;\n }\n onProgress?.({ percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);\n }\n previousChunk = currentChunk;\n },\n flush() {\n if (previousChunk) {\n transferredBytes += previousChunk.byteLength;\n onProgress?.({ percent: 1, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes }, previousChunk);\n }\n },\n }));\n};\nexport const streamResponse = (response, onDownloadProgress) => {\n if (!response.body) {\n return response;\n }\n const responseInit = {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n };\n if (response.status === 204) {\n return new Response(null, responseInit);\n }\n const totalBytes = Math.max(0, Number(response.headers.get('content-length')) || 0);\n return new Response(withProgress(response.body, totalBytes, onDownloadProgress), responseInit);\n};\n// eslint-disable-next-line @typescript-eslint/no-restricted-types\nexport const streamRequest = (request, onUploadProgress, originalBody) => {\n if (!request.body) {\n return request;\n }\n // Use original body for size calculation since request.body is already a stream\n const totalBytes = getBodySize(originalBody ?? request.body);\n return new Request(request, {\n // @ts-expect-error - Types are outdated.\n duplex: 'half',\n body: withProgress(request.body, totalBytes, onUploadProgress),\n });\n};\n//# sourceMappingURL=body.js.map","// eslint-disable-next-line @typescript-eslint/no-restricted-types\nexport const isObject = (value) => value !== null && typeof value === 'object';\n//# sourceMappingURL=is.js.map","import { supportsAbortSignal } from '../core/constants.js';\nimport { isObject } from './is.js';\nconst replaceSymbol = Symbol('replaceOption');\nconst getReplaceState = (value) => isObject(value) && value[replaceSymbol] === true\n ? {\n isReplace: true,\n value: value.value,\n }\n : {\n isReplace: false,\n value,\n };\n/**\nWraps a value so that `ky.extend()` will replace the parent value instead of merging with it. Works with hooks, headers, search parameters, context, and any other deep-merged option.\n\nBy default, `.extend()` deep-merges options with the parent instance: hooks get appended, headers get merged, and search parameters get accumulated. Use `replaceOption` when you want to fully replace a merged property instead.\n\n@example\n```\nimport ky, {replaceOption} from 'ky';\n\nconst base = ky.create({\n hooks: {beforeRequest: [addAuth, addTracking]},\n});\n\n// Replaces instead of appending\nconst extended = base.extend({\n hooks: replaceOption({beforeRequest: [onlyThis]}),\n});\n// hooks.beforeRequest is now [onlyThis], not [addAuth, addTracking, onlyThis]\n```\n*/\nexport const replaceOption = (value) => {\n const markedValue = { [replaceSymbol]: true, value };\n return markedValue;\n};\nexport const validateAndMerge = (...sources) => {\n for (const source of sources) {\n if ((!isObject(source) || Array.isArray(source)) && source !== undefined) {\n throw new TypeError('The `options` argument must be an object');\n }\n }\n return deepMerge({}, ...sources);\n};\nexport const mergeHeaders = (source1 = {}, source2 = {}) => {\n const result = new globalThis.Headers(source1);\n const isHeadersInstance = source2 instanceof globalThis.Headers;\n const source = new globalThis.Headers(source2);\n for (const [key, value] of source.entries()) {\n if ((isHeadersInstance && value === 'undefined') || value === undefined) {\n result.delete(key);\n }\n else {\n result.set(key, value);\n }\n }\n return result;\n};\nconst isPlainObject = (value) => {\n if (!isObject(value) || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\nexport const cloneShallow = (value) => {\n if (value instanceof URLSearchParams) {\n const copy = new URLSearchParams(value);\n const deleted = value[deletedParametersSymbol];\n if (deleted) {\n // Preserve internal deletion markers so init-hook cloning does not resurrect params removed during option merging.\n copy[deletedParametersSymbol] = new Set(deleted);\n }\n return copy;\n }\n if (value instanceof globalThis.Headers) {\n return new globalThis.Headers(value);\n }\n if (Array.isArray(value)) {\n return [...value];\n }\n if (isPlainObject(value)) {\n const copy = { ...value };\n return copy;\n }\n return value;\n};\nconst normalizeHeaderObject = (headers) => Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== undefined));\nconst mergeHeaderContainers = (source1, source2) => {\n if (isPlainObject(source1) && isPlainObject(source2)) {\n return normalizeHeaderObject({ ...source1, ...source2 });\n }\n return mergeHeaders(source1, source2);\n};\nfunction newHookValue(original, incoming, property) {\n return (Object.hasOwn(incoming, property) && incoming[property] === undefined)\n ? []\n : deepMerge(original[property] ?? [], incoming[property] ?? []);\n}\nexport const mergeHooks = (original = {}, incoming = {}) => ({\n init: newHookValue(original, incoming, 'init'),\n beforeRequest: newHookValue(original, incoming, 'beforeRequest'),\n beforeRetry: newHookValue(original, incoming, 'beforeRetry'),\n beforeError: newHookValue(original, incoming, 'beforeError'),\n afterResponse: newHookValue(original, incoming, 'afterResponse'),\n});\nexport const deletedParametersSymbol = Symbol('deletedParameters');\nconst appendSearchParameters = (target, source) => {\n const result = new URLSearchParams();\n const deleted = new Set();\n for (const input of [target, source]) {\n if (input === undefined) {\n continue;\n }\n if (input instanceof URLSearchParams) {\n for (const [key, value] of input.entries()) {\n result.append(key, value);\n deleted.delete(key);\n }\n const inputDeleted = input[deletedParametersSymbol];\n if (inputDeleted) {\n for (const key of inputDeleted) {\n result.delete(key);\n deleted.add(key);\n }\n }\n }\n else if (Array.isArray(input)) {\n for (const pair of input) {\n if (!Array.isArray(pair) || pair.length !== 2) {\n throw new TypeError('Array search parameters must be provided in [[key, value], ...] format');\n }\n result.append(String(pair[0]), String(pair[1]));\n deleted.delete(String(pair[0]));\n }\n }\n else if (isObject(input)) {\n for (const [key, value] of Object.entries(input)) {\n if (value === undefined) {\n result.delete(key);\n deleted.add(key);\n }\n else {\n result.append(key, String(value));\n deleted.delete(key);\n }\n }\n }\n else {\n // String\n const parameters = new URLSearchParams(input);\n for (const [key, value] of parameters.entries()) {\n result.append(key, value);\n deleted.delete(key);\n }\n }\n }\n if (deleted.size > 0) {\n result[deletedParametersSymbol] = deleted;\n }\n return result;\n};\n// TODO: Make this strongly-typed (no `any`).\nexport const deepMerge = (...sources) => {\n let returnValue = {};\n let headers = {};\n let hooks = {};\n let searchParameters;\n const signals = [];\n for (const source of sources) {\n if (Array.isArray(source)) {\n if (!Array.isArray(returnValue)) {\n returnValue = [];\n }\n returnValue = [...returnValue, ...source];\n }\n else if (isObject(source)) {\n for (let [key, value] of Object.entries(source)) {\n // Special handling for AbortSignal instances\n if (key === 'signal' && value instanceof globalThis.AbortSignal) {\n signals.push(value);\n continue;\n }\n const replaceState = getReplaceState(value);\n const { isReplace } = replaceState;\n value = replaceState.value;\n // Special handling for context - shallow merge only\n if (key === 'context') {\n if (value !== undefined && value !== null && (!isObject(value) || Array.isArray(value))) {\n throw new TypeError('The `context` option must be an object');\n }\n // Shallow merge: always create a new object to prevent mutation bugs\n returnValue = {\n ...returnValue,\n context: (value === undefined || value === null)\n ? {}\n : (isReplace\n ? { ...value }\n : { ...returnValue.context, ...value }),\n };\n continue;\n }\n // Special handling for searchParams\n if (key === 'searchParams') {\n if (value === undefined || value === null) {\n // Explicit undefined or null removes searchParams\n searchParameters = undefined;\n }\n else if (isReplace) {\n searchParameters = value;\n }\n else {\n // First source: keep as-is to preserve type (string/object/URLSearchParams)\n // Subsequent sources: merge and convert to URLSearchParams\n searchParameters = searchParameters === undefined ? value : appendSearchParameters(searchParameters, value);\n }\n continue;\n }\n if (isObject(value) && !isReplace && key in returnValue) {\n value = deepMerge(returnValue[key], value);\n }\n returnValue = { ...returnValue, [key]: value };\n }\n if (isObject(source.hooks)) {\n const { value: hookValue, isReplace } = getReplaceState(source.hooks);\n hooks = isReplace\n ? mergeHooks({}, hookValue)\n : mergeHooks(hooks, hookValue);\n returnValue.hooks = hooks;\n }\n if (isObject(source.headers)) {\n const { value: headerValue, isReplace } = getReplaceState(source.headers);\n headers = isReplace\n ? cloneShallow(headerValue)\n : mergeHeaderContainers(headers, headerValue);\n returnValue.headers = headers;\n }\n }\n }\n if (searchParameters !== undefined) {\n returnValue.searchParams = searchParameters;\n }\n if (signals.length > 0) {\n if (signals.length === 1) {\n returnValue.signal = signals[0];\n }\n else if (supportsAbortSignal) {\n returnValue.signal = AbortSignal.any(signals);\n }\n else {\n // When AbortSignal.any is not available, use the last signal\n // This maintains the previous behavior before signal merging was added\n // This can be remove when the `supportsAbortSignal` check is removed.`\n returnValue.signal = signals.at(-1);\n }\n }\n return returnValue;\n};\n//# sourceMappingURL=merge.js.map","import { requestMethods } from '../core/constants.js';\nexport const normalizeRequestMethod = (input) => requestMethods.includes(input) ? input.toUpperCase() : input;\nconst retryMethods = ['get', 'put', 'head', 'delete', 'options', 'trace'];\nconst retryStatusCodes = [408, 413, 429, 500, 502, 503, 504];\nconst retryAfterStatusCodes = [413, 429, 503];\nconst defaultRetryOptions = {\n limit: 2,\n methods: retryMethods,\n statusCodes: retryStatusCodes,\n afterStatusCodes: retryAfterStatusCodes,\n maxRetryAfter: Number.POSITIVE_INFINITY,\n backoffLimit: Number.POSITIVE_INFINITY,\n delay: attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000,\n jitter: undefined,\n retryOnTimeout: false,\n};\nexport const normalizeRetryOptions = (retry = {}) => {\n if (typeof retry === 'number') {\n return {\n ...defaultRetryOptions,\n limit: retry,\n };\n }\n if (retry.methods && !Array.isArray(retry.methods)) {\n throw new Error('retry.methods must be an array');\n }\n if (retry.statusCodes && !Array.isArray(retry.statusCodes)) {\n throw new Error('retry.statusCodes must be an array');\n }\n const normalizedRetry = Object.fromEntries(Object.entries({\n ...retry,\n methods: retry.methods?.map(method => method.toLowerCase()),\n }).filter(([, value]) => value !== undefined));\n return {\n ...defaultRetryOptions,\n ...normalizedRetry,\n };\n};\n//# sourceMappingURL=normalize.js.map","import { TimeoutError } from '../errors/TimeoutError.js';\n// `Promise.race()` workaround (#91)\nexport default async function timeout(request, init, abortController, options) {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n if (abortController) {\n abortController.abort();\n }\n reject(new TimeoutError(request));\n }, options.timeout);\n void options\n .fetch(request, init)\n .then(resolve)\n .catch(reject)\n .then(() => {\n clearTimeout(timeoutId);\n });\n });\n}\n//# sourceMappingURL=timeout.js.map","// https://github.com/sindresorhus/delay/tree/ab98ae8dfcb38e1593286c94d934e70d14a4e111\nexport default async function delay(ms, { signal }) {\n return new Promise((resolve, reject) => {\n if (signal) {\n signal.throwIfAborted();\n signal.addEventListener('abort', abortHandler, { once: true });\n }\n function abortHandler() {\n clearTimeout(timeoutId);\n reject(signal.reason);\n }\n const timeoutId = setTimeout(() => {\n signal?.removeEventListener('abort', abortHandler);\n resolve();\n }, ms);\n });\n}\n//# sourceMappingURL=delay.js.map","import { kyOptionKeys, requestOptionsRegistry } from '../core/constants.js';\nimport { deletedParametersSymbol } from './merge.js';\nexport const findUnknownOptions = (options) => {\n const unknownOptions = {};\n for (const key in options) {\n // Skip inherited properties\n if (!Object.hasOwn(options, key)) {\n continue;\n }\n // Forward every non-standard, non-Ky option to fetch().\n // We intentionally do not check whether the key also exists on `Request`, because some runtimes\n // patch `Request.prototype` with fetch-only extensions. For example, Next.js adds `next`, and the\n // old `key in request` heuristic dropped it unless Ky kept a special-case allowlist.\n // Passing all non-standard keys makes that allowlist unnecessary and preserves future fetch extensions too.\n if (!(key in requestOptionsRegistry) && !(key in kyOptionKeys)) {\n unknownOptions[key] = options[key];\n }\n }\n return unknownOptions;\n};\nexport const hasSearchParameters = (search) => {\n if (search === undefined) {\n return false;\n }\n // The `typeof array` still gives \"object\", so we need different checking for array.\n if (Array.isArray(search)) {\n return search.length > 0;\n }\n if (search instanceof URLSearchParams) {\n return search.size > 0 || Boolean(search[deletedParametersSymbol]?.size);\n }\n // Record\n if (typeof search === 'object') {\n return Object.keys(search).length > 0;\n }\n if (typeof search === 'string') {\n return search.trim().length > 0;\n }\n return Boolean(search);\n};\n//# sourceMappingURL=options.js.map","// Inlined from https://github.com/sindresorhus/is-network-error v1.3.1\nconst objectToString = Object.prototype.toString;\nconst isError = (value) => objectToString.call(value) === '[object Error]';\nconst errorMessages = new Set([\n 'network error', // Chrome\n 'NetworkError when attempting to fetch resource.', // Firefox\n 'The Internet connection appears to be offline.', // Safari 16\n 'Network request failed', // `cross-fetch`\n 'fetch failed', // Undici (Node.js)\n 'terminated', // Undici (Node.js)\n ' A network error occurred.', // Bun (WebKit) - leading space is intentional\n 'Network connection lost', // Cloudflare Workers (fetch)\n]);\nexport default function isRawNetworkError(error) {\n const isValid = error\n && isError(error)\n && error.name === 'TypeError'\n && typeof error.message === 'string';\n if (!isValid) {\n return false;\n }\n const { message, stack } = error;\n // Safari 17+ has generic message but no stack for network errors\n if (message === 'Load failed') {\n return stack === undefined\n // Sentry adds its own stack trace to the fetch error, so also check for that\n || '__sentry_captured__' in error;\n }\n // Deno network errors start with specific text\n if (message.startsWith('error sending request for url')) {\n return true;\n }\n // Chrome: exact \"Failed to fetch\" or with hostname: \"Failed to fetch (example.com)\"\n if (message === 'Failed to fetch' || (message.startsWith('Failed to fetch (') && message.endsWith(')'))) {\n return true;\n }\n // Standard network error messages\n return errorMessages.has(message);\n}\n//# sourceMappingURL=is-network-error.js.map","import { HTTPError } from '../errors/HTTPError.js';\nimport { NetworkError } from '../errors/NetworkError.js';\nimport { TimeoutError } from '../errors/TimeoutError.js';\nimport { ForceRetryError } from '../errors/ForceRetryError.js';\n// Handles cross-realm cases (e.g., iframes, different JS contexts) where `instanceof` fails.\nconst isErrorType = (error, cls) => error instanceof cls || error?.name === cls.name;\n/**\nType guard to check if an error is a `KyError`.\n\nNote: `SchemaValidationError` is intentionally not considered a Ky error. `KyError` covers failures in Ky's HTTP lifecycle (bad status, timeout, retry), while schema validation errors originate from the user-provided schema, not from Ky itself.\n\n@param error - The error to check\n@returns `true` if the error is a Ky error, `false` otherwise\n\n@example\n```\nimport ky, {isKyError} from 'ky';\ntry {\n const response = await ky.get('/api/data');\n} catch (error) {\n if (isKyError(error)) {\n // Handle Ky-specific errors\n console.log('Ky error occurred:', error.message);\n } else {\n // Handle other errors\n console.log('Unknown error:', error);\n }\n}\n```\n*/\nexport function isKyError(error) {\n return error?.isKyError === true || isHTTPError(error) || isNetworkError(error) || isTimeoutError(error) || isForceRetryError(error);\n}\n/**\nType guard to check if an error is an `HTTPError`.\n\n@param error - The error to check\n@returns `true` if the error is an `HTTPError`, `false` otherwise\n\n@example\n```\nimport ky, {isHTTPError} from 'ky';\ntry {\n const response = await ky.get('/api/data');\n} catch (error) {\n if (isHTTPError(error)) {\n console.log('HTTP error status:', error.response.status);\n }\n}\n```\n*/\nexport function isHTTPError(error) {\n return isErrorType(error, HTTPError);\n}\n/**\nType guard to check if an error is a `NetworkError`.\n\n@param error - The error to check\n@returns `true` if the error is a `NetworkError`, `false` otherwise\n\n@example\n```\nimport ky, {isNetworkError} from 'ky';\ntry {\n const response = await ky.get('/api/data');\n} catch (error) {\n if (isNetworkError(error)) {\n console.log('Network error:', error.request.url);\n }\n}\n```\n*/\nexport function isNetworkError(error) {\n return isErrorType(error, NetworkError);\n}\n/**\nType guard to check if an error is a `TimeoutError`.\n\n@param error - The error to check\n@returns `true` if the error is a `TimeoutError`, `false` otherwise\n\n@example\n```\nimport ky, {isTimeoutError} from 'ky';\ntry {\n const response = await ky.get('/api/data', { timeout: 1000 });\n} catch (error) {\n if (isTimeoutError(error)) {\n console.log('Request timed out:', error.request.url);\n }\n}\n```\n*/\nexport function isTimeoutError(error) {\n return isErrorType(error, TimeoutError);\n}\n/**\nType guard to check if an error is a `ForceRetryError`.\n\n@param error - The error to check\n@returns `true` if the error is a `ForceRetryError`, `false` otherwise\n\n@example\n```\nimport ky, {isForceRetryError} from 'ky';\n\nconst api = ky.extend({\n hooks: {\n beforeRetry: [\n ({error, retryCount}) => {\n if (isForceRetryError(error)) {\n console.log(`Forced retry #${retryCount}: ${error.code}`);\n }\n }\n ]\n }\n});\n```\n*/\nexport function isForceRetryError(error) {\n return isErrorType(error, ForceRetryError);\n}\n//# sourceMappingURL=type-guards.js.map","import { HTTPError } from '../errors/HTTPError.js';\nimport { NetworkError } from '../errors/NetworkError.js';\nimport { NonError } from '../errors/NonError.js';\nimport { ForceRetryError } from '../errors/ForceRetryError.js';\nimport { SchemaValidationError } from '../errors/SchemaValidationError.js';\nimport { TimeoutError } from '../errors/TimeoutError.js';\nimport { streamRequest, streamResponse } from '../utils/body.js';\nimport { cloneShallow, mergeHeaders, mergeHooks, deletedParametersSymbol, } from '../utils/merge.js';\nimport { normalizeRequestMethod, normalizeRetryOptions } from '../utils/normalize.js';\nimport timeout from '../utils/timeout.js';\nimport delay from '../utils/delay.js';\nimport { findUnknownOptions, hasSearchParameters } from '../utils/options.js';\nimport isRawNetworkError from '../utils/is-network-error.js';\nimport { isHTTPError, isNetworkError, isTimeoutError } from '../utils/type-guards.js';\nimport { maxSafeTimeout, responseTypes, stop, RetryMarker, supportsAbortController, supportsAbortSignal, supportsFormData, supportsResponseStreams, supportsRequestStreams, } from './constants.js';\nconst maxErrorResponseBodySize = 10 * 1024 * 1024;\nconst prefixUrlRenamedErrorMessage = 'The `prefixUrl` option has been renamed `prefix` in v2 and enhanced to allow slashes in input. See also the new `baseUrl` option for improved flexibility with standard URL resolution: https://github.com/sindresorhus/ky#baseurl';\nconst timedOutResponseData = Symbol('timedOutResponseData');\nconst createTextDecoder = (contentType) => {\n const match = /;\\s*charset\\s*=\\s*(?:\"([^\"]+)\"|([^;,\\s]+))/i.exec(contentType);\n const charset = match?.[1] ?? match?.[2];\n if (charset) {\n try {\n return new TextDecoder(charset);\n }\n catch { }\n }\n return new TextDecoder();\n};\nconst invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';\nconst cloneRetryOptions = (retry) => {\n if (typeof retry !== 'object') {\n return retry;\n }\n // Clone nested arrays too so init hooks can mutate retry config without leaking state across requests.\n return {\n ...retry,\n ...(retry.methods && { methods: [...retry.methods] }),\n ...(retry.statusCodes && { statusCodes: [...retry.statusCodes] }),\n ...(retry.afterStatusCodes && { afterStatusCodes: [...retry.afterStatusCodes] }),\n };\n};\nconst objectToString = Object.prototype.toString;\nconst isRequestInstance = (value) => value instanceof globalThis.Request || objectToString.call(value) === '[object Request]';\n// Accepted custom responses are treated as full Responses throughout Ky.\n// If a custom fetch returns one, it must behave like a Response for cloning,\n// body consumption, `json()` decoration, and any enabled stream features.\nconst isResponseInstance = (value) => value instanceof globalThis.Response || objectToString.call(value) === '[object Response]';\nconst cloneSearchParametersForInitHook = (searchParameters) => {\n if (Array.isArray(searchParameters)) {\n return searchParameters.map(parameter => [...parameter]);\n }\n return cloneShallow(searchParameters);\n};\n// Shallow-clone mutable option properties so init hook mutations don't leak across requests.\nfunction cloneInitHookOptions(options) {\n const clonedOptions = {\n ...options,\n json: cloneShallow(options.json),\n context: cloneShallow(options.context),\n headers: cloneShallow(options.headers),\n searchParams: cloneSearchParametersForInitHook(options.searchParams),\n };\n if (options.retry !== undefined) {\n clonedOptions.retry = cloneRetryOptions(options.retry);\n }\n return clonedOptions;\n}\nconst validateJsonWithSchema = async (jsonValue, schema) => {\n if ((typeof schema !== 'object'\n && typeof schema !== 'function')\n || schema === null) {\n throw new TypeError(invalidSchemaMessage);\n }\n const standardSchema = schema['~standard'];\n if (typeof standardSchema !== 'object'\n || standardSchema === null\n || typeof standardSchema.validate !== 'function') {\n throw new TypeError(invalidSchemaMessage);\n }\n const validationResult = await standardSchema.validate(jsonValue);\n if (validationResult.issues) {\n throw new SchemaValidationError(validationResult.issues);\n }\n return validationResult.value;\n};\nexport class Ky {\n static create(input, options) {\n const initHooks = options.hooks?.init ?? [];\n const initHookOptions = initHooks.length > 0 ? cloneInitHookOptions(options) : options;\n for (const hook of initHooks) {\n hook(initHookOptions);\n }\n const ky = new Ky(input, initHookOptions);\n const function_ = async () => {\n if (typeof ky.#options.timeout === 'number' && ky.#options.timeout > maxSafeTimeout) {\n throw new RangeError(`The \\`timeout\\` option cannot be greater than ${maxSafeTimeout}`);\n }\n if (typeof ky.#options.totalTimeout === 'number' && ky.#options.totalTimeout > maxSafeTimeout) {\n throw new RangeError(`The \\`totalTimeout\\` option cannot be greater than ${maxSafeTimeout}`);\n }\n // Delay the fetch so that body method shortcuts can set the Accept header\n await Promise.resolve();\n const beforeRequestResponse = await ky.#runBeforeRequestHooks();\n let response = beforeRequestResponse ?? await ky.#retry(async () => ky.#fetch());\n let responseFromHook = beforeRequestResponse !== undefined\n || ky.#consumeReturnedResponseFromBeforeRetryHook();\n for (;;) {\n // `undefined` means a hook stopped the flow without providing a response.\n // Non-native Responses still continue through Ky if they pass `isResponseInstance()`.\n if (response === undefined) {\n return response;\n }\n if (isResponseInstance(response)) {\n try {\n // eslint-disable-next-line no-await-in-loop\n response = await ky.#runAfterResponseHooks(response);\n }\n catch (error) {\n if (!(error instanceof ForceRetryError)) {\n throw error;\n }\n // eslint-disable-next-line no-await-in-loop\n const retriedResponse = await ky.#retryFromError(error, async () => ky.#fetch());\n if (retriedResponse === undefined) {\n return retriedResponse;\n }\n response = retriedResponse;\n responseFromHook = ky.#consumeReturnedResponseFromBeforeRetryHook();\n continue;\n }\n }\n const currentResponse = response;\n // Opaque responses (`response.type === 'opaque'`) from `no-cors` requests always have `status: 0` and `ok: false`, but this is not a failure - the actual status is hidden by the browser.\n if (!currentResponse.ok && currentResponse.type !== 'opaque' && (typeof ky.#options.throwHttpErrors === 'function'\n ? ky.#options.throwHttpErrors(currentResponse.status)\n : ky.#options.throwHttpErrors)) {\n // `request` must reflect the request that actually failed, but `options` stays as Ky's\n // normalized options snapshot. Replacement `Request` instances do not preserve the\n // original `BodyInit`, so trying to make `options` mirror arbitrary requests would be lossy.\n const httpError = new HTTPError(currentResponse, ky.#getResponseRequest(currentResponse), ky.#getNormalizedOptions());\n const errorToThrow = httpError;\n // eslint-disable-next-line no-await-in-loop\n httpError.data = await ky.#getResponseData(currentResponse);\n if (responseFromHook) {\n throw errorToThrow;\n }\n // eslint-disable-next-line no-await-in-loop\n const retriedResponse = await ky.#retryFromError(httpError, async () => ky.#fetch());\n if (retriedResponse === undefined) {\n return retriedResponse;\n }\n response = retriedResponse;\n responseFromHook = ky.#consumeReturnedResponseFromBeforeRetryHook();\n continue;\n }\n break;\n }\n if (!isResponseInstance(response)) {\n return response;\n }\n ky.#decorateResponse(response);\n // If `onDownloadProgress` is passed, it uses the stream API internally\n if (ky.#options.onDownloadProgress) {\n if (typeof ky.#options.onDownloadProgress !== 'function') {\n throw new TypeError('The `onDownloadProgress` option must be a function');\n }\n if (!supportsResponseStreams) {\n throw new Error('Streams are not supported in your environment. `ReadableStream` is missing.');\n }\n const progressResponse = response.clone();\n ky.#cancelResponseBody(response);\n return streamResponse(progressResponse, ky.#options.onDownloadProgress);\n }\n return response;\n };\n const result = (async () => {\n try {\n return await function_();\n }\n catch (error) {\n // Non-Error throws (e.g., thrown strings) pass through unchanged\n if (!(error instanceof Error)) {\n throw error;\n }\n // Errors thrown by beforeRetry hooks must propagate unchanged.\n if (ky.#beforeRetryHookErrors.has(error)) {\n throw error;\n }\n let processedError = error;\n for (const hook of ky.#options.hooks.beforeError) {\n // `request` is the current failing request. `options` intentionally remains the\n // stable normalized Ky options snapshot for the same reason as `HTTPError` above.\n // eslint-disable-next-line no-await-in-loop\n const hookResult = await hook({\n request: ky.request,\n options: ky.#getNormalizedOptions(),\n error: processedError,\n retryCount: ky.#retryCount,\n });\n // Only overwrite if the hook returns a valid Error instance.\n if (hookResult instanceof Error) {\n processedError = hookResult;\n }\n }\n throw processedError;\n }\n finally {\n const originalRequest = ky.#originalRequest;\n // Ignore cancellation errors from already-locked or already-consumed streams.\n ky.#cancelBody(originalRequest?.body ?? undefined);\n // Only cancel the current request body if it's distinct from the original (i.e. it was cloned for retries).\n if (ky.request !== originalRequest) {\n ky.#cancelBody(ky.request.body ?? undefined);\n }\n }\n })();\n for (const [type, mimeType] of Object.entries(responseTypes)) {\n // Only expose `.bytes()` when the environment implements it.\n if (type === 'bytes'\n && typeof globalThis.Response?.prototype?.bytes !== 'function') {\n continue;\n }\n result[type] = async (schema) => {\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n ky.request.headers.set('accept', ky.request.headers.get('accept') || mimeType);\n const response = await result;\n if (type !== 'json') {\n return response[type]();\n }\n const text = await response.text();\n if (text === '') {\n if (schema !== undefined) {\n return validateJsonWithSchema(undefined, schema);\n }\n return JSON.parse(text);\n }\n const jsonValue = initHookOptions.parseJson\n ? await initHookOptions.parseJson(text, { request: ky.#getResponseRequest(response), response })\n : JSON.parse(text);\n return schema === undefined ? jsonValue : validateJsonWithSchema(jsonValue, schema);\n };\n }\n return result;\n }\n // eslint-disable-next-line unicorn/prevent-abbreviations\n static #normalizeSearchParams(searchParams) {\n // Filter out undefined values from plain objects\n if (searchParams && typeof searchParams === 'object' && !Array.isArray(searchParams) && !(searchParams instanceof URLSearchParams)) {\n return Object.fromEntries(Object.entries(searchParams).filter(([, value]) => value !== undefined));\n }\n return searchParams;\n }\n request;\n #abortController;\n #retryCount = 0;\n // eslint-disable-next-line @typescript-eslint/prefer-readonly -- False positive: #input is reassigned on line 202\n #input;\n #options;\n #originalRequest;\n #userProvidedAbortSignal;\n #beforeRetryHookErrors = new WeakSet();\n #cachedNormalizedOptions;\n #startTime;\n #returnedResponseFromBeforeRetryHook = false;\n #responseRequests = new WeakMap();\n // eslint-disable-next-line complexity\n constructor(input, options = {}) {\n this.#input = input;\n if (Object.hasOwn(options, 'prefixUrl')) {\n throw new Error(prefixUrlRenamedErrorMessage);\n }\n this.#options = {\n ...options,\n headers: mergeHeaders(this.#input.headers, options.headers),\n hooks: mergeHooks({}, options.hooks),\n method: normalizeRequestMethod(options.method ?? this.#input.method ?? 'GET'),\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n prefix: String(options.prefix || ''),\n retry: normalizeRetryOptions(options.retry),\n throwHttpErrors: options.throwHttpErrors ?? true,\n timeout: options.timeout ?? 10_000,\n totalTimeout: options.totalTimeout ?? false,\n fetch: options.fetch ?? globalThis.fetch.bind(globalThis),\n context: options.context ?? {},\n };\n if (typeof this.#input !== 'string' && !(this.#input instanceof URL || this.#input instanceof globalThis.Request)) {\n throw new TypeError('`input` must be a string, URL, or Request');\n }\n if (typeof this.#input === 'string') {\n if (this.#options.prefix) {\n const normalizedPrefix = this.#options.prefix.replace(/\\/+$/, '');\n const normalizedInput = this.#input.replace(/^\\/+/, '');\n this.#input = `${normalizedPrefix}/${normalizedInput}`;\n }\n if (this.#options.baseUrl) {\n let absoluteInput;\n try {\n absoluteInput = new URL(this.#input);\n }\n catch { }\n if (!absoluteInput) {\n this.#input = new URL(this.#input, (new Request(this.#options.baseUrl)).url);\n }\n }\n }\n if (supportsAbortController && supportsAbortSignal) {\n this.#userProvidedAbortSignal = this.#options.signal ?? this.#input.signal;\n this.#abortController = new globalThis.AbortController();\n this.#options.signal = this.#createManagedSignal();\n }\n if (supportsRequestStreams) {\n // @ts-expect-error - Types are outdated.\n this.#options.duplex = 'half';\n }\n if (this.#options.json !== undefined) {\n this.#options.body = this.#options.stringifyJson?.(this.#options.json) ?? JSON.stringify(this.#options.json);\n this.#options.headers.set('content-type', this.#options.headers.get('content-type') ?? 'application/json');\n }\n // To provide correct form boundary, Content-Type header should be deleted when creating Request from another Request with FormData/URLSearchParams body\n // Only delete if user didn't explicitly provide a custom content-type\n const userProvidedContentType = options.headers && new globalThis.Headers(options.headers).has('content-type');\n if (this.#input instanceof globalThis.Request\n && ((supportsFormData && this.#options.body instanceof globalThis.FormData) || this.#options.body instanceof URLSearchParams)\n && !userProvidedContentType) {\n this.#options.headers.delete('content-type');\n }\n this.request = new globalThis.Request(this.#input, this.#options);\n if (hasSearchParameters(this.#options.searchParams)) {\n const url = new URL(this.request.url);\n const deleted = this.#options.searchParams?.[deletedParametersSymbol];\n if (deleted) {\n // Remove keys from the input URL first so later searchParams entries can intentionally re-add them.\n for (const key of deleted) {\n url.searchParams.delete(key);\n }\n }\n if (typeof this.#options.searchParams === 'string') {\n const stringSearchParameters = this.#options.searchParams.replace(/^\\?/, '');\n if (stringSearchParameters !== '') {\n url.search = url.search ? `${url.search}&${stringSearchParameters}` : `?${stringSearchParameters}`;\n }\n }\n else {\n const optionsSearchParameters = new URLSearchParams(Ky.#normalizeSearchParams(this.#options.searchParams));\n for (const [key, value] of optionsSearchParameters.entries()) {\n url.searchParams.append(key, value);\n }\n }\n if (this.#options.searchParams\n && typeof this.#options.searchParams === 'object'\n && !Array.isArray(this.#options.searchParams)\n && !(this.#options.searchParams instanceof URLSearchParams)) {\n for (const [key, value] of Object.entries(this.#options.searchParams)) {\n if (value === undefined) {\n url.searchParams.delete(key);\n }\n }\n }\n // Recreate request with the updated URL. We already have all options in this.#options, including duplex.\n this.request = new globalThis.Request(url, this.#options);\n }\n if (this.#options.onUploadProgress && typeof this.#options.onUploadProgress !== 'function') {\n throw new TypeError('The `onUploadProgress` option must be a function');\n }\n // `totalTimeout` starts when the request pipeline is created, so it also includes\n // Ky's internal scheduling and user hook time before the first fetch attempt.\n this.#startTime = typeof this.#options.totalTimeout === 'number' ? this.#getCurrentTime() : undefined;\n }\n #calculateDelay() {\n const retryDelay = this.#options.retry.delay(this.#retryCount + 1);\n let jitteredDelay = retryDelay;\n if (this.#options.retry.jitter === true) {\n jitteredDelay = Math.random() * retryDelay;\n }\n else if (typeof this.#options.retry.jitter === 'function') {\n jitteredDelay = this.#options.retry.jitter(retryDelay);\n if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {\n jitteredDelay = retryDelay;\n }\n }\n return Math.min(this.#options.retry.backoffLimit, jitteredDelay);\n }\n async #calculateRetryDelay(error) {\n if (this.#retryCount >= this.#options.retry.limit) {\n throw error;\n }\n // Wrap non-Error throws to ensure consistent error handling\n const errorObject = error instanceof Error ? error : new NonError(error);\n // Handle forced retry from afterResponse hook - skip method check and shouldRetry\n if (errorObject instanceof ForceRetryError) {\n return errorObject.customDelay ?? this.#calculateDelay();\n }\n // Check if method is retriable for non-forced retries\n if (!this.#options.retry.methods.includes(this.request.method.toLowerCase())) {\n throw error;\n }\n // User-provided shouldRetry function takes precedence over default checks (retryOnTimeout, status codes, etc.)\n if (this.#options.retry.shouldRetry !== undefined) {\n const result = await this.#options.retry.shouldRetry({ error: errorObject, retryCount: this.#retryCount + 1 });\n // Strict boolean checking - only exact true/false are handled specially\n if (result === false) {\n throw error;\n }\n if (result === true) {\n // Force retry - skip all other validation and return delay\n return this.#calculateDelay();\n }\n // If undefined or any other value, fall through to default behavior\n }\n // Default timeout behavior\n if (isTimeoutError(error)) {\n if (!this.#options.retry.retryOnTimeout) {\n throw error;\n }\n return this.#calculateDelay();\n }\n if (isHTTPError(error)) {\n if (!this.#options.retry.statusCodes.includes(error.response.status)) {\n throw error;\n }\n const retryAfter = error.response.headers.get('Retry-After')\n ?? error.response.headers.get('RateLimit-Reset')\n ?? error.response.headers.get('X-RateLimit-Retry-After') // Symfony-based services\n ?? error.response.headers.get('X-RateLimit-Reset') // GitHub\n ?? error.response.headers.get('X-Rate-Limit-Reset'); // Twitter\n if (retryAfter && this.#options.retry.afterStatusCodes.includes(error.response.status)) {\n let after = Number(retryAfter) * 1000;\n if (Number.isNaN(after)) {\n after = Date.parse(retryAfter) - Date.now();\n }\n else if (after >= Date.parse('2024-01-01')) {\n // A large number is treated as a timestamp (fixed threshold protects against clock skew)\n after -= Date.now();\n }\n if (!Number.isFinite(after)) {\n return Math.min(this.#options.retry.maxRetryAfter, this.#calculateDelay());\n }\n after = Math.max(0, after);\n // Don't apply jitter when server provides explicit retry timing\n return Math.min(this.#options.retry.maxRetryAfter, after);\n }\n if (error.response.status === 413) {\n throw error;\n }\n return this.#calculateDelay();\n }\n // Only retry known retriable error types. Unknown errors (e.g., programming bugs) are not retried.\n if (!isNetworkError(error)) {\n throw error;\n }\n return this.#calculateDelay();\n }\n #decorateResponse(response) {\n const request = this.#getResponseRequest(response);\n if (this.#options.parseJson) {\n response.json = async () => {\n const text = await response.text();\n if (text === '') {\n return JSON.parse(text);\n }\n return this.#options.parseJson(text, { request, response });\n };\n }\n return response;\n }\n async #getResponseData(response) {\n // Even with request timeouts disabled, bound error-body reads so retries and error propagation\n // cannot be stalled indefinitely by never-ending response streams.\n const text = await this.#readResponseText(response, this.#getErrorDataTimeout());\n if (text === timedOutResponseData) {\n this.#throwIfTotalTimeoutExhausted();\n return undefined;\n }\n if (!text) {\n return undefined;\n }\n if (!this.#isJsonContentType(response.headers.get('content-type') ?? '')) {\n return text;\n }\n const data = await this.#parseJson(text, response, this.#getErrorDataTimeout(), this.#getResponseRequest(response));\n if (data === timedOutResponseData) {\n this.#throwIfTotalTimeoutExhausted();\n return undefined;\n }\n return data;\n }\n #getErrorDataTimeout() {\n const errorDataTimeout = this.#options.timeout === false ? 10_000 : this.#options.timeout;\n const remainingTotal = this.#getRemainingTotalTimeout();\n if (remainingTotal === undefined) {\n return errorDataTimeout;\n }\n if (remainingTotal <= 0) {\n throw new TimeoutError(this.request);\n }\n return Math.min(errorDataTimeout, remainingTotal);\n }\n #isJsonContentType(contentType) {\n // Match JSON subtypes like `json`, `problem+json`, and `vnd.api+json`.\n const mimeType = (contentType.split(';', 1)[0] ?? '').trim().toLowerCase();\n return /\\/(?:.*[.+-])?json$/.test(mimeType);\n }\n async #readResponseText(response, timeoutMs) {\n const { body } = response;\n if (!body) {\n try {\n return await response.text();\n }\n catch {\n return undefined;\n }\n }\n let reader;\n try {\n reader = body.getReader();\n }\n catch {\n // Another consumer already locked the stream.\n return undefined;\n }\n const decoder = createTextDecoder(response.headers.get('content-type') ?? '');\n const chunks = [];\n let totalBytes = 0;\n const readAll = (async () => {\n try {\n for (;;) {\n // eslint-disable-next-line no-await-in-loop\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n totalBytes += value.byteLength;\n if (totalBytes > maxErrorResponseBodySize) {\n void reader.cancel().catch(() => undefined);\n return undefined;\n }\n chunks.push(decoder.decode(value, { stream: true }));\n }\n }\n catch {\n return undefined;\n }\n chunks.push(decoder.decode());\n return chunks.join('');\n })();\n const timeoutPromise = new Promise(resolve => {\n const timeoutId = setTimeout(() => {\n resolve(timedOutResponseData);\n }, timeoutMs);\n void readAll.finally(() => {\n clearTimeout(timeoutId);\n });\n });\n const result = await Promise.race([readAll, timeoutPromise]);\n if (result === timedOutResponseData) {\n void reader.cancel().catch(() => undefined);\n }\n return result;\n }\n async #parseJson(text, response, timeoutMs, request) {\n let timeoutId;\n try {\n return await Promise.race([\n Promise.resolve().then(() => this.#options.parseJson\n ? this.#options.parseJson(text, { request, response })\n : JSON.parse(text)),\n new Promise(resolve => {\n timeoutId = setTimeout(() => {\n resolve(timedOutResponseData);\n }, timeoutMs);\n }),\n ]);\n }\n catch {\n return undefined;\n }\n finally {\n clearTimeout(timeoutId);\n }\n }\n #cancelBody(body) {\n if (!body) {\n return;\n }\n // Ignore cancellation failures from already-locked or already-consumed streams.\n void body.cancel().catch(() => undefined);\n }\n #cancelResponseBody(response) {\n // Ignore cancellation failures from already-locked or already-consumed streams.\n this.#cancelBody(response.body ?? undefined);\n }\n #createManagedSignal() {\n return this.#userProvidedAbortSignal\n ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController.signal])\n : this.#abortController.signal;\n }\n #throwIfTotalTimeoutExhausted() {\n const remaining = this.#getRemainingTotalTimeout();\n if (remaining !== undefined && remaining <= 0) {\n throw new TimeoutError(this.request);\n }\n }\n async #runBeforeRequestHooks() {\n for (const hook of this.#options.hooks.beforeRequest) {\n // eslint-disable-next-line no-await-in-loop\n const result = await hook({\n request: this.request,\n options: this.#getNormalizedOptions(),\n retryCount: 0,\n });\n if (isRequestInstance(result)) {\n this.#assignRequest(result);\n }\n else if (isResponseInstance(result)) {\n return result;\n }\n }\n return undefined;\n }\n async #runAfterResponseHooks(response) {\n const responseRequest = this.#getResponseRequest(response);\n for (const hook of this.#options.hooks.afterResponse) {\n const hookResponse = this.#setResponseRequest(response.clone(), responseRequest);\n this.#decorateResponse(hookResponse);\n let modifiedResponse;\n try {\n // eslint-disable-next-line no-await-in-loop\n modifiedResponse = await hook({\n request: this.request,\n options: this.#getNormalizedOptions(),\n response: hookResponse,\n retryCount: this.#retryCount,\n });\n }\n catch (error) {\n // Cancel both responses to prevent memory leaks when hook throws\n if (hookResponse !== response) {\n this.#cancelResponseBody(hookResponse);\n }\n this.#cancelResponseBody(response);\n throw error;\n }\n if (modifiedResponse instanceof RetryMarker) {\n // Cancel both the cloned response passed to the hook and the current response to prevent resource leaks (especially important in Deno/Bun).\n // Do not await cancellation since hooks can clone the response, leaving extra tee branches that keep cancel promises pending per the Streams spec.\n if (hookResponse !== response) {\n this.#cancelResponseBody(hookResponse);\n }\n this.#cancelResponseBody(response);\n throw new ForceRetryError(modifiedResponse.options);\n }\n const nextResponse = isResponseInstance(modifiedResponse)\n ? this.#setResponseRequest(modifiedResponse, responseRequest)\n : response;\n // Cancel any response bodies we won't use to prevent memory leaks.\n // Uses fire-and-forget since hooks may have cloned the response, creating tee branches that block cancellation.\n // If the hook wrapped an existing body into a new Response, both Response objects can still point at the same stream.\n if (hookResponse !== response && hookResponse !== nextResponse && hookResponse.body !== nextResponse.body) {\n this.#cancelResponseBody(hookResponse);\n }\n if (response !== nextResponse && response.body !== nextResponse.body) {\n this.#cancelResponseBody(response);\n }\n response = nextResponse;\n }\n return response;\n }\n async #retry(function_) {\n try {\n return await function_();\n }\n catch (error) {\n return this.#retryFromError(error, function_);\n }\n }\n async #retryFromError(error, function_) {\n this.#returnedResponseFromBeforeRetryHook = false;\n const retryDelay = Math.min(await this.#calculateRetryDelay(error), maxSafeTimeout);\n const delayOptions = { signal: this.#userProvidedAbortSignal };\n const remainingTimeout = this.#getRemainingTotalTimeout();\n if (remainingTimeout !== undefined) {\n if (remainingTimeout <= 0) {\n throw new TimeoutError(this.request);\n }\n // If waiting would consume all remaining budget, time out without starting another request.\n if (retryDelay >= remainingTimeout) {\n await delay(remainingTimeout, delayOptions);\n throw new TimeoutError(this.request);\n }\n }\n // Only use user-provided signal for delay, not our internal abortController\n await delay(retryDelay, delayOptions);\n this.#throwIfTotalTimeoutExhausted();\n // Apply custom request from forced retry before beforeRetry hooks\n // Ensure the custom request has the correct managed signal for timeouts and user aborts\n if (error instanceof ForceRetryError && error.customRequest) {\n const customRequest = new globalThis.Request(error.customRequest, this.#options.signal ? { signal: this.#options.signal } : undefined);\n // Replacement Requests are authoritative by design. Do not rewrite headers here,\n // even for cross-origin retries. Callers using `ky.retry({request})` explicitly\n // opted into the exact Request they constructed.\n this.#assignRequest(customRequest);\n }\n for (const hook of this.#options.hooks.beforeRetry) {\n let hookResult;\n try {\n // eslint-disable-next-line no-await-in-loop\n hookResult = await hook({\n request: this.request,\n options: this.#getNormalizedOptions(),\n error: error,\n retryCount: this.#retryCount + 1,\n });\n }\n catch (hookError) {\n // Preserve the original request error path (`throw error`) so beforeError hooks can still run.\n if (hookError instanceof Error && hookError !== error) {\n this.#beforeRetryHookErrors.add(hookError);\n }\n throw hookError;\n }\n if (isRequestInstance(hookResult)) {\n // Same contract as `ky.retry({request})`: a Request returned from `beforeRetry`\n // is used as-is rather than being sanitized or otherwise rewritten by Ky.\n this.#assignRequest(hookResult);\n break;\n }\n if (isResponseInstance(hookResult)) {\n this.#returnedResponseFromBeforeRetryHook = true;\n this.#retryCount++;\n return hookResult;\n }\n // If `stop` is returned from the hook, the retry process is stopped\n if (hookResult === stop) {\n return;\n }\n }\n this.#throwIfTotalTimeoutExhausted();\n this.#retryCount++;\n return this.#retry(function_);\n }\n #consumeReturnedResponseFromBeforeRetryHook() {\n const value = this.#returnedResponseFromBeforeRetryHook;\n this.#returnedResponseFromBeforeRetryHook = false;\n return value;\n }\n async #fetch() {\n // Reset abortController if it was aborted (happens on timeout retry)\n if (this.#abortController?.signal.aborted) {\n this.#abortController = new globalThis.AbortController();\n this.#options.signal = this.#createManagedSignal();\n // Recreate request with new signal\n this.request = new globalThis.Request(this.request, { signal: this.#options.signal });\n }\n const nonRequestOptions = findUnknownOptions(this.#options);\n const retryRequest = this.#options.retry.limit > 0 ? this.request.clone() : undefined;\n const request = this.#wrapRequestWithUploadProgress(this.request, this.#options.body ?? undefined);\n // Cloning is done here to prepare in advance for retries.\n // Skip cloning when retries are disabled - cloning a streaming body calls ReadableStream#tee()\n // which buffers the entire stream in memory, causing excessive memory usage for large uploads.\n this.#originalRequest = request;\n if (retryRequest) {\n this.request = retryRequest;\n }\n try {\n const remainingTotal = this.#getRemainingTotalTimeout();\n if (remainingTotal !== undefined && remainingTotal <= 0) {\n throw new TimeoutError(this.request);\n }\n const effectiveTimeout = this.#options.timeout === false\n ? remainingTotal\n : (remainingTotal === undefined\n ? this.#options.timeout\n : Math.min(this.#options.timeout, remainingTotal));\n const response = effectiveTimeout === undefined\n ? await this.#options.fetch(request, nonRequestOptions)\n : await timeout(request, nonRequestOptions, this.#abortController, {\n timeout: effectiveTimeout,\n fetch: this.#options.fetch,\n });\n return this.#setResponseRequest(response, request);\n }\n catch (error) {\n if (isRawNetworkError(error)) {\n throw new NetworkError(this.request, { cause: error });\n }\n throw error;\n }\n }\n #getRemainingTotalTimeout() {\n if (this.#startTime === undefined) {\n return undefined;\n }\n const elapsed = this.#getCurrentTime() - this.#startTime;\n return Math.max(0, this.#options.totalTimeout - elapsed);\n }\n #getCurrentTime() {\n return globalThis.performance?.now() ?? Date.now();\n }\n #getNormalizedOptions() {\n if (!this.#cachedNormalizedOptions) {\n // Exclude Ky-specific options that are not part of `RequestInit`.\n const { hooks, json, parseJson, stringifyJson, searchParams, timeout, totalTimeout, throwHttpErrors, fetch, ...normalizedOptions } = this.#options;\n this.#cachedNormalizedOptions = Object.freeze(normalizedOptions);\n }\n return this.#cachedNormalizedOptions;\n }\n #assignRequest(request) {\n this.#cachedNormalizedOptions = undefined;\n this.request = request;\n }\n #getResponseRequest(response) {\n return this.#responseRequests.get(response) ?? this.request;\n }\n #setResponseRequest(response, request) {\n this.#responseRequests.set(response, request);\n return response;\n }\n #wrapRequestWithUploadProgress(request, originalBody) {\n if (!this.#options.onUploadProgress || !request.body || !supportsRequestStreams) {\n return request;\n }\n return streamRequest(request, this.#options.onUploadProgress, originalBody ?? this.#options.body ?? undefined);\n }\n}\n//# sourceMappingURL=Ky.js.map","/*! MIT License © Sindre Sorhus */\nimport { Ky } from './core/Ky.js';\nimport { requestMethods, stop, retry } from './core/constants.js';\nimport { validateAndMerge } from './utils/merge.js';\nconst createInstance = (defaults) => {\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const ky = (input, options) => Ky.create(input, validateAndMerge(defaults, options));\n for (const method of requestMethods) {\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n ky[method] = (input, options) => Ky.create(input, validateAndMerge(defaults, options, { method }));\n }\n ky.create = (newDefaults) => createInstance(validateAndMerge(newDefaults));\n ky.extend = (newDefaults) => {\n if (typeof newDefaults === 'function') {\n newDefaults = newDefaults(defaults ?? {});\n }\n return createInstance(validateAndMerge(defaults, newDefaults));\n };\n ky.stop = stop;\n ky.retry = retry;\n return ky;\n};\nconst ky = createInstance();\nexport default ky;\nexport { KyError } from './errors/KyError.js';\nexport { HTTPError } from './errors/HTTPError.js';\nexport { SchemaValidationError } from './errors/SchemaValidationError.js';\nexport { NetworkError } from './errors/NetworkError.js';\nexport { TimeoutError } from './errors/TimeoutError.js';\nexport { ForceRetryError } from './errors/ForceRetryError.js';\nexport { isKyError, isHTTPError, isNetworkError, isTimeoutError, isForceRetryError, } from './utils/type-guards.js';\nexport { replaceOption } from './utils/merge.js';\n// Intentionally not exporting this for now as it's just an implementation detail and we don't want to commit to a certain API yet at least.\n// export {NonError} from './errors/NonError.js';\n//# sourceMappingURL=index.js.map","import ky, { isHTTPError } from \"ky\";\nimport { ACTIVE_ORG_HEADER, AgentSessionDetailResponseSchema, AgentSessionListResponseSchema, ConnectAuthorizeUrlResponseSchema, ConnectProvidersResponseSchema, CreateCredentialInstanceBodySchema, CredentialInstanceListResponseSchema, CredentialInstanceRecordSchema, HealthResponseSchema, PollRunResponseSchema, PromptInputSchema, PromptResponseSchema, QueuedAgentPromptResponseSchema, QueuedRunResponseSchema, SkipResponseSchema, TriggerDetailResponseSchema, TriggerListResponseSchema, TriggerRunDetailResponseSchema, TriggerRunListResponseSchema, UpdateCredentialInstanceBodySchema, WorkflowRunDetailResponseSchema, WorkflowRunListResponseSchema, parseErrorResponse } from \"@keystrokehq/shared\";\n//#region src/auth.ts\nfunction normalizeBaseUrl(baseUrl) {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\nfunction applyActiveOrganizationHeader(request, organizationId) {\n\tif (organizationId) request.headers.set(ACTIVE_ORG_HEADER, organizationId);\n}\nfunction applyAuthHeaders(request, auth, getToken) {\n\tif (!auth || auth.type === \"none\") return;\n\tif (auth.type === \"apiKey\") {\n\t\tconst key = auth.getKey();\n\t\tif (key) request.headers.set(\"x-api-key\", key);\n\t\treturn;\n\t}\n\tif (auth.type === \"bearer\") {\n\t\tconst tokenPromise = getToken?.() ?? auth.getToken();\n\t\treturn Promise.resolve(tokenPromise).then((token) => {\n\t\t\tif (token) request.headers.set(\"Authorization\", `Bearer ${token}`);\n\t\t});\n\t}\n}\n//#endregion\n//#region src/errors.ts\nvar KeystrokeError = class extends Error {\n\tstatus;\n\tbody;\n\tconstructor(message, status, body) {\n\t\tsuper(message);\n\t\tthis.name = \"KeystrokeError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t}\n};\nasync function toKeystrokeError(error) {\n\tif (!isHTTPError(error)) return new KeystrokeError(error instanceof Error ? error.message : \"Request failed\", 0, null);\n\tconst status = error.response.status;\n\tconst body = error.data ?? null;\n\tconst parsed = parseErrorResponse(body);\n\treturn new KeystrokeError(parsed ? parsed.message ?? parsed.error : `Request failed with status ${status}`, status, body);\n}\n//#endregion\n//#region src/resources/shared.ts\nasync function readJson(response) {\n\treturn response.json();\n}\n//#endregion\n//#region src/resources/agents.ts\nfunction isQueuedAgentPromptResponse(value) {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (\"messages\" in value) return false;\n\treturn QueuedAgentPromptResponseSchema.safeParse(value).success;\n}\nfunction listSessionsSearchParams(query) {\n\tif (!query) return {};\n\tconst params = {};\n\tif (query.limit !== void 0) params.limit = String(query.limit);\n\tif (query.cursor) params.cursor = query.cursor;\n\tif (query.status) params.status = query.status;\n\tif (query.source) params.source = query.source;\n\treturn params;\n}\nfunction detailSearchParams$2(query) {\n\tif (!query?.include) return {};\n\treturn { include: query.include };\n}\nfunction createAgentsResource(http) {\n\treturn {\n\t\tasync prompt(id, input) {\n\t\t\tconst body = PromptInputSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst response = await http.post(`agents/${id}`, { json: body });\n\t\t\t\tconst data = await readJson(response);\n\t\t\t\tif (response.status === 202) return QueuedAgentPromptResponseSchema.parse(data);\n\t\t\t\treturn PromptResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync listSessions(agentId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`agents/${agentId}/sessions`, { searchParams: listSessionsSearchParams(query) }).json();\n\t\t\t\treturn AgentSessionListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync getSession(agentId, sessionId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`agents/${agentId}/sessions/${sessionId}`, { searchParams: detailSearchParams$2(query) }).json();\n\t\t\t\treturn AgentSessionDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/resources/connect.ts\nfunction routeFromPath(path) {\n\treturn path.replace(/^\\//, \"\");\n}\nfunction createConnectResource(http) {\n\treturn {\n\t\tasync listProviders() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"connect/providers\").json();\n\t\t\t\treturn ConnectProvidersResponseSchema.parse(data).providers;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync getAuthorizeUrl(path) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(routeFromPath(path)).json();\n\t\t\t\treturn ConnectAuthorizeUrlResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/resources/credentials.ts\nfunction createCredentialsResource(http) {\n\treturn {\n\t\tasync listInstances(options) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = options?.key ? { key: options.key } : void 0;\n\t\t\t\tconst data = await http.get(\"credentials/instances\", { searchParams }).json();\n\t\t\t\treturn CredentialInstanceListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync createInstance(body) {\n\t\t\ttry {\n\t\t\t\tconst payload = CreateCredentialInstanceBodySchema.parse(body);\n\t\t\t\tconst data = await http.post(\"credentials/instances\", { json: payload }).json();\n\t\t\t\treturn CredentialInstanceRecordSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync updateInstance(id, body) {\n\t\t\ttry {\n\t\t\t\tconst payload = UpdateCredentialInstanceBodySchema.parse(body);\n\t\t\t\tconst data = await http.put(`credentials/instances/${id}`, { json: payload }).json();\n\t\t\t\treturn CredentialInstanceRecordSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync deleteInstance(id) {\n\t\t\ttry {\n\t\t\t\tawait http.delete(`credentials/instances/${id}`);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/resources/health.ts\nfunction createHealthResource(http) {\n\treturn { async check() {\n\t\ttry {\n\t\t\tconst data = await http.get(\"health\").json();\n\t\t\treturn HealthResponseSchema.parse(data);\n\t\t} catch (error) {\n\t\t\tthrow await toKeystrokeError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/resources/openapi.ts\nfunction createOpenApiResource(http) {\n\treturn { async fetch() {\n\t\ttry {\n\t\t\treturn await http.get(\"openapi.json\").json();\n\t\t} catch (error) {\n\t\t\tthrow await toKeystrokeError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/resources/triggers.ts\nfunction pollRunBody(options) {\n\tif (!options?.workflows?.length && !options?.attachments?.length) return;\n\treturn {\n\t\t...options.workflows?.length ? { workflows: options.workflows } : {},\n\t\t...options.attachments?.length ? { attachments: options.attachments } : {}\n\t};\n}\nfunction listRunsSearchParams$1(query) {\n\tif (!query) return {};\n\tconst params = {};\n\tif (query.limit !== void 0) params.limit = String(query.limit);\n\tif (query.cursor) params.cursor = query.cursor;\n\tif (query.triggerType) params.triggerType = query.triggerType;\n\treturn params;\n}\nfunction detailSearchParams$1(query) {\n\tif (!query?.include) return {};\n\treturn { include: query.include };\n}\nfunction createTriggersResource(http) {\n\treturn {\n\t\tasync list(query) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = query?.endpoint ? { endpoint: query.endpoint } : void 0;\n\t\t\t\tconst data = await http.get(\"triggers\", { searchParams }).json();\n\t\t\t\treturn TriggerListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(id) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`triggers/${id}`).json();\n\t\t\t\tconst list = TriggerListResponseSchema.safeParse(data);\n\t\t\t\tif (list.success) return list.data;\n\t\t\t\treturn TriggerDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync webhookUrl(id) {\n\t\t\tconst result = await this.get(id);\n\t\t\tconst webhookUrl = \"triggers\" in result ? result.triggers.find((entry) => entry.webhookUrl)?.webhookUrl : result.webhookUrl;\n\t\t\tif (!webhookUrl) throw new KeystrokeError(`Webhook URL not found: ${id}`, 404, { error: \"Not found\" });\n\t\t\treturn webhookUrl;\n\t\t},\n\t\tasync webhook(endpoint, body = {}, options = {}) {\n\t\t\ttry {\n\t\t\t\tconst searchParams = options.token ? { token: options.token } : void 0;\n\t\t\t\tconst normalized = endpoint.replace(/^\\/+|\\/+$/g, \"\").replace(/^triggers\\/?/, \"\");\n\t\t\t\treturn await http.post(`triggers/${normalized}`, {\n\t\t\t\t\tjson: body,\n\t\t\t\t\tsearchParams\n\t\t\t\t}).json();\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync poll(id, options = {}) {\n\t\t\ttry {\n\t\t\t\tconst { group, ...target } = options;\n\t\t\t\tconst json = pollRunBody(target);\n\t\t\t\tconst path = group ? `triggers/polls/${id}/run` : `triggers/${id}/poll`;\n\t\t\t\tconst data = await readJson(await http.post(path, json ? { json } : void 0));\n\t\t\t\tPollRunResponseSchema.parse(data);\n\t\t\t\treturn data;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync runPollGroup(pollId, options = {}) {\n\t\t\treturn this.poll(pollId, {\n\t\t\t\t...options,\n\t\t\t\tgroup: true\n\t\t\t});\n\t\t},\n\t\tasync listRuns(attachmentId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`triggers/${attachmentId}/runs`, { searchParams: listRunsSearchParams$1(query) }).json();\n\t\t\t\treturn TriggerRunListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync getRun(attachmentId, runId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`triggers/${attachmentId}/runs/${runId}`, { searchParams: detailSearchParams$1(query) }).json();\n\t\t\t\treturn TriggerRunDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t}\n\t};\n}\nfunction isSkippedTriggerResponse(value) {\n\treturn SkipResponseSchema.safeParse(value).success;\n}\n//#endregion\n//#region src/resources/workflows.ts\nfunction isQueuedRunResponse(value) {\n\treturn QueuedRunResponseSchema.safeParse(value).success;\n}\nfunction listRunsSearchParams(query) {\n\tif (!query) return {};\n\tconst params = {};\n\tif (query.limit !== void 0) params.limit = String(query.limit);\n\tif (query.cursor) params.cursor = query.cursor;\n\tif (query.status) params.status = query.status;\n\tif (query.trigger) params.trigger = query.trigger;\n\treturn params;\n}\nfunction detailSearchParams(query) {\n\tif (!query?.include) return {};\n\treturn { include: query.include };\n}\nfunction createWorkflowsResource(http) {\n\treturn {\n\t\tasync run(id, input = {}) {\n\t\t\ttry {\n\t\t\t\tconst response = await http.post(`workflows/${id}`, { json: input });\n\t\t\t\tconst data = await readJson(response);\n\t\t\t\tif (response.status === 202) return QueuedRunResponseSchema.parse(data);\n\t\t\t\treturn data;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync listRuns(workflowId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`workflows/${workflowId}/runs`, { searchParams: listRunsSearchParams(query) }).json();\n\t\t\t\treturn WorkflowRunListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t},\n\t\tasync getRun(workflowId, runId, query) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`workflows/${workflowId}/runs/${runId}`, { searchParams: detailSearchParams(query) }).json();\n\t\t\t\treturn WorkflowRunDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toKeystrokeError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/index.ts\nfunction createKeystrokeClient(options) {\n\tconst auth = options.auth ?? { type: \"none\" };\n\tconst base = normalizeBaseUrl(options.baseUrl);\n\tconst getActiveOrganizationId = options.getActiveOrganizationId;\n\tconst http = ky.create({\n\t\tprefix: base === \"\" ? void 0 : `${base}/`,\n\t\tcredentials: \"omit\",\n\t\thooks: { beforeRequest: [({ request }) => {\n\t\t\tapplyActiveOrganizationHeader(request, getActiveOrganizationId?.());\n\t\t\treturn applyAuthHeaders(request, auth);\n\t\t}] },\n\t\t...options.ky\n\t});\n\treturn {\n\t\thttp,\n\t\thealth: createHealthResource(http),\n\t\tconnect: createConnectResource(http),\n\t\tcredentials: createCredentialsResource(http),\n\t\topenapi: createOpenApiResource(http),\n\t\tagents: createAgentsResource(http),\n\t\tworkflows: createWorkflowsResource(http),\n\t\ttriggers: createTriggersResource(http)\n\t};\n}\n//#endregion\nexport { KeystrokeError, createKeystrokeClient, isQueuedAgentPromptResponse, isQueuedRunResponse, isSkippedTriggerResponse, toKeystrokeError };\n\n//# sourceMappingURL=index.mjs.map","import { Entry } from \"@napi-rs/keyring\";\n\nconst SERVICE = \"keystroke\";\n\nfunction accountForWebUrl(webUrl: string): string {\n return new URL(webUrl).hostname;\n}\n\nexport function getAccessToken(webUrl: string): string | undefined {\n const entry = new Entry(SERVICE, accountForWebUrl(webUrl));\n const password = entry.getPassword();\n return password === null ? undefined : password;\n}\n\nexport function setAccessToken(webUrl: string, token: string): void {\n const entry = new Entry(SERVICE, accountForWebUrl(webUrl));\n entry.setPassword(token);\n}\n\nexport function clearAccessToken(webUrl: string): void {\n const entry = new Entry(SERVICE, accountForWebUrl(webUrl));\n entry.deletePassword();\n}\n","import { createRemoteJWKSet, jwtVerify } from \"jose\";\n//#region src/constants.ts\n/** OAuth device-flow client id for `keystroke auth login`. */\nconst CLI_CLIENT_ID = \"keystroke-cli\";\n//#endregion\n//#region src/jwt.ts\nconst jwksCache = /* @__PURE__ */ new Map();\nfunction getRemoteJwks(jwksUrl) {\n\tconst cached = jwksCache.get(jwksUrl);\n\tif (cached) return cached;\n\tconst jwks = createRemoteJWKSet(new URL(jwksUrl));\n\tjwksCache.set(jwksUrl, jwks);\n\treturn jwks;\n}\nfunction payloadToUser(payload) {\n\tconst id = typeof payload.id === \"string\" ? payload.id : payload.sub;\n\tconst email = typeof payload.email === \"string\" ? payload.email : void 0;\n\tconst name = typeof payload.name === \"string\" && payload.name.length > 0 ? payload.name : email?.split(\"@\")[0];\n\tif (!id || !email || !name) return null;\n\treturn {\n\t\tid,\n\t\temail,\n\t\tname,\n\t\timage: typeof payload.image === \"string\" ? payload.image : null,\n\t\temailVerified: typeof payload.emailVerified === \"boolean\" ? payload.emailVerified : void 0\n\t};\n}\nfunction createJwtVerifier(options) {\n\tconst audience = options.audience ?? options.issuer;\n\tlet jwks;\n\treturn { verify: async (token) => {\n\t\ttry {\n\t\t\tjwks ??= getRemoteJwks(options.jwksUrl);\n\t\t\tconst { payload } = await jwtVerify(token, jwks, {\n\t\t\t\tissuer: options.issuer,\n\t\t\t\taudience\n\t\t\t});\n\t\t\treturn payloadToUser(payload);\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t} };\n}\nfunction extractBearerToken(headers) {\n\tconst authorization = headers.get(\"authorization\");\n\tif (!authorization?.startsWith(\"Bearer \")) return null;\n\tconst token = authorization.slice(7).trim();\n\treturn token.length > 0 ? token : null;\n}\nfunction looksLikeJwt(token) {\n\treturn token.split(\".\").length === 3;\n}\nfunction userFromJwt(jwtUser) {\n\treturn {\n\t\tid: jwtUser.id,\n\t\temail: jwtUser.email,\n\t\tname: jwtUser.name,\n\t\timage: jwtUser.image ?? null,\n\t\temailVerified: jwtUser.emailVerified ?? true,\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n}\nfunction sessionFromJwt(jwtUser, token) {\n\treturn {\n\t\tid: jwtUser.id,\n\t\tuserId: jwtUser.id,\n\t\ttoken,\n\t\texpiresAt: new Date(Date.now() + 900 * 1e3),\n\t\tcreatedAt: /* @__PURE__ */ new Date(),\n\t\tupdatedAt: /* @__PURE__ */ new Date()\n\t};\n}\nasync function resolveRequestAuth(jwtVerifier, headers) {\n\tconst bearerToken = extractBearerToken(headers);\n\tif (!bearerToken || !jwtVerifier || !looksLikeJwt(bearerToken)) return null;\n\tconst jwtUser = await jwtVerifier.verify(bearerToken);\n\tif (!jwtUser) return null;\n\treturn {\n\t\tuser: userFromJwt(jwtUser),\n\t\tsession: sessionFromJwt(jwtUser, bearerToken)\n\t};\n}\n/** Auth API origin for JWT verification — platform URL when auth is mounted there. */\nfunction resolveAuthApiBaseUrl() {\n\treturn (process.env.PUBLIC_PLATFORM_URL ?? process.env.PUBLIC_WEB_URL ?? \"\").replace(/\\/+$/, \"\");\n}\nfunction createDefaultAuthJwtVerifier() {\n\treturn createAuthJwtVerifier(resolveAuthApiBaseUrl());\n}\nfunction createAuthJwtVerifier(authBaseUrl) {\n\tconst normalizedBaseUrl = authBaseUrl.replace(/\\/+$/, \"\");\n\tif (!normalizedBaseUrl) return;\n\treturn createJwtVerifier({\n\t\tissuer: normalizedBaseUrl,\n\t\taudience: normalizedBaseUrl,\n\t\tjwksUrl: `${normalizedBaseUrl}/api/auth/jwks`\n\t});\n}\nasync function fetchJwtWithSession(authBaseUrl, sessionCredential) {\n\tconst headers = new Headers();\n\tif (sessionCredential.cookie) headers.set(\"cookie\", sessionCredential.cookie);\n\tif (sessionCredential.bearerToken) headers.set(\"authorization\", `Bearer ${sessionCredential.bearerToken}`);\n\tconst normalizedBaseUrl = authBaseUrl.replace(/\\/+$/, \"\");\n\tconst response = await fetch(`${normalizedBaseUrl}/api/auth/token`, { headers });\n\tif (!response.ok) return null;\n\tconst body = await response.json();\n\treturn typeof body.token === \"string\" ? body.token : null;\n}\n//#endregion\nexport { fetchJwtWithSession as a, CLI_CLIENT_ID as c, extractBearerToken as i, createDefaultAuthJwtVerifier as n, resolveAuthApiBaseUrl as o, createJwtVerifier as r, resolveRequestAuth as s, createAuthJwtVerifier as t };\n\n//# sourceMappingURL=jwt-BVJ7dVm9.mjs.map","//#region src/jwt-cache.ts\nconst REFRESH_BUFFER_MS = 6e4;\nconst FALLBACK_TTL_MS = 840 * 1e3;\nfunction decodeBase64Url(value) {\n\tconst base64 = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n\tconst padded = base64.padEnd(base64.length + (4 - base64.length % 4) % 4, \"=\");\n\treturn atob(padded);\n}\nfunction decodeJwtExpiryMs(token) {\n\tconst parts = token.split(\".\");\n\tif (parts.length !== 3) return null;\n\ttry {\n\t\tconst payload = JSON.parse(decodeBase64Url(parts[1] ?? \"\"));\n\t\treturn typeof payload.exp === \"number\" ? payload.exp * 1e3 : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/** Caches JWTs minted by `mint`, refreshing shortly before expiry and deduping concurrent mints. */\nfunction createJwtTokenCache(mint) {\n\tlet cached = null;\n\tlet pending = null;\n\treturn {\n\t\tget: async (force = false) => {\n\t\t\tif (!force && cached && cached.expiresAtMs - Date.now() > REFRESH_BUFFER_MS) return cached.token;\n\t\t\tif (pending) return pending;\n\t\t\tpending = (async () => {\n\t\t\t\tconst token = await mint();\n\t\t\t\tif (!token) {\n\t\t\t\t\tcached = null;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tcached = {\n\t\t\t\t\ttoken,\n\t\t\t\t\texpiresAtMs: decodeJwtExpiryMs(token) ?? Date.now() + FALLBACK_TTL_MS\n\t\t\t\t};\n\t\t\t\treturn token;\n\t\t\t})();\n\t\t\ttry {\n\t\t\t\treturn await pending;\n\t\t\t} finally {\n\t\t\t\tpending = null;\n\t\t\t}\n\t\t},\n\t\tclear: () => {\n\t\t\tcached = null;\n\t\t}\n\t};\n}\n//#endregion\nexport { decodeJwtExpiryMs as n, createJwtTokenCache as t };\n\n//# sourceMappingURL=jwt-cache-4YqHn3jM.mjs.map","//#region package.json\nvar version = \"1.6.11\";\n//#endregion\nexport { version };\n","import { version } from \"./package.mjs\";\n//#region src/version.ts\nconst PACKAGE_VERSION = version;\n//#endregion\nexport { PACKAGE_VERSION };\n","//#region src/error.ts\nfunction isErrorStackTraceLimitWritable() {\n\tconst desc = Object.getOwnPropertyDescriptor(Error, \"stackTraceLimit\");\n\tif (desc === void 0) return Object.isExtensible(Error);\n\treturn Object.prototype.hasOwnProperty.call(desc, \"writable\") ? desc.writable : desc.set !== void 0;\n}\n/**\n* Hide internal stack frames from the error stack trace.\n*/\nfunction hideInternalStackFrames(stack) {\n\tconst lines = stack.split(\"\\n at \");\n\tif (lines.length <= 1) return stack;\n\tlines.splice(1, 1);\n\treturn lines.join(\"\\n at \");\n}\n/**\n* Creates a custom error class that hides stack frames.\n*/\nfunction makeErrorForHideStackFrame(Base, clazz) {\n\tclass HideStackFramesError extends Base {\n\t\t#hiddenStack;\n\t\tconstructor(...args) {\n\t\t\tif (isErrorStackTraceLimitWritable()) {\n\t\t\t\tconst limit = Error.stackTraceLimit;\n\t\t\t\tError.stackTraceLimit = 0;\n\t\t\t\tsuper(...args);\n\t\t\t\tError.stackTraceLimit = limit;\n\t\t\t} else super(...args);\n\t\t\tconst stack = (/* @__PURE__ */ new Error()).stack;\n\t\t\tif (stack) this.#hiddenStack = hideInternalStackFrames(stack.replace(/^Error/, this.name));\n\t\t}\n\t\tget errorStack() {\n\t\t\treturn this.#hiddenStack;\n\t\t}\n\t}\n\tObject.defineProperty(HideStackFramesError.prototype, \"constructor\", {\n\t\tget() {\n\t\t\treturn clazz;\n\t\t},\n\t\tenumerable: false,\n\t\tconfigurable: true\n\t});\n\treturn HideStackFramesError;\n}\nconst statusCodes = {\n\tOK: 200,\n\tCREATED: 201,\n\tACCEPTED: 202,\n\tNO_CONTENT: 204,\n\tMULTIPLE_CHOICES: 300,\n\tMOVED_PERMANENTLY: 301,\n\tFOUND: 302,\n\tSEE_OTHER: 303,\n\tNOT_MODIFIED: 304,\n\tTEMPORARY_REDIRECT: 307,\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tPAYMENT_REQUIRED: 402,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tMETHOD_NOT_ALLOWED: 405,\n\tNOT_ACCEPTABLE: 406,\n\tPROXY_AUTHENTICATION_REQUIRED: 407,\n\tREQUEST_TIMEOUT: 408,\n\tCONFLICT: 409,\n\tGONE: 410,\n\tLENGTH_REQUIRED: 411,\n\tPRECONDITION_FAILED: 412,\n\tPAYLOAD_TOO_LARGE: 413,\n\tURI_TOO_LONG: 414,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tEXPECTATION_FAILED: 417,\n\t\"I'M_A_TEAPOT\": 418,\n\tMISDIRECTED_REQUEST: 421,\n\tUNPROCESSABLE_ENTITY: 422,\n\tLOCKED: 423,\n\tFAILED_DEPENDENCY: 424,\n\tTOO_EARLY: 425,\n\tUPGRADE_REQUIRED: 426,\n\tPRECONDITION_REQUIRED: 428,\n\tTOO_MANY_REQUESTS: 429,\n\tREQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\tUNAVAILABLE_FOR_LEGAL_REASONS: 451,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tHTTP_VERSION_NOT_SUPPORTED: 505,\n\tVARIANT_ALSO_NEGOTIATES: 506,\n\tINSUFFICIENT_STORAGE: 507,\n\tLOOP_DETECTED: 508,\n\tNOT_EXTENDED: 510,\n\tNETWORK_AUTHENTICATION_REQUIRED: 511\n};\nvar InternalAPIError = class extends Error {\n\tconstructor(status = \"INTERNAL_SERVER_ERROR\", body = void 0, headers = {}, statusCode = typeof status === \"number\" ? status : statusCodes[status]) {\n\t\tsuper(body?.message, body?.cause ? { cause: body.cause } : void 0);\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t\tthis.headers = headers;\n\t\tthis.statusCode = statusCode;\n\t\tthis.name = \"APIError\";\n\t\tthis.status = status;\n\t\tthis.headers = headers;\n\t\tthis.statusCode = statusCode;\n\t\tthis.body = body;\n\t}\n};\nvar ValidationError = class extends InternalAPIError {\n\tconstructor(message, issues) {\n\t\tsuper(400, {\n\t\t\tmessage,\n\t\t\tcode: \"VALIDATION_ERROR\"\n\t\t});\n\t\tthis.message = message;\n\t\tthis.issues = issues;\n\t\tthis.issues = issues;\n\t}\n};\nvar BetterCallError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"BetterCallError\";\n\t}\n};\nconst kAPIErrorHeaderSymbol = Symbol.for(\"better-call:api-error-headers\");\nconst APIError = makeErrorForHideStackFrame(InternalAPIError, Error);\n\n//#endregion\nexport { APIError, BetterCallError, ValidationError, hideInternalStackFrames, kAPIErrorHeaderSymbol, makeErrorForHideStackFrame, statusCodes };\n//# sourceMappingURL=error.mjs.map","import { BASE_ERROR_CODES } from \"./codes.mjs\";\nimport { APIError as APIError$1 } from \"better-call/error\";\n//#region src/error/index.ts\nvar BetterAuthError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message, options);\n\t\tthis.name = \"BetterAuthError\";\n\t\tthis.message = message;\n\t\tthis.stack = \"\";\n\t}\n};\nvar APIError = class APIError extends APIError$1 {\n\tconstructor(...args) {\n\t\tsuper(...args);\n\t}\n\tstatic fromStatus(status, body) {\n\t\treturn new APIError(status, body);\n\t}\n\tstatic from(status, error) {\n\t\treturn new APIError(status, {\n\t\t\tmessage: error.message,\n\t\t\tcode: error.code\n\t\t});\n\t}\n};\n//#endregion\nexport { APIError, BASE_ERROR_CODES, BetterAuthError };\n","import { PACKAGE_VERSION } from \"../../version.mjs\";\n//#region src/plugins/device-authorization/client.ts\nconst deviceAuthorizationClient = () => {\n\treturn {\n\t\tid: \"device-authorization\",\n\t\tversion: PACKAGE_VERSION,\n\t\t$InferServerPlugin: {},\n\t\tpathMethods: {\n\t\t\t\"/device/code\": \"POST\",\n\t\t\t\"/device/token\": \"POST\",\n\t\t\t\"/device\": \"GET\",\n\t\t\t\"/device/approve\": \"POST\",\n\t\t\t\"/device/deny\": \"POST\"\n\t\t}\n\t};\n};\n//#endregion\nexport { deviceAuthorizationClient };\n","import { cleanTasks } from '../task/index.js'\n\nexport const clean = Symbol('clean')\n\nexport const cleanStores = (...stores) => {\n if (process.env.NODE_ENV === 'production') {\n throw new Error(\n 'cleanStores() can be used only during development or tests'\n )\n }\n cleanTasks()\n for (let $store of stores) {\n if ($store) {\n if ($store.mocked) delete $store.mocked\n if ($store[clean]) $store[clean]()\n }\n }\n}\n","import { clean } from '../clean-stores/index.js'\n\nlet listenerQueue = []\nlet lqIndex = 0\nconst QUEUE_ITEMS_PER_LISTENER = 4\n// Use globalThis.nanostoresGlobal to store epoch so all module instances share\n// the same counter. This fixes issues when Nano Store is bundled separately\n// in different parts of an application (e.g., tree-shaking separates core\n// from React), causing each bundle to have its own epoch instance.\nexport const nanostoresGlobal = (globalThis.nanostoresGlobal ||= { epoch: 0 })\n\n/* @__NO_SIDE_EFFECTS__ */\nexport const atom = initialValue => {\n let listeners = []\n let $atom = {\n get() {\n if (!$atom.lc) {\n $atom.listen(() => {})()\n }\n return $atom.value\n },\n init: initialValue,\n lc: 0,\n listen(listener) {\n $atom.lc = listeners.push(listener)\n\n return () => {\n for (\n let i = lqIndex + QUEUE_ITEMS_PER_LISTENER;\n i < listenerQueue.length;\n ) {\n if (listenerQueue[i] === listener) {\n listenerQueue.splice(i, QUEUE_ITEMS_PER_LISTENER)\n } else {\n i += QUEUE_ITEMS_PER_LISTENER\n }\n }\n\n let index = listeners.indexOf(listener)\n if (~index) {\n listeners.splice(index, 1)\n if (!--$atom.lc) $atom.off()\n }\n }\n },\n notify(oldValue, changedKey) {\n nanostoresGlobal.epoch++\n let runListenerQueue = !listenerQueue.length\n for (let listener of listeners) {\n listenerQueue.push(listener, $atom.value, oldValue, changedKey)\n }\n\n if (runListenerQueue) {\n for (\n lqIndex = 0;\n lqIndex < listenerQueue.length;\n lqIndex += QUEUE_ITEMS_PER_LISTENER\n ) {\n listenerQueue[lqIndex](\n listenerQueue[lqIndex + 1],\n listenerQueue[lqIndex + 2],\n listenerQueue[lqIndex + 3]\n )\n }\n listenerQueue.length = 0\n }\n },\n /* It will be called on last listener unsubscribing.\n We will redefine it in onMount and onStop. */\n off() {},\n set(newValue) {\n let oldValue = $atom.value\n if (oldValue !== newValue) {\n $atom.value = newValue\n $atom.notify(oldValue)\n }\n },\n subscribe(listener) {\n let unbind = $atom.listen(listener)\n listener($atom.value)\n return unbind\n },\n value: initialValue\n }\n\n if (process.env.NODE_ENV !== 'production') {\n $atom[clean] = () => {\n listeners = []\n $atom.lc = 0\n $atom.off()\n }\n }\n\n return $atom\n}\n\nexport const readonlyType = store => store\n","import { clean } from '../clean-stores/index.js'\n\nconst START = 0\nconst STOP = 1\nconst SET = 2\nconst NOTIFY = 3\nconst MOUNT = 5\nconst UNMOUNT = 6\nconst REVERT_MUTATION = 10\n\nexport let on = (object, listener, eventKey, mutateStore) => {\n object.events = object.events || {}\n if (!object.events[eventKey + REVERT_MUTATION]) {\n object.events[eventKey + REVERT_MUTATION] = mutateStore(eventProps => {\n // eslint-disable-next-line no-sequences\n object.events[eventKey].reduceRight((event, l) => (l(event), event), {\n shared: {},\n ...eventProps\n })\n })\n }\n object.events[eventKey] = object.events[eventKey] || []\n object.events[eventKey].push(listener)\n return () => {\n let currentListeners = object.events[eventKey]\n let index = currentListeners.indexOf(listener)\n currentListeners.splice(index, 1)\n if (!currentListeners.length) {\n delete object.events[eventKey]\n object.events[eventKey + REVERT_MUTATION]()\n delete object.events[eventKey + REVERT_MUTATION]\n }\n }\n}\n\nexport let onStart = ($store, listener) =>\n on($store, listener, START, runListeners => {\n let originListen = $store.listen\n $store.listen = arg => {\n if (!$store.lc && !$store.starting) {\n $store.starting = true\n runListeners()\n delete $store.starting\n }\n return originListen(arg)\n }\n return () => {\n $store.listen = originListen\n }\n })\n\nexport let onStop = ($store, listener) =>\n on($store, listener, STOP, runListeners => {\n let originOff = $store.off\n $store.off = () => {\n runListeners()\n originOff()\n }\n return () => {\n $store.off = originOff\n }\n })\n\nexport let onSet = ($store, listener) =>\n on($store, listener, SET, runListeners => {\n let originSet = $store.set\n let originSetKey = $store.setKey\n if ($store.setKey) {\n $store.setKey = (changed, changedValue) => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({\n abort,\n changed,\n newValue: { ...$store.value, [changed]: changedValue }\n })\n if (!isAborted) return originSetKey(changed, changedValue)\n }\n }\n $store.set = newValue => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({ abort, newValue })\n if (!isAborted) return originSet(newValue)\n }\n return () => {\n $store.set = originSet\n $store.setKey = originSetKey\n }\n })\n\nexport let onNotify = ($store, listener) =>\n on($store, listener, NOTIFY, runListeners => {\n let originNotify = $store.notify\n $store.notify = (oldValue, changed) => {\n let isAborted\n let abort = () => {\n isAborted = true\n }\n\n runListeners({ abort, changed, oldValue })\n if (!isAborted) return originNotify(oldValue, changed)\n }\n return () => {\n $store.notify = originNotify\n }\n })\n\nexport const STORE_UNMOUNT_DELAY = 1000\n\nexport let onMount = ($store, initialize) => {\n let listener = payload => {\n let destroy = initialize(payload)\n if (destroy) $store.events[UNMOUNT].push(destroy)\n }\n return on($store, listener, MOUNT, runListeners => {\n let originListen = $store.listen\n $store.listen = (...args) => {\n if (!$store.lc && !$store.active) {\n $store.active = true\n runListeners()\n }\n return originListen(...args)\n }\n\n let originOff = $store.off\n $store.events[UNMOUNT] = []\n $store.off = () => {\n originOff()\n setTimeout(() => {\n if ($store.active && !$store.lc) {\n $store.active = false\n for (let destroy of $store.events[UNMOUNT]) destroy()\n $store.events[UNMOUNT] = []\n }\n }, STORE_UNMOUNT_DELAY)\n }\n\n if (process.env.NODE_ENV !== 'production') {\n let originClean = $store[clean]\n $store[clean] = () => {\n for (let destroy of $store.events[UNMOUNT]) destroy()\n $store.events[UNMOUNT] = []\n $store.active = false\n originClean()\n }\n }\n\n return () => {\n $store.listen = originListen\n $store.off = originOff\n }\n })\n}\n","import { atom, onMount } from \"nanostores\";\n//#region src/client/query.ts\nconst isServer = () => typeof window === \"undefined\";\nconst useAuthQuery = (initializedAtom, path, $fetch, options) => {\n\tconst value = atom({\n\t\tdata: null,\n\t\terror: null,\n\t\tisPending: true,\n\t\tisRefetching: false,\n\t\trefetch: (queryParams) => fn(queryParams)\n\t});\n\tconst fn = async (queryParams) => {\n\t\treturn new Promise((resolve) => {\n\t\t\tconst opts = typeof options === \"function\" ? options({\n\t\t\t\tdata: value.get().data,\n\t\t\t\terror: value.get().error,\n\t\t\t\tisPending: value.get().isPending\n\t\t\t}) : options;\n\t\t\t$fetch(path, {\n\t\t\t\t...opts,\n\t\t\t\tquery: {\n\t\t\t\t\t...opts?.query,\n\t\t\t\t\t...queryParams?.query\n\t\t\t\t},\n\t\t\t\tasync onSuccess(context) {\n\t\t\t\t\tvalue.set({\n\t\t\t\t\t\tdata: context.data,\n\t\t\t\t\t\terror: null,\n\t\t\t\t\t\tisPending: false,\n\t\t\t\t\t\tisRefetching: false,\n\t\t\t\t\t\trefetch: value.value.refetch\n\t\t\t\t\t});\n\t\t\t\t\tawait opts?.onSuccess?.(context);\n\t\t\t\t},\n\t\t\t\tasync onError(context) {\n\t\t\t\t\tconst { request } = context;\n\t\t\t\t\tconst retryAttempts = typeof request.retry === \"number\" ? request.retry : request.retry?.attempts;\n\t\t\t\t\tconst retryAttempt = request.retryAttempt || 0;\n\t\t\t\t\tif (retryAttempts && retryAttempt < retryAttempts) return;\n\t\t\t\t\tconst isUnauthorized = context.error.status === 401;\n\t\t\t\t\tvalue.set({\n\t\t\t\t\t\terror: context.error,\n\t\t\t\t\t\tdata: isUnauthorized ? null : value.get().data,\n\t\t\t\t\t\tisPending: false,\n\t\t\t\t\t\tisRefetching: false,\n\t\t\t\t\t\trefetch: value.value.refetch\n\t\t\t\t\t});\n\t\t\t\t\tawait opts?.onError?.(context);\n\t\t\t\t},\n\t\t\t\tasync onRequest(context) {\n\t\t\t\t\tconst currentValue = value.get();\n\t\t\t\t\tvalue.set({\n\t\t\t\t\t\tisPending: currentValue.data === null,\n\t\t\t\t\t\tdata: currentValue.data,\n\t\t\t\t\t\terror: null,\n\t\t\t\t\t\tisRefetching: true,\n\t\t\t\t\t\trefetch: value.value.refetch\n\t\t\t\t\t});\n\t\t\t\t\tawait opts?.onRequest?.(context);\n\t\t\t\t}\n\t\t\t}).catch((error) => {\n\t\t\t\tvalue.set({\n\t\t\t\t\terror,\n\t\t\t\t\tdata: value.get().data,\n\t\t\t\t\tisPending: false,\n\t\t\t\t\tisRefetching: false,\n\t\t\t\t\trefetch: value.value.refetch\n\t\t\t\t});\n\t\t\t}).finally(() => {\n\t\t\t\tresolve(void 0);\n\t\t\t});\n\t\t});\n\t};\n\tinitializedAtom = Array.isArray(initializedAtom) ? initializedAtom : [initializedAtom];\n\tlet isInitialized = false;\n\tfor (const initAtom of initializedAtom) initAtom.subscribe(async () => {\n\t\tif (isServer()) return;\n\t\tif (isInitialized) await fn();\n\t\telse onMount(value, () => {\n\t\t\tconst timeoutId = setTimeout(async () => {\n\t\t\t\tif (!isInitialized) {\n\t\t\t\t\tisInitialized = true;\n\t\t\t\t\tawait fn();\n\t\t\t\t}\n\t\t\t}, 0);\n\t\t\treturn () => {\n\t\t\t\tvalue.off();\n\t\t\t\tinitAtom.off();\n\t\t\t\tclearTimeout(timeoutId);\n\t\t\t};\n\t\t});\n\t});\n\treturn value;\n};\n//#endregion\nexport { useAuthQuery };\n","//#region src/client/broadcast-channel.ts\nconst kBroadcastChannel = Symbol.for(\"better-auth:broadcast-channel\");\nconst now = () => Math.floor(Date.now() / 1e3);\nvar WindowBroadcastChannel = class {\n\tlisteners = /* @__PURE__ */ new Set();\n\tname;\n\tconstructor(name = \"better-auth.message\") {\n\t\tthis.name = name;\n\t}\n\tsubscribe(listener) {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\tpost(message) {\n\t\tif (typeof window === \"undefined\") return;\n\t\ttry {\n\t\t\tlocalStorage.setItem(this.name, JSON.stringify({\n\t\t\t\t...message,\n\t\t\t\ttimestamp: now()\n\t\t\t}));\n\t\t} catch {}\n\t}\n\tsetup() {\n\t\tif (typeof window === \"undefined\" || typeof window.addEventListener === \"undefined\") return () => {};\n\t\tconst handler = (event) => {\n\t\t\tif (event.key !== this.name) return;\n\t\t\tconst message = JSON.parse(event.newValue ?? \"{}\");\n\t\t\tif (message?.event !== \"session\" || !message?.data) return;\n\t\t\tthis.listeners.forEach((listener) => listener(message));\n\t\t};\n\t\twindow.addEventListener(\"storage\", handler);\n\t\treturn () => {\n\t\t\twindow.removeEventListener(\"storage\", handler);\n\t\t};\n\t}\n};\nfunction getGlobalBroadcastChannel(name = \"better-auth.message\") {\n\tif (!globalThis[kBroadcastChannel]) globalThis[kBroadcastChannel] = new WindowBroadcastChannel(name);\n\treturn globalThis[kBroadcastChannel];\n}\n//#endregion\nexport { getGlobalBroadcastChannel, kBroadcastChannel };\n","//#region src/client/focus-manager.ts\nconst kFocusManager = Symbol.for(\"better-auth:focus-manager\");\nvar WindowFocusManager = class {\n\tlisteners = /* @__PURE__ */ new Set();\n\tsubscribe(listener) {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\tsetFocused(focused) {\n\t\tthis.listeners.forEach((listener) => listener(focused));\n\t}\n\tsetup() {\n\t\tif (typeof window === \"undefined\" || typeof document === \"undefined\" || typeof window.addEventListener === \"undefined\") return () => {};\n\t\tconst visibilityHandler = () => {\n\t\t\tif (document.visibilityState === \"visible\") this.setFocused(true);\n\t\t};\n\t\tdocument.addEventListener(\"visibilitychange\", visibilityHandler, false);\n\t\treturn () => {\n\t\t\tdocument.removeEventListener(\"visibilitychange\", visibilityHandler, false);\n\t\t};\n\t}\n};\nfunction getGlobalFocusManager() {\n\tif (!globalThis[kFocusManager]) globalThis[kFocusManager] = new WindowFocusManager();\n\treturn globalThis[kFocusManager];\n}\n//#endregion\nexport { getGlobalFocusManager, kFocusManager };\n","//#region src/client/online-manager.ts\nconst kOnlineManager = Symbol.for(\"better-auth:online-manager\");\nvar WindowOnlineManager = class {\n\tlisteners = /* @__PURE__ */ new Set();\n\tisOnline = typeof navigator !== \"undefined\" ? navigator.onLine : true;\n\tsubscribe(listener) {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\tsetOnline(online) {\n\t\tthis.isOnline = online;\n\t\tthis.listeners.forEach((listener) => listener(online));\n\t}\n\tsetup() {\n\t\tif (typeof window === \"undefined\" || typeof window.addEventListener === \"undefined\") return () => {};\n\t\tconst onOnline = () => this.setOnline(true);\n\t\tconst onOffline = () => this.setOnline(false);\n\t\twindow.addEventListener(\"online\", onOnline, false);\n\t\twindow.addEventListener(\"offline\", onOffline, false);\n\t\treturn () => {\n\t\t\twindow.removeEventListener(\"online\", onOnline, false);\n\t\t\twindow.removeEventListener(\"offline\", onOffline, false);\n\t\t};\n\t}\n};\nfunction getGlobalOnlineManager() {\n\tif (!globalThis[kOnlineManager]) globalThis[kOnlineManager] = new WindowOnlineManager();\n\treturn globalThis[kOnlineManager];\n}\n//#endregion\nexport { getGlobalOnlineManager, kOnlineManager };\n","//#region src/client/parser.ts\nconst PROTO_POLLUTION_PATTERNS = {\n\tproto: /\"(?:_|\\\\u0{2}5[Ff]){2}(?:p|\\\\u0{2}70)(?:r|\\\\u0{2}72)(?:o|\\\\u0{2}6[Ff])(?:t|\\\\u0{2}74)(?:o|\\\\u0{2}6[Ff])(?:_|\\\\u0{2}5[Ff]){2}\"\\s*:/,\n\tconstructor: /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/,\n\tprotoShort: /\"__proto__\"\\s*:/,\n\tconstructorShort: /\"constructor\"\\s*:/\n};\nconst JSON_SIGNATURE = /^\\s*[\"[{]|^\\s*-?\\d{1,16}(\\.\\d{1,17})?([Ee][+-]?\\d+)?\\s*$/;\nconst SPECIAL_VALUES = {\n\ttrue: true,\n\tfalse: false,\n\tnull: null,\n\tundefined: void 0,\n\tnan: NaN,\n\tinfinity: Number.POSITIVE_INFINITY,\n\t\"-infinity\": Number.NEGATIVE_INFINITY\n};\nconst ISO_DATE_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d{1,7}))?(?:Z|([+-])(\\d{2}):(\\d{2}))$/;\nfunction isValidDate(date) {\n\treturn date instanceof Date && !isNaN(date.getTime());\n}\nfunction parseISODate(value) {\n\tconst match = ISO_DATE_REGEX.exec(value);\n\tif (!match) return null;\n\tconst [, year, month, day, hour, minute, second, ms, offsetSign, offsetHour, offsetMinute] = match;\n\tconst date = new Date(Date.UTC(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10), parseInt(hour, 10), parseInt(minute, 10), parseInt(second, 10), ms ? parseInt(ms.padEnd(3, \"0\"), 10) : 0));\n\tif (offsetSign) {\n\t\tconst offset = (parseInt(offsetHour, 10) * 60 + parseInt(offsetMinute, 10)) * (offsetSign === \"+\" ? -1 : 1);\n\t\tdate.setUTCMinutes(date.getUTCMinutes() + offset);\n\t}\n\treturn isValidDate(date) ? date : null;\n}\nfunction betterJSONParse(value, options = {}) {\n\tconst { strict = false, warnings = false, reviver, parseDates = true } = options;\n\tif (typeof value !== \"string\") return value;\n\tconst trimmed = value.trim();\n\tif (trimmed.length > 0 && trimmed[0] === \"\\\"\" && trimmed.endsWith(\"\\\"\") && !trimmed.slice(1, -1).includes(\"\\\"\")) return trimmed.slice(1, -1);\n\tconst lowerValue = trimmed.toLowerCase();\n\tif (lowerValue.length <= 9 && lowerValue in SPECIAL_VALUES) return SPECIAL_VALUES[lowerValue];\n\tif (!JSON_SIGNATURE.test(trimmed)) {\n\t\tif (strict) throw new SyntaxError(\"[better-json] Invalid JSON\");\n\t\treturn value;\n\t}\n\tif (Object.entries(PROTO_POLLUTION_PATTERNS).some(([key, pattern]) => {\n\t\tconst matches = pattern.test(trimmed);\n\t\tif (matches && warnings) console.warn(`[better-json] Detected potential prototype pollution attempt using ${key} pattern`);\n\t\treturn matches;\n\t}) && strict) throw new Error(\"[better-json] Potential prototype pollution attempt detected\");\n\ttry {\n\t\tconst secureReviver = (key, value) => {\n\t\t\tif (key === \"__proto__\" || key === \"constructor\" && value && typeof value === \"object\" && \"prototype\" in value) {\n\t\t\t\tif (warnings) console.warn(`[better-json] Dropping \"${key}\" key to prevent prototype pollution`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (parseDates && typeof value === \"string\") {\n\t\t\t\tconst date = parseISODate(value);\n\t\t\t\tif (date) return date;\n\t\t\t}\n\t\t\treturn reviver ? reviver(key, value) : value;\n\t\t};\n\t\treturn JSON.parse(trimmed, secureReviver);\n\t} catch (error) {\n\t\tif (strict) throw error;\n\t\treturn value;\n\t}\n}\nfunction parseJSON(value, options = { strict: true }) {\n\treturn betterJSONParse(value, options);\n}\n//#endregion\nexport { parseJSON };\n","import { getGlobalBroadcastChannel } from \"./broadcast-channel.mjs\";\nimport { getGlobalFocusManager } from \"./focus-manager.mjs\";\nimport { getGlobalOnlineManager } from \"./online-manager.mjs\";\n//#region src/client/session-refresh.ts\nconst now = () => Math.floor(Date.now() / 1e3);\n/**\n* Normalize $fetch response: `throw: true` returns data directly, otherwise `{ data, error }`.\n*/\nfunction normalizeSessionResponse(res) {\n\tif (typeof res === \"object\" && res !== null && \"data\" in res && \"error\" in res) return res;\n\treturn {\n\t\tdata: res,\n\t\terror: null\n\t};\n}\n/**\n* Rate limit: don't refetch on focus if a session request was made within this many seconds\n*/\nconst FOCUS_REFETCH_RATE_LIMIT_SECONDS = 5;\nfunction createSessionRefreshManager(opts) {\n\tconst { sessionAtom, sessionSignal, $fetch, options = {} } = opts;\n\tconst refetchInterval = options.sessionOptions?.refetchInterval ?? 0;\n\tconst refetchOnWindowFocus = options.sessionOptions?.refetchOnWindowFocus ?? true;\n\tconst refetchWhenOffline = options.sessionOptions?.refetchWhenOffline ?? false;\n\tconst state = {\n\t\tlastSync: 0,\n\t\tlastSessionRequest: 0,\n\t\tcachedSession: void 0\n\t};\n\tconst shouldRefetch = () => {\n\t\treturn refetchWhenOffline || getGlobalOnlineManager().isOnline;\n\t};\n\tconst triggerRefetch = (event) => {\n\t\tif (!shouldRefetch()) return;\n\t\tif (event?.event === \"storage\") {\n\t\t\tstate.lastSync = now();\n\t\t\tsessionSignal.set(!sessionSignal.get());\n\t\t\treturn;\n\t\t}\n\t\tconst currentSession = sessionAtom.get();\n\t\tconst fetchSessionWithRefresh = () => {\n\t\t\tstate.lastSessionRequest = now();\n\t\t\t$fetch(\"/get-session\").then(async (res) => {\n\t\t\t\tlet { data, error } = normalizeSessionResponse(res);\n\t\t\t\tif (data?.needsRefresh) try {\n\t\t\t\t\tconst refreshRes = await $fetch(\"/get-session\", { method: \"POST\" });\n\t\t\t\t\t({data, error} = normalizeSessionResponse(refreshRes));\n\t\t\t\t} catch {}\n\t\t\t\tconst sessionData = data?.session && data?.user ? data : null;\n\t\t\t\tsessionAtom.set({\n\t\t\t\t\t...currentSession,\n\t\t\t\t\tdata: sessionData,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tstate.lastSync = now();\n\t\t\t\tsessionSignal.set(!sessionSignal.get());\n\t\t\t}).catch(() => {});\n\t\t};\n\t\tif (event?.event === \"poll\") {\n\t\t\tfetchSessionWithRefresh();\n\t\t\treturn;\n\t\t}\n\t\tif (event?.event === \"visibilitychange\") {\n\t\t\tif (now() - state.lastSessionRequest < FOCUS_REFETCH_RATE_LIMIT_SECONDS) return;\n\t\t\tstate.lastSessionRequest = now();\n\t\t}\n\t\tif (event?.event === \"visibilitychange\") {\n\t\t\tfetchSessionWithRefresh();\n\t\t\treturn;\n\t\t}\n\t\tif (currentSession?.data === null || currentSession?.data === void 0) {\n\t\t\tstate.lastSync = now();\n\t\t\tsessionSignal.set(!sessionSignal.get());\n\t\t}\n\t};\n\tconst broadcastSessionUpdate = (trigger) => {\n\t\tgetGlobalBroadcastChannel().post({\n\t\t\tevent: \"session\",\n\t\t\tdata: { trigger },\n\t\t\tclientId: Math.random().toString(36).substring(7)\n\t\t});\n\t};\n\tconst setupPolling = () => {\n\t\tif (refetchInterval && refetchInterval > 0) state.pollInterval = setInterval(() => {\n\t\t\tif (sessionAtom.get()?.data) triggerRefetch({ event: \"poll\" });\n\t\t}, refetchInterval * 1e3);\n\t};\n\tconst setupBroadcast = () => {\n\t\tstate.unsubscribeBroadcast = getGlobalBroadcastChannel().subscribe(() => {\n\t\t\ttriggerRefetch({ event: \"storage\" });\n\t\t});\n\t};\n\tconst setupFocusRefetch = () => {\n\t\tif (!refetchOnWindowFocus) return;\n\t\tstate.unsubscribeFocus = getGlobalFocusManager().subscribe(() => {\n\t\t\ttriggerRefetch({ event: \"visibilitychange\" });\n\t\t});\n\t};\n\tconst setupOnlineRefetch = () => {\n\t\tstate.unsubscribeOnline = getGlobalOnlineManager().subscribe((online) => {\n\t\t\tif (online) triggerRefetch({ event: \"visibilitychange\" });\n\t\t});\n\t};\n\tconst init = () => {\n\t\tsetupPolling();\n\t\tsetupBroadcast();\n\t\tsetupFocusRefetch();\n\t\tsetupOnlineRefetch();\n\t\tgetGlobalBroadcastChannel().setup();\n\t\tgetGlobalFocusManager().setup();\n\t\tgetGlobalOnlineManager().setup();\n\t};\n\tconst cleanup = () => {\n\t\tif (state.pollInterval) {\n\t\t\tclearInterval(state.pollInterval);\n\t\t\tstate.pollInterval = void 0;\n\t\t}\n\t\tif (state.unsubscribeBroadcast) {\n\t\t\tstate.unsubscribeBroadcast();\n\t\t\tstate.unsubscribeBroadcast = void 0;\n\t\t}\n\t\tif (state.unsubscribeFocus) {\n\t\t\tstate.unsubscribeFocus();\n\t\t\tstate.unsubscribeFocus = void 0;\n\t\t}\n\t\tif (state.unsubscribeOnline) {\n\t\t\tstate.unsubscribeOnline();\n\t\t\tstate.unsubscribeOnline = void 0;\n\t\t}\n\t\tstate.lastSync = 0;\n\t\tstate.lastSessionRequest = 0;\n\t\tstate.cachedSession = void 0;\n\t};\n\treturn {\n\t\tinit,\n\t\tcleanup,\n\t\ttriggerRefetch,\n\t\tbroadcastSessionUpdate\n\t};\n}\n//#endregion\nexport { createSessionRefreshManager };\n","//#region src/env/env-impl.ts\nconst _envShim = Object.create(null);\nconst _getEnv = (useShim) => globalThis.process?.env || globalThis.Deno?.env.toObject() || globalThis.__env__ || (useShim ? _envShim : globalThis);\nconst env = new Proxy(_envShim, {\n\tget(_, prop) {\n\t\treturn _getEnv()[prop] ?? _envShim[prop];\n\t},\n\thas(_, prop) {\n\t\treturn prop in _getEnv() || prop in _envShim;\n\t},\n\tset(_, prop, value) {\n\t\tconst env = _getEnv(true);\n\t\tenv[prop] = value;\n\t\treturn true;\n\t},\n\tdeleteProperty(_, prop) {\n\t\tif (!prop) return false;\n\t\tconst env = _getEnv(true);\n\t\tdelete env[prop];\n\t\treturn true;\n\t},\n\townKeys() {\n\t\tconst env = _getEnv(true);\n\t\treturn Object.keys(env);\n\t}\n});\nfunction toBoolean(val) {\n\treturn val ? val !== \"false\" : false;\n}\nconst nodeENV = typeof process !== \"undefined\" && process.env && process.env.NODE_ENV || \"\";\n/** Detect if `NODE_ENV` environment variable is `production` */\nconst isProduction = nodeENV === \"production\";\n/** Detect if `NODE_ENV` environment variable is `dev` or `development` */\nconst isDevelopment = () => nodeENV === \"dev\" || nodeENV === \"development\";\n/** Detect if `NODE_ENV` environment variable is `test` */\nconst isTest = () => nodeENV === \"test\" || toBoolean(env.TEST);\n/**\n* Get environment variable with fallback\n*/\nfunction getEnvVar(key, fallback) {\n\tif (typeof process !== \"undefined\" && process.env) return process.env[key] ?? fallback;\n\tif (typeof Deno !== \"undefined\") return Deno.env.get(key) ?? fallback;\n\tif (typeof Bun !== \"undefined\") return Bun.env[key] ?? fallback;\n\treturn fallback;\n}\n/**\n* Get boolean environment variable\n*/\nfunction getBooleanEnvVar(key, fallback = true) {\n\tconst value = getEnvVar(key);\n\tif (!value) return fallback;\n\treturn value !== \"0\" && value.toLowerCase() !== \"false\" && value !== \"\";\n}\n/**\n* Common environment variables used in Better Auth\n*/\nconst ENV = Object.freeze({\n\tget BETTER_AUTH_SECRET() {\n\t\treturn getEnvVar(\"BETTER_AUTH_SECRET\");\n\t},\n\tget AUTH_SECRET() {\n\t\treturn getEnvVar(\"AUTH_SECRET\");\n\t},\n\tget BETTER_AUTH_TELEMETRY() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY\");\n\t},\n\tget BETTER_AUTH_TELEMETRY_ID() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY_ID\");\n\t},\n\tget NODE_ENV() {\n\t\treturn getEnvVar(\"NODE_ENV\", \"development\");\n\t},\n\tget PACKAGE_VERSION() {\n\t\treturn getEnvVar(\"PACKAGE_VERSION\", \"0.0.0\");\n\t},\n\tget BETTER_AUTH_TELEMETRY_ENDPOINT() {\n\t\treturn getEnvVar(\"BETTER_AUTH_TELEMETRY_ENDPOINT\", \"\");\n\t}\n});\n//#endregion\nexport { ENV, env, getBooleanEnvVar, getEnvVar, isDevelopment, isProduction, isTest, nodeENV };\n","import { wildcardMatch } from \"./wildcard.mjs\";\nimport { env } from \"@better-auth/core/env\";\nimport { BetterAuthError } from \"@better-auth/core/error\";\n//#region src/utils/url.ts\n/**\n* Minimal loopback check for dev scheme inference only. Reachable from\n* `client/config.ts` via `getBaseURL`, so we MUST NOT import the full\n* `@better-auth/core/utils/host` classifier here: its `utils/ip` dependency\n* on zod would leak into the client bundle (see `e2e/smoke/test/vite.spec.ts`).\n*\n* Server-side SSRF/loopback checks (oauth redirect matching, trusted-origin\n* resolution, electron fetch gate) continue to use the authoritative\n* `isLoopbackHost` from `@better-auth/core/utils/host`. This helper's only\n* job is picking `http` vs `https` for dev ergonomics.\n*/\nfunction isLoopbackForDevScheme(host) {\n\tconst hostname = host.replace(/:\\d+$/, \"\").replace(/^\\[|\\]$/g, \"\").toLowerCase();\n\treturn hostname === \"localhost\" || hostname.endsWith(\".localhost\") || hostname === \"::1\" || hostname.startsWith(\"127.\");\n}\nfunction checkHasPath(url) {\n\ttry {\n\t\treturn (new URL(url).pathname.replace(/\\/+$/, \"\") || \"/\") !== \"/\";\n\t} catch {\n\t\tthrow new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`);\n\t}\n}\nfunction assertHasProtocol(url) {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\tif (parsedUrl.protocol !== \"http:\" && parsedUrl.protocol !== \"https:\") throw new BetterAuthError(`Invalid base URL: ${url}. URL must include 'http://' or 'https://'`);\n\t} catch (error) {\n\t\tif (error instanceof BetterAuthError) throw error;\n\t\tthrow new BetterAuthError(`Invalid base URL: ${url}. Please provide a valid base URL.`, { cause: error });\n\t}\n}\nfunction withPath(url, path = \"/api/auth\") {\n\tassertHasProtocol(url);\n\tif (checkHasPath(url)) return url;\n\tconst trimmedUrl = url.replace(/\\/+$/, \"\");\n\tif (!path || path === \"/\") return trimmedUrl;\n\tpath = path.startsWith(\"/\") ? path : `/${path}`;\n\treturn `${trimmedUrl}${path}`;\n}\nfunction validateProxyHeader(header, type) {\n\tif (!header || header.trim() === \"\") return false;\n\tif (type === \"proto\") return header === \"http\" || header === \"https\";\n\tif (type === \"host\") {\n\t\tif ([\n\t\t\t/\\.\\./,\n\t\t\t/\\0/,\n\t\t\t/[\\s]/,\n\t\t\t/^[.]/,\n\t\t\t/[<>'\"]/,\n\t\t\t/javascript:/i,\n\t\t\t/file:/i,\n\t\t\t/data:/i\n\t\t].some((pattern) => pattern.test(header))) return false;\n\t\treturn /^[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])?)*(:[0-9]{1,5})?$/.test(header) || /^(\\d{1,3}\\.){3}\\d{1,3}(:[0-9]{1,5})?$/.test(header) || /^\\[[0-9a-fA-F:]+\\](:[0-9]{1,5})?$/.test(header) || /^localhost(:[0-9]{1,5})?$/i.test(header);\n\t}\n\treturn false;\n}\nfunction getBaseURL(url, path, request, loadEnv, trustedProxyHeaders) {\n\tif (url) return withPath(url, path);\n\tif (loadEnv !== false) {\n\t\tconst fromEnv = env.BETTER_AUTH_URL || env.NEXT_PUBLIC_BETTER_AUTH_URL || env.PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_BETTER_AUTH_URL || env.NUXT_PUBLIC_AUTH_URL || (env.BASE_URL !== \"/\" ? env.BASE_URL : void 0);\n\t\tif (fromEnv) return withPath(fromEnv, path);\n\t}\n\tconst fromRequest = request?.headers.get(\"x-forwarded-host\");\n\tconst fromRequestProto = request?.headers.get(\"x-forwarded-proto\");\n\tif (fromRequest && fromRequestProto && trustedProxyHeaders) {\n\t\tif (validateProxyHeader(fromRequestProto, \"proto\") && validateProxyHeader(fromRequest, \"host\")) try {\n\t\t\treturn withPath(`${fromRequestProto}://${fromRequest}`, path);\n\t\t} catch (_error) {}\n\t}\n\tif (request) {\n\t\tconst url = getOrigin(request.url);\n\t\tif (!url) throw new BetterAuthError(\"Could not get origin from request. Please provide a valid base URL.\");\n\t\treturn withPath(url, path);\n\t}\n\tif (typeof window !== \"undefined\" && window.location) return withPath(window.location.origin, path);\n}\nfunction getOrigin(url) {\n\ttry {\n\t\tconst parsedUrl = new URL(url);\n\t\treturn parsedUrl.origin === \"null\" ? null : parsedUrl.origin;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getProtocol(url) {\n\ttry {\n\t\treturn new URL(url).protocol;\n\t} catch {\n\t\treturn null;\n\t}\n}\nfunction getHost(url) {\n\ttry {\n\t\treturn new URL(url).host;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/**\n* Checks if the baseURL config is a dynamic config object\n*/\nfunction isDynamicBaseURLConfig(config) {\n\treturn typeof config === \"object\" && config !== null && \"allowedHosts\" in config && Array.isArray(config.allowedHosts);\n}\n/**\n* Check if a value is a `Request`\n* - `instanceof`: works for native Request instances\n* - `toString`: handles where instanceof check fails but the object is still a\n* valid Request (e.g. cross-realm, polyfills). Paired with a shape check so\n* an object that only spoofs `Symbol.toStringTag` without the real shape is\n* rejected before downstream code tries to read `.headers` / `.url`.\n*\n* @param value The value to check\n* @returns `true` if the value is a Request instance\n*/\nfunction isRequestLike(value) {\n\tif (value instanceof Request) return true;\n\tif (typeof value !== \"object\" || value === null || Object.prototype.toString.call(value) !== \"[object Request]\") return false;\n\tconst v = value;\n\treturn typeof v.url === \"string\" && typeof v.headers === \"object\" && v.headers !== null && typeof v.headers.get === \"function\";\n}\n/**\n* Extracts the host from a `Request` or `Headers`.\n* Honors `x-forwarded-host` only when `trustedProxyHeaders` is enabled,\n* then falls back to the `host` header and finally the request URL.\n*/\nfunction getHostFromSource(source, trustedProxyHeaders) {\n\tconst headers = isRequestLike(source) ? source.headers : source;\n\tif (trustedProxyHeaders) {\n\t\tconst forwardedHost = headers.get(\"x-forwarded-host\");\n\t\tif (forwardedHost && validateProxyHeader(forwardedHost, \"host\")) return forwardedHost;\n\t}\n\tconst host = headers.get(\"host\");\n\tif (host && validateProxyHeader(host, \"host\")) return host;\n\tif (isRequestLike(source)) try {\n\t\treturn new URL(source.url).host;\n\t} catch {\n\t\treturn null;\n\t}\n\treturn null;\n}\n/**\n* Extracts the protocol from a `Request` or `Headers`.\n* Honors `x-forwarded-proto` only when `trustedProxyHeaders` is enabled,\n* then falls back to the request URL, then to \"https\".\n*/\nfunction getProtocolFromSource(source, configProtocol, trustedProxyHeaders) {\n\tif (configProtocol === \"http\" || configProtocol === \"https\") return configProtocol;\n\tconst headers = isRequestLike(source) ? source.headers : source;\n\tif (trustedProxyHeaders) {\n\t\tconst forwardedProto = headers.get(\"x-forwarded-proto\");\n\t\tif (forwardedProto && validateProxyHeader(forwardedProto, \"proto\")) return forwardedProto;\n\t}\n\tif (isRequestLike(source)) try {\n\t\tconst url = new URL(source.url);\n\t\tif (url.protocol === \"http:\" || url.protocol === \"https:\") return url.protocol.slice(0, -1);\n\t} catch {}\n\tconst host = getHostFromSource(source, trustedProxyHeaders);\n\tif (host && isLoopbackForDevScheme(host)) return \"http\";\n\treturn \"https\";\n}\n/**\n* Matches a hostname against a host pattern.\n* Supports wildcard patterns like `*.vercel.app` or `preview-*.myapp.com`.\n*\n* @param host The hostname to test (e.g., \"myapp.com\", \"preview-123.vercel.app\")\n* @param pattern The host pattern (e.g., \"myapp.com\", \"*.vercel.app\")\n* @returns {boolean} true if the host matches the pattern, false otherwise.\n*\n* @example\n* ```ts\n* matchesHostPattern(\"myapp.com\", \"myapp.com\") // true\n* matchesHostPattern(\"preview-123.vercel.app\", \"*.vercel.app\") // true\n* matchesHostPattern(\"preview-123.myapp.com\", \"preview-*.myapp.com\") // true\n* matchesHostPattern(\"evil.com\", \"myapp.com\") // false\n* ```\n*/\nconst matchesHostPattern = (host, pattern) => {\n\tif (!host || !pattern) return false;\n\tconst normalizedHost = host.replace(/^https?:\\/\\//, \"\").split(\"/\")[0].toLowerCase();\n\tconst normalizedPattern = pattern.replace(/^https?:\\/\\//, \"\").split(\"/\")[0].toLowerCase();\n\tif (normalizedPattern.includes(\"*\") || normalizedPattern.includes(\"?\")) return wildcardMatch(normalizedPattern)(normalizedHost);\n\treturn normalizedHost.toLowerCase() === normalizedPattern.toLowerCase();\n};\n/**\n* Resolves the base URL from a dynamic config based on the incoming request.\n* Validates the derived host against the allowedHosts allowlist.\n*\n* @param config The dynamic base URL config\n* @param request The incoming request\n* @param basePath The base path to append\n* @returns The resolved base URL with path\n* @throws BetterAuthError if host is not in allowedHosts and no fallback is set\n*/\nfunction resolveDynamicBaseURL(config, source, basePath, trustedProxyHeaders) {\n\tconst host = getHostFromSource(source, trustedProxyHeaders);\n\tif (!host) {\n\t\tif (config.fallback) return withPath(config.fallback, basePath);\n\t\tthrow new BetterAuthError(\"Could not determine host from request headers. Please provide a fallback URL in your baseURL config.\");\n\t}\n\tif (config.allowedHosts.some((pattern) => matchesHostPattern(host, pattern))) return withPath(`${getProtocolFromSource(source, config.protocol, trustedProxyHeaders)}://${host}`, basePath);\n\tif (config.fallback) return withPath(config.fallback, basePath);\n\tthrow new BetterAuthError(`Host \"${host}\" is not in the allowed hosts list. Allowed hosts: ${config.allowedHosts.join(\", \")}. Add this host to your allowedHosts config or provide a fallback URL.`);\n}\n/**\n* Resolves the base URL from any config type (static string or dynamic object).\n* This is the main entry point for base URL resolution.\n*\n* @param config The base URL config (string or object)\n* @param basePath The base path to append\n* @param request Optional request for dynamic resolution\n* @param loadEnv Whether to load from environment variables\n* @param trustedProxyHeaders Whether to trust proxy headers (for legacy behavior)\n* @returns The resolved base URL with path\n*/\nfunction resolveBaseURL(config, basePath, source, loadEnv, trustedProxyHeaders) {\n\tif (isDynamicBaseURLConfig(config)) {\n\t\tif (source) return resolveDynamicBaseURL(config, source, basePath, trustedProxyHeaders);\n\t\tif (config.fallback) return withPath(config.fallback, basePath);\n\t\treturn getBaseURL(void 0, basePath, void 0, loadEnv, trustedProxyHeaders);\n\t}\n\tconst request = isRequestLike(source) ? source : void 0;\n\tif (typeof config === \"string\") return getBaseURL(config, basePath, request, loadEnv, trustedProxyHeaders);\n\treturn getBaseURL(void 0, basePath, request, loadEnv, trustedProxyHeaders);\n}\n//#endregion\nexport { getBaseURL, getHost, getHostFromSource, getOrigin, getProtocol, getProtocolFromSource, isDynamicBaseURLConfig, isRequestLike, matchesHostPattern, resolveBaseURL, resolveDynamicBaseURL };\n","//#region src/client/fetch-plugins.ts\nconst redirectPlugin = {\n\tid: \"redirect\",\n\tname: \"Redirect\",\n\thooks: { onSuccess(context) {\n\t\tif (context.data?.url && context.data?.redirect) {\n\t\t\tif (typeof window !== \"undefined\" && window.location) {\n\t\t\t\tif (window.location) try {\n\t\t\t\t\twindow.location.href = context.data.url;\n\t\t\t\t} catch {}\n\t\t\t}\n\t\t}\n\t} }\n};\n//#endregion\nexport { redirectPlugin };\n","import { useAuthQuery } from \"./query.mjs\";\nimport { createSessionRefreshManager } from \"./session-refresh.mjs\";\nimport { atom, onMount } from \"nanostores\";\n//#region src/client/session-atom.ts\nfunction getSessionAtom($fetch, options) {\n\tconst $signal = atom(false);\n\tconst session = useAuthQuery($signal, \"/get-session\", $fetch, { method: \"GET\" });\n\tlet broadcastSessionUpdate = () => {};\n\tonMount(session, () => {\n\t\tconst refreshManager = createSessionRefreshManager({\n\t\t\tsessionAtom: session,\n\t\t\tsessionSignal: $signal,\n\t\t\t$fetch,\n\t\t\toptions\n\t\t});\n\t\trefreshManager.init();\n\t\tbroadcastSessionUpdate = refreshManager.broadcastSessionUpdate;\n\t\treturn () => {\n\t\t\trefreshManager.cleanup();\n\t\t};\n\t});\n\treturn {\n\t\tsession,\n\t\t$sessionSignal: $signal,\n\t\tbroadcastSessionUpdate: (trigger) => broadcastSessionUpdate(trigger)\n\t};\n}\n//#endregion\nexport { getSessionAtom };\n","function isPlainObject(value) {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {\n return false;\n }\n if (Symbol.iterator in value) {\n return false;\n }\n if (Symbol.toStringTag in value) {\n return Object.prototype.toString.call(value) === \"[object Module]\";\n }\n return true;\n}\n\nfunction _defu(baseObject, defaults, namespace = \".\", merger) {\n if (!isPlainObject(defaults)) {\n return _defu(baseObject, {}, namespace, merger);\n }\n const object = { ...defaults };\n for (const key of Object.keys(baseObject)) {\n if (key === \"__proto__\" || key === \"constructor\") {\n continue;\n }\n const value = baseObject[key];\n if (value === null || value === void 0) {\n continue;\n }\n if (merger && merger(object, key, value, namespace)) {\n continue;\n }\n if (Array.isArray(value) && Array.isArray(object[key])) {\n object[key] = [...value, ...object[key]];\n } else if (isPlainObject(value) && isPlainObject(object[key])) {\n object[key] = _defu(\n value,\n object[key],\n (namespace ? `${namespace}.` : \"\") + key.toString(),\n merger\n );\n } else {\n object[key] = value;\n }\n }\n return object;\n}\nfunction createDefu(merger) {\n return (...arguments_) => (\n // eslint-disable-next-line unicorn/no-array-reduce\n arguments_.reduce((p, c) => _defu(p, c, \"\", merger), {})\n );\n}\nconst defu = createDefu();\nconst defuFn = createDefu((object, key, currentValue) => {\n if (object[key] !== void 0 && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\nconst defuArrayFn = createDefu((object, key, currentValue) => {\n if (Array.isArray(object[key]) && typeof currentValue === \"function\") {\n object[key] = currentValue(object[key]);\n return true;\n }\n});\n\nexport { createDefu, defu as default, defu, defuArrayFn, defuFn };\n","var __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\n\n// src/error.ts\nvar BetterFetchError = class extends Error {\n constructor(status, statusText, error) {\n super(statusText || status.toString(), {\n cause: error\n });\n this.status = status;\n this.statusText = statusText;\n this.error = error;\n Error.captureStackTrace(this, this.constructor);\n }\n};\n\n// src/plugins.ts\nvar initializePlugins = async (url, options) => {\n var _a, _b, _c, _d, _e, _f;\n let opts = options || {};\n const hooks = {\n onRequest: [options == null ? void 0 : options.onRequest],\n onResponse: [options == null ? void 0 : options.onResponse],\n onSuccess: [options == null ? void 0 : options.onSuccess],\n onError: [options == null ? void 0 : options.onError],\n onRetry: [options == null ? void 0 : options.onRetry]\n };\n if (!options || !(options == null ? void 0 : options.plugins)) {\n return {\n url,\n options: opts,\n hooks\n };\n }\n for (const plugin of (options == null ? void 0 : options.plugins) || []) {\n if (plugin.init) {\n const pluginRes = await ((_a = plugin.init) == null ? void 0 : _a.call(plugin, url.toString(), options));\n opts = pluginRes.options || opts;\n url = pluginRes.url;\n }\n hooks.onRequest.push((_b = plugin.hooks) == null ? void 0 : _b.onRequest);\n hooks.onResponse.push((_c = plugin.hooks) == null ? void 0 : _c.onResponse);\n hooks.onSuccess.push((_d = plugin.hooks) == null ? void 0 : _d.onSuccess);\n hooks.onError.push((_e = plugin.hooks) == null ? void 0 : _e.onError);\n hooks.onRetry.push((_f = plugin.hooks) == null ? void 0 : _f.onRetry);\n }\n return {\n url,\n options: opts,\n hooks\n };\n};\n\n// src/retry.ts\nvar LinearRetryStrategy = class {\n constructor(options) {\n this.options = options;\n }\n shouldAttemptRetry(attempt, response) {\n if (this.options.shouldRetry) {\n return Promise.resolve(\n attempt < this.options.attempts && this.options.shouldRetry(response)\n );\n }\n return Promise.resolve(attempt < this.options.attempts);\n }\n getDelay() {\n return this.options.delay;\n }\n};\nvar ExponentialRetryStrategy = class {\n constructor(options) {\n this.options = options;\n }\n shouldAttemptRetry(attempt, response) {\n if (this.options.shouldRetry) {\n return Promise.resolve(\n attempt < this.options.attempts && this.options.shouldRetry(response)\n );\n }\n return Promise.resolve(attempt < this.options.attempts);\n }\n getDelay(attempt) {\n const delay = Math.min(\n this.options.maxDelay,\n this.options.baseDelay * 2 ** attempt\n );\n return delay;\n }\n};\nfunction createRetryStrategy(options) {\n if (typeof options === \"number\") {\n return new LinearRetryStrategy({\n type: \"linear\",\n attempts: options,\n delay: 1e3\n });\n }\n switch (options.type) {\n case \"linear\":\n return new LinearRetryStrategy(options);\n case \"exponential\":\n return new ExponentialRetryStrategy(options);\n default:\n throw new Error(\"Invalid retry strategy\");\n }\n}\n\n// src/auth.ts\nvar getAuthHeader = async (options) => {\n const headers = {};\n const getValue = async (value) => typeof value === \"function\" ? await value() : value;\n if (options == null ? void 0 : options.auth) {\n if (options.auth.type === \"Bearer\") {\n const token = await getValue(options.auth.token);\n if (!token) {\n return headers;\n }\n headers[\"authorization\"] = `Bearer ${token}`;\n } else if (options.auth.type === \"Basic\") {\n const [username, password] = await Promise.all([\n getValue(options.auth.username),\n getValue(options.auth.password)\n ]);\n if (!username || !password) {\n return headers;\n }\n headers[\"authorization\"] = `Basic ${btoa(`${username}:${password}`)}`;\n } else if (options.auth.type === \"Custom\") {\n const [prefix, value] = await Promise.all([\n getValue(options.auth.prefix),\n getValue(options.auth.value)\n ]);\n if (!value) {\n return headers;\n }\n headers[\"authorization\"] = `${prefix != null ? prefix : \"\"} ${value}`;\n }\n }\n return headers;\n};\n\n// src/utils.ts\nvar JSON_RE = /^application\\/(?:[\\w!#$%&*.^`~-]*\\+)?json(;.+)?$/i;\nfunction detectResponseType(request) {\n const _contentType = request.headers.get(\"content-type\");\n const textTypes = /* @__PURE__ */ new Set([\n \"image/svg\",\n \"application/xml\",\n \"application/xhtml\",\n \"application/html\"\n ]);\n if (!_contentType) {\n return \"json\";\n }\n const contentType = _contentType.split(\";\").shift() || \"\";\n if (JSON_RE.test(contentType)) {\n return \"json\";\n }\n if (textTypes.has(contentType) || contentType.startsWith(\"text/\")) {\n return \"text\";\n }\n return \"blob\";\n}\nfunction isJSONParsable(value) {\n try {\n JSON.parse(value);\n return true;\n } catch (error) {\n return false;\n }\n}\nfunction isJSONSerializable(value) {\n if (value === void 0) {\n return false;\n }\n const t = typeof value;\n if (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) {\n return true;\n }\n if (t !== \"object\") {\n return false;\n }\n if (Array.isArray(value)) {\n return true;\n }\n if (value.buffer) {\n return false;\n }\n return value.constructor && value.constructor.name === \"Object\" || typeof value.toJSON === \"function\";\n}\nfunction jsonParse(text) {\n try {\n return JSON.parse(text);\n } catch (error) {\n return text;\n }\n}\nfunction isFunction(value) {\n return typeof value === \"function\";\n}\nfunction getFetch(options) {\n if (options == null ? void 0 : options.customFetchImpl) {\n return options.customFetchImpl;\n }\n if (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) {\n return globalThis.fetch;\n }\n if (typeof window !== \"undefined\" && isFunction(window.fetch)) {\n return window.fetch;\n }\n throw new Error(\"No fetch implementation found\");\n}\nfunction isPayloadMethod(method) {\n if (!method) {\n return false;\n }\n const payloadMethod = [\"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n return payloadMethod.includes(method.toUpperCase());\n}\nfunction isRouteMethod(method) {\n const routeMethod = [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"];\n if (!method) {\n return false;\n }\n return routeMethod.includes(method.toUpperCase());\n}\nasync function getHeaders(opts) {\n const headers = new Headers(opts == null ? void 0 : opts.headers);\n const authHeader = await getAuthHeader(opts);\n for (const [key, value] of Object.entries(authHeader || {})) {\n headers.set(key, value);\n }\n if (!headers.has(\"content-type\")) {\n const t = detectContentType(opts == null ? void 0 : opts.body);\n if (t) {\n headers.set(\"content-type\", t);\n }\n }\n return headers;\n}\nfunction getURL(url, options) {\n if (url.startsWith(\"@\")) {\n const m = url.toString().split(\"@\")[1].split(\"/\")[0];\n if (methods.includes(m)) {\n url = url.replace(`@${m}/`, \"/\");\n }\n }\n let _url;\n try {\n if (url.startsWith(\"http\")) {\n _url = url;\n } else {\n let baseURL = options == null ? void 0 : options.baseURL;\n if (baseURL && !(baseURL == null ? void 0 : baseURL.endsWith(\"/\"))) {\n baseURL = baseURL + \"/\";\n }\n if (url.startsWith(\"/\")) {\n _url = new URL(url.substring(1), baseURL);\n } else {\n _url = new URL(url, options == null ? void 0 : options.baseURL);\n }\n }\n } catch (e) {\n if (e instanceof TypeError) {\n if (!(options == null ? void 0 : options.baseURL)) {\n throw TypeError(\n `Invalid URL ${url}. Are you passing in a relative url but not setting the baseURL?`\n );\n }\n throw TypeError(\n `Invalid URL ${url}. Please validate that you are passing the correct input.`\n );\n }\n throw e;\n }\n if (options == null ? void 0 : options.params) {\n if (Array.isArray(options == null ? void 0 : options.params)) {\n const params = (options == null ? void 0 : options.params) ? Array.isArray(options.params) ? `/${options.params.join(\"/\")}` : `/${Object.values(options.params).join(\"/\")}` : \"\";\n _url = _url.toString().split(\"/:\")[0];\n _url = `${_url.toString()}${params}`;\n } else {\n for (const [key, value] of Object.entries(options == null ? void 0 : options.params)) {\n _url = _url.toString().replace(`:${key}`, String(value));\n }\n }\n }\n const __url = new URL(_url);\n const queryParams = options == null ? void 0 : options.query;\n if (queryParams) {\n for (const [key, value] of Object.entries(queryParams)) {\n __url.searchParams.append(key, String(value));\n }\n }\n return __url;\n}\nfunction detectContentType(body) {\n if (isJSONSerializable(body)) {\n return \"application/json\";\n }\n return null;\n}\nfunction getBody(options) {\n if (!(options == null ? void 0 : options.body)) {\n return null;\n }\n const headers = new Headers(options == null ? void 0 : options.headers);\n if (isJSONSerializable(options.body) && !headers.has(\"content-type\")) {\n for (const [key, value] of Object.entries(options == null ? void 0 : options.body)) {\n if (value instanceof Date) {\n options.body[key] = value.toISOString();\n }\n }\n return JSON.stringify(options.body);\n }\n if (headers.has(\"content-type\") && headers.get(\"content-type\") === \"application/x-www-form-urlencoded\") {\n if (isJSONSerializable(options.body)) {\n return new URLSearchParams(options.body).toString();\n }\n return options.body;\n }\n return options.body;\n}\nfunction getMethod(url, options) {\n var _a;\n if (options == null ? void 0 : options.method) {\n return options.method.toUpperCase();\n }\n if (url.startsWith(\"@\")) {\n const pMethod = (_a = url.split(\"@\")[1]) == null ? void 0 : _a.split(\"/\")[0];\n if (!methods.includes(pMethod)) {\n return (options == null ? void 0 : options.body) ? \"POST\" : \"GET\";\n }\n return pMethod.toUpperCase();\n }\n return (options == null ? void 0 : options.body) ? \"POST\" : \"GET\";\n}\nfunction getTimeout(options, controller) {\n let abortTimeout;\n if (!(options == null ? void 0 : options.signal) && (options == null ? void 0 : options.timeout)) {\n abortTimeout = setTimeout(() => controller == null ? void 0 : controller.abort(), options == null ? void 0 : options.timeout);\n }\n return {\n abortTimeout,\n clearTimeout: () => {\n if (abortTimeout) {\n clearTimeout(abortTimeout);\n }\n }\n };\n}\nfunction bodyParser(data, responseType) {\n if (responseType === \"json\") {\n return JSON.parse(data);\n }\n return data;\n}\nvar ValidationError = class _ValidationError extends Error {\n constructor(issues, message) {\n super(message || JSON.stringify(issues, null, 2));\n this.issues = issues;\n Object.setPrototypeOf(this, _ValidationError.prototype);\n }\n};\nasync function parseStandardSchema(schema, input) {\n const result = await schema[\"~standard\"].validate(input);\n if (result.issues) {\n throw new ValidationError(result.issues);\n }\n return result.value;\n}\n\n// src/create-fetch/schema.ts\nvar methods = [\"get\", \"post\", \"put\", \"patch\", \"delete\"];\nvar createSchema = (schema, config) => {\n return {\n schema,\n config\n };\n};\n\n// src/create-fetch/index.ts\nvar applySchemaPlugin = (config) => ({\n id: \"apply-schema\",\n name: \"Apply Schema\",\n version: \"1.0.0\",\n async init(url, options) {\n var _a, _b, _c, _d;\n const schema = ((_b = (_a = config.plugins) == null ? void 0 : _a.find(\n (plugin) => {\n var _a2;\n return ((_a2 = plugin.schema) == null ? void 0 : _a2.config) ? url.startsWith(plugin.schema.config.baseURL || \"\") || url.startsWith(plugin.schema.config.prefix || \"\") : false;\n }\n )) == null ? void 0 : _b.schema) || config.schema;\n if (schema) {\n let urlKey = url;\n if ((_c = schema.config) == null ? void 0 : _c.prefix) {\n if (urlKey.startsWith(schema.config.prefix)) {\n urlKey = urlKey.replace(schema.config.prefix, \"\");\n if (schema.config.baseURL) {\n url = url.replace(schema.config.prefix, schema.config.baseURL);\n }\n }\n }\n if ((_d = schema.config) == null ? void 0 : _d.baseURL) {\n if (urlKey.startsWith(schema.config.baseURL)) {\n urlKey = urlKey.replace(schema.config.baseURL, \"\");\n }\n }\n const keySchema = schema.schema[urlKey];\n if (keySchema) {\n let opts = __spreadProps(__spreadValues({}, options), {\n method: keySchema.method,\n output: keySchema.output\n });\n if (!(options == null ? void 0 : options.disableValidation)) {\n opts = __spreadProps(__spreadValues({}, opts), {\n body: keySchema.input ? await parseStandardSchema(keySchema.input, options == null ? void 0 : options.body) : options == null ? void 0 : options.body,\n params: keySchema.params ? await parseStandardSchema(keySchema.params, options == null ? void 0 : options.params) : options == null ? void 0 : options.params,\n query: keySchema.query ? await parseStandardSchema(keySchema.query, options == null ? void 0 : options.query) : options == null ? void 0 : options.query\n });\n }\n return {\n url,\n options: opts\n };\n }\n }\n return {\n url,\n options\n };\n }\n});\nvar createFetch = (config) => {\n async function $fetch(url, options) {\n const opts = __spreadProps(__spreadValues(__spreadValues({}, config), options), {\n plugins: [...(config == null ? void 0 : config.plugins) || [], applySchemaPlugin(config || {}), ...(options == null ? void 0 : options.plugins) || []]\n });\n if (config == null ? void 0 : config.catchAllError) {\n try {\n return await betterFetch(url, opts);\n } catch (error) {\n return {\n data: null,\n error: {\n status: 500,\n statusText: \"Fetch Error\",\n message: \"Fetch related error. Captured by catchAllError option. See error property for more details.\",\n error\n }\n };\n }\n }\n return await betterFetch(url, opts);\n }\n return $fetch;\n};\n\n// src/url.ts\nfunction getURL2(url, option) {\n const { baseURL, params, query } = option || {\n query: {},\n params: {},\n baseURL: \"\"\n };\n let basePath = url.startsWith(\"http\") ? url.split(\"/\").slice(0, 3).join(\"/\") : baseURL || \"\";\n if (url.startsWith(\"@\")) {\n const m = url.toString().split(\"@\")[1].split(\"/\")[0];\n if (methods.includes(m)) {\n url = url.replace(`@${m}/`, \"/\");\n }\n }\n if (!basePath.endsWith(\"/\")) basePath += \"/\";\n let [path, urlQuery] = url.replace(basePath, \"\").split(\"?\");\n const queryParams = new URLSearchParams(urlQuery);\n for (const [key, value] of Object.entries(query || {})) {\n if (value == null) continue;\n let serializedValue;\n if (typeof value === \"string\") {\n serializedValue = value;\n } else if (Array.isArray(value)) {\n for (const val of value) {\n queryParams.append(key, val);\n }\n continue;\n } else {\n serializedValue = JSON.stringify(value);\n }\n queryParams.set(key, serializedValue);\n }\n if (params) {\n if (Array.isArray(params)) {\n const paramPaths = path.split(\"/\").filter((p) => p.startsWith(\":\"));\n for (const [index, key] of paramPaths.entries()) {\n const value = params[index];\n path = path.replace(key, value);\n }\n } else {\n for (const [key, value] of Object.entries(params)) {\n path = path.replace(`:${key}`, String(value));\n }\n }\n }\n path = path.split(\"/\").map(encodeURIComponent).join(\"/\");\n if (path.startsWith(\"/\")) path = path.slice(1);\n let queryParamString = queryParams.toString();\n queryParamString = queryParamString.length > 0 ? `?${queryParamString}`.replace(/\\+/g, \"%20\") : \"\";\n if (!basePath.startsWith(\"http\")) {\n return `${basePath}${path}${queryParamString}`;\n }\n const _url = new URL(`${path}${queryParamString}`, basePath);\n return _url;\n}\n\n// src/fetch.ts\nvar betterFetch = async (url, options) => {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n const {\n hooks,\n url: __url,\n options: opts\n } = await initializePlugins(url, options);\n const fetch = getFetch(opts);\n const controller = new AbortController();\n const signal = (_a = opts.signal) != null ? _a : controller.signal;\n const _url = getURL2(__url, opts);\n const body = getBody(opts);\n const headers = await getHeaders(opts);\n const method = getMethod(__url, opts);\n let context = __spreadProps(__spreadValues({}, opts), {\n url: _url,\n headers,\n body,\n method,\n signal\n });\n for (const onRequest of hooks.onRequest) {\n if (onRequest) {\n const res = await onRequest(context);\n if (typeof res === \"object\" && res !== null) {\n context = res;\n }\n }\n }\n if (\"pipeTo\" in context && typeof context.pipeTo === \"function\" || typeof ((_b = options == null ? void 0 : options.body) == null ? void 0 : _b.pipe) === \"function\") {\n if (!(\"duplex\" in context)) {\n context.duplex = \"half\";\n }\n }\n const { clearTimeout: clearTimeout2 } = getTimeout(opts, controller);\n let response = await fetch(context.url, context);\n clearTimeout2();\n const responseContext = {\n response,\n request: context\n };\n for (const onResponse of hooks.onResponse) {\n if (onResponse) {\n const r = await onResponse(__spreadProps(__spreadValues({}, responseContext), {\n response: ((_c = options == null ? void 0 : options.hookOptions) == null ? void 0 : _c.cloneResponse) ? response.clone() : response\n }));\n if (r instanceof Response) {\n response = r;\n } else if (typeof r === \"object\" && r !== null) {\n response = r.response;\n }\n }\n }\n if (response.ok) {\n const hasBody = context.method !== \"HEAD\";\n if (!hasBody) {\n return {\n data: \"\",\n error: null\n };\n }\n const responseType = detectResponseType(response);\n const successContext = {\n data: null,\n response,\n request: context\n };\n if (responseType === \"json\" || responseType === \"text\") {\n const text = await response.text();\n const parser2 = (_d = context.jsonParser) != null ? _d : jsonParse;\n successContext.data = await parser2(text);\n } else {\n successContext.data = await response[responseType]();\n }\n if (context == null ? void 0 : context.output) {\n if (context.output && !context.disableValidation) {\n successContext.data = await parseStandardSchema(\n context.output,\n successContext.data\n );\n }\n }\n for (const onSuccess of hooks.onSuccess) {\n if (onSuccess) {\n await onSuccess(__spreadProps(__spreadValues({}, successContext), {\n response: ((_e = options == null ? void 0 : options.hookOptions) == null ? void 0 : _e.cloneResponse) ? response.clone() : response\n }));\n }\n }\n if (options == null ? void 0 : options.throw) {\n return successContext.data;\n }\n return {\n data: successContext.data,\n error: null\n };\n }\n const parser = (_f = options == null ? void 0 : options.jsonParser) != null ? _f : jsonParse;\n const responseText = await response.text();\n const isJSONResponse = isJSONParsable(responseText);\n const errorObject = isJSONResponse ? await parser(responseText) : null;\n const errorContext = {\n response,\n responseText,\n request: context,\n error: __spreadProps(__spreadValues({}, errorObject), {\n status: response.status,\n statusText: response.statusText\n })\n };\n for (const onError of hooks.onError) {\n if (onError) {\n await onError(__spreadProps(__spreadValues({}, errorContext), {\n response: ((_g = options == null ? void 0 : options.hookOptions) == null ? void 0 : _g.cloneResponse) ? response.clone() : response\n }));\n }\n }\n if (options == null ? void 0 : options.retry) {\n const retryStrategy = createRetryStrategy(options.retry);\n const _retryAttempt = (_h = options.retryAttempt) != null ? _h : 0;\n if (await retryStrategy.shouldAttemptRetry(_retryAttempt, response)) {\n for (const onRetry of hooks.onRetry) {\n if (onRetry) {\n await onRetry(responseContext);\n }\n }\n const delay = retryStrategy.getDelay(_retryAttempt);\n await new Promise((resolve) => setTimeout(resolve, delay));\n return await betterFetch(url, __spreadProps(__spreadValues({}, options), {\n retryAttempt: _retryAttempt + 1\n }));\n }\n }\n if (options == null ? void 0 : options.throw) {\n throw new BetterFetchError(\n response.status,\n response.statusText,\n isJSONResponse ? errorObject : responseText\n );\n }\n return {\n data: null,\n error: __spreadProps(__spreadValues({}, errorObject), {\n status: response.status,\n statusText: response.statusText\n })\n };\n};\nexport {\n BetterFetchError,\n ValidationError,\n applySchemaPlugin,\n betterFetch,\n bodyParser,\n createFetch,\n createRetryStrategy,\n createSchema,\n detectContentType,\n detectResponseType,\n getBody,\n getFetch,\n getHeaders,\n getMethod,\n getTimeout,\n getURL,\n initializePlugins,\n isFunction,\n isJSONParsable,\n isJSONSerializable,\n isPayloadMethod,\n isRouteMethod,\n jsonParse,\n methods,\n parseStandardSchema\n};\n//# sourceMappingURL=index.js.map","import { getBaseURL } from \"../utils/url.mjs\";\nimport { parseJSON } from \"./parser.mjs\";\nimport { redirectPlugin } from \"./fetch-plugins.mjs\";\nimport { getSessionAtom } from \"./session-atom.mjs\";\nimport { defu } from \"defu\";\nimport { createFetch } from \"@better-fetch/fetch\";\n//#region src/client/config.ts\nconst resolvePublicAuthUrl = (basePath) => {\n\tif (typeof process === \"undefined\") return void 0;\n\tconst path = basePath ?? \"/api/auth\";\n\tif (process.env.NEXT_PUBLIC_AUTH_URL) return process.env.NEXT_PUBLIC_AUTH_URL;\n\tif (typeof window === \"undefined\") {\n\t\tif (process.env.NEXTAUTH_URL) try {\n\t\t\treturn process.env.NEXTAUTH_URL;\n\t\t} catch {}\n\t\tif (process.env.VERCEL_URL) try {\n\t\t\tconst protocol = process.env.VERCEL_URL.startsWith(\"http\") ? \"\" : \"https://\";\n\t\t\treturn `${new URL(`${protocol}${process.env.VERCEL_URL}`).origin}${path}`;\n\t\t} catch {}\n\t}\n};\nconst getClientConfig = (options, loadEnv) => {\n\tconst isCredentialsSupported = \"credentials\" in Request.prototype;\n\tconst baseURL = getBaseURL(options?.baseURL, options?.basePath, void 0, loadEnv) ?? resolvePublicAuthUrl(options?.basePath) ?? \"/api/auth\";\n\tconst pluginsFetchPlugins = options?.plugins?.flatMap((plugin) => plugin.fetchPlugins).filter((pl) => pl !== void 0) || [];\n\tconst lifeCyclePlugin = {\n\t\tid: \"lifecycle-hooks\",\n\t\tname: \"lifecycle-hooks\",\n\t\thooks: {\n\t\t\tonSuccess: options?.fetchOptions?.onSuccess,\n\t\t\tonError: options?.fetchOptions?.onError,\n\t\t\tonRequest: options?.fetchOptions?.onRequest,\n\t\t\tonResponse: options?.fetchOptions?.onResponse\n\t\t}\n\t};\n\tconst { onSuccess: _onSuccess, onError: _onError, onRequest: _onRequest, onResponse: _onResponse, ...restOfFetchOptions } = options?.fetchOptions || {};\n\tconst $fetch = createFetch({\n\t\tbaseURL,\n\t\t...isCredentialsSupported ? { credentials: \"include\" } : {},\n\t\tmethod: \"GET\",\n\t\tjsonParser(text) {\n\t\t\tif (!text) return null;\n\t\t\treturn parseJSON(text, { strict: false });\n\t\t},\n\t\tcustomFetchImpl: fetch,\n\t\t...restOfFetchOptions,\n\t\tplugins: [\n\t\t\tlifeCyclePlugin,\n\t\t\t...restOfFetchOptions.plugins || [],\n\t\t\t...options?.disableDefaultFetchPlugins ? [] : [redirectPlugin],\n\t\t\t...pluginsFetchPlugins\n\t\t]\n\t});\n\tconst { $sessionSignal, session, broadcastSessionUpdate } = getSessionAtom($fetch, options);\n\tconst plugins = options?.plugins || [];\n\tlet pluginsActions = {};\n\tconst pluginsAtoms = {\n\t\t$sessionSignal,\n\t\tsession\n\t};\n\tconst pluginPathMethods = {\n\t\t\"/sign-out\": \"POST\",\n\t\t\"/revoke-sessions\": \"POST\",\n\t\t\"/revoke-other-sessions\": \"POST\",\n\t\t\"/delete-user\": \"POST\"\n\t};\n\tconst atomListeners = [{\n\t\tsignal: \"$sessionSignal\",\n\t\tmatcher(path) {\n\t\t\treturn path === \"/sign-out\" || path === \"/update-user\" || path === \"/update-session\" || path === \"/sign-up/email\" || path === \"/sign-in/email\" || path === \"/delete-user\" || path === \"/verify-email\" || path === \"/revoke-sessions\" || path === \"/revoke-session\" || path === \"/revoke-other-sessions\" || path === \"/change-email\" || path === \"/change-password\";\n\t\t},\n\t\tcallback(path) {\n\t\t\tif (path === \"/sign-out\") broadcastSessionUpdate(\"signout\");\n\t\t\telse if (path === \"/update-user\" || path === \"/update-session\") broadcastSessionUpdate(\"updateUser\");\n\t\t}\n\t}];\n\tfor (const plugin of plugins) {\n\t\tif (plugin.getAtoms) Object.assign(pluginsAtoms, plugin.getAtoms?.($fetch));\n\t\tif (plugin.pathMethods) Object.assign(pluginPathMethods, plugin.pathMethods);\n\t\tif (plugin.atomListeners) atomListeners.push(...plugin.atomListeners);\n\t}\n\tconst $store = {\n\t\tnotify: (signal) => {\n\t\t\tpluginsAtoms[signal].set(!pluginsAtoms[signal].get());\n\t\t},\n\t\tlisten: (signal, listener) => {\n\t\t\tpluginsAtoms[signal].subscribe(listener);\n\t\t},\n\t\tatoms: pluginsAtoms\n\t};\n\tfor (const plugin of plugins) if (plugin.getActions) pluginsActions = defu(plugin.getActions?.($fetch, $store, options) ?? {}, pluginsActions);\n\treturn {\n\t\tget baseURL() {\n\t\t\treturn baseURL;\n\t\t},\n\t\tpluginsActions,\n\t\tpluginsAtoms,\n\t\tpluginPathMethods,\n\t\tatomListeners,\n\t\t$fetch,\n\t\t$store\n\t};\n};\n//#endregion\nexport { getClientConfig };\n","//#region src/utils/is-atom.ts\nfunction isAtom(value) {\n\treturn typeof value === \"object\" && value !== null && \"get\" in value && typeof value.get === \"function\" && \"lc\" in value && typeof value.lc === \"number\";\n}\n//#endregion\nexport { isAtom };\n","import { isAtom } from \"../utils/is-atom.mjs\";\n//#region src/client/proxy.ts\nfunction getMethod(path, knownPathMethods, args) {\n\tconst method = knownPathMethods[path];\n\tconst { fetchOptions, query: _query, ...body } = args || {};\n\tif (method) return method;\n\tif (fetchOptions?.method) return fetchOptions.method;\n\tif (body && Object.keys(body).length > 0) return \"POST\";\n\treturn \"GET\";\n}\nfunction createDynamicPathProxy(routes, client, knownPathMethods, atoms, atomListeners) {\n\tfunction createProxy(path = []) {\n\t\treturn new Proxy(function() {}, {\n\t\t\tget(_, prop) {\n\t\t\t\tif (typeof prop !== \"string\") return;\n\t\t\t\tif (prop === \"then\" || prop === \"catch\" || prop === \"finally\") return;\n\t\t\t\tconst fullPath = [...path, prop];\n\t\t\t\tlet current = routes;\n\t\t\t\tfor (const segment of fullPath) if (current && typeof current === \"object\" && segment in current) current = current[segment];\n\t\t\t\telse {\n\t\t\t\t\tcurrent = void 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (typeof current === \"function\") return current;\n\t\t\t\tif (isAtom(current)) return current;\n\t\t\t\treturn createProxy(fullPath);\n\t\t\t},\n\t\t\tapply: async (_, __, args) => {\n\t\t\t\tconst routePath = \"/\" + path.map((segment) => segment.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)).join(\"/\");\n\t\t\t\tconst arg = args[0] || {};\n\t\t\t\tconst fetchOptions = args[1] || {};\n\t\t\t\tconst { query, fetchOptions: argFetchOptions, ...body } = arg;\n\t\t\t\tconst options = {\n\t\t\t\t\t...fetchOptions,\n\t\t\t\t\t...argFetchOptions\n\t\t\t\t};\n\t\t\t\tconst method = getMethod(routePath, knownPathMethods, arg);\n\t\t\t\treturn await client(routePath, {\n\t\t\t\t\t...options,\n\t\t\t\t\tbody: method === \"GET\" ? void 0 : {\n\t\t\t\t\t\t...body,\n\t\t\t\t\t\t...options?.body || {}\n\t\t\t\t\t},\n\t\t\t\t\tquery: query || options?.query,\n\t\t\t\t\tmethod,\n\t\t\t\t\tasync onSuccess(context) {\n\t\t\t\t\t\tawait options?.onSuccess?.(context);\n\t\t\t\t\t\tif (!atomListeners || options.disableSignal) return;\n\t\t\t\t\t\t/**\n\t\t\t\t\t\t* We trigger listeners\n\t\t\t\t\t\t*/\n\t\t\t\t\t\tconst matches = atomListeners.filter((s) => s.matcher(routePath));\n\t\t\t\t\t\tif (!matches.length) return;\n\t\t\t\t\t\tconst visited = /* @__PURE__ */ new Set();\n\t\t\t\t\t\tfor (const match of matches) {\n\t\t\t\t\t\t\tconst signal = atoms[match.signal];\n\t\t\t\t\t\t\tif (!signal) return;\n\t\t\t\t\t\t\tif (visited.has(match.signal)) continue;\n\t\t\t\t\t\t\tvisited.add(match.signal);\n\t\t\t\t\t\t\t/**\n\t\t\t\t\t\t\t* To avoid race conditions we set the signal in a setTimeout\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tconst val = signal.get();\n\t\t\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\t\t\tsignal.set(!val);\n\t\t\t\t\t\t\t}, 10);\n\t\t\t\t\t\t\tmatch.callback?.(routePath);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\treturn createProxy();\n}\n//#endregion\nexport { createDynamicPathProxy };\n","//#region src/utils/string.ts\nfunction capitalizeFirstLetter(str) {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n//#endregion\nexport { capitalizeFirstLetter };\n","import { getClientConfig } from \"./config.mjs\";\nimport { createDynamicPathProxy } from \"./proxy.mjs\";\nimport { capitalizeFirstLetter } from \"@better-auth/core/utils/string\";\n//#region src/client/vanilla.ts\nfunction createAuthClient(options) {\n\tconst { pluginPathMethods, pluginsActions, pluginsAtoms, $fetch, atomListeners, $store } = getClientConfig(options);\n\tconst resolvedHooks = {};\n\tfor (const [key, value] of Object.entries(pluginsAtoms)) resolvedHooks[`use${capitalizeFirstLetter(key)}`] = value;\n\treturn createDynamicPathProxy({\n\t\t...pluginsActions,\n\t\t...resolvedHooks,\n\t\t$fetch,\n\t\t$store\n\t}, $fetch, pluginPathMethods, pluginsAtoms, atomListeners);\n}\n//#endregion\nexport { createAuthClient };\n","import { a as fetchJwtWithSession, c as CLI_CLIENT_ID } from \"./jwt-BVJ7dVm9.mjs\";\nimport { t as createJwtTokenCache } from \"./jwt-cache-4YqHn3jM.mjs\";\nimport { deviceAuthorizationClient } from \"better-auth/client/plugins\";\nimport { createAuthClient } from \"better-auth/client\";\n//#region src/cli.ts\nfunction createCliAuthClient(baseURL) {\n\treturn createAuthClient({\n\t\tbaseURL,\n\t\tplugins: [deviceAuthorizationClient()]\n\t});\n}\nfunction sleep(ms) {\n\treturn new Promise((resolve) => setTimeout(resolve, ms));\n}\nfunction isDeviceTokenError(value) {\n\treturn typeof value === \"object\" && value !== null && \"error\" in value && typeof value.error === \"string\";\n}\nasync function runDeviceLogin(options) {\n\tconst client = createCliAuthClient(options.baseURL);\n\tconst codeResult = await client.device.code({ client_id: options.clientId });\n\tif (codeResult.error) {\n\t\tconst message = \"error_description\" in codeResult.error ? codeResult.error.error_description : \"Failed to request device code\";\n\t\tthrow new Error(message);\n\t}\n\tconst { device_code: deviceCode, user_code: userCode, verification_uri: verificationUri, verification_uri_complete: verificationUriComplete, expires_in: expiresIn, interval } = codeResult.data;\n\tif (options.onCodes) options.onCodes({\n\t\tuserCode,\n\t\tverificationUri,\n\t\tverificationUriComplete\n\t});\n\telse if (options.openUrl) {\n\t\tprocess.stderr.write(\"Opening browser to authorize…\\n\");\n\t\toptions.openUrl(verificationUriComplete);\n\t} else process.stderr.write(`Visit ${verificationUriComplete} to authorize.\\n`);\n\tconst deadline = Date.now() + expiresIn * 1e3;\n\tlet pollIntervalMs = interval * 1e3;\n\twhile (Date.now() < deadline) {\n\t\tconst tokenResult = await client.device.token({\n\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\tdevice_code: deviceCode,\n\t\t\tclient_id: options.clientId\n\t\t});\n\t\tif (!tokenResult.error) {\n\t\t\tconst token = tokenResult.data;\n\t\t\tconst organizationId = token.scope?.trim();\n\t\t\treturn {\n\t\t\t\taccessToken: token.access_token,\n\t\t\t\texpiresIn: token.expires_in,\n\t\t\t\torganizationId: organizationId || void 0\n\t\t\t};\n\t\t}\n\t\tconst errorPayload = tokenResult.error;\n\t\tconst oauthError = isDeviceTokenError(errorPayload.body) ? errorPayload.body : isDeviceTokenError(tokenResult.error) ? tokenResult.error : null;\n\t\tif (oauthError?.error === \"authorization_pending\") {\n\t\t\tawait sleep(pollIntervalMs);\n\t\t\tcontinue;\n\t\t}\n\t\tif (oauthError?.error === \"slow_down\") {\n\t\t\tpollIntervalMs += 5e3;\n\t\t\tawait sleep(pollIntervalMs);\n\t\t\tcontinue;\n\t\t}\n\t\tif (oauthError?.error === \"expired_token\") throw new Error(\"Device code expired. Run auth login again.\");\n\t\tif (oauthError?.error === \"access_denied\") throw new Error(\"Device authorization was denied.\");\n\t\tthrow new Error(oauthError?.error_description ?? errorPayload.message ?? \"Device login failed\");\n\t}\n\tthrow new Error(\"Device code expired. Run auth login again.\");\n}\nasync function getSessionWithBearer(baseURL, accessToken) {\n\tconst result = await createCliAuthClient(baseURL).getSession({ fetchOptions: { headers: { Authorization: `Bearer ${accessToken}` } } });\n\tconst user = result && \"user\" in result ? result.user : result && \"data\" in result && result.data && \"user\" in result.data ? result.data.user : void 0;\n\tif (typeof user !== \"object\" || user === null || !(\"id\" in user) || !(\"email\" in user) || !(\"name\" in user) || typeof user.id !== \"string\" || typeof user.email !== \"string\" || typeof user.name !== \"string\") return null;\n\treturn {\n\t\tid: user.id,\n\t\temail: user.email,\n\t\tname: user.name\n\t};\n}\nasync function getJwtWithBearer(baseURL, sessionToken) {\n\treturn fetchJwtWithSession(baseURL, { bearerToken: sessionToken });\n}\n//#endregion\nexport { CLI_CLIENT_ID, createCliAuthClient, createJwtTokenCache, getJwtWithBearer, getSessionWithBearer, runDeviceLogin };\n\n//# sourceMappingURL=cli.mjs.map","import { createJwtTokenCache, getJwtWithBearer, type JwtTokenCache } from \"@keystrokehq/auth/cli\";\n\nimport { getAccessToken } from \"./credentials\";\n\nconst caches = new Map<string, JwtTokenCache>();\n\nexport function clearCliJwtCache(): void {\n caches.clear();\n}\n\nexport async function getCliJwt(platformUrl: string, force = false): Promise<string | undefined> {\n if (!getAccessToken(platformUrl)) {\n caches.delete(platformUrl);\n return undefined;\n }\n\n let cache = caches.get(platformUrl);\n if (!cache) {\n cache = createJwtTokenCache(async () => {\n const sessionToken = getAccessToken(platformUrl);\n return sessionToken ? getJwtWithBearer(platformUrl, sessionToken) : null;\n });\n caches.set(platformUrl, cache);\n }\n\n return cache.get(force);\n}\n","import type { AuthStrategy } from \"@keystrokehq/sdk\";\nimport type Conf from \"conf\";\n\nimport { getAccessToken } from \"./credentials\";\nimport { getCliJwt } from \"./jwt-cache\";\nimport { getPlatformUrl, type CliConfig } from \"../config\";\n\n/** Returns JWT bearer auth when a session refresh token is stored; otherwise none. */\nexport function resolveCliAuth(config: Conf<CliConfig>): AuthStrategy {\n const platformUrl = getPlatformUrl(config);\n if (!getAccessToken(platformUrl)) {\n return { type: \"none\" };\n }\n\n return {\n type: \"bearer\",\n getToken: () => getCliJwt(platformUrl),\n };\n}\n","import { createKeystrokeClient, type KeystrokeClient } from \"@keystrokehq/sdk\";\nimport type Conf from \"conf\";\nimport { resolveCliAuth } from \"./auth/resolve-cli-auth\";\nimport type { CliConfig } from \"./config\";\n\nexport function createCliClient(\n config: Conf<CliConfig>,\n options: { baseUrl: string; platform?: boolean },\n): KeystrokeClient {\n return createKeystrokeClient({\n baseUrl: options.baseUrl,\n auth: resolveCliAuth(config),\n getActiveOrganizationId: options.platform\n ? () => config.get(\"activeOrganizationId\") ?? null\n : undefined,\n });\n}\n","import ky, { isHTTPError } from \"ky\";\nimport { ACTIVE_ORG_HEADER, AcceptOrganizationInvitationResponseSchema, ActiveOrganizationResponseSchema, AgentSummaryDetailResponseSchema, AgentSummaryListResponseSchema, CompleteProjectArtifactResponseSchema, ConnectAuthorizeUrlResponseSchema, CreateCredentialsRequestSchema, CreateCredentialsResponseSchema, CreateOrganizationRequestSchema, CreateOrganizationResponseSchema, CreateProjectArtifactResponseSchema, CreateProjectRequestSchema, CreateProjectResponseSchema, DEFAULT_ORGANIZATION_SIDEBAR_BRANDING, DEFAULT_USER_PREFERENCES, DeclineOrganizationInvitationResponseSchema, ErrorResponseSchema, GatewayAttachmentRecordSchema, GetCredentialResponseSchema, HealthResponseSchema, HistoryRunCancelResponseSchema, HistoryRunDetailResponseSchema, HistoryRunListQuerySchema, HistoryRunListResponseSchema, InviteOrganizationMembersRequestSchema, InviteOrganizationMembersResponseSchema, ListAppsResponseSchema, ListCredentialsResponseSchema, ListOrganizationInvitationsResponseSchema, ListOrganizationMembersResponseSchema, ListOrganizationsResponseSchema, ListProjectDeploymentsResponseSchema, ListProjectFilesResponseSchema, ListProjectMetricsResponseSchema, ListProjectsResponseSchema, OrganizationSidebarBrandingPatchSchema, OrganizationSidebarBrandingSchema, PROJECT_REACHABILITY_REQUEST_TIMEOUT_MS, PresignOrgLogoRequestSchema, PresignOrgLogoResponseSchema, PresignProjectSourceRequestSchema, PresignProjectSourceResponseSchema, PresignUserAvatarRequestSchema, PresignUserAvatarResponseSchema, ProjectReachabilityResponseSchema, ProjectResponseSchema, ProjectSlugAvailabilityResponseSchema, RecentResourceListResponseSchema, SkillSummaryDetailResponseSchema, SkillSummaryListResponseSchema, SlugAvailabilityResponseSchema, StartOAuthConnectionInputSchema, StartOAuthConnectionResultSchema, UpdateCredentialRequestSchema, UpdateOrganizationMemberRequestSchema, UpdateOrganizationMemberResponseSchema, UpdateOrganizationRequestSchema, UpdateProjectRequestSchema, UploadProjectSourceManifestRequestSchema, UploadProjectSourceResponseSchema, UpsertGatewayAttachmentBodySchema, UserAvatarPatchSchema, UserAvatarSchema, UserPreferencesPatchSchema, UserPreferencesSchema, WorkflowSummaryDetailResponseSchema, WorkflowSummaryListResponseSchema, mergeOrganizationSidebarBranding, mergeUserPreferences, normalizeOrganizationSidebarBranding, normalizeUserPreferences } from \"@keystrokehq/shared\";\n//#region src/platform/active-organization.ts\nconst STORAGE_KEY = \"keystroke-active-org-id\";\nfunction readActiveOrganizationId() {\n\tif (typeof localStorage === \"undefined\") return null;\n\treturn localStorage.getItem(STORAGE_KEY);\n}\nfunction writeActiveOrganizationId(organizationId) {\n\tif (typeof localStorage === \"undefined\") return;\n\tif (organizationId) {\n\t\tlocalStorage.setItem(STORAGE_KEY, organizationId);\n\t\treturn;\n\t}\n\tlocalStorage.removeItem(STORAGE_KEY);\n}\n//#endregion\n//#region src/platform/auth.ts\nfunction normalizeBaseUrl(baseUrl) {\n\treturn baseUrl.replace(/\\/+$/, \"\");\n}\nfunction applyAuthHeaders(request, auth, getToken) {\n\tif (!auth || auth.type === \"none\") return;\n\tif (auth.type === \"bearer\") {\n\t\tconst tokenPromise = getToken?.() ?? auth.getToken();\n\t\treturn Promise.resolve(tokenPromise).then((token) => {\n\t\t\tif (token) request.headers.set(\"Authorization\", `Bearer ${token}`);\n\t\t});\n\t}\n}\nfunction applyActiveOrganizationHeader(request, organizationId) {\n\tif (organizationId) request.headers.set(ACTIVE_ORG_HEADER, organizationId);\n}\n/** Browser client — sends JWT bearer tokens minted from the Better Auth session cookie. */\nfunction browserAuthStrategy(getToken) {\n\treturn {\n\t\ttype: \"bearer\",\n\t\tgetToken\n\t};\n}\n//#endregion\n//#region src/platform/errors.ts\nvar PlatformError = class extends Error {\n\tstatus;\n\tbody;\n\tcode;\n\tconstructor(message, status, body, code) {\n\t\tsuper(message);\n\t\tthis.name = \"PlatformError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t\tthis.code = code;\n\t}\n};\nasync function toPlatformError(error) {\n\tif (!isHTTPError(error)) return new PlatformError(error instanceof Error ? error.message : \"Request failed\", 0, null);\n\tconst status = error.response.status;\n\tconst body = error.data ?? null;\n\tconst parsed = ErrorResponseSchema.safeParse(body);\n\treturn new PlatformError(parsed.success ? parsed.data.error : `Request failed with status ${status}`, status, body, parsed.success ? parsed.data.code : void 0);\n}\n//#endregion\n//#region src/platform/resources/artifacts.ts\nfunction createArtifactsResource(http) {\n\treturn {\n\t\tasync create(projectId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/projects/${encodeURIComponent(projectId)}/artifacts`).json();\n\t\t\t\treturn CreateProjectArtifactResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync complete(projectId, artifactId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/projects/${encodeURIComponent(projectId)}/artifacts/${encodeURIComponent(artifactId)}/complete`).json();\n\t\t\t\treturn CompleteProjectArtifactResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\t/** Ask which source blobs are missing and get presigned PUTs for them. */\n\t\tasync presignSource(projectId, artifactId, blobs) {\n\t\t\tconst body = PresignProjectSourceRequestSchema.parse({ blobs });\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/projects/${encodeURIComponent(projectId)}/artifacts/${encodeURIComponent(artifactId)}/source/presign`, { json: body }).json();\n\t\t\t\treturn PresignProjectSourceResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\t/** Finalize the deploy's source manifest (path -> hash tree + resource refs). */\n\t\tasync uploadManifest(projectId, artifactId, manifest) {\n\t\t\tconst body = UploadProjectSourceManifestRequestSchema.parse(manifest);\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/projects/${encodeURIComponent(projectId)}/artifacts/${encodeURIComponent(artifactId)}/source/manifest`, { json: body }).json();\n\t\t\t\treturn UploadProjectSourceResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/deployments.ts\nfunction createDeploymentsResource(http) {\n\treturn { async listForProject(projectId) {\n\t\ttry {\n\t\t\tconst data = await http.get(`/api/projects/${encodeURIComponent(projectId)}/deployments`).json();\n\t\t\treturn ListProjectDeploymentsResponseSchema.parse(data).deployments;\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/gateway-attachments.ts\nfunction createGatewayAttachmentsResource(http) {\n\tconst projectPrefix = (projectId) => `/api/projects/${encodeURIComponent(projectId)}/gateways/slack/attachments`;\n\treturn { async upsertSlackAttachment(projectId, channelId, body) {\n\t\tconst payload = UpsertGatewayAttachmentBodySchema.parse(body);\n\t\ttry {\n\t\t\tconst data = await http.put(`${projectPrefix(projectId)}/${encodeURIComponent(channelId)}`, { json: payload }).json();\n\t\t\treturn GatewayAttachmentRecordSchema.parse(data);\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/project-files.ts\nfunction createProjectFilesResource(http) {\n\treturn {\n\t\t/** File tree (no contents) for a project's active deploy; empty before first deploy. */\n\t\tasync listForProject(projectId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/projects/${encodeURIComponent(projectId)}/files`).json();\n\t\t\t\treturn ListProjectFilesResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\t/** Lazily fetch a single file's contents by path for a specific deploy. */\n\t\tasync getContent(projectId, artifactId, path) {\n\t\t\ttry {\n\t\t\t\treturn await http.get(`/api/projects/${encodeURIComponent(projectId)}/artifacts/${encodeURIComponent(artifactId)}/files/content`, { searchParams: { path } }).text();\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/health.ts\nfunction createHealthResource(http) {\n\treturn { async check() {\n\t\ttry {\n\t\t\tconst data = await http.get(\"/health\").json();\n\t\t\treturn HealthResponseSchema.parse(data);\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/organizations.ts\nfunction createOrganizationsResource(http, options = {}) {\n\tasync function get(organizationId) {\n\t\ttry {\n\t\t\tconst data = await http.get(`/api/organizations/${organizationId}`).json();\n\t\t\tconst organization = ActiveOrganizationResponseSchema.parse(data).organization;\n\t\t\tif (!organization) throw new Error(\"Organization was not returned\");\n\t\t\treturn organization;\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t}\n\tasync function update(input) {\n\t\tconst body = UpdateOrganizationRequestSchema.parse(input);\n\t\tconst organizationId = options.getActiveOrganizationId?.();\n\t\tif (!organizationId) throw new Error(\"No active organization\");\n\t\ttry {\n\t\t\tconst data = await http.patch(`/api/organizations/${organizationId}`, { json: body }).json();\n\t\t\tconst organization = ActiveOrganizationResponseSchema.parse(data).organization;\n\t\t\tif (!organization) throw new Error(\"Active organization was not returned\");\n\t\t\treturn organization;\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t}\n\treturn {\n\t\tasync list() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/organizations\").json();\n\t\t\t\treturn ListOrganizationsResponseSchema.parse(data).organizations;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tget,\n\t\tasync getActive() {\n\t\t\tconst organizationId = options.getActiveOrganizationId?.();\n\t\t\tif (!organizationId) return null;\n\t\t\ttry {\n\t\t\t\treturn await get(organizationId);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof PlatformError && (error.status === 401 || error.status === 403)) return null;\n\t\t\t\tif (isHTTPError(error) && (error.response.status === 401 || error.response.status === 403)) return null;\n\t\t\t\tthrow error instanceof PlatformError ? error : await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync setActive(input) {\n\t\t\tconst organizationId = input.organizationId.trim();\n\t\t\tif (!organizationId) throw new Error(\"Organization id is required\");\n\t\t\tconst membership = await get(organizationId);\n\t\t\toptions.onActiveOrganizationChange?.(organizationId);\n\t\t\treturn membership;\n\t\t},\n\t\tasync clearActive() {\n\t\t\toptions.onActiveOrganizationChange?.(null);\n\t\t},\n\t\tupdate,\n\t\tasync create(input) {\n\t\t\tconst body = CreateOrganizationRequestSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(\"/api/organizations\", { json: body }).json();\n\t\t\t\treturn CreateOrganizationResponseSchema.parse(data).organization;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync checkSlug(slug, slugOptions = {}) {\n\t\t\tconst searchParams = new URLSearchParams({ slug });\n\t\t\tif (slugOptions.excludeOrganizationId) searchParams.set(\"excludeOrganizationId\", slugOptions.excludeOrganizationId);\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/organizations/slug-available?${searchParams}`).json();\n\t\t\t\treturn SlugAvailabilityResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/projects.ts\nfunction createProjectsResource(http) {\n\treturn {\n\t\tasync list() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/projects\").json();\n\t\t\t\treturn ListProjectsResponseSchema.parse(data).projects;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync create(input) {\n\t\t\tconst body = CreateProjectRequestSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(\"/api/projects\", { json: body }).json();\n\t\t\t\treturn CreateProjectResponseSchema.parse(data).project;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(projectId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/projects/${encodeURIComponent(projectId)}`).json();\n\t\t\t\treturn ProjectResponseSchema.parse(data).project;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync update(projectId, patch) {\n\t\t\tconst body = UpdateProjectRequestSchema.parse(patch);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(`/api/projects/${encodeURIComponent(projectId)}`, { json: body }).json();\n\t\t\t\treturn ProjectResponseSchema.parse(data).project;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync delete(projectId) {\n\t\t\ttry {\n\t\t\t\tawait http.delete(`/api/projects/${encodeURIComponent(projectId)}`);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync checkReachability(projectId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/projects/${encodeURIComponent(projectId)}/reachability`, { timeout: PROJECT_REACHABILITY_REQUEST_TIMEOUT_MS }).json();\n\t\t\t\treturn ProjectReachabilityResponseSchema.parse(data).reachable;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync checkSlug(slug, options = {}) {\n\t\t\tconst searchParams = new URLSearchParams({ slug });\n\t\t\tif (options.excludeProjectId) searchParams.set(\"excludeProjectId\", options.excludeProjectId);\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/projects/slug-available?${searchParams}`).json();\n\t\t\t\treturn ProjectSlugAvailabilityResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\nfunction createProjectMetricsResource(http) {\n\treturn { async list() {\n\t\ttry {\n\t\t\tconst data = await http.get(\"/api/projects/metrics\").json();\n\t\t\treturn ListProjectMetricsResponseSchema.parse(data).metrics;\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/agents.ts\nfunction listSearchParams$2(options) {\n\tconst projectId = options?.projectId?.trim();\n\treturn projectId ? { projectId } : void 0;\n}\nfunction createAgentsResource(http) {\n\treturn {\n\t\tasync list(options) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/agents\", { searchParams: listSearchParams$2(options) }).json();\n\t\t\t\treturn AgentSummaryListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(agentId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/agents/${encodeURIComponent(agentId)}`).json();\n\t\t\t\treturn AgentSummaryDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/workflows.ts\nfunction listSearchParams$1(options) {\n\tconst projectId = options?.projectId?.trim();\n\treturn projectId ? { projectId } : void 0;\n}\nfunction createWorkflowsResource(http) {\n\treturn {\n\t\tasync list(options) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/workflows\", { searchParams: listSearchParams$1(options) }).json();\n\t\t\t\treturn WorkflowSummaryListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(workflowId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/workflows/${encodeURIComponent(workflowId)}`).json();\n\t\t\t\treturn WorkflowSummaryDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/skills.ts\nfunction listSearchParams(options) {\n\tconst projectId = options?.projectId?.trim();\n\treturn projectId ? { projectId } : void 0;\n}\nfunction createSkillsResource(http) {\n\treturn {\n\t\tasync list(options) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/skills\", { searchParams: listSearchParams(options) }).json();\n\t\t\t\treturn SkillSummaryListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(skillId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/skills/${encodeURIComponent(skillId)}`).json();\n\t\t\t\treturn SkillSummaryDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/recents.ts\nfunction createRecentsResource(http) {\n\treturn { async list() {\n\t\ttry {\n\t\t\tconst data = await http.get(\"/api/recents\").json();\n\t\t\treturn RecentResourceListResponseSchema.parse(data);\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/mock-registry.ts\nconst registry = /* @__PURE__ */ new Map();\n/**\n* Wraps a mock implementation, registering it in the manifest. The returned\n* function is the unchanged implementation — `mock()` only adds bookkeeping.\n*/\nfunction mock(entry, impl) {\n\tregistry.set(`${entry.domain}.${entry.method}`, entry);\n\treturn impl;\n}\n/** The current inventory of mocked methods. Populated once a client is created. */\nfunction mockManifest() {\n\treturn [...registry.values()];\n}\n//#endregion\n//#region src/platform/resources/mock-project-settings.ts\nconst DEFAULT_PROJECT_SETTINGS = {\n\tdescription: \"\",\n\tdefaultRole: \"editor\",\n\tinvitePermission: \"admin\"\n};\nconst MOCK_STORAGE_KEY$1 = \"keystroke:mock-project-settings:v1\";\nfunction getBrowserLocalStorage$1() {\n\tif (typeof globalThis !== \"object\") return null;\n\treturn globalThis.localStorage ?? null;\n}\nfunction normalizeDefaultRole(value) {\n\treturn value === \"admin\" ? \"admin\" : \"editor\";\n}\nfunction normalizeInvitePermission(value) {\n\treturn value === \"all\" ? \"all\" : \"admin\";\n}\nfunction normalizeProjectSettings(value) {\n\tif (!value || typeof value !== \"object\") return DEFAULT_PROJECT_SETTINGS;\n\tconst settings = value;\n\treturn {\n\t\tdescription: typeof settings.description === \"string\" ? settings.description : \"\",\n\t\tdefaultRole: normalizeDefaultRole(settings.defaultRole),\n\t\tinvitePermission: normalizeInvitePermission(settings.invitePermission)\n\t};\n}\nfunction mergeProjectSettings(current, patch) {\n\treturn normalizeProjectSettings({\n\t\t...current,\n\t\t...patch\n\t});\n}\nfunction readSettingsStore() {\n\tconst localStorage = getBrowserLocalStorage$1();\n\tif (!localStorage) return {};\n\ttry {\n\t\tconst raw = localStorage.getItem(MOCK_STORAGE_KEY$1);\n\t\tif (!raw) return {};\n\t\tconst parsed = JSON.parse(raw);\n\t\tif (!parsed || typeof parsed !== \"object\") return {};\n\t\treturn Object.fromEntries(Object.entries(parsed).map(([projectId, value]) => [projectId, normalizeProjectSettings(value)]));\n\t} catch {\n\t\treturn {};\n\t}\n}\nfunction writeSettingsStore(store) {\n\tconst localStorage = getBrowserLocalStorage$1();\n\tif (!localStorage) return;\n\ttry {\n\t\tlocalStorage.setItem(MOCK_STORAGE_KEY$1, JSON.stringify(store));\n\t} catch {}\n}\nfunction requireProjectId(projectId) {\n\tconst trimmed = projectId.trim();\n\tif (!trimmed) throw new Error(\"Project settings require a project id\");\n\treturn trimmed;\n}\nfunction createProjectSettingsResource() {\n\treturn {\n\t\tget: mock({\n\t\t\tdomain: \"projectSettings\",\n\t\t\tmethod: \"get\",\n\t\t\tplannedEndpoint: \"GET /api/projects/:id/settings\"\n\t\t}, async (projectId) => {\n\t\t\tconst id = requireProjectId(projectId);\n\t\t\treturn readSettingsStore()[id] ?? DEFAULT_PROJECT_SETTINGS;\n\t\t}),\n\t\tupdate: mock({\n\t\t\tdomain: \"projectSettings\",\n\t\t\tmethod: \"update\",\n\t\t\tplannedEndpoint: \"PATCH /api/projects/:id/settings\"\n\t\t}, async (projectId, patch) => {\n\t\t\tconst id = requireProjectId(projectId);\n\t\t\tconst store = readSettingsStore();\n\t\t\tconst next = mergeProjectSettings(store[id] ?? DEFAULT_PROJECT_SETTINGS, patch);\n\t\t\twriteSettingsStore({\n\t\t\t\t...store,\n\t\t\t\t[id]: next\n\t\t\t});\n\t\t\treturn next;\n\t\t})\n\t};\n}\n//#endregion\n//#region src/platform/resources/invitations.ts\nfunction createInvitationsResource(http) {\n\treturn {\n\t\tasync list() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/invitations\").json();\n\t\t\t\treturn ListOrganizationInvitationsResponseSchema.parse(data).invitations;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync accept(invitationId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/invitations/${encodeURIComponent(invitationId)}/accept`).json();\n\t\t\t\treturn AcceptOrganizationInvitationResponseSchema.parse(data).organization;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync decline(invitationId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(`/api/invitations/${encodeURIComponent(invitationId)}/decline`).json();\n\t\t\t\tDeclineOrganizationInvitationResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/credentials.ts\nfunction buildOAuthAuthorizeSearchParams(input) {\n\tconst params = {};\n\tconst scopes = input.scopes ?? [];\n\tif (scopes.length > 0) params.scopes = scopes.join(\",\");\n\tconst projectIds = input.projectIds ?? [];\n\tif (projectIds.length > 0) params.projectIds = projectIds.join(\",\");\n\tif (input.createOrganizationCredential) params.org = \"true\";\n\tif (input.createUserProvidedCredential) params.user = \"true\";\n\treturn params;\n}\nfunction createCredentialsResource(http) {\n\treturn {\n\t\tasync list() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/credentials\").json();\n\t\t\t\treturn ListCredentialsResponseSchema.parse(data).credentials;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(credentialId) {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/credentials/${encodeURIComponent(credentialId)}`).json();\n\t\t\t\treturn GetCredentialResponseSchema.parse(data).credential;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync create(input) {\n\t\t\tconst body = CreateCredentialsRequestSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(\"/api/credentials\", { json: body }).json();\n\t\t\t\treturn CreateCredentialsResponseSchema.parse(data).credentials;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync update(credentialId, patch) {\n\t\t\tconst body = UpdateCredentialRequestSchema.parse(patch);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(`/api/credentials/${encodeURIComponent(credentialId)}`, { json: body }).json();\n\t\t\t\treturn GetCredentialResponseSchema.parse(data).credential;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync delete(credentialId) {\n\t\t\ttry {\n\t\t\t\tawait http.delete(`/api/credentials/${encodeURIComponent(credentialId)}`);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync startOAuthConnection(input) {\n\t\t\tconst body = StartOAuthConnectionInputSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(`/api/oauth/${encodeURIComponent(body.appId)}/authorize-url`, { searchParams: buildOAuthAuthorizeSearchParams(body) }).json();\n\t\t\t\tconst { url } = ConnectAuthorizeUrlResponseSchema.parse(data);\n\t\t\t\treturn StartOAuthConnectionResultSchema.parse({\n\t\t\t\t\tstatus: \"redirecting\",\n\t\t\t\t\tauthorizeUrl: url\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/apps.ts\nfunction createAppsResource(http) {\n\treturn { async listCatalog() {\n\t\ttry {\n\t\t\tconst data = await http.get(\"/api/apps\").json();\n\t\t\treturn ListAppsResponseSchema.parse(data).apps;\n\t\t} catch (error) {\n\t\t\tthrow await toPlatformError(error);\n\t\t}\n\t} };\n}\n//#endregion\n//#region src/platform/resources/members.ts\nfunction createMembersResource$1(http) {\n\treturn {\n\t\tasync listOrganizationMembers() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/members\").json();\n\t\t\t\treturn ListOrganizationMembersResponseSchema.parse(data).members;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync inviteOrganizationMembers(input) {\n\t\t\tconst body = InviteOrganizationMembersRequestSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst data = await http.post(\"/api/members/invitations\", { json: body }).json();\n\t\t\t\treturn InviteOrganizationMembersResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync updateOrganizationMember(userId, input) {\n\t\t\tconst body = UpdateOrganizationMemberRequestSchema.parse(input);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(`/api/members/${encodeURIComponent(userId)}`, { json: body }).json();\n\t\t\t\treturn UpdateOrganizationMemberResponseSchema.parse(data).member;\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync removeOrganizationMember(userId) {\n\t\t\ttry {\n\t\t\t\tawait http.delete(`/api/members/${encodeURIComponent(userId)}`);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/mock-seed.ts\n/** Review personas for mocked project members and API key authors (not org membership). */\nconst mockPersonaSeed = [\n\t{\n\t\tid: \"user_blake_rouse\",\n\t\tname: \"Blake Rouse\",\n\t\temail: \"blake@keystroke.ai\",\n\t\tavatarUrl: \"/icons/avatars/blake-rouse.png\",\n\t\tjoinedAt: \"2026-01-12T18:00:00Z\",\n\t\tlastActiveAt: \"2026-05-31T18:00:00Z\"\n\t},\n\t{\n\t\tid: \"org-member-nate\",\n\t\tname: \"Nate Wells\",\n\t\temail: \"nate@keystroke.ai\",\n\t\tavatarUrl: \"/icons/avatars/nate-kelley.png\",\n\t\tjoinedAt: \"2026-02-03T18:00:00Z\",\n\t\tlastActiveAt: \"2026-05-31T16:00:00Z\"\n\t},\n\t{\n\t\tid: \"org-member-dallin\",\n\t\tname: \"Dallin Bentley\",\n\t\temail: \"dallin@keystroke.ai\",\n\t\tavatarUrl: \"/icons/avatars/dallin-bentley.png\",\n\t\tjoinedAt: \"2026-03-18T18:00:00Z\",\n\t\tlastActiveAt: \"2026-05-30T16:00:00Z\"\n\t},\n\t{\n\t\tid: \"org-member-wells\",\n\t\tname: \"Wells Riley\",\n\t\temail: \"wells@keystroke.ai\",\n\t\tavatarUrl: \"/icons/avatars/wells-bunker.png\",\n\t\tjoinedAt: \"2026-04-09T18:00:00Z\",\n\t\tlastActiveAt: \"2026-05-20T16:00:00Z\"\n\t}\n];\nconst projectMemberSeed = mockPersonaSeed.map((member, index) => ({\n\tid: `project-member-${member.id}`,\n\tprojectId: \"project_personal_repo\",\n\tname: member.name,\n\temail: member.email,\n\trole: index <= 1 ? \"admin\" : \"editor\",\n\tstatus: \"active\",\n\tavatarUrl: member.avatarUrl,\n\tjoinedAt: member.joinedAt,\n\tlastActiveAt: member.lastActiveAt,\n\tisCurrentUser: member.id === \"user_blake_rouse\"\n}));\nconst apiKeySeed = [\n\t{\n\t\tid: \"api-key-local-dev\",\n\t\tname: \"LOCAL_DEV_BLAKE\",\n\t\tkeyPreview: \"******J7Pt\",\n\t\tcreatedAt: \"2026-04-20T15:44:00Z\",\n\t\tcreatedBy: mockPersonaSeed[0],\n\t\tisCreatedByCurrentUser: true\n\t},\n\t{\n\t\tid: \"api-key-ci-deploy\",\n\t\tname: \"CI deploy\",\n\t\tkeyPreview: \"******TJb7\",\n\t\tcreatedAt: \"2026-03-08T15:44:00Z\",\n\t\tcreatedBy: mockPersonaSeed[1],\n\t\tisCreatedByCurrentUser: false\n\t},\n\t{\n\t\tid: \"api-key-partner-webhooks\",\n\t\tname: \"partner_webhooks\",\n\t\tkeyPreview: \"******9Qzc\",\n\t\tcreatedAt: \"2026-02-18T15:44:00Z\",\n\t\tcreatedBy: mockPersonaSeed[2],\n\t\tisCreatedByCurrentUser: false\n\t}\n];\n//#endregion\n//#region src/platform/resources/mock-resources.ts\nfunction createMockApiKeySecret() {\n\tconst secret = `sk_${`${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`}`;\n\treturn {\n\t\tsecret,\n\t\tkeyPreview: `******${secret.slice(-4)}`\n\t};\n}\nconst projectMembersStore = /* @__PURE__ */ new Map();\nfunction getProjectMembers(projectId) {\n\tlet members = projectMembersStore.get(projectId);\n\tif (!members) {\n\t\tmembers = projectMemberSeed.map((member) => ({\n\t\t\t...member,\n\t\t\tprojectId\n\t\t}));\n\t\tprojectMembersStore.set(projectId, members);\n\t}\n\treturn members;\n}\n/** Derive a best-effort display name from an email local part. */\nfunction displayNameFromEmail(email) {\n\treturn (email.split(\"@\")[0] ?? email).split(/[._-]+/).filter((part) => part.length > 0).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(\" \");\n}\nfunction createMembersResource(http) {\n\treturn {\n\t\t...createMembersResource$1(http),\n\t\tlistForProject: mock({\n\t\t\tdomain: \"members\",\n\t\t\tmethod: \"listForProject\",\n\t\t\tplannedEndpoint: \"GET /api/projects/:id/members\"\n\t\t}, async (projectId) => [...getProjectMembers(projectId)]),\n\t\tinviteToProject: mock({\n\t\t\tdomain: \"members\",\n\t\t\tmethod: \"inviteToProject\",\n\t\t\tplannedEndpoint: \"POST /api/projects/:id/members/invitations\"\n\t\t}, async (input) => {\n\t\t\tconst members = getProjectMembers(input.projectId);\n\t\t\tconst pendingOrgEmails = new Set((input.pendingOrgEmails ?? []).map((email) => email.toLowerCase()));\n\t\t\tconst seen = new Set(members.map((member) => member.email.toLowerCase()));\n\t\t\tconst invited = [];\n\t\t\tinput.emails.forEach((email, index) => {\n\t\t\t\tconst key = email.toLowerCase();\n\t\t\t\tif (seen.has(key)) return;\n\t\t\t\tseen.add(key);\n\t\t\t\tinvited.push({\n\t\t\t\t\tid: `project-member-invite-${Date.now().toString(36)}-${index}`,\n\t\t\t\t\tprojectId: input.projectId,\n\t\t\t\t\tname: displayNameFromEmail(email),\n\t\t\t\t\temail,\n\t\t\t\t\trole: input.role,\n\t\t\t\t\tstatus: pendingOrgEmails.has(key) ? \"invited\" : \"active\",\n\t\t\t\t\tjoinedAt: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\t\t\tlastActiveAt: null\n\t\t\t\t});\n\t\t\t});\n\t\t\tif (invited.length > 0) projectMembersStore.set(input.projectId, [...members, ...invited]);\n\t\t\treturn { invited };\n\t\t})\n\t};\n}\nlet apiKeyRecords = [...apiKeySeed];\nfunction createApiKeysResource() {\n\treturn {\n\t\tlist: mock({\n\t\t\tdomain: \"apiKeys\",\n\t\t\tmethod: \"list\",\n\t\t\tplannedEndpoint: \"GET /api/api-keys\"\n\t\t}, async () => apiKeyRecords),\n\t\tcreate: mock({\n\t\t\tdomain: \"apiKeys\",\n\t\t\tmethod: \"create\",\n\t\t\tplannedEndpoint: \"POST /api/api-keys\"\n\t\t}, async (input) => {\n\t\t\tconst { secret, keyPreview } = createMockApiKeySecret();\n\t\t\tconst created = {\n\t\t\t\tid: `api-key-${Date.now().toString(36)}`,\n\t\t\t\tname: input.name,\n\t\t\t\tkeyPreview,\n\t\t\t\tcreatedAt: (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\t\tcreatedBy: mockPersonaSeed[0],\n\t\t\t\tisCreatedByCurrentUser: true\n\t\t\t};\n\t\t\tapiKeyRecords = [created, ...apiKeyRecords];\n\t\t\treturn {\n\t\t\t\t...created,\n\t\t\t\tsecret\n\t\t\t};\n\t\t}),\n\t\trevoke: mock({\n\t\t\tdomain: \"apiKeys\",\n\t\t\tmethod: \"revoke\",\n\t\t\tplannedEndpoint: \"DELETE /api/api-keys/:id\"\n\t\t}, async (apiKeyId) => {\n\t\t\tapiKeyRecords = apiKeyRecords.filter((apiKey) => apiKey.id !== apiKeyId);\n\t\t})\n\t};\n}\n//#endregion\n//#region src/platform/resources/history.ts\nfunction createHistoryResource(http) {\n\treturn {\n\t\t/** Runs across projects the current user can access in the active org. */\n\t\tasync list(filters) {\n\t\t\ttry {\n\t\t\t\tconst parsedFilters = filters ? HistoryRunListQuerySchema.parse(filters) : void 0;\n\t\t\t\tconst searchParams = new URLSearchParams();\n\t\t\t\tif (parsedFilters?.project) searchParams.set(\"project\", parsedFilters.project);\n\t\t\t\tif (parsedFilters?.status) searchParams.set(\"status\", parsedFilters.status);\n\t\t\t\tif (parsedFilters?.kind) searchParams.set(\"kind\", parsedFilters.kind);\n\t\t\t\tconst query = searchParams.toString();\n\t\t\t\tconst data = await http.get(query ? `api/history?${query}` : \"api/history\").json();\n\t\t\t\treturn HistoryRunListResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync get(runId) {\n\t\t\ttry {\n\t\t\t\tconst response = await http.get(`api/history/${encodeURIComponent(runId)}`);\n\t\t\t\tif (response.status === 404) return null;\n\t\t\t\tconst data = await response.json();\n\t\t\t\treturn HistoryRunDetailResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync cancel(runId) {\n\t\t\ttry {\n\t\t\t\tconst response = await http.post(`api/history/${encodeURIComponent(runId)}/cancel`);\n\t\t\t\tif (response.status === 404) return null;\n\t\t\t\tconst data = await response.json();\n\t\t\t\treturn HistoryRunCancelResponseSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/presign-upload.ts\nasync function presignPutAndFinalize(input) {\n\tconst contentType = input.file.type?.trim() || \"application/octet-stream\";\n\tconst uploadFailedMessage = input.uploadFailedMessage ?? \"Upload failed\";\n\ttry {\n\t\tconst { uploadUrl, storageKey } = await input.presign(contentType);\n\t\tif (!(await fetch(uploadUrl, {\n\t\t\tmethod: \"PUT\",\n\t\t\tbody: input.file,\n\t\t\theaders: { \"Content-Type\": contentType }\n\t\t})).ok) throw new Error(uploadFailedMessage);\n\t\treturn await input.finalize(storageKey);\n\t} catch (error) {\n\t\tif (error instanceof Error && error.message === uploadFailedMessage) throw error;\n\t\tthrow await input.toPlatformError(error);\n\t}\n}\n//#endregion\n//#region src/platform/resources/organization-sidebar-branding.ts\nfunction createOrganizationSidebarBrandingResource(http, options = {}) {\n\tfunction brandingPath() {\n\t\tconst organizationId = options.getActiveOrganizationId?.();\n\t\tif (!organizationId) throw new Error(\"No active organization\");\n\t\treturn `/api/organizations/${organizationId}/branding`;\n\t}\n\tasync function presignLogoUpload(variant, contentType) {\n\t\tconst body = PresignOrgLogoRequestSchema.parse({\n\t\t\tvariant,\n\t\t\tcontentType\n\t\t});\n\t\tconst data = await http.post(`${brandingPath()}/logo/presign`, { json: body }).json();\n\t\treturn PresignOrgLogoResponseSchema.parse(data);\n\t}\n\treturn {\n\t\tasync get() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(brandingPath()).json();\n\t\t\t\treturn OrganizationSidebarBrandingSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync uploadLogo(file, variant) {\n\t\t\tconst storageKeyField = variant === \"light\" ? \"logoLightStorageKey\" : \"logoDarkStorageKey\";\n\t\t\treturn presignPutAndFinalize({\n\t\t\t\tfile,\n\t\t\t\tpresign: (contentType) => presignLogoUpload(variant, contentType),\n\t\t\t\tfinalize: (storageKey) => this.update({\n\t\t\t\t\t[storageKeyField]: storageKey,\n\t\t\t\t\tcustomLogoEnabled: true,\n\t\t\t\t\tcustomLogoExplicitlyDisabled: false\n\t\t\t\t}),\n\t\t\t\tuploadFailedMessage: \"Logo upload failed\",\n\t\t\t\ttoPlatformError\n\t\t\t});\n\t\t},\n\t\tasync removeLogo(variant) {\n\t\t\tconst storageKeyField = variant === \"light\" ? \"logoLightStorageKey\" : \"logoDarkStorageKey\";\n\t\t\treturn this.update({ [storageKeyField]: null });\n\t\t},\n\t\tasync update(patch) {\n\t\t\tconst body = OrganizationSidebarBrandingPatchSchema.parse(patch);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(brandingPath(), { json: body }).json();\n\t\t\t\treturn OrganizationSidebarBrandingSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/user-preferences.ts\nconst USER_PREFERENCES_PATH = \"/api/users/me/preferences\";\nfunction createUserPreferencesResource(http) {\n\treturn {\n\t\tasync get() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(USER_PREFERENCES_PATH).json();\n\t\t\t\treturn UserPreferencesSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync update(patch) {\n\t\t\tconst body = UserPreferencesPatchSchema.parse(patch);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(USER_PREFERENCES_PATH, { json: body }).json();\n\t\t\t\treturn UserPreferencesSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/user-avatar.ts\nconst DEFAULT_USER_AVATAR = { url: null };\nfunction createUserAvatarResource(http) {\n\tasync function presignUpload(contentType) {\n\t\tconst body = PresignUserAvatarRequestSchema.parse({ contentType });\n\t\tconst data = await http.post(\"/api/users/me/avatar/presign\", { json: body }).json();\n\t\treturn PresignUserAvatarResponseSchema.parse(data);\n\t}\n\treturn {\n\t\tasync get() {\n\t\t\ttry {\n\t\t\t\tconst data = await http.get(\"/api/users/me/avatar\").json();\n\t\t\t\treturn UserAvatarSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t},\n\t\tasync upload(file) {\n\t\t\treturn presignPutAndFinalize({\n\t\t\t\tfile,\n\t\t\t\tpresign: presignUpload,\n\t\t\t\tfinalize: (storageKey) => this.update({ storageKey }),\n\t\t\t\tuploadFailedMessage: \"Avatar upload failed\",\n\t\t\t\ttoPlatformError\n\t\t\t});\n\t\t},\n\t\tasync remove() {\n\t\t\treturn this.update({ storageKey: null });\n\t\t},\n\t\tasync update(patch) {\n\t\t\tconst body = UserAvatarPatchSchema.parse(patch);\n\t\t\ttry {\n\t\t\t\tconst data = await http.patch(\"/api/users/me/avatar\", { json: body }).json();\n\t\t\t\treturn UserAvatarSchema.parse(data);\n\t\t\t} catch (error) {\n\t\t\t\tthrow await toPlatformError(error);\n\t\t\t}\n\t\t}\n\t};\n}\n//#endregion\n//#region src/platform/resources/mock-channels.ts\nconst CHANNEL_PLATFORMS = [\n\t{\n\t\tkey: \"slack\",\n\t\tname: \"Slack\",\n\t\tappLogoId: \"slack\",\n\t\tfallbackDomain: \"slack.com\",\n\t\tdescription: \"Connect a Slack workspace so this agent can respond in channels, threads, and DMs.\",\n\t\ttagline: \"Respond in channels, threads, and DMs.\",\n\t\tauthKind: \"oauth\",\n\t\tcredentialFields: [],\n\t\tcapabilities: {\n\t\t\tmentions: true,\n\t\t\treactions: \"full\",\n\t\t\tcards: \"full\",\n\t\t\tmodals: true,\n\t\t\tstreaming: \"native\",\n\t\t\tdms: true\n\t\t},\n\t\tsupportedModes: [\n\t\t\t\"mention\",\n\t\t\t\"all\",\n\t\t\t\"dm\"\n\t\t],\n\t\tresourceNoun: {\n\t\t\tsingular: \"channel\",\n\t\t\tplural: \"channels\"\n\t\t},\n\t\twebhookPathHint: \"/gateways/slack\",\n\t\tsupportsChannelDirectory: true,\n\t\tdocsUrl: \"https://chat-sdk.dev/adapters/official/slack\"\n\t},\n\t{\n\t\tkey: \"discord\",\n\t\tname: \"Discord\",\n\t\tappLogoId: \"discord\",\n\t\tfallbackDomain: \"discord.com\",\n\t\tdescription: \"Connect a Discord application so this agent can respond in servers and channels.\",\n\t\ttagline: \"Respond in servers and channels.\",\n\t\tauthKind: \"credentials\",\n\t\tcredentialFields: [\n\t\t\t{\n\t\t\t\tkey: \"botToken\",\n\t\t\t\tlabel: \"Bot token\",\n\t\t\t\tplaceholder: \"Bot token from the Discord developer portal\",\n\t\t\t\thelpText: \"Bot → Reset Token. Shown only once.\",\n\t\t\t\ttype: \"password\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\t{\n\t\t\t\tkey: \"applicationId\",\n\t\t\t\tlabel: \"Application ID\",\n\t\t\t\tplaceholder: \"Application ID\",\n\t\t\t\ttype: \"text\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\t{\n\t\t\t\tkey: \"publicKey\",\n\t\t\t\tlabel: \"Public key\",\n\t\t\t\tplaceholder: \"Public key\",\n\t\t\t\thelpText: \"General Information → Public Key, used to verify interactions.\",\n\t\t\t\ttype: \"text\",\n\t\t\t\trequired: true\n\t\t\t}\n\t\t],\n\t\tcapabilities: {\n\t\t\tmentions: true,\n\t\t\treactions: \"full\",\n\t\t\tcards: \"full\",\n\t\t\tmodals: false,\n\t\t\tstreaming: \"post-edit\",\n\t\t\tdms: true\n\t\t},\n\t\tsupportedModes: [\n\t\t\t\"mention\",\n\t\t\t\"all\",\n\t\t\t\"dm\"\n\t\t],\n\t\tresourceNoun: {\n\t\t\tsingular: \"channel\",\n\t\t\tplural: \"channels\"\n\t\t},\n\t\twebhookPathHint: \"/gateways/discord\",\n\t\tsupportsChannelDirectory: true,\n\t\tdocsUrl: \"https://chat-sdk.dev/adapters/official/discord\"\n\t},\n\t{\n\t\tkey: \"telegram\",\n\t\tname: \"Telegram\",\n\t\tappLogoId: \"telegram\",\n\t\tfallbackDomain: \"telegram.org\",\n\t\tdescription: \"Connect a Telegram bot so this agent can respond in chats and groups.\",\n\t\ttagline: \"Respond in chats and groups.\",\n\t\tauthKind: \"bot-token\",\n\t\tcredentialFields: [{\n\t\t\tkey: \"botToken\",\n\t\t\tlabel: \"Bot token\",\n\t\t\tplaceholder: \"123456:ABC-DEF…\",\n\t\t\thelpText: \"Create a bot with @BotFather and paste its token.\",\n\t\t\ttype: \"password\",\n\t\t\trequired: true\n\t\t}, {\n\t\t\tkey: \"botUsername\",\n\t\t\tlabel: \"Bot username\",\n\t\t\tplaceholder: \"my_agent_bot\",\n\t\t\ttype: \"text\",\n\t\t\trequired: false,\n\t\t\tprefix: \"@\"\n\t\t}],\n\t\tcapabilities: {\n\t\t\tmentions: true,\n\t\t\treactions: \"full\",\n\t\t\tcards: \"partial\",\n\t\t\tmodals: false,\n\t\t\tstreaming: \"drafts\",\n\t\t\tdms: true\n\t\t},\n\t\tsupportedModes: [\n\t\t\t\"mention\",\n\t\t\t\"all\",\n\t\t\t\"dm\"\n\t\t],\n\t\tresourceNoun: {\n\t\t\tsingular: \"chat\",\n\t\t\tplural: \"chats\"\n\t\t},\n\t\twebhookPathHint: \"/gateways/telegram\",\n\t\tsupportsChannelDirectory: false,\n\t\tdocsUrl: \"https://chat-sdk.dev/adapters/official/telegram\"\n\t},\n\t{\n\t\tkey: \"microsoft-teams\",\n\t\tname: \"Microsoft Teams\",\n\t\tappLogoId: \"microsoft-teams\",\n\t\tfallbackDomain: \"teams.microsoft.com\",\n\t\tdescription: \"Connect a Microsoft Teams app so this agent can respond in channels and chats.\",\n\t\ttagline: \"Respond in channels and chats.\",\n\t\tauthKind: \"credentials\",\n\t\tcredentialFields: [\n\t\t\t{\n\t\t\t\tkey: \"appId\",\n\t\t\t\tlabel: \"App ID\",\n\t\t\t\tplaceholder: \"Azure AD application (client) ID\",\n\t\t\t\ttype: \"text\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\t{\n\t\t\t\tkey: \"appPassword\",\n\t\t\t\tlabel: \"App password\",\n\t\t\t\tplaceholder: \"Client secret\",\n\t\t\t\ttype: \"password\",\n\t\t\t\trequired: true\n\t\t\t},\n\t\t\t{\n\t\t\t\tkey: \"tenantId\",\n\t\t\t\tlabel: \"Tenant ID\",\n\t\t\t\tplaceholder: \"Azure AD tenant ID\",\n\t\t\t\ttype: \"text\",\n\t\t\t\trequired: true\n\t\t\t}\n\t\t],\n\t\tcapabilities: {\n\t\t\tmentions: true,\n\t\t\treactions: \"read-only\",\n\t\t\tcards: \"full\",\n\t\t\tmodals: true,\n\t\t\tstreaming: \"buffered\",\n\t\t\tdms: true\n\t\t},\n\t\tsupportedModes: [\n\t\t\t\"mention\",\n\t\t\t\"all\",\n\t\t\t\"dm\"\n\t\t],\n\t\tresourceNoun: {\n\t\t\tsingular: \"channel\",\n\t\t\tplural: \"channels\"\n\t\t},\n\t\twebhookPathHint: \"/gateways/teams\",\n\t\tsupportsChannelDirectory: true,\n\t\tdocsUrl: \"https://chat-sdk.dev/adapters/official/teams\"\n\t},\n\t{\n\t\tkey: \"google-chat\",\n\t\tname: \"Google Chat\",\n\t\tappLogoId: \"google-chat\",\n\t\tfallbackDomain: \"chat.google.com\",\n\t\tdescription: \"Connect a Google Chat app so this agent can respond in spaces and direct messages.\",\n\t\ttagline: \"Respond in spaces and DMs.\",\n\t\tauthKind: \"credentials\",\n\t\tcredentialFields: [{\n\t\t\tkey: \"serviceAccountJson\",\n\t\t\tlabel: \"Service account JSON\",\n\t\t\tplaceholder: \"Paste the service account key JSON\",\n\t\t\thelpText: \"IAM → Service Accounts → Keys → Add key → JSON.\",\n\t\t\ttype: \"textarea\",\n\t\t\trequired: true\n\t\t}, {\n\t\t\tkey: \"projectNumber\",\n\t\t\tlabel: \"GCP project number\",\n\t\t\tplaceholder: \"Project number used to verify webhooks\",\n\t\t\ttype: \"text\",\n\t\t\trequired: true\n\t\t}],\n\t\tcapabilities: {\n\t\t\tmentions: true,\n\t\t\treactions: \"full\",\n\t\t\tcards: \"full\",\n\t\t\tmodals: false,\n\t\t\tstreaming: \"post-edit\",\n\t\t\tdms: true\n\t\t},\n\t\tsupportedModes: [\n\t\t\t\"mention\",\n\t\t\t\"all\",\n\t\t\t\"dm\"\n\t\t],\n\t\tresourceNoun: {\n\t\t\tsingular: \"space\",\n\t\t\tplural: \"spaces\"\n\t\t},\n\t\twebhookPathHint: \"/gateways/gchat\",\n\t\tsupportsChannelDirectory: true,\n\t\tdocsUrl: \"https://chat-sdk.dev/adapters/official/google-chat\"\n\t}\n];\nfunction getChannelPlatform(key) {\n\treturn CHANNEL_PLATFORMS.find((platform) => platform.key === key);\n}\nconst CHANNEL_DIRECTORY = {\n\tslack: [\n\t\t{\n\t\t\tid: \"C0SUPPORT\",\n\t\t\tname: \"support\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 48\n\t\t},\n\t\t{\n\t\t\tid: \"C0GENERAL\",\n\t\t\tname: \"general\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 132\n\t\t},\n\t\t{\n\t\t\tid: \"C0ENG\",\n\t\t\tname: \"engineering\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 27\n\t\t},\n\t\t{\n\t\t\tid: \"C0INCIDENTS\",\n\t\t\tname: \"incidents\",\n\t\t\tkind: \"private\",\n\t\t\tmemberCount: 12\n\t\t},\n\t\t{\n\t\t\tid: \"C0RANDOM\",\n\t\t\tname: \"random\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 118\n\t\t},\n\t\t{\n\t\t\tid: \"C0ARCHIVE\",\n\t\t\tname: \"launch-2025\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 9,\n\t\t\tisArchived: true\n\t\t}\n\t],\n\tdiscord: [\n\t\t{\n\t\t\tid: \"d-general\",\n\t\t\tname: \"general\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 540\n\t\t},\n\t\t{\n\t\t\tid: \"d-help\",\n\t\t\tname: \"help\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 312\n\t\t},\n\t\t{\n\t\t\tid: \"d-dev\",\n\t\t\tname: \"dev\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 76\n\t\t},\n\t\t{\n\t\t\tid: \"d-staff\",\n\t\t\tname: \"staff\",\n\t\t\tkind: \"private\",\n\t\t\tmemberCount: 8\n\t\t}\n\t],\n\ttelegram: [],\n\t\"microsoft-teams\": [\n\t\t{\n\t\t\tid: \"t-general\",\n\t\t\tname: \"General\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 64\n\t\t},\n\t\t{\n\t\t\tid: \"t-support\",\n\t\t\tname: \"Customer Support\",\n\t\t\tkind: \"public\",\n\t\t\tmemberCount: 22\n\t\t},\n\t\t{\n\t\t\tid: \"t-leads\",\n\t\t\tname: \"Leadership\",\n\t\t\tkind: \"private\",\n\t\t\tmemberCount: 6\n\t\t}\n\t],\n\t\"google-chat\": [\n\t\t{\n\t\t\tid: \"spaces/AAA-support\",\n\t\t\tname: \"Support\",\n\t\t\tkind: \"space\",\n\t\t\tmemberCount: 31\n\t\t},\n\t\t{\n\t\t\tid: \"spaces/AAA-eng\",\n\t\t\tname: \"Engineering\",\n\t\t\tkind: \"space\",\n\t\t\tmemberCount: 44\n\t\t},\n\t\t{\n\t\t\tid: \"spaces/AAA-ops\",\n\t\t\tname: \"Ops On-call\",\n\t\t\tkind: \"space\",\n\t\t\tmemberCount: 10\n\t\t}\n\t]\n};\nconst MOCK_STORAGE_KEY = \"keystroke:mock-channels:v1\";\nfunction getBrowserLocalStorage() {\n\tif (typeof globalThis !== \"object\") return null;\n\treturn globalThis.localStorage ?? null;\n}\n/** A connected Slack workspace with two bindings, so the panel is reviewable. */\nfunction seedStore() {\n\treturn { \"agent-support\": [{\n\t\tid: \"chan-conn-slack-support\",\n\t\tplatform: \"slack\",\n\t\tagentId: \"agent-support\",\n\t\taccountLabel: \"Keystroke HQ\",\n\t\taccountId: \"T0KEYSTROKE\",\n\t\tconnectedAt: \"2026-05-28T15:30:00Z\",\n\t\tbindings: [{\n\t\t\tid: \"chan-bind-support\",\n\t\t\tchannelId: \"C0SUPPORT\",\n\t\t\tchannelName: \"support\",\n\t\t\tchannelKind: \"public\",\n\t\t\tmode: \"all\",\n\t\t\tsubscribeOnMention: true,\n\t\t\tcreatedAt: \"2026-05-28T15:31:00Z\",\n\t\t\tupdatedAt: \"2026-05-28T15:31:00Z\"\n\t\t}, {\n\t\t\tid: \"chan-bind-incidents\",\n\t\t\tchannelId: \"C0INCIDENTS\",\n\t\t\tchannelName: \"incidents\",\n\t\t\tchannelKind: \"private\",\n\t\t\tmode: \"mention\",\n\t\t\tsubscribeOnMention: true,\n\t\t\tcreatedAt: \"2026-05-29T09:05:00Z\",\n\t\t\tupdatedAt: \"2026-05-29T09:05:00Z\"\n\t\t}]\n\t}] };\n}\nfunction readStore() {\n\tconst localStorage = getBrowserLocalStorage();\n\tif (!localStorage) return seedStore();\n\ttry {\n\t\tconst raw = localStorage.getItem(MOCK_STORAGE_KEY);\n\t\tif (!raw) {\n\t\t\tconst seeded = seedStore();\n\t\t\tlocalStorage.setItem(MOCK_STORAGE_KEY, JSON.stringify(seeded));\n\t\t\treturn seeded;\n\t\t}\n\t\tconst parsed = JSON.parse(raw);\n\t\tif (!parsed || typeof parsed !== \"object\") return {};\n\t\treturn parsed;\n\t} catch {\n\t\treturn {};\n\t}\n}\nfunction writeStore(store) {\n\tconst localStorage = getBrowserLocalStorage();\n\tif (!localStorage) return;\n\ttry {\n\t\tlocalStorage.setItem(MOCK_STORAGE_KEY, JSON.stringify(store));\n\t} catch {}\n}\nfunction newId(prefix) {\n\tconst cryptoRef = globalThis.crypto;\n\tif (cryptoRef?.randomUUID) return `${prefix}-${cryptoRef.randomUUID()}`;\n\treturn `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n}\nfunction requireAgentId(agentId) {\n\tconst trimmed = agentId.trim();\n\tif (!trimmed) throw new Error(\"Channels require an agent id\");\n\treturn trimmed;\n}\nfunction clone(value) {\n\treturn JSON.parse(JSON.stringify(value));\n}\nfunction defaultAccountLabel(platform) {\n\tconst meta = getChannelPlatform(platform);\n\treturn meta ? `${meta.name} workspace` : platform;\n}\nfunction findConnection(connections, connectionId) {\n\tconst connection = connections.find((entry) => entry.id === connectionId);\n\tif (!connection) throw new Error(`Channel connection not found: ${connectionId}`);\n\treturn connection;\n}\nfunction toBinding(input, now) {\n\treturn {\n\t\tid: newId(\"chan-bind\"),\n\t\tchannelId: input.channelId,\n\t\tchannelName: input.channelName,\n\t\tchannelKind: input.channelKind ?? \"public\",\n\t\tmode: input.mode ?? \"mention\",\n\t\tsubscribeOnMention: input.subscribeOnMention ?? true,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now\n\t};\n}\nfunction createChannelsResource() {\n\treturn {\n\t\t/** The supported-platform catalog (static; backend may derive from the adapter registry). */\n\t\tlistPlatforms: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"listPlatforms\",\n\t\t\tplannedEndpoint: \"GET /api/channels/platforms\"\n\t\t}, async () => clone(CHANNEL_PLATFORMS)),\n\t\t/** Connections (with their channel bindings) for one agent. */\n\t\tlistForAgent: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"listForAgent\",\n\t\t\tplannedEndpoint: \"GET /api/agents/:agentId/channels\"\n\t\t}, async (agentId) => {\n\t\t\tconst id = requireAgentId(agentId);\n\t\t\treturn clone(readStore()[id] ?? []);\n\t\t}),\n\t\t/**\n\t\t* Channel directory for a platform — the picker source. NET-NEW vs. the\n\t\t* current backend (no channel-list endpoint exists). The runtime team needs\n\t\t* to expose this (e.g. Slack `conversations.list`) for a real picker.\n\t\t*/\n\t\tlistChannels: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"listChannels\",\n\t\t\tplannedEndpoint: \"GET /api/channels/:platform/directory\"\n\t\t}, async (platform) => clone(CHANNEL_DIRECTORY[platform] ?? [])),\n\t\t/** Connect a platform for an agent (OAuth install or credential entry), optionally with a first binding. */\n\t\tconnect: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"connect\",\n\t\t\tplannedEndpoint: \"POST /api/agents/:agentId/channels\"\n\t\t}, async (input) => {\n\t\t\tconst agentId = requireAgentId(input.agentId);\n\t\t\tconst store = readStore();\n\t\t\tconst now = (/* @__PURE__ */ new Date()).toISOString();\n\t\t\tconst connection = {\n\t\t\t\tid: newId(\"chan-conn\"),\n\t\t\t\tplatform: input.platform,\n\t\t\t\tagentId,\n\t\t\t\taccountLabel: input.accountLabel ?? defaultAccountLabel(input.platform),\n\t\t\t\taccountId: newId(\"acct\").toUpperCase(),\n\t\t\t\tconnectedAt: now,\n\t\t\t\tbindings: input.initialBinding ? [toBinding(input.initialBinding, now)] : []\n\t\t\t};\n\t\t\twriteStore({\n\t\t\t\t...store,\n\t\t\t\t[agentId]: [...store[agentId] ?? [], connection]\n\t\t\t});\n\t\t\treturn clone(connection);\n\t\t}),\n\t\t/** Add a channel binding to an existing connection. */\n\t\taddBinding: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"addBinding\",\n\t\t\tplannedEndpoint: \"PUT /gateways/:platform/attachments/:channelId\"\n\t\t}, async (input) => {\n\t\t\tconst agentId = requireAgentId(input.agentId);\n\t\t\tconst store = readStore();\n\t\t\tconst connections = store[agentId] ?? [];\n\t\t\tconst connection = findConnection(connections, input.connectionId);\n\t\t\tconst now = (/* @__PURE__ */ new Date()).toISOString();\n\t\t\tconnection.bindings = [...connection.bindings, toBinding(input.binding, now)];\n\t\t\twriteStore({\n\t\t\t\t...store,\n\t\t\t\t[agentId]: connections\n\t\t\t});\n\t\t\treturn clone(connection);\n\t\t}),\n\t\t/** Update a binding's listen mode / subscribe flag. */\n\t\tupdateBinding: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"updateBinding\",\n\t\t\tplannedEndpoint: \"PUT /gateways/:platform/attachments/:channelId\"\n\t\t}, async (input) => {\n\t\t\tconst agentId = requireAgentId(input.agentId);\n\t\t\tconst store = readStore();\n\t\t\tconst connections = store[agentId] ?? [];\n\t\t\tconst connection = findConnection(connections, input.connectionId);\n\t\t\tconst binding = connection.bindings.find((entry) => entry.id === input.bindingId);\n\t\t\tif (!binding) throw new Error(`Channel binding not found: ${input.bindingId}`);\n\t\t\tif (input.patch.mode !== void 0) binding.mode = input.patch.mode;\n\t\t\tif (input.patch.subscribeOnMention !== void 0) binding.subscribeOnMention = input.patch.subscribeOnMention;\n\t\t\tbinding.updatedAt = (/* @__PURE__ */ new Date()).toISOString();\n\t\t\twriteStore({\n\t\t\t\t...store,\n\t\t\t\t[agentId]: connections\n\t\t\t});\n\t\t\treturn clone(connection);\n\t\t}),\n\t\t/** Remove a channel binding. */\n\t\tremoveBinding: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"removeBinding\",\n\t\t\tplannedEndpoint: \"DELETE /gateways/:platform/attachments/:channelId\"\n\t\t}, async (input) => {\n\t\t\tconst agentId = requireAgentId(input.agentId);\n\t\t\tconst store = readStore();\n\t\t\tconst connections = store[agentId] ?? [];\n\t\t\tconst connection = findConnection(connections, input.connectionId);\n\t\t\tconnection.bindings = connection.bindings.filter((entry) => entry.id !== input.bindingId);\n\t\t\twriteStore({\n\t\t\t\t...store,\n\t\t\t\t[agentId]: connections\n\t\t\t});\n\t\t\treturn clone(connection);\n\t\t}),\n\t\t/** Disconnect the agent from a platform (removes the connection + its bindings). */\n\t\tdisconnect: mock({\n\t\t\tdomain: \"channels\",\n\t\t\tmethod: \"disconnect\",\n\t\t\tplannedEndpoint: \"DELETE /api/agents/:agentId/channels/:connectionId\"\n\t\t}, async (input) => {\n\t\t\tconst agentId = requireAgentId(input.agentId);\n\t\t\tconst store = readStore();\n\t\t\tconst next = (store[agentId] ?? []).filter((entry) => entry.id !== input.connectionId);\n\t\t\twriteStore({\n\t\t\t\t...store,\n\t\t\t\t[agentId]: next\n\t\t\t});\n\t\t})\n\t};\n}\n//#endregion\n//#region src/platform/index.ts\nconst JWT_RETRY_HEADER = \"x-keystroke-jwt-retry\";\nfunction createPlatformClient(options) {\n\tconst auth = options.auth ?? { type: \"none\" };\n\tconst base = normalizeBaseUrl(options.baseUrl);\n\tlet activeOrganizationId = options.getActiveOrganizationId?.() ?? null;\n\tconst setActiveOrganizationId = (organizationId) => {\n\t\tactiveOrganizationId = organizationId;\n\t\toptions.onActiveOrganizationChange?.(organizationId);\n\t};\n\tconst http = ky.create({\n\t\tprefix: base === \"\" ? void 0 : `${base}/`,\n\t\tcredentials: \"omit\",\n\t\thooks: {\n\t\t\tbeforeRequest: [({ request }) => {\n\t\t\t\tapplyActiveOrganizationHeader(request, activeOrganizationId);\n\t\t\t\treturn applyAuthHeaders(request, auth);\n\t\t\t}],\n\t\t\tafterResponse: [async ({ request, response, retryCount }) => {\n\t\t\t\tif (response.status !== 401 || auth.type !== \"bearer\" || !options.refreshBearerToken || retryCount > 0 || request.headers.get(JWT_RETRY_HEADER) === \"1\") return;\n\t\t\t\tconst refreshed = await options.refreshBearerToken();\n\t\t\t\tif (!refreshed) return;\n\t\t\t\tconst retryHeaders = new Headers(request.headers);\n\t\t\t\tretryHeaders.set(\"Authorization\", `Bearer ${refreshed}`);\n\t\t\t\tretryHeaders.set(JWT_RETRY_HEADER, \"1\");\n\t\t\t\treturn ky.retry({\n\t\t\t\t\trequest: new Request(request, { headers: retryHeaders }),\n\t\t\t\t\tcode: \"JWT_REFRESHED\"\n\t\t\t\t});\n\t\t\t}]\n\t\t},\n\t\t...options.ky\n\t});\n\treturn {\n\t\thttp,\n\t\thealth: createHealthResource(http),\n\t\torganizations: createOrganizationsResource(http, {\n\t\t\tonActiveOrganizationChange: setActiveOrganizationId,\n\t\t\tgetActiveOrganizationId: () => activeOrganizationId\n\t\t}),\n\t\tprojects: createProjectsResource(http),\n\t\tartifacts: createArtifactsResource(http),\n\t\tprojectSettings: createProjectSettingsResource(),\n\t\tagents: createAgentsResource(http),\n\t\tworkflows: createWorkflowsResource(http),\n\t\tskills: createSkillsResource(http),\n\t\tapps: createAppsResource(http),\n\t\tcredentials: createCredentialsResource(http),\n\t\thistory: createHistoryResource(http),\n\t\tdeployments: createDeploymentsResource(http),\n\t\tgatewayAttachments: createGatewayAttachmentsResource(http),\n\t\tprojectMetrics: createProjectMetricsResource(http),\n\t\tprojectFiles: createProjectFilesResource(http),\n\t\tchannels: createChannelsResource(),\n\t\tmembers: createMembersResource(http),\n\t\tinvitations: createInvitationsResource(http),\n\t\tapiKeys: createApiKeysResource(),\n\t\trecents: createRecentsResource(http),\n\t\tuserPreferences: createUserPreferencesResource(http),\n\t\tuserAvatar: createUserAvatarResource(http),\n\t\torganizationSidebarBranding: createOrganizationSidebarBrandingResource(http, { getActiveOrganizationId: () => activeOrganizationId }),\n\t\tgetActiveOrganizationId: () => activeOrganizationId,\n\t\tsetActiveOrganizationId\n\t};\n}\n/** Browser client for apps using JWT bearer auth minted from Better Auth sessions. */\nfunction createBrowserPlatformClient(options) {\n\treturn createPlatformClient({\n\t\t...options,\n\t\tbaseUrl: options.baseUrl ?? \"\",\n\t\tauth: browserAuthStrategy(options.getToken),\n\t\trefreshBearerToken: options.refreshBearerToken,\n\t\tgetActiveOrganizationId: readActiveOrganizationId,\n\t\tonActiveOrganizationChange: writeActiveOrganizationId\n\t});\n}\n//#endregion\nexport { CHANNEL_PLATFORMS, DEFAULT_ORGANIZATION_SIDEBAR_BRANDING, DEFAULT_PROJECT_SETTINGS, DEFAULT_USER_AVATAR, DEFAULT_USER_PREFERENCES, PlatformError, browserAuthStrategy, createBrowserPlatformClient, createPlatformClient, getChannelPlatform, mergeOrganizationSidebarBranding, mergeProjectSettings, mergeUserPreferences, mockManifest, normalizeBaseUrl, normalizeOrganizationSidebarBranding, normalizeProjectSettings, normalizeUserPreferences, readActiveOrganizationId, toPlatformError, writeActiveOrganizationId };\n\n//# sourceMappingURL=index.mjs.map","import {\n createPlatformClient,\n type AuthStrategy as PlatformAuthStrategy,\n type PlatformClient,\n} from \"@keystrokehq/sdk/platform\";\nimport type { AuthStrategy as CliAuthStrategy } from \"@keystrokehq/sdk\";\nimport type Conf from \"conf\";\n\nimport { resolveCliAuth } from \"./auth/resolve-cli-auth\";\nimport { getCliJwt } from \"./auth/jwt-cache\";\nimport { getPlatformUrl, type CliConfig } from \"./config\";\n\nfunction toPlatformAuth(auth: CliAuthStrategy): PlatformAuthStrategy {\n if (auth.type === \"bearer\") {\n return auth;\n }\n\n if (auth.type === \"apiKey\") {\n return {\n type: \"bearer\",\n getToken: async () => auth.getKey(),\n };\n }\n\n return { type: \"none\" };\n}\n\nexport function createCliPlatformClient(config: Conf<CliConfig>): PlatformClient {\n const platformUrl = getPlatformUrl(config);\n return createPlatformClient({\n baseUrl: platformUrl,\n auth: toPlatformAuth(resolveCliAuth(config)),\n refreshBearerToken: () => getCliJwt(platformUrl, true),\n getActiveOrganizationId: () => config.get(\"activeOrganizationId\") ?? null,\n onActiveOrganizationChange: (organizationId) => {\n if (organizationId) {\n config.set(\"activeOrganizationId\", organizationId);\n } else {\n config.delete(\"activeOrganizationId\");\n }\n },\n });\n}\n","import type { PlatformClient } from \"@keystrokehq/sdk/platform\";\nimport { PlatformError } from \"@keystrokehq/sdk/platform\";\nimport type { Project, UserOrganization } from \"@keystrokehq/shared\";\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport function looksLikeUuid(value: string): boolean {\n return UUID_PATTERN.test(value);\n}\n\nexport function formatProjectLabel(project: Pick<Project, \"slug\">): string {\n return project.slug;\n}\n\nexport async function resolveProjectRef(platform: PlatformClient, ref: string): Promise<Project> {\n if (looksLikeUuid(ref)) {\n try {\n return await platform.projects.get(ref);\n } catch (error) {\n if (error instanceof PlatformError && error.status === 404) {\n throw new Error(\n `Project ${ref} not found in the active organization. Run \\`keystroke project list\\`, then \\`keystroke config use project <slug>\\`.`,\n );\n }\n throw error;\n }\n }\n\n const projects = await platform.projects.list();\n const match = projects.find((project) => project.slug === ref);\n if (!match) {\n throw new Error(\n `Project \"${ref}\" not found in the active organization. Run \\`keystroke project list\\`.`,\n );\n }\n\n return match;\n}\n\nexport function resolveOrganizationRef(\n organizations: UserOrganization[],\n ref: string,\n): UserOrganization {\n const byId = organizations.find((entry) => entry.organization.id === ref);\n if (byId) {\n return byId;\n }\n\n const bySlug = organizations.find((entry) => entry.organization.slug === ref);\n if (bySlug) {\n return bySlug;\n }\n\n throw new Error(`Organization \"${ref}\" was not found or you do not have access`);\n}\n","import { select } from \"@inquirer/prompts\";\nimport type Conf from \"conf\";\nimport type { UserOrganization } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"../config\";\nimport { getWebUrl } from \"../config\";\nimport { createCliPlatformClient } from \"../platform-client\";\nimport { resolveOrganizationRef } from \"../resolve-resource-ref\";\n\nexport type ActivateOrganizationOptions = {\n organizationId?: string;\n organizationRef?: string;\n /** Organization active in the browser when device auth was approved. */\n deviceOrganizationId?: string;\n /** Last active organization stored in CLI config. */\n storedOrganizationId?: string;\n};\n\nfunction formatOrganization(membership: UserOrganization): string {\n return `${membership.organization.name} (${membership.role})`;\n}\n\nexport async function listOrganizations(config: Conf<CliConfig>): Promise<UserOrganization[]> {\n const platform = createCliPlatformClient(config);\n return platform.organizations.list();\n}\n\nexport async function activateOrganization(\n config: Conf<CliConfig>,\n organizationId: string,\n): Promise<UserOrganization> {\n const platform = createCliPlatformClient(config);\n const membership = await platform.organizations.setActive({ organizationId });\n platform.setActiveOrganizationId(membership.organization.id);\n return membership;\n}\n\nexport function resolveOrganizationIdForLogin(\n organizations: UserOrganization[],\n options: ActivateOrganizationOptions = {},\n): string {\n if (options.organizationRef ?? options.organizationId) {\n return resolveOrganizationRef(organizations, options.organizationRef ?? options.organizationId!)\n .organization.id;\n }\n\n for (const candidateId of [options.deviceOrganizationId, options.storedOrganizationId]) {\n const organizationId = candidateId?.trim();\n if (organizationId && organizations.some((entry) => entry.organization.id === organizationId)) {\n return organizationId;\n }\n }\n\n if (organizations.length === 1) {\n return organizations[0]!.organization.id;\n }\n\n return [...organizations].sort((left, right) =>\n left.organization.slug.localeCompare(right.organization.slug),\n )[0]!.organization.id;\n}\n\nasync function pickOrganization(\n config: Conf<CliConfig>,\n organizations: UserOrganization[],\n organizationRef?: string,\n): Promise<UserOrganization> {\n if (organizationRef) {\n const membership = resolveOrganizationRef(organizations, organizationRef);\n return activateOrganization(config, membership.organization.id);\n }\n\n if (!process.stdin.isTTY) {\n const names = organizations.map((entry) => entry.organization.slug).join(\", \");\n throw new Error(\n `Multiple organizations found. Run \\`keystroke config use org <slug>\\`. Options: ${names}`,\n );\n }\n\n const selectedId = await select({\n message: \"Select an organization\",\n choices: organizations.map((entry) => ({\n name: formatOrganization(entry),\n value: entry.organization.id,\n })),\n });\n\n return activateOrganization(config, selectedId);\n}\n\nexport async function selectActiveOrganization(\n config: Conf<CliConfig>,\n options: ActivateOrganizationOptions = {},\n): Promise<UserOrganization> {\n const organizations = await listOrganizations(config);\n\n if (organizations.length === 0) {\n throw new Error(`No organization found — create one at ${getWebUrl(config)}`);\n }\n\n if (organizations.length === 1) {\n return activateOrganization(config, organizations[0]!.organization.id);\n }\n\n return pickOrganization(config, organizations, options.organizationRef ?? options.organizationId);\n}\n\nexport async function syncActiveOrganizationAfterLogin(\n config: Conf<CliConfig>,\n options: ActivateOrganizationOptions = {},\n): Promise<UserOrganization> {\n const organizations = await listOrganizations(config);\n\n if (organizations.length === 0) {\n throw new Error(`No organization found — create one at ${getWebUrl(config)}`);\n }\n\n const organizationId = resolveOrganizationIdForLogin(organizations, {\n organizationRef: options.organizationRef,\n organizationId: options.organizationId,\n deviceOrganizationId: options.deviceOrganizationId,\n storedOrganizationId: config.get(\"activeOrganizationId\"),\n });\n\n return activateOrganization(config, organizationId);\n}\n\nexport async function ensureActiveOrganization(config: Conf<CliConfig>): Promise<void> {\n const organizations = await listOrganizations(config);\n\n if (organizations.length === 0) {\n throw new Error(\n \"No organization found. Run `keystroke auth login` after creating one in the dashboard.\",\n );\n }\n\n const storedId = config.get(\"activeOrganizationId\");\n if (storedId && organizations.some((entry) => entry.organization.id === storedId)) {\n await activateOrganization(config, storedId);\n return;\n }\n\n if (organizations.length === 1) {\n await activateOrganization(config, organizations[0]!.organization.id);\n return;\n }\n\n throw new Error(\n \"No active organization. Run `keystroke auth login` or `keystroke config use org`.\",\n );\n}\n","import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\nimport { getCliConfigDir } from \"./config\";\n\nexport type DevSession = {\n pid: number;\n port: number;\n root: string;\n serverUrl: string;\n};\n\nexport function getDevSessionPath(configDir = getCliConfigDir()): string {\n return join(configDir, \"dev-session.json\");\n}\n\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function writeDevSession(session: DevSession, configDir = getCliConfigDir()): void {\n const path = getDevSessionPath(configDir);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(session)}\\n`, \"utf8\");\n}\n\nexport function clearDevSession(configDir = getCliConfigDir()): void {\n const path = getDevSessionPath(configDir);\n if (existsSync(path)) {\n unlinkSync(path);\n }\n}\n\nexport function readDevSession(configDir = getCliConfigDir()): DevSession | undefined {\n const path = getDevSessionPath(configDir);\n if (!existsSync(path)) {\n return undefined;\n }\n\n try {\n const session = JSON.parse(readFileSync(path, \"utf8\")) as DevSession;\n if (!isProcessAlive(session.pid)) {\n clearDevSession(configDir);\n return undefined;\n }\n return session;\n } catch {\n clearDevSession(configDir);\n return undefined;\n }\n}\n","import type Conf from \"conf\";\n\nimport {\n getConfigDir,\n getEffectiveApiTarget,\n getPlatformUrl,\n getServerUrl,\n type CliConfig,\n} from \"./config\";\nimport { readDevSession } from \"./dev-session\";\nimport { createCliPlatformClient } from \"./platform-client\";\nimport { formatProjectLabel, resolveProjectRef } from \"./resolve-resource-ref\";\n\nexport type ApiTargetOptions = {\n projectId?: string;\n local?: boolean;\n /** Route to `/api/projects/:id` and require a project id. Default false. */\n projectScoped?: boolean;\n /** Org-level platform API; ignores `--project` and activeProjectId. */\n orgScoped?: boolean;\n};\n\nexport const projectScopedTarget: ApiTargetOptions = { projectScoped: true };\n\nexport type ResolvedApiTarget = {\n baseUrl: string;\n projectId?: string;\n mode: \"local\" | \"platform\";\n};\n\nfunction resolveLocalTarget(config: Conf<CliConfig>): ResolvedApiTarget {\n return {\n baseUrl: getServerUrl(config),\n mode: \"local\",\n };\n}\n\nfunction resolveOrgPlatformTarget(config: Conf<CliConfig>): ResolvedApiTarget {\n return {\n baseUrl: `${getPlatformUrl(config).replace(/\\/+$/, \"\")}/api`,\n mode: \"platform\",\n };\n}\n\nasync function resolvePlatformTarget(\n config: Conf<CliConfig>,\n projectRef: string,\n): Promise<ResolvedApiTarget> {\n const platform = createCliPlatformClient(config);\n let project;\n try {\n project = await resolveProjectRef(platform, projectRef);\n } catch (error) {\n if (error instanceof Error) {\n throw error;\n }\n throw error;\n }\n if (project.status !== \"active\") {\n throw new Error(`Project ${formatProjectLabel(project)} is not active (${project.status})`);\n }\n\n const platformUrl = getPlatformUrl(config).replace(/\\/+$/, \"\");\n return {\n baseUrl: `${platformUrl}/api/projects/${encodeURIComponent(project.id)}`,\n projectId: project.id,\n mode: \"platform\",\n };\n}\n\nexport async function resolveApiTarget(\n config: Conf<CliConfig>,\n options: ApiTargetOptions = {},\n): Promise<ResolvedApiTarget> {\n if (options.local) {\n return resolveLocalTarget(config);\n }\n\n const devSession = readDevSession(getConfigDir(config));\n if (devSession && getEffectiveApiTarget(config) !== \"platform\") {\n return {\n baseUrl: devSession.serverUrl,\n mode: \"local\",\n };\n }\n\n if (options.orgScoped || options.projectScoped === false) {\n if (getEffectiveApiTarget(config) === \"local\") {\n return resolveLocalTarget(config);\n }\n return resolveOrgPlatformTarget(config);\n }\n\n if (options.projectId) {\n return resolvePlatformTarget(config, options.projectId);\n }\n\n if (getEffectiveApiTarget(config) === \"local\") {\n return resolveLocalTarget(config);\n }\n\n if (!options.projectScoped) {\n return resolveOrgPlatformTarget(config);\n }\n\n const projectRef = options.projectId ?? config.get(\"activeProjectId\");\n if (!projectRef) {\n throw new Error(\n \"No project selected. Pass `--project <slug>` or run `keystroke config use project <slug>`.\",\n );\n }\n\n return resolvePlatformTarget(config, projectRef);\n}\n","import type { ApiTargetOptions } from \"./resolve-api-target\";\n\nlet targetOptions: ApiTargetOptions = {};\n\nexport function setCliTargetOptions(options: ApiTargetOptions): void {\n targetOptions = options;\n}\n\nexport function getCliTargetOptions(): ApiTargetOptions {\n return targetOptions;\n}\n","import type { ValidationErrorDetail } from \"@keystrokehq/shared\";\n\nfunction exampleValueFromValidationMessage(message: string): unknown {\n if (/expected number/i.test(message)) {\n return 0;\n }\n if (/expected string/i.test(message)) {\n return \"\";\n }\n if (/expected boolean/i.test(message)) {\n return false;\n }\n if (/expected array/i.test(message)) {\n return [];\n }\n if (/expected object/i.test(message)) {\n return {};\n }\n\n const enumMatch = message.match(/expected one of (.+)/i);\n if (enumMatch) {\n const firstOption = enumMatch[1]?.match(/\"([^\"]+)\"/);\n if (firstOption?.[1]) {\n return firstOption[1];\n }\n }\n\n return null;\n}\n\nfunction setNestedExampleValue(input: Record<string, unknown>, path: string, value: unknown): void {\n const parts = path.split(\".\").filter(Boolean);\n if (parts.length === 0) {\n return;\n }\n\n let current: Record<string, unknown> = input;\n for (let index = 0; index < parts.length - 1; index += 1) {\n const key = parts[index]!;\n const next = current[key];\n if (typeof next !== \"object\" || next === null || Array.isArray(next)) {\n current[key] = {};\n }\n current = current[key] as Record<string, unknown>;\n }\n\n current[parts[parts.length - 1]!] = value;\n}\n\nexport function exampleInputFromValidationDetails(\n details: ValidationErrorDetail[],\n): Record<string, unknown> {\n const input: Record<string, unknown> = {};\n\n for (const detail of details) {\n if (!detail.path) {\n continue;\n }\n setNestedExampleValue(input, detail.path, exampleValueFromValidationMessage(detail.message));\n }\n\n return input;\n}\n","import type { ErrorResponse } from \"@keystrokehq/shared\";\nimport { exampleInputFromValidationDetails } from \"./example-input\";\nimport type { CliUsageHint } from \"./types\";\n\n/** Turn a parsed API error body into terminal output. */\nexport function formatApiErrorMessage(\n response: ErrorResponse,\n fallback: string,\n options?: CliUsageHint,\n): string {\n const summary = response.message ?? response.error ?? fallback;\n\n if (!response.details?.length) {\n return summary;\n }\n\n const lines = response.details.map((detail) => {\n const field = detail.path || \"(root)\";\n return ` • ${field}: ${detail.message}`;\n });\n let message = `${summary}:\\n${lines.join(\"\\n\")}`;\n\n if (options?.usage) {\n const example = JSON.stringify(exampleInputFromValidationDetails(response.details));\n const flag = options.usage.flag ?? \"--input\";\n message += `\\n\\nTry: ${options.usage.command} ${flag} '${example}'`;\n }\n\n return message;\n}\n","import { parseErrorResponse } from \"@keystrokehq/shared\";\nimport { KeystrokeError } from \"@keystrokehq/sdk\";\nimport { PlatformError } from \"@keystrokehq/sdk/platform\";\nimport { getAccessToken } from \"../auth/credentials\";\nimport { resolvePlatformUrlForWebUrl } from \"../resolve-platform-url\";\nimport type { CliErrorContext } from \"./types\";\nimport { formatApiErrorMessage } from \"./format-api-message\";\n\nfunction isUnreachableServerError(error: Error): boolean {\n return (\n error.message.includes(\"network error\") ||\n error.message.includes(\"ECONNREFUSED\") ||\n error.message.includes(\"ENOTFOUND\") ||\n error.message.includes(\"fetch failed\")\n );\n}\n\nfunction unreachableTarget(context?: CliErrorContext): string | undefined {\n return context?.serverUrl ?? context?.webUrl;\n}\n\nfunction unreachableServerMessage(targetUrl?: string): string {\n const target = targetUrl ?? \"the keystroke server\";\n return `Could not reach ${target}. Is the server running? (keystroke dev or keystroke start)`;\n}\n\ntype HttpClientError = {\n status: number;\n body: unknown;\n message: string;\n};\n\nfunction authApiOrigin(context?: CliErrorContext): string | undefined {\n if (context?.platformUrl) {\n return context.platformUrl;\n }\n\n if (context?.webUrl) {\n return resolvePlatformUrlForWebUrl(context.webUrl, {});\n }\n\n return undefined;\n}\n\nfunction formatHttpClientError(error: HttpClientError, context?: CliErrorContext): string {\n if (error.status === 401) {\n const origin = authApiOrigin(context);\n if (origin && !getAccessToken(origin)) {\n return \"Not logged in. Run `keystroke auth login` first.\";\n }\n return \"Authentication failed. Run `keystroke auth login` again.\";\n }\n\n if (error.status === 0) {\n return unreachableServerMessage(unreachableTarget(context));\n }\n\n const parsed = parseErrorResponse(error.body);\n if (parsed) {\n return formatApiErrorMessage(parsed, error.message, context);\n }\n\n return error.message;\n}\n\nexport function formatCliError(\n error: unknown,\n fallback: string,\n context?: CliErrorContext,\n): string {\n if (error instanceof KeystrokeError || error instanceof PlatformError) {\n return formatHttpClientError(error, context);\n }\n\n if (error instanceof Error) {\n if (isUnreachableServerError(error)) {\n return unreachableServerMessage(unreachableTarget(context));\n }\n return error.message;\n }\n\n return fallback;\n}\n","import { createCliClient } from \"../client\";\nimport { createCliConfig, getWebUrl } from \"../config\";\nimport { ensureActiveOrganization } from \"../organization/active-organization\";\nimport {\n projectScopedTarget,\n resolveApiTarget,\n type ApiTargetOptions,\n} from \"../resolve-api-target\";\nimport { getCliTargetOptions } from \"../target-options\";\nimport type { CliContext, CliErrorContext } from \"./types\";\nimport { formatCliError } from \"./format-cli-error\";\n\nexport async function runProjectCliCommand(\n fallback: string,\n fn: (ctx: CliContext) => Promise<void>,\n errorContext?: CliErrorContext,\n targetOptions: ApiTargetOptions = {},\n): Promise<void> {\n return runCliCommand(fallback, fn, errorContext, {\n ...projectScopedTarget,\n ...targetOptions,\n });\n}\n\nexport async function runCliCommand(\n fallback: string,\n fn: (ctx: CliContext) => Promise<void>,\n errorContext?: CliErrorContext,\n targetOptions: ApiTargetOptions = {},\n): Promise<void> {\n const config = createCliConfig();\n const target = await resolveApiTarget(config, {\n ...getCliTargetOptions(),\n ...targetOptions,\n });\n\n if (target.mode === \"platform\") {\n await ensureActiveOrganization(config);\n }\n\n const ctx: CliContext = {\n config,\n client: createCliClient(config, {\n baseUrl: target.baseUrl,\n platform: target.mode === \"platform\",\n }),\n serverUrl: target.baseUrl,\n webUrl: getWebUrl(config),\n apiTarget: target,\n };\n\n try {\n await fn(ctx);\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, fallback, {\n ...errorContext,\n serverUrl: ctx.serverUrl,\n webUrl: ctx.webUrl,\n })}\\n`,\n );\n process.exitCode = 1;\n }\n}\n","/**\n * Binary name to show in help text and \"Try: ...\" hints. Always the published\n * `keystroke`, or the `keystroke-dev` wrapper (which sets KEYSTROKE_DEV) so\n * examples stay copy-pasteable while developing on keystroke itself.\n */\nexport function cliBinaryName(): string {\n return process.env.KEYSTROKE_DEV ? \"keystroke-dev\" : \"keystroke\";\n}\n\n/** Parse a JSON CLI flag; throws a readable error on invalid input. */\nexport function parseJsonOption(value: string, flag: string): unknown {\n try {\n return JSON.parse(value) as unknown;\n } catch {\n throw new Error(`Invalid ${flag} JSON`);\n }\n}\n","import type Conf from \"conf\";\nimport type { PlatformClient } from \"@keystrokehq/sdk/platform\";\nimport type { Project } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"./config\";\nimport { createCliPlatformClient } from \"./platform-client\";\nimport { looksLikeUuid, resolveProjectRef } from \"./resolve-resource-ref\";\nimport { getCliTargetOptions } from \"./target-options\";\n\nexport async function resolveActiveProject(\n config: Conf<CliConfig>,\n platform?: PlatformClient,\n): Promise<Project | undefined> {\n const ref = getCliTargetOptions().projectId ?? config.get(\"activeProjectId\");\n if (!ref) {\n return undefined;\n }\n\n const client = platform ?? createCliPlatformClient(config);\n const fromFlag = getCliTargetOptions().projectId;\n\n if (!fromFlag && looksLikeUuid(ref)) {\n return resolveProjectRef(client, ref);\n }\n\n return resolveProjectRef(client, ref);\n}\n\nexport async function resolveActiveProjectId(config: Conf<CliConfig>): Promise<string | undefined> {\n const project = await resolveActiveProject(config);\n return project?.id;\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../../config\";\nimport { runCliCommand } from \"../../errors\";\nimport { ensureActiveOrganization } from \"../../organization/active-organization\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { resolveActiveProjectId } from \"../../resolve-project-target\";\n\nexport function registerAgentListCommand(agent: Command): void {\n agent\n .command(\"list\")\n .description(\"List agents in the active organization\")\n .action(() =>\n runCliCommand(\n \"List agents failed\",\n async () => {\n const config = createCliConfig();\n const client = createCliPlatformClient(config);\n await ensureActiveOrganization(config);\n const projectId = await resolveActiveProjectId(config);\n const result = await client.agents.list(projectId ? { projectId } : undefined);\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n },\n undefined,\n { orgScoped: true },\n ),\n );\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nexport function registerAgentPromptCommand(agent: Command): void {\n agent\n .command(\"prompt\")\n .description(\"Send a message to an agent (or follow up in an existing session)\")\n .argument(\"<agentId>\", \"Agent key / route id\")\n .requiredOption(\"--message <text>\", \"Message to send\")\n .option(\"--session-id <id>\", \"Existing session id for follow-up\")\n .action((agentId: string, options: { message: string; sessionId?: string }) =>\n runProjectCliCommand(\"Agent prompt failed\", async ({ client }) => {\n const result = await client.agents.prompt(agentId, {\n message: options.message,\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nexport function registerAgentSessionsCommand(agent: Command): void {\n const sessions = agent.command(\"sessions\").description(\"List and inspect agent sessions\");\n\n sessions\n .command(\"list\")\n .description(\"List sessions for an agent\")\n .argument(\"<agentId>\", \"Agent key / route id\")\n .option(\"--limit <n>\", \"Page size (1–100)\", \"20\")\n .option(\"--cursor <cursor>\", \"Pagination cursor from a previous page\")\n .option(\"--status <status>\", \"Filter by status (running, completed, failed)\")\n .option(\"--source <source>\", \"Filter by source (api, gateway)\")\n .action((agentId: string, options: Record<string, string | undefined>) =>\n runProjectCliCommand(\"List agent sessions failed\", async ({ client }) => {\n const result = await client.agents.listSessions(agentId, {\n limit: Number(options.limit),\n ...(options.cursor ? { cursor: options.cursor } : {}),\n ...(options.status\n ? { status: options.status as \"running\" | \"completed\" | \"failed\" }\n : {}),\n ...(options.source ? { source: options.source as \"api\" | \"gateway\" } : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n\n sessions\n .command(\"get\")\n .description(\"Get full details for an agent session\")\n .argument(\"<agentId>\", \"Agent key / route id\")\n .argument(\"<sessionId>\", \"Agent session id\")\n .option(\"--include <parts>\", \"Comma-separated: gateway, messages, events, trace\")\n .action((agentId: string, sessionId: string, options: { include?: string }) =>\n runProjectCliCommand(\"Get agent session failed\", async ({ client }) => {\n const result = await client.agents.getSession(agentId, sessionId, {\n include: options.include,\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { registerAgentListCommand } from \"./list\";\nimport { registerAgentPromptCommand } from \"./prompt\";\nimport { registerAgentSessionsCommand } from \"./sessions\";\n\nexport function registerAgentCommand(program: Command): void {\n const agent = program.command(\"agent\").description(\"Invoke and inspect agents\");\n\n registerAgentListCommand(agent);\n registerAgentPromptCommand(agent);\n registerAgentSessionsCommand(agent);\n}\n","import type { AppCatalogEntry } from \"@keystrokehq/shared\";\nimport type { PlatformClient } from \"@keystrokehq/sdk/platform\";\n\nexport async function runAppList(client: PlatformClient): Promise<AppCatalogEntry[]> {\n return client.apps.listCatalog();\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../../config\";\nimport { runCliCommand } from \"../../errors\";\nimport { ensureActiveOrganization } from \"../../organization/active-organization\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { runAppList } from \"./run-app-list\";\n\nexport function registerAppListCommand(app: Command): void {\n app\n .command(\"list\")\n .description(\"List connectable apps in the active organization\")\n .action(() =>\n runCliCommand(\n \"List apps failed\",\n async () => {\n const config = createCliConfig();\n const client = createCliPlatformClient(config);\n await ensureActiveOrganization(config);\n const apps = await runAppList(client);\n process.stdout.write(`${JSON.stringify(apps, null, 2)}\\n`);\n },\n undefined,\n { orgScoped: true },\n ),\n );\n}\n","import type { Command } from \"commander\";\n\nimport { registerAppListCommand } from \"./list\";\n\nexport function registerAppCommand(program: Command): void {\n const app = program.command(\"app\").description(\"Browse connectable integrations\");\n\n registerAppListCommand(app);\n}\n","export type ConnectCredentialScope = \"org\" | \"user\" | \"project\";\n\nexport type ParsedConnectScopes = {\n createOrganizationCredential: boolean;\n createUserProvidedCredential: boolean;\n projectIds: string[];\n};\n\nexport function parseConnectScopes(scopes: string[], projectIds: string[]): ParsedConnectScopes {\n const normalized = scopes.length > 0 ? scopes : [\"org\"];\n\n for (const scope of normalized) {\n if (scope !== \"org\" && scope !== \"user\" && scope !== \"project\") {\n throw new Error(`Unknown scope \"${scope}\". Expected org, user, or project.`);\n }\n }\n\n const createOrganizationCredential = normalized.includes(\"org\");\n const createUserProvidedCredential = normalized.includes(\"user\");\n const includesProject = normalized.includes(\"project\");\n const selectedProjectIds = includesProject ? projectIds : [];\n\n if (includesProject && selectedProjectIds.length === 0) {\n throw new Error(\"--project-id is required when scope includes project\");\n }\n\n if (\n !createOrganizationCredential &&\n !createUserProvidedCredential &&\n selectedProjectIds.length === 0\n ) {\n throw new Error(\"At least one scope is required via --scope and/or --project-id\");\n }\n\n return {\n createOrganizationCredential,\n createUserProvidedCredential,\n projectIds: selectedProjectIds,\n };\n}\n","import { spawn } from \"node:child_process\";\n\nexport function openUrl(url: string): void {\n const platform = process.platform;\n const command = platform === \"darwin\" ? \"open\" : platform === \"win32\" ? \"start\" : \"xdg-open\";\n\n spawn(command, [url], {\n detached: true,\n stdio: \"ignore\",\n }).unref();\n}\n","import type {\n ConnectAuthorizeUrlResponse,\n ConnectProvider,\n StartOAuthConnectionInput,\n StartOAuthConnectionResult,\n} from \"@keystrokehq/shared\";\nimport { openUrl } from \"../../auth/open-url\";\nimport { parseConnectScopes, type ParsedConnectScopes } from \"./parse-connect-scopes\";\n\n/** Minimal server SDK surface used by `runConnect` for local OAuth. */\nexport type ConnectOAuthServerClient = {\n connect: {\n getAuthorizeUrl(path: string): Promise<ConnectAuthorizeUrlResponse>;\n };\n};\n\n/** Minimal platform SDK surface used by `runConnect` for scoped OAuth. */\nexport type ConnectOAuthPlatformClient = {\n credentials: {\n startOAuthConnection(input: StartOAuthConnectionInput): Promise<StartOAuthConnectionResult>;\n };\n};\n\nfunction providerLabel(key: string): string {\n return key.charAt(0).toUpperCase() + key.slice(1);\n}\n\nexport async function runConnect(options: {\n client: ConnectOAuthServerClient;\n platform?: ConnectOAuthPlatformClient;\n provider: ConnectProvider;\n serverUrl: string;\n printUrl?: boolean;\n oauthScopes?: string[];\n credentialScopes?: ParsedConnectScopes;\n}): Promise<void> {\n const {\n client,\n platform,\n provider,\n serverUrl,\n printUrl,\n oauthScopes = [],\n credentialScopes,\n } = options;\n const label = providerLabel(provider.key);\n\n if (provider.mode === \"browser-redirect\") {\n const url = `${serverUrl}${provider.path}`;\n\n if (printUrl) {\n process.stdout.write(`${url}\\n`);\n return;\n }\n\n openUrl(url);\n process.stdout.write(`Complete ${label} sign-in in your browser.\\n`);\n return;\n }\n\n if (platform) {\n const scopes = credentialScopes ?? parseConnectScopes([], []);\n\n const result = await platform.credentials.startOAuthConnection({\n appId: provider.key,\n scopes: oauthScopes,\n permissionMode: \"default\",\n projectIds: scopes.projectIds,\n createOrganizationCredential: scopes.createOrganizationCredential,\n createUserProvidedCredential: scopes.createUserProvidedCredential,\n });\n\n if (!result.authorizeUrl) {\n throw new Error(\"OAuth provider did not return an authorize URL\");\n }\n\n if (oauthScopes.length > 0) {\n process.stdout.write(\"Requested OAuth scopes:\\n\");\n for (const scope of oauthScopes) {\n process.stdout.write(` - ${scope}\\n`);\n }\n process.stdout.write(\"\\n\");\n }\n\n if (printUrl) {\n process.stdout.write(`${result.authorizeUrl}\\n`);\n return;\n }\n\n openUrl(result.authorizeUrl);\n process.stdout.write(`Complete ${label} sign-in in your browser.\\n`);\n return;\n }\n\n const payload = await client.connect.getAuthorizeUrl(provider.path);\n\n const authorizeUrl = new URL(payload.url);\n const scopes = authorizeUrl.searchParams.get(\"scope\")?.split(\" \").filter(Boolean) ?? [];\n\n if (scopes.length > 0) {\n process.stdout.write(\"Requested scopes:\\n\");\n for (const scope of scopes) {\n process.stdout.write(` - ${scope}\\n`);\n }\n process.stdout.write(\"\\n\");\n }\n\n if (printUrl) {\n process.stdout.write(`${payload.url}\\n`);\n return;\n }\n\n openUrl(payload.url);\n process.stdout.write(`Complete ${label} sign-in in your browser.\\n`);\n}\n","import type { Command } from \"commander\";\nimport { createCliConfig } from \"../../config\";\nimport { runCliCommand } from \"../../errors\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { getCliTargetOptions } from \"../../target-options\";\nimport type { ApiTargetOptions } from \"../../resolve-api-target\";\nimport { parseConnectScopes } from \"./parse-connect-scopes\";\nimport { runConnect } from \"./run-connect\";\n\nfunction resolveConnectTargetOptions(): ApiTargetOptions {\n const { local } = getCliTargetOptions();\n if (local) {\n return { local: true };\n }\n return { orgScoped: true };\n}\n\nfunction collectValues(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\nexport function registerConnectCommand(program: Command): void {\n program\n .command(\"connect [provider]\")\n .description(\"Connect third-party accounts (uses apiTarget; --local for local server)\")\n .option(\n \"--oauth-scope <scope>\",\n \"OAuth permission scope to request (repeatable)\",\n collectValues,\n [],\n )\n .option(\n \"--scope <scope>\",\n \"Credential scope: org, user, or project (repeatable)\",\n collectValues,\n [],\n )\n .option(\n \"--project-id <id>\",\n \"Project id when scope includes project (repeatable)\",\n collectValues,\n [],\n )\n .option(\"--print-url\", \"Print the authorize URL and exit without opening the browser\")\n .action(\n (\n provider: string | undefined,\n options: {\n oauthScope: string[];\n scope: string[];\n projectId: string[];\n printUrl?: boolean;\n },\n ) =>\n runCliCommand(\n \"Could not fetch connect providers\",\n async (ctx) => {\n const providers = await ctx.client.connect.listProviders();\n\n if (!provider) {\n if (providers.length === 0) {\n process.stdout.write(\"No connect providers available on this server.\\n\");\n return;\n }\n\n process.stdout.write(\"Available providers:\\n\");\n for (const entry of providers) {\n process.stdout.write(` ${entry.key}\\n`);\n }\n return;\n }\n\n const match = providers.find((entry) => entry.key === provider);\n if (!match) {\n const available = providers.map((entry) => entry.key).join(\", \") || \"(none)\";\n throw new Error(`Unknown provider \"${provider}\". Available: ${available}`);\n }\n\n const hasScopeFlags = options.scope.length > 0 || options.projectId.length > 0;\n if (ctx.apiTarget.mode === \"local\" && hasScopeFlags) {\n throw new Error(\n \"--scope and --project-id are only supported against the platform API (omit --local)\",\n );\n }\n\n const credentialScopes =\n ctx.apiTarget.mode === \"platform\"\n ? parseConnectScopes(options.scope, options.projectId)\n : undefined;\n\n const platform =\n ctx.apiTarget.mode === \"platform\"\n ? createCliPlatformClient(createCliConfig())\n : undefined;\n\n await runConnect({\n client: ctx.client,\n platform,\n provider: match,\n serverUrl: ctx.serverUrl,\n printUrl: options.printUrl,\n oauthScopes: options.oauthScope,\n credentialScopes,\n });\n },\n undefined,\n resolveConnectTargetOptions(),\n ),\n );\n}\n","import type { CredentialScopeType } from \"@keystrokehq/shared\";\nimport type { ApiTargetOptions } from \"../../resolve-api-target\";\nimport { projectScopedTarget } from \"../../resolve-api-target\";\n\nexport function resolveCredentialsTargetOptions(\n options: {\n scopeType?: CredentialScopeType;\n projectId?: string;\n } = {},\n): ApiTargetOptions {\n if (options.scopeType === \"project\") {\n return {\n ...projectScopedTarget,\n projectId: options.projectId,\n };\n }\n\n return { orgScoped: true };\n}\n","import type Conf from \"conf\";\nimport type { PlatformClient } from \"@keystrokehq/sdk/platform\";\nimport type { CreateCredentialsRequest, UpdateCredentialRequest } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"../../config\";\nimport { createCliConfig, getPlatformUrl, getWebUrl } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { ensureActiveOrganization } from \"../../organization/active-organization\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { getCliTargetOptions } from \"../../target-options\";\n\nexport async function withActivePlatformClient(\n config: Conf<CliConfig>,\n fn: (platform: PlatformClient) => Promise<void>,\n): Promise<void> {\n const platform = createCliPlatformClient(config);\n await ensureActiveOrganization(config);\n await fn(platform);\n}\n\nexport function isLocalCredentialsTarget(): boolean {\n return Boolean(getCliTargetOptions().local);\n}\n\nexport async function runCredentialsCommand(\n fallback: string,\n fn: (ctx: {\n config: Conf<CliConfig>;\n platform?: PlatformClient;\n local: boolean;\n }) => Promise<void>,\n): Promise<void> {\n const config = createCliConfig();\n const local = isLocalCredentialsTarget();\n\n try {\n if (local) {\n await fn({ config, local: true });\n return;\n }\n\n await withActivePlatformClient(config, async (platform) => {\n await fn({ config, platform, local: false });\n });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, fallback, {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n}\n\nexport function buildPlatformCreateRequest(args: {\n appId: string;\n value: Record<string, string>;\n scope: string;\n projectId?: string;\n}): CreateCredentialsRequest {\n const apiKey = Object.values(args.value)[0];\n if (!apiKey) {\n throw new Error(\"At least one --set field is required\");\n }\n\n return {\n appId: args.appId,\n connectionKind: \"manual\",\n apiKey,\n projectIds: args.scope === \"project\" && args.projectId ? [args.projectId] : [],\n createOrganizationCredential: args.scope === \"org\",\n createUserProvidedCredential: args.scope === \"user\",\n };\n}\n\nexport function buildPlatformUpdatePatch(args: {\n label?: string;\n isDefault?: boolean;\n value?: Record<string, string>;\n}): UpdateCredentialRequest {\n return {\n ...(args.label !== undefined ? { label: args.label } : {}),\n ...(args.isDefault !== undefined ? { isDefault: args.isDefault } : {}),\n ...(args.value ? { value: args.value } : {}),\n };\n}\n","import type { Command } from \"commander\";\nimport { createCliClient } from \"../../client\";\nimport { createCliConfig } from \"../../config\";\nimport { resolveApiTarget } from \"../../resolve-api-target\";\nimport { getCliTargetOptions } from \"../../target-options\";\nimport { resolveCredentialsTargetOptions } from \"./target-options\";\nimport { runCredentialsCommand } from \"./run-credentials\";\n\nexport function registerCredentialsDeleteCommand(credentials: Command): void {\n credentials\n .command(\"delete\")\n .description(\"Delete a credential instance\")\n .argument(\"<id>\", \"Credential instance id\")\n .action((id: string) =>\n runCredentialsCommand(\"Delete credential failed\", async ({ platform, local }) => {\n if (local) {\n const config = createCliConfig();\n const target = await resolveApiTarget(config, {\n ...getCliTargetOptions(),\n ...resolveCredentialsTargetOptions(),\n });\n const client = createCliClient(config, {\n baseUrl: target.baseUrl,\n platform: target.mode === \"platform\",\n });\n await client.credentials.deleteInstance(id);\n return;\n }\n\n await platform!.credentials.delete(id);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { createCliClient } from \"../../client\";\nimport { createCliConfig } from \"../../config\";\nimport { resolveApiTarget } from \"../../resolve-api-target\";\nimport { getCliTargetOptions } from \"../../target-options\";\nimport { resolveCredentialsTargetOptions } from \"./target-options\";\nimport { runCredentialsCommand } from \"./run-credentials\";\n\nexport function registerCredentialsGetCommand(credentials: Command): void {\n credentials\n .command(\"get\")\n .description(\"Get a credential instance by id\")\n .argument(\"<id>\", \"Credential instance id\")\n .action((id: string) =>\n runCredentialsCommand(\"Get credential failed\", async ({ platform, local }) => {\n if (local) {\n const config = createCliConfig();\n const target = await resolveApiTarget(config, {\n ...getCliTargetOptions(),\n ...resolveCredentialsTargetOptions(),\n });\n const client = createCliClient(config, {\n baseUrl: target.baseUrl,\n platform: target.mode === \"platform\",\n });\n const result = await client.credentials.listInstances();\n const match = result.instances.find((instance) => instance.id === id);\n if (!match) {\n throw new Error(`Credential ${id} not found`);\n }\n process.stdout.write(`${JSON.stringify(match, null, 2)}\\n`);\n return;\n }\n\n const credential = await platform!.credentials.get(id);\n process.stdout.write(`${JSON.stringify({ credential }, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { createCliClient } from \"../../client\";\nimport { createCliConfig } from \"../../config\";\nimport { resolveApiTarget } from \"../../resolve-api-target\";\nimport { getCliTargetOptions } from \"../../target-options\";\nimport { resolveCredentialsTargetOptions } from \"./target-options\";\nimport { runCredentialsCommand } from \"./run-credentials\";\n\nexport function registerCredentialsListCommand(credentials: Command): void {\n credentials\n .command(\"list\")\n .description(\"List stored credential instances\")\n .option(\"--key <key>\", \"Filter by credential key (local server only)\")\n .action((options: { key?: string }) =>\n runCredentialsCommand(\"List credential instances failed\", async ({ platform, local }) => {\n if (local) {\n const config = createCliConfig();\n const target = await resolveApiTarget(config, {\n ...getCliTargetOptions(),\n ...resolveCredentialsTargetOptions(),\n });\n const client = createCliClient(config, {\n baseUrl: target.baseUrl,\n platform: target.mode === \"platform\",\n });\n const result = await client.credentials.listInstances(\n options.key ? { key: options.key } : undefined,\n );\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n return;\n }\n\n const credentialsList = await platform!.credentials.list();\n process.stdout.write(`${JSON.stringify({ credentials: credentialsList }, null, 2)}\\n`);\n }),\n );\n}\n","export const ENV_REF_PREFIX = \"@env:\";\n\nexport function isEnvRef(raw: string): boolean {\n return raw.startsWith(ENV_REF_PREFIX);\n}\n\nexport function envRefName(raw: string): string {\n return raw.slice(ENV_REF_PREFIX.length);\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\n\nfunction hasProjectLayout(dir: string): boolean {\n return existsSync(join(dir, \"package.json\")) && existsSync(join(dir, \"src\", \"agents\"));\n}\n\nexport function resolveProjectRoot(fromDir = process.cwd()): string {\n let dir = resolve(fromDir);\n\n while (dir !== dirname(dir)) {\n if (hasProjectLayout(dir)) {\n return dir;\n }\n\n dir = dirname(dir);\n }\n\n if (hasProjectLayout(dir)) {\n return dir;\n }\n\n throw new Error(\"Could not find keystroke project root (expected package.json and src/agents/)\");\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { resolveProjectRoot } from \"./resolve-project-root\";\n\nlet loaded = false;\n\nexport function parseEnvFile(contents: string): Record<string, string> {\n const values: Record<string, string> = {};\n\n for (const line of contents.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n\n const key = trimmed.slice(0, eq).trim();\n let value = trimmed.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n\n values[key] = value;\n }\n\n return values;\n}\n\nexport function loadProjectEnv(fromDir = process.cwd()): void {\n if (loaded) {\n return;\n }\n\n loaded = true;\n\n let envPath: string;\n try {\n envPath = join(resolveProjectRoot(fromDir), \".env\");\n } catch {\n return;\n }\n\n if (!existsSync(envPath)) {\n return;\n }\n\n for (const [key, value] of Object.entries(parseEnvFile(readFileSync(envPath, \"utf8\")))) {\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n}\n\nexport function resetProjectEnvLoadedForTests(): void {\n loaded = false;\n}\n","import { envRefName, isEnvRef } from \"../../project/env-ref\";\nimport { loadProjectEnv } from \"../../project/load-project-env\";\n\nexport function parseCredentialValueFields(fields: string[]): Record<string, string> {\n const value: Record<string, string> = {};\n\n for (const field of fields) {\n const separatorIndex = field.indexOf(\"=\");\n if (separatorIndex <= 0) {\n throw new Error(`Invalid --set value: ${field}`);\n }\n\n const key = field.slice(0, separatorIndex);\n let rawValue = field.slice(separatorIndex + 1);\n\n if (isEnvRef(rawValue)) {\n const envName = envRefName(rawValue);\n if (process.env[envName] === undefined) {\n loadProjectEnv();\n }\n rawValue = process.env[envName] ?? \"\";\n if (!rawValue) {\n throw new Error(`Environment variable ${envName} is not set`);\n }\n }\n\n value[key] = rawValue;\n }\n\n if (Object.keys(value).length === 0) {\n throw new Error(\"At least one --set field is required\");\n }\n\n return value;\n}\n\nexport function scopeTypeFromCli(scope: string): \"organization\" | \"user\" | \"project\" | \"global\" {\n switch (scope) {\n case \"org\":\n return \"organization\";\n case \"user\":\n return \"user\";\n case \"project\":\n return \"project\";\n case \"global\":\n return \"global\";\n default:\n throw new Error(`Unknown scope \"${scope}\". Expected org, user, project, or global.`);\n }\n}\n","import type { Command } from \"commander\";\nimport { parseCredentialValueFields } from \"./parse-value\";\nimport { buildPlatformUpdatePatch, runCredentialsCommand } from \"./run-credentials\";\n\nexport function registerCredentialsRotateKeyCommand(credentials: Command): void {\n credentials\n .command(\"rotate-key\")\n .description(\"Rotate an api_key credential secret\")\n .argument(\"<id>\", \"Credential instance id\")\n .requiredOption(\n \"--set <field>\",\n \"Credential field as key=value or key=@env:VAR\",\n collectSetValues,\n [],\n )\n .action(\n (\n id: string,\n options: {\n set: string[];\n },\n ) =>\n runCredentialsCommand(\"Rotate credential key failed\", async ({ platform, local }) => {\n const value = parseCredentialValueFields(options.set);\n\n if (local) {\n throw new Error(\n \"credentials rotate-key requires the platform API target (omit --local)\",\n );\n }\n\n const patch = buildPlatformUpdatePatch({ value });\n const credential = await platform!.credentials.update(id, patch);\n process.stdout.write(`${JSON.stringify({ credential }, null, 2)}\\n`);\n }),\n );\n}\n\nfunction collectSetValues(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n","import type { CredentialScopeType } from \"@keystrokehq/shared\";\nimport type { KeystrokeClient } from \"@keystrokehq/sdk\";\nimport { cliBinaryName } from \"../../errors\";\n\ntype ConflictInstance = {\n id: string;\n label: string | null;\n isDefault: boolean;\n};\n\nfunction describeInstance(instance: ConflictInstance): string {\n const defaultStatus = instance.isDefault ? \"default\" : \"not default\";\n const labelStatus = instance.label ? `label: ${instance.label}` : \"no label\";\n return `id: ${instance.id}, ${defaultStatus}, ${labelStatus}`;\n}\n\nfunction formatSetFields(setFields: string[]): string {\n return setFields.map((field) => `--set ${field}`).join(\" \");\n}\n\nfunction formatSetConflictError(args: {\n key: string;\n scope: string;\n setFields: string[];\n matching: ConflictInstance[];\n}): string {\n const binary = cliBinaryName();\n const setArgs = formatSetFields(args.setFields);\n const listCmd = `${binary} credentials list --key ${args.key}`;\n const addSecondCmd = `${binary} credentials set ${args.key} --scope ${args.scope} --label <name> ${setArgs}`;\n\n if (args.matching.length === 1) {\n const instance = args.matching[0]!;\n const updateCmd = `${binary} credentials update ${instance.id} ${setArgs}`;\n\n return [\n `An ${args.key} credential already exists in ${args.scope} scope (${describeInstance(instance)}).`,\n \"credentials set creates a new instance — it does not update an existing one.\",\n \"To update the existing credential:\",\n ` ${updateCmd}`,\n \"To add a second credential in the same scope:\",\n ` ${addSecondCmd}`,\n `List instances: ${listCmd}`,\n ].join(\"\\n\");\n }\n\n const instanceLines = args.matching.map((instance) => ` • ${describeInstance(instance)}`);\n\n return [\n `Multiple ${args.key} credentials already exist in ${args.scope} scope. --label is required to add another:`,\n ...instanceLines,\n \"To add another credential in the same scope:\",\n ` ${addSecondCmd}`,\n `List instances: ${listCmd}`,\n ].join(\"\\n\");\n}\n\nexport async function assertNoSetConflict(\n client: KeystrokeClient,\n args: {\n key: string;\n scope: string;\n scopeType: CredentialScopeType;\n projectId?: string;\n label?: string;\n setFields: string[];\n },\n): Promise<void> {\n if (args.label) {\n return;\n }\n\n const { instances } = await client.credentials.listInstances({ key: args.key });\n const matching = instances.filter(\n (instance) =>\n instance.scopeType === args.scopeType &&\n (args.scopeType !== \"project\" || instance.scopeId === args.projectId),\n );\n\n if (matching.length === 0) {\n return;\n }\n\n throw new Error(\n formatSetConflictError({\n key: args.key,\n scope: args.scope,\n setFields: args.setFields,\n matching,\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { createCliClient } from \"../../client\";\nimport { createCliConfig } from \"../../config\";\nimport { resolveApiTarget } from \"../../resolve-api-target\";\nimport { getCliTargetOptions } from \"../../target-options\";\nimport { assertNoSetConflict } from \"./format-set-conflict-error\";\nimport { parseCredentialValueFields, scopeTypeFromCli } from \"./parse-value\";\nimport { resolveCredentialsTargetOptions } from \"./target-options\";\nimport {\n buildPlatformCreateRequest,\n buildPlatformUpdatePatch,\n runCredentialsCommand,\n} from \"./run-credentials\";\n\nexport function registerCredentialsSetCommand(credentials: Command): void {\n credentials\n .command(\"set\")\n .description(\"Create a new api_key credential instance\")\n .argument(\"<key>\", \"Credential key or app id, e.g. exa\")\n .requiredOption(\"--scope <scope>\", \"org, user, project, or global\")\n .option(\"--project-id <id>\", \"Project id when scope is project\")\n .option(\"--label <label>\", \"Human-readable label within the scope\")\n .option(\"--default\", \"Mark as default for this scope\")\n .option(\n \"--set <field>\",\n \"Credential field as key=value or key=@env:VAR (falls back to project .env when unset in shell)\",\n collectSetValues,\n [],\n )\n .action(\n (\n key: string,\n options: {\n scope: string;\n projectId?: string;\n label?: string;\n default?: boolean;\n set: string[];\n },\n ) =>\n runCredentialsCommand(\"Set credential failed\", async ({ platform, local }) => {\n const value = parseCredentialValueFields(options.set);\n const scopeType = scopeTypeFromCli(options.scope);\n\n if (scopeType === \"project\" && !options.projectId) {\n throw new Error(\"--project-id is required when scope is project\");\n }\n\n if (local) {\n const config = createCliConfig();\n const target = await resolveApiTarget(config, {\n ...getCliTargetOptions(),\n ...resolveCredentialsTargetOptions({\n scopeType,\n projectId: options.projectId,\n }),\n });\n const client = createCliClient(config, {\n baseUrl: target.baseUrl,\n platform: target.mode === \"platform\",\n });\n\n await assertNoSetConflict(client, {\n key,\n scope: options.scope,\n scopeType,\n projectId: options.projectId,\n label: options.label,\n setFields: options.set,\n });\n\n const result = await client.credentials.createInstance({\n key,\n scopeType,\n scopeId: scopeType === \"project\" ? options.projectId! : undefined,\n label: options.label,\n isDefault: options.default,\n value,\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n return;\n }\n\n if (options.scope === \"global\") {\n throw new Error(\"global scope is only supported against a local keystroke server\");\n }\n\n const created = await platform!.credentials.create(\n buildPlatformCreateRequest({\n appId: key,\n value,\n scope: options.scope,\n projectId: options.projectId,\n }),\n );\n\n if (options.label !== undefined || options.default !== undefined) {\n const patch = buildPlatformUpdatePatch({\n ...(options.label !== undefined ? { label: options.label } : {}),\n ...(options.default !== undefined ? { isDefault: options.default } : {}),\n });\n for (const credential of created) {\n const updated = await platform!.credentials.update(credential.id, patch);\n process.stdout.write(`${JSON.stringify({ credential: updated }, null, 2)}\\n`);\n }\n return;\n }\n\n process.stdout.write(`${JSON.stringify({ credentials: created }, null, 2)}\\n`);\n }),\n );\n}\n\nfunction collectSetValues(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n","import type { Command } from \"commander\";\nimport { createCliClient } from \"../../client\";\nimport { createCliConfig } from \"../../config\";\nimport { resolveApiTarget } from \"../../resolve-api-target\";\nimport { getCliTargetOptions } from \"../../target-options\";\nimport { parseCredentialValueFields } from \"./parse-value\";\nimport { resolveCredentialsTargetOptions } from \"./target-options\";\nimport { buildPlatformUpdatePatch, runCredentialsCommand } from \"./run-credentials\";\n\nexport function registerCredentialsUpdateCommand(credentials: Command): void {\n credentials\n .command(\"update\")\n .description(\"Update a credential instance\")\n .argument(\"<id>\", \"Credential instance id\")\n .option(\"--label <label>\", \"Human-readable label within the scope\")\n .option(\"--default\", \"Mark as default for this scope\")\n .option(\"--set <field>\", \"Credential field as key=value or key=@env:VAR\", collectSetValues, [])\n .action(\n (\n id: string,\n options: {\n label?: string;\n default?: boolean;\n set: string[];\n },\n ) =>\n runCredentialsCommand(\"Update credential failed\", async ({ platform, local }) => {\n const value =\n options.set.length > 0 ? parseCredentialValueFields(options.set) : undefined;\n\n if (local) {\n const config = createCliConfig();\n const target = await resolveApiTarget(config, {\n ...getCliTargetOptions(),\n ...resolveCredentialsTargetOptions(),\n });\n const client = createCliClient(config, {\n baseUrl: target.baseUrl,\n platform: target.mode === \"platform\",\n });\n const result = await client.credentials.updateInstance(id, {\n ...(options.label !== undefined ? { label: options.label } : {}),\n ...(options.default !== undefined ? { isDefault: options.default } : {}),\n ...(value ? { value } : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n return;\n }\n\n const patch = buildPlatformUpdatePatch({\n ...(options.label !== undefined ? { label: options.label } : {}),\n ...(options.default !== undefined ? { isDefault: options.default } : {}),\n ...(value ? { value } : {}),\n });\n const credential = await platform!.credentials.update(id, patch);\n process.stdout.write(`${JSON.stringify({ credential }, null, 2)}\\n`);\n }),\n );\n}\n\nfunction collectSetValues(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n","import type { Command } from \"commander\";\nimport { registerCredentialsDeleteCommand } from \"./delete\";\nimport { registerCredentialsGetCommand } from \"./get\";\nimport { registerCredentialsListCommand } from \"./list\";\nimport { registerCredentialsRotateKeyCommand } from \"./rotate-key\";\nimport { registerCredentialsSetCommand } from \"./set\";\nimport { registerCredentialsUpdateCommand } from \"./update\";\n\nexport function registerCredentialsCommand(program: Command): void {\n const credentials = program\n .command(\"credentials\")\n .description(\"Manage platform app credentials and local api_key instances\");\n\n registerCredentialsListCommand(credentials);\n registerCredentialsGetCommand(credentials);\n registerCredentialsSetCommand(credentials);\n registerCredentialsUpdateCommand(credentials);\n registerCredentialsRotateKeyCommand(credentials);\n registerCredentialsDeleteCommand(credentials);\n}\n","import type Conf from \"conf\";\nimport type { CliConfig } from \"../config\";\nimport { getPlatformUrl } from \"../config\";\nimport {\n DEFAULT_PLATFORM_URL,\n DEFAULT_WEB_URL,\n resolvePlatformUrlForWebUrl,\n} from \"../resolve-platform-url\";\n\nexport type AuthLoginTargetOptions = {\n webUrl?: string;\n platformUrl?: string;\n};\n\nexport function resolveAuthLoginTargets(\n options: AuthLoginTargetOptions,\n config: Conf<CliConfig>,\n): { webUrl: string; platformUrl: string } {\n const webUrl = options.webUrl ?? DEFAULT_WEB_URL;\n const platformUrl = resolvePlatformUrlForWebUrl(webUrl, {\n platformUrl: options.platformUrl,\n fallback: options.webUrl ? getPlatformUrl(config) : DEFAULT_PLATFORM_URL,\n });\n\n return { webUrl, platformUrl };\n}\n","import type { Command } from \"commander\";\nimport { CLI_CLIENT_ID, getSessionWithBearer, runDeviceLogin } from \"@keystrokehq/auth/cli\";\nimport { setAccessToken } from \"../../auth/credentials\";\nimport { openUrl } from \"../../auth/open-url\";\nimport { resolveAuthLoginTargets } from \"../../auth/resolve-login-targets\";\nimport { createCliConfig } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { syncActiveOrganizationAfterLogin } from \"../../organization/active-organization\";\n\ntype LoginOptions = {\n webUrl?: string;\n platformUrl?: string;\n org?: string;\n};\n\nexport function registerAuthLoginCommand(auth: Command): void {\n auth\n .command(\"login\")\n .description(\"Authenticate via browser device flow\")\n .option(\n \"--web-url <url>\",\n \"Web dashboard origin (omit to use production defaults; local dev: http://localhost:3000)\",\n )\n .option(\"--platform-url <url>\", \"Platform API origin (derived from web URL when omitted)\")\n .option(\"--org <slug>\", \"Active organization slug (overrides browser default)\")\n .action(async (options: LoginOptions) => {\n const config = createCliConfig();\n const { webUrl, platformUrl } = resolveAuthLoginTargets(options, config);\n\n config.set(\"webUrl\", webUrl);\n config.set(\"platformUrl\", platformUrl);\n\n try {\n const result = await runDeviceLogin({\n baseURL: platformUrl,\n clientId: CLI_CLIENT_ID,\n openUrl,\n });\n\n setAccessToken(platformUrl, result.accessToken);\n\n const user = await getSessionWithBearer(platformUrl, result.accessToken);\n const membership = await syncActiveOrganizationAfterLogin(config, {\n organizationRef: options.org,\n deviceOrganizationId: result.organizationId,\n });\n\n if (user) {\n process.stdout.write(\n `Logged in as ${user.name} (${user.email}) — organization ${membership.organization.name}\\n`,\n );\n } else {\n process.stdout.write(\n `Logged in to ${webUrl} — organization ${membership.organization.name}\\n`,\n );\n }\n } catch (error) {\n process.stderr.write(`${formatCliError(error, \"Login failed\", { webUrl, platformUrl })}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { clearAccessToken } from \"../../auth/credentials\";\nimport { createCliConfig, getPlatformUrl, getWebUrl } from \"../../config\";\n\ntype LogoutOptions = {\n webUrl?: string;\n};\n\nexport function registerAuthLogoutCommand(auth: Command): void {\n auth\n .command(\"logout\")\n .description(\"Clear stored credentials\")\n .option(\"--web-url <url>\", \"Web dashboard origin (default from config)\")\n .action((options: LogoutOptions) => {\n const config = createCliConfig();\n const webUrl = options.webUrl ?? getWebUrl(config);\n const platformUrl = getPlatformUrl(config);\n clearAccessToken(platformUrl);\n process.stdout.write(`${JSON.stringify({ authenticated: false, webUrl, platformUrl })}\\n`);\n });\n}\n","import { getSessionWithBearer } from \"@keystrokehq/auth/cli\";\nimport type { Command } from \"commander\";\nimport { getAccessToken } from \"../../auth/credentials\";\nimport { createCliConfig, getPlatformUrl, getWebUrl } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { listOrganizations } from \"../../organization/active-organization\";\n\ntype StatusOptions = {\n webUrl?: string;\n};\n\nexport function registerAuthStatusCommand(auth: Command): void {\n auth\n .command(\"status\")\n .description(\"Show authentication status\")\n .option(\"--web-url <url>\", \"Web dashboard origin (default from config)\")\n .action(async (options: StatusOptions) => {\n const config = createCliConfig();\n const webUrl = options.webUrl ?? getWebUrl(config);\n const platformUrl = getPlatformUrl(config);\n const token = getAccessToken(platformUrl);\n\n if (!token) {\n process.stdout.write(`${JSON.stringify({ authenticated: false, webUrl, platformUrl })}\\n`);\n return;\n }\n\n try {\n const user = await getSessionWithBearer(platformUrl, token);\n const organizations = user ? await listOrganizations(config).catch(() => []) : [];\n const activeOrganizationId = config.get(\"activeOrganizationId\");\n const activeOrganization = activeOrganizationId\n ? organizations.find((entry) => entry.organization.id === activeOrganizationId)\n : undefined;\n\n process.stdout.write(\n `${JSON.stringify({\n authenticated: user !== null,\n webUrl,\n user,\n activeOrganizationId: activeOrganizationId ?? null,\n activeOrganization: activeOrganization?.organization.name ?? null,\n })}\\n`,\n );\n\n if (!user) {\n process.exitCode = 1;\n }\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Status check failed\", { webUrl, platformUrl })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { registerAuthLoginCommand } from \"./login\";\nimport { registerAuthLogoutCommand } from \"./logout\";\nimport { registerAuthStatusCommand } from \"./status\";\n\nexport function registerAuthCommand(program: Command): void {\n const auth = program.command(\"auth\").description(\"Authenticate with an keystroke deployment\");\n\n registerAuthLoginCommand(auth);\n registerAuthLogoutCommand(auth);\n registerAuthStatusCommand(auth);\n}\n","import type { Command } from \"commander\";\nimport { resolveProjectRoot } from \"../project/resolve-project-root\";\n\nexport function registerBuildCommand(program: Command): void {\n program\n .command(\"build\")\n .description(\"Build the keystroke project for production\")\n .option(\"--dir <path>\", \"Project directory\", process.cwd())\n .action(async (options) => {\n try {\n const root = resolveProjectRoot(options.dir);\n const { buildApp } = await import(\"@keystrokehq/build\");\n await buildApp({ root });\n process.stdout.write(`Built ${root}\\n`);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Build failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import { spawnSync } from \"node:child_process\";\nimport { existsSync, mkdtempSync, readFileSync, rmSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n//#region src/pack-artifact.ts\n/** Pack `dist/` into a gzip tarball suitable for `/app` extraction in the project server image. */\nfunction packProjectArtifact(projectRoot) {\n\tif (!existsSync(join(projectRoot, \"dist\"))) throw new Error(\"dist/ not found — run keystroke build first\");\n\tconst tempDir = mkdtempSync(join(tmpdir(), \"keystroke-artifact-\"));\n\tconst archivePath = join(tempDir, \"artifact.tgz\");\n\ttry {\n\t\tconst result = spawnSync(\"tar\", [\n\t\t\t\"-czf\",\n\t\t\tarchivePath,\n\t\t\t\"--exclude=._*\",\n\t\t\t\"--exclude=.DS_Store\",\n\t\t\t\"-C\",\n\t\t\tprojectRoot,\n\t\t\t\"dist\"\n\t\t], {\n\t\t\tencoding: \"utf8\",\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\tCOPYFILE_DISABLE: \"1\"\n\t\t\t}\n\t\t});\n\t\tif (result.status !== 0) throw new Error(result.stderr?.trim() || \"Failed to pack project artifact\");\n\t\treturn readFileSync(archivePath);\n\t} finally {\n\t\trmSync(tempDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\nexport { packProjectArtifact };\n\n//# sourceMappingURL=pack-artifact.mjs.map","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { walkProject } from \"@keystrokehq/build/walk\";\nimport type { ProjectSourceFile } from \"@keystrokehq/shared\";\nimport { ROUTE_MANIFEST_REL_PATH } from \"@keystrokehq/shared\";\n\nexport type CollectedProjectSource = {\n files: ProjectSourceFile[];\n};\n\n/** Collect deploy source files via the shared project walk (for `--skip-build`). */\nexport function collectProjectSource(root: string): CollectedProjectSource {\n const manifestPath = join(root, ROUTE_MANIFEST_REL_PATH);\n if (!existsSync(manifestPath)) {\n throw new Error(\n `Route manifest missing at ${ROUTE_MANIFEST_REL_PATH}. Run keystroke build before deploy --skip-build.`,\n );\n }\n\n return { files: walkProject(root, { collectSources: true }).sourceFiles };\n}\n","import type { PlatformClient } from \"@keystrokehq/sdk/platform\";\nimport { packProjectArtifact } from \"@keystrokehq/storage/pack-artifact\";\nimport type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../config\";\nimport { selectActiveOrganization } from \"../organization/active-organization\";\nimport { createCliPlatformClient } from \"../platform-client\";\nimport { collectProjectSource, type CollectedProjectSource } from \"../project/collect-source\";\nimport { resolveProjectRoot } from \"../project/resolve-project-root\";\nimport { resolveActiveProjectId } from \"../resolve-project-target\";\n\nconst POLL_INTERVAL_MS = 2_000;\nconst DEPLOY_TIMEOUT_MS = 120_000;\nconst SOURCE_BLOB_CONTENT_TYPE = \"text/plain; charset=utf-8\";\n\n/**\n * Upload the project's source so the dashboard can render a read-only file\n * view. Content-addressed: only blobs the platform reports missing are PUT, so\n * unchanged files are never re-uploaded. The manifest (path -> hash) is sent\n * last and marks the snapshot complete.\n */\nasync function uploadProjectSourceSnapshot(\n client: PlatformClient,\n projectId: string,\n artifactId: string,\n source: CollectedProjectSource,\n): Promise<void> {\n const contentsByHash = new Map<string, string>();\n const blobsByHash = new Map<string, { hash: string; size: number }>();\n for (const file of source.files) {\n contentsByHash.set(file.hash, file.contents);\n if (!blobsByHash.has(file.hash)) {\n blobsByHash.set(file.hash, { hash: file.hash, size: Buffer.byteLength(file.contents) });\n }\n }\n\n const { uploads } = await client.artifacts.presignSource(projectId, artifactId, [\n ...blobsByHash.values(),\n ]);\n\n await Promise.all(\n uploads.map(async (upload) => {\n const contents = contentsByHash.get(upload.hash);\n if (contents === undefined) {\n return;\n }\n const response = await fetch(upload.url, {\n method: \"PUT\",\n body: contents,\n headers: { \"Content-Type\": SOURCE_BLOB_CONTENT_TYPE },\n });\n if (!response.ok) {\n throw new Error(`Source blob upload failed (${response.status})`);\n }\n }),\n );\n\n await client.artifacts.uploadManifest(projectId, artifactId, {\n files: source.files.map((file) => ({ path: file.path, hash: file.hash })),\n });\n}\n\ntype DeployOptions = {\n dir: string;\n projectId: string;\n skipBuild?: boolean;\n};\n\nasync function sleep(ms: number): Promise<void> {\n await new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport async function runDeploy(options: DeployOptions): Promise<void> {\n const root = resolveProjectRoot(options.dir);\n const config = createCliConfig();\n const client = createCliPlatformClient(config);\n\n let source: CollectedProjectSource;\n if (!options.skipBuild) {\n const { buildApp } = await import(\"@keystrokehq/build\");\n const result = await buildApp({ root, collectSources: true, emitManifest: true });\n source = { files: result.sourceFiles };\n } else {\n source = collectProjectSource(root);\n }\n\n const archive = packProjectArtifact(root);\n\n let active = await client.organizations.getActive();\n if (!active) {\n active = await selectActiveOrganization(config);\n }\n\n client.setActiveOrganizationId(active.organization.id);\n\n const project = await client.projects.get(options.projectId);\n\n const created = await client.artifacts.create(project.id);\n\n // Upload the runtime tarball and the source snapshot in parallel. Source\n // powers the dashboard's read-only file views; a failure there must not block\n // the deploy, so it only warns.\n const uploadPromise = fetch(created.uploadUrl, {\n method: \"PUT\",\n body: archive,\n headers: {\n \"Content-Type\": \"application/gzip\",\n },\n });\n const sourcePromise = uploadProjectSourceSnapshot(\n client,\n project.id,\n created.artifact.id,\n source,\n ).catch((error: unknown) => {\n const message = error instanceof Error ? error.message : \"unknown error\";\n process.stderr.write(`Warning: failed to upload project source files: ${message}\\n`);\n });\n\n const upload = await uploadPromise;\n await sourcePromise;\n\n if (!upload.ok) {\n throw new Error(`Artifact upload failed (${upload.status})`);\n }\n\n const completed = await client.artifacts.complete(project.id, created.artifact.id);\n process.stdout.write(`Deploy ${completed.artifact.id} uploaded\\n`);\n\n const deadline = Date.now() + DEPLOY_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const current = await client.projects.get(project.id);\n if (current.status === \"active\") {\n config.set(\"activeProjectId\", project.id);\n config.set(\"apiTarget\", \"platform\");\n process.stdout.write(`Project active${current.baseUrl ? `: ${current.baseUrl}` : \"\"}\\n`);\n return;\n }\n\n if (current.status === \"failed\") {\n throw new Error(current.lastError ?? \"Project runtime failed\");\n }\n\n await sleep(POLL_INTERVAL_MS);\n }\n\n throw new Error(\"Timed out waiting for project to become active\");\n}\n\nexport function registerDeployCommand(program: Command): void {\n program\n .command(\"deploy\")\n .description(\"Build, upload, and deploy the project to the platform\")\n .option(\"--dir <path>\", \"Project directory\", process.cwd())\n .option(\"--skip-build\", \"Upload the existing dist/ without rebuilding\")\n .action(async (options) => {\n try {\n const config = createCliConfig();\n const projectId = await resolveActiveProjectId(config);\n if (!projectId) {\n throw new Error(\"Usage: keystroke deploy --project <slug>\");\n }\n\n await runDeploy({\n dir: options.dir,\n projectId,\n skipBuild: options.skipBuild,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Deploy failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","/** Strip dev-only Node flags so the API child loads built `dist/`, not package `src/`. */\nexport function runtimeChildNodeOptions(nodeOptions: string | undefined): string | undefined {\n if (!nodeOptions?.trim()) {\n return undefined;\n }\n\n const parts = nodeOptions.trim().split(/\\s+/);\n const cleaned: string[] = [];\n\n for (let index = 0; index < parts.length; index++) {\n const part = parts[index]!;\n if (part === \"--conditions=development\") {\n continue;\n }\n if (part === \"--conditions\" && parts[index + 1] === \"development\") {\n index++;\n continue;\n }\n cleaned.push(part);\n }\n\n const result = cleaned.join(\" \").trim();\n return result || undefined;\n}\n\nexport function runtimeChildEnv(\n parentEnv: NodeJS.ProcessEnv,\n overrides: Record<string, string>,\n): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = { ...parentEnv, ...overrides };\n delete env.KEYSTROKE_DEV;\n\n const nodeOptions = runtimeChildNodeOptions(env.NODE_OPTIONS);\n if (nodeOptions) {\n env.NODE_OPTIONS = nodeOptions;\n } else {\n delete env.NODE_OPTIONS;\n }\n\n // Local project API — sqlite only; Infisical POSTGRES_* is for platform/orchestrator.\n for (const key of [\n \"POSTGRES_HOST\",\n \"POSTGRES_PORT\",\n \"POSTGRES_DB\",\n \"POSTGRES_USER\",\n \"POSTGRES_PASSWORD\",\n \"DATABASE_SEARCH_PATH\",\n ]) {\n delete env[key];\n }\n if (!env.DATABASE_URL?.trim()) {\n env.DATABASE_URL = \"file:./data/dev.db\";\n }\n\n return env;\n}\n","import { pathToFileURL } from \"node:url\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { listenPortFromPublicUrl } from \"@keystrokehq/shared\";\nimport { runtimeChildEnv } from \"./runtime-child-env\";\n\nexport type BootstrapRunOptions = {\n root: string;\n runtimeNodeModules: string;\n apiPort: number;\n};\n\nexport type BootstrapRun = {\n cwd: string;\n args: string[];\n env: NodeJS.ProcessEnv;\n};\n\n/** Node args + env for `@keystrokehq/build` bootstrap (shared by start + dev). */\nexport async function resolveBootstrapRun(options: BootstrapRunOptions): Promise<BootstrapRun> {\n const { resolveRuntimeBuildArtifact } = await import(\"@keystrokehq/build\");\n const loader = pathToFileURL(\n resolveRuntimeBuildArtifact(options.runtimeNodeModules, \"dist/runtime-loader.mjs\"),\n ).href;\n const bootstrap = resolveRuntimeBuildArtifact(options.runtimeNodeModules, \"dist/bootstrap.mjs\");\n\n const args: string[] = [`--import=${loader}`];\n const envFile = join(options.root, \".env\");\n\n if (existsSync(envFile)) {\n args.push(`--env-file=${envFile}`);\n }\n\n args.push(bootstrap);\n\n const childEnv = runtimeChildEnv(process.env, {\n KEYSTROKE_ROOT: options.root,\n KEYSTROKE_RUNTIME_NODE_MODULES: options.runtimeNodeModules,\n PROJECT_ID: process.env.PROJECT_ID ?? \"default\",\n });\n childEnv.PORT = String(listenPortFromPublicUrl(childEnv.PUBLIC_SERVER_URL, options.apiPort));\n\n return {\n cwd: options.root,\n args,\n env: childEnv,\n };\n}\n","import { spawn, type ChildProcess } from \"node:child_process\";\n\nexport type ManagedProcess = {\n name: string;\n child: ChildProcess;\n};\n\nexport function waitForExit(child: ChildProcess): Promise<number | null> {\n return new Promise((resolve) => {\n child.on(\"exit\", (code) => resolve(code ?? null));\n });\n}\n\nexport async function runUntilExit(processes: ManagedProcess[]): Promise<number | null> {\n const shutdown = (signal: NodeJS.Signals = \"SIGTERM\") => {\n for (const { child } of processes) {\n if (!child.killed && child.pid !== undefined) {\n child.kill(signal);\n }\n }\n };\n\n const onSignal = () => {\n shutdown(\"SIGINT\");\n process.exit(0);\n };\n\n process.on(\"SIGINT\", onSignal);\n process.on(\"SIGTERM\", onSignal);\n\n try {\n const results = await Promise.race(\n processes.map(async ({ name, child }) => {\n const code = await waitForExit(child);\n return { name, code };\n }),\n );\n\n if (results.code !== 0 && results.code !== null) {\n shutdown();\n throw new Error(`${results.name} exited with status ${results.code}`);\n }\n\n shutdown();\n return results.code;\n } finally {\n process.off(\"SIGINT\", onSignal);\n process.off(\"SIGTERM\", onSignal);\n }\n}\n\nexport function spawnNodeScript(options: {\n cwd: string;\n args: string[];\n env: NodeJS.ProcessEnv;\n}): ChildProcess {\n return spawn(\"node\", options.args, {\n cwd: options.cwd,\n env: options.env,\n stdio: \"inherit\",\n });\n}\n","import { spawnSync } from \"node:child_process\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\n\nconst NATIVE_PACKAGES = [\"better-sqlite3\"] as const;\n\nfunction isMissingBindingsError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(\"Could not locate the bindings file\");\n}\n\nfunction rebuildNativePackage(require: NodeRequire, pkg: string): void {\n const pkgDir = dirname(require.resolve(`${pkg}/package.json`));\n const npm = process.platform === \"win32\" ? \"npm.cmd\" : \"npm\";\n const result = spawnSync(npm, [\"run\", \"install\"], { cwd: pkgDir, stdio: \"inherit\" });\n\n if (result.status !== 0) {\n throw new Error(`Failed to build ${pkg} native bindings. Try: pnpm rebuild -g ${pkg}`);\n }\n}\n\n/** Compile native addons when pnpm skipped dependency install scripts (common on global install). */\nexport function ensureNativeDeps(nodeModulesRoot: string): void {\n const anchor = join(nodeModulesRoot, \"@keystrokehq\", \"server\", \"package.json\");\n const require = createRequire(anchor);\n\n for (const pkg of NATIVE_PACKAGES) {\n try {\n require(pkg);\n } catch (error) {\n if (!isMissingBindingsError(error)) {\n throw error;\n }\n\n process.stderr.write(`Building ${pkg} native bindings…\\n`);\n rebuildNativePackage(require, pkg);\n require(pkg);\n }\n }\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\n\n/** Directory whose `node_modules/@keystrokehq/server` ships with the CLI pack. */\nexport function resolveCliRuntimeNodeModules(cliRoot: string): string {\n let dir = cliRoot;\n\n while (dir !== dirname(dir)) {\n const nodeModules = join(dir, \"node_modules\");\n if (existsSync(join(nodeModules, \"@keystrokehq\", \"server\"))) {\n return nodeModules;\n }\n dir = dirname(dir);\n }\n\n throw new Error(\n \"Keystroke runtime packages are missing. Reinstall or repack the CLI (expected @keystrokehq/server in node_modules).\",\n );\n}\n","/**\n * `keystroke dev` — watch-build + API restart.\n *\n * NOT true hot reload. On src/ changes tsdown rebuilds dist/, then we stop and\n * boot the API again so route discovery picks up new agents/workflows/triggers.\n */\nimport type { Command } from \"commander\";\nimport type { ChildProcess } from \"node:child_process\";\nimport { createCliConfig, getConfigDir, getServerUrl } from \"../config\";\nimport { clearDevSession, writeDevSession } from \"../dev-session\";\nimport { resolveBootstrapRun } from \"../project/bootstrap-run\";\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\nimport { resolveProjectRoot } from \"../project/resolve-project-root\";\nimport { spawnNodeScript } from \"../process/run-processes\";\nimport { ensureNativeDeps } from \"../runtime/ensure-native-deps\";\nimport { resolveCliRuntimeNodeModules } from \"../runtime/resolve-runtime-node-modules\";\n\nconst DEV_BANNER = \"keystroke dev: watch rebuilds dist/ and restarts the API — not hot reload.\\n\";\n\ntype DevOptions = {\n dir: string;\n port?: number;\n};\n\nfunction stopChild(child: ChildProcess | undefined): void {\n if (child && !child.killed && child.pid !== undefined) {\n child.kill(\"SIGTERM\");\n }\n}\n\nfunction resolveDevServerUrl(\n config: ReturnType<typeof createCliConfig>,\n portOverride?: number,\n): string {\n const url = new URL(getServerUrl(config));\n if (portOverride !== undefined) {\n url.port = String(portOverride);\n }\n return url.origin;\n}\n\nexport async function runDev(options: DevOptions): Promise<void> {\n const root = resolveProjectRoot(options.dir);\n\n const runtimeNodeModules = resolveCliRuntimeNodeModules(resolveCliRoot(import.meta.url));\n ensureNativeDeps(runtimeNodeModules);\n\n const cliConfig = createCliConfig();\n const configDir = getConfigDir(cliConfig);\n\n process.stdout.write(DEV_BANNER);\n\n const serverUrl = resolveDevServerUrl(cliConfig, options.port);\n const apiPort = Number(new URL(serverUrl).port || 80);\n\n writeDevSession(\n {\n pid: process.pid,\n port: apiPort,\n root,\n serverUrl,\n },\n configDir,\n );\n\n let apiChild: ChildProcess | undefined;\n let restarting = false;\n let firstBoot = true;\n\n const restartApi = async () => {\n if (restarting) {\n return;\n }\n\n restarting = true;\n stopChild(apiChild);\n const bootstrap = await resolveBootstrapRun({\n root,\n runtimeNodeModules,\n apiPort,\n });\n apiChild = spawnNodeScript(bootstrap);\n\n if (firstBoot) {\n firstBoot = false;\n process.stdout.write(`API: ${serverUrl}\\n`);\n } else {\n process.stdout.write(\"API restarted after dist rebuild (not hot reload).\\n\");\n }\n\n restarting = false;\n };\n\n const shutdown = () => {\n clearDevSession(configDir);\n stopChild(apiChild);\n process.exit(0);\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n try {\n const { watchApp } = await import(\"@keystrokehq/build\");\n await watchApp({\n root,\n clean: false,\n onRebuild: restartApi,\n });\n } finally {\n process.off(\"SIGINT\", shutdown);\n process.off(\"SIGTERM\", shutdown);\n clearDevSession(configDir);\n stopChild(apiChild);\n }\n}\n\nexport function registerDevCommand(program: Command): void {\n program\n .command(\"dev\")\n .description(\"Watch src/, rebuild dist/, and restart the API (not true hot reload)\")\n .option(\"--dir <path>\", \"Project directory\", process.cwd())\n .option(\"--port <number>\", \"API port\", (value) => Number(value))\n .action(async (options) => {\n try {\n await runDev({\n dir: options.dir,\n port: options.port,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Dev failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import type Conf from \"conf\";\nimport type { PlatformClient } from \"@keystrokehq/sdk/platform\";\nimport type { CreateProjectRequest, Project, UpdateProjectRequest } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"../../config\";\nimport { cliBinaryName } from \"../../errors/command-input\";\nimport { selectActiveOrganization } from \"../../organization/active-organization\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { formatProjectLabel } from \"../../resolve-resource-ref\";\nimport { resolveProjectRef } from \"../../resolve-resource-ref\";\n\nexport async function withActivePlatformClient(\n config: Conf<CliConfig>,\n fn: (platform: PlatformClient) => Promise<void>,\n): Promise<void> {\n const platform = createCliPlatformClient(config);\n let active = await platform.organizations.getActive();\n if (!active) {\n active = await selectActiveOrganization(config);\n }\n\n platform.setActiveOrganizationId(active.organization.id);\n await fn(platform);\n}\n\nfunction writeInactiveDeployHints(projects: Pick<Project, \"slug\" | \"status\">[]): void {\n const bin = cliBinaryName();\n for (const project of projects) {\n if (project.status !== \"inactive\") {\n continue;\n }\n\n process.stderr.write(\n `Project ${formatProjectLabel(project)} is inactive. Deploy with: ${bin} deploy --project ${formatProjectLabel(project)}\\n`,\n );\n }\n}\n\nexport async function runProjectList(config: Conf<CliConfig>): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const projects = await platform.projects.list();\n process.stdout.write(`${JSON.stringify({ projects }, null, 2)}\\n`);\n\n if (projects.length === 0) {\n const bin = cliBinaryName();\n process.stderr.write(\n `No projects yet. Create one with: ${bin} project create --name \"My project\"\\n`,\n );\n return;\n }\n\n writeInactiveDeployHints(projects);\n });\n}\n\nexport async function runProjectMetrics(\n config: Conf<CliConfig>,\n options: { projectRef?: string },\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const metrics = await platform.projectMetrics.list();\n if (options.projectRef === undefined) {\n process.stdout.write(`${JSON.stringify(metrics, null, 2)}\\n`);\n return;\n }\n\n const project = await resolveProjectRef(platform, options.projectRef);\n const output = Object.fromEntries(\n Object.entries(metrics).filter(([projectId]) => projectId === project.id),\n );\n process.stdout.write(`${JSON.stringify(output, null, 2)}\\n`);\n });\n}\n\nexport async function runProjectDeploymentsList(\n config: Conf<CliConfig>,\n options: { projectRef: string },\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const project = await resolveProjectRef(platform, options.projectRef);\n const deployments = await platform.deployments.listForProject(project.id);\n process.stdout.write(`${JSON.stringify({ deployments }, null, 2)}\\n`);\n });\n}\n\nexport async function runProjectCreate(\n config: Conf<CliConfig>,\n input: CreateProjectRequest,\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const project = await platform.projects.create(input);\n process.stdout.write(`${JSON.stringify({ project }, null, 2)}\\n`);\n writeInactiveDeployHints([project]);\n });\n}\n\nexport type UpdateProjectCommandInput = {\n projectId: string;\n} & UpdateProjectRequest;\n\nexport async function runProjectUpdate(\n config: Conf<CliConfig>,\n input: UpdateProjectCommandInput,\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const { projectId, ...patch } = input;\n const project = await platform.projects.update(projectId, patch);\n process.stdout.write(`${JSON.stringify({ project }, null, 2)}\\n`);\n });\n}\n\nexport async function runProjectDelete(config: Conf<CliConfig>, projectId: string): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n await platform.projects.delete(projectId);\n process.stdout.write(`${JSON.stringify({ deleted: projectId }, null, 2)}\\n`);\n });\n}\n","import type Conf from \"conf\";\nimport type { HistoryRunListQuery } from \"@keystrokehq/sdk/platform\";\n\nimport type { CliConfig } from \"../../config\";\nimport { withActivePlatformClient } from \"../project/run-project\";\n\nexport async function runHistoryList(\n config: Conf<CliConfig>,\n filters?: HistoryRunListQuery,\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const runs = await platform.history.list(filters);\n process.stdout.write(`${JSON.stringify(runs, null, 2)}\\n`);\n });\n}\n\nexport async function runHistoryGet(config: Conf<CliConfig>, runId: string): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const run = await platform.history.get(runId);\n process.stdout.write(`${JSON.stringify(run, null, 2)}\\n`);\n });\n}\n\nexport async function runHistoryCancel(config: Conf<CliConfig>, runId: string): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const run = await platform.history.cancel(runId);\n process.stdout.write(`${JSON.stringify(run, null, 2)}\\n`);\n });\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { getPlatformUrl, getWebUrl } from \"../../config\";\nimport { runHistoryCancel, runHistoryGet, runHistoryList } from \"./run-history\";\n\nexport function registerHistoryCommand(program: Command): void {\n const history = program\n .command(\"history\")\n .description(\"List, inspect, and cancel platform run history\");\n\n history\n .command(\"list\")\n .description(\"List runs across projects in the active organization\")\n .option(\"--project <id>\", \"Filter by project id\")\n .option(\n \"--status <status>\",\n \"Filter by status (pending, running, sleeping, waiting_hook, completed, failed, canceled)\",\n )\n .option(\"--kind <kind>\", \"Filter by kind (workflow or agent)\")\n .action(async (options: { project?: string; status?: string; kind?: string }) => {\n const config = createCliConfig();\n try {\n await runHistoryList(config, {\n ...(options.project ? { project: options.project } : {}),\n ...(options.status\n ? {\n status: options.status as\n | \"pending\"\n | \"running\"\n | \"sleeping\"\n | \"waiting_hook\"\n | \"completed\"\n | \"failed\"\n | \"canceled\",\n }\n : {}),\n ...(options.kind ? { kind: options.kind as \"workflow\" | \"agent\" } : {}),\n });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"List history failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n history\n .command(\"get\")\n .description(\"Get run details\")\n .argument(\"<runId>\", \"Run id\")\n .action(async (runId: string) => {\n const config = createCliConfig();\n try {\n await runHistoryGet(config, runId);\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Get history run failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n history\n .command(\"cancel\")\n .description(\"Cancel a pending workflow run\")\n .argument(\"<runId>\", \"Run id\")\n .action(async (runId: string) => {\n const config = createCliConfig();\n try {\n await runHistoryCancel(config, runId);\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Cancel history run failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { runCliCommand } from \"../errors\";\n\nexport function registerHealthCommand(program: Command): void {\n program\n .command(\"health\")\n .description(\"Check connectivity to the keystroke API\")\n .action(() =>\n runCliCommand(\"Health check failed\", async ({ client }) => {\n const result = await client.health.check();\n process.stdout.write(`${JSON.stringify(result)}\\n`);\n }),\n );\n}\n","const KEBAB_CASE = /^[a-z][a-z0-9-]*$/;\nconst HAS_EMOJI = /\\p{Extended_Pictographic}/u;\nconst HAS_UPPERCASE = /[A-Z]/;\nconst HAS_WHITESPACE = /\\s/;\nconst HAS_UNDERSCORE = /_/;\n\nconst EXAMPLE = \"my-keystroke\";\nconst RULES = \"Use lowercase letters, numbers, and hyphens only\";\n\nfunction projectNameValidationError(name: string): string {\n if (HAS_UPPERCASE.test(name)) {\n return `Project name must be lowercase (${RULES}; e.g. ${EXAMPLE})`;\n }\n if (HAS_WHITESPACE.test(name)) {\n return `Project name cannot contain spaces (${RULES}; e.g. ${EXAMPLE})`;\n }\n if (HAS_UNDERSCORE.test(name)) {\n return `Project name cannot contain underscores (${RULES}; e.g. ${EXAMPLE})`;\n }\n if (HAS_EMOJI.test(name)) {\n return `Project name cannot contain emojis (${RULES}; e.g. ${EXAMPLE})`;\n }\n if (/[^a-z0-9-]/.test(name)) {\n return `Project name cannot contain special characters (${RULES}; e.g. ${EXAMPLE})`;\n }\n if (!/^[a-z]/.test(name)) {\n return `Project name must start with a lowercase letter (e.g. ${EXAMPLE})`;\n }\n return `Project name must be kebab-case (${RULES}; e.g. ${EXAMPLE})`;\n}\n\nexport function assertProjectName(name: string): string {\n const trimmed = name.trim();\n if (!trimmed) {\n throw new Error(\"Project name is required\");\n }\n\n if (!KEBAB_CASE.test(trimmed)) {\n throw new Error(projectNameValidationError(trimmed));\n }\n\n return trimmed;\n}\n\nexport function projectNameFromDirectory(directory: string): string {\n const base = directory.split(/[/\\\\]/).filter(Boolean).at(-1) ?? directory;\n return assertProjectName(base);\n}\n","import { confirm, input } from \"@inquirer/prompts\";\nimport { resolve } from \"node:path\";\nimport { assertProjectName, projectNameFromDirectory } from \"./project-name\";\nimport type { InitOptions } from \"./types\";\n\nexport type InitPromptResult = {\n projectName: string;\n targetDir: string;\n};\n\nexport async function promptInitOptions(options: InitOptions): Promise<InitPromptResult> {\n const defaultName =\n options.name ??\n (options.directory ? projectNameFromDirectory(options.directory) : \"my-keystroke\");\n\n const projectName = assertProjectName(\n options.name ??\n (await input({\n message: \"Project name\",\n default: defaultName,\n validate: (value) => {\n try {\n assertProjectName(value);\n return true;\n } catch (error) {\n return error instanceof Error ? error.message : \"Invalid project name\";\n }\n },\n })),\n );\n\n const targetDir = resolve(\n options.directory ??\n (await input({\n message: \"Project directory\",\n default: `./${projectName}`,\n })),\n );\n\n return { projectName, targetDir };\n}\n\nexport async function confirmTargetDir(targetDir: string): Promise<boolean> {\n return confirm({\n message: `Directory \"${targetDir}\" is not empty. Continue and merge files?`,\n default: false,\n });\n}\n","// Generated by scripts/generate-catalog-versions.ts — do not edit.\n// Baked when @keystrokehq/cli is built and bundled into the published CLI; keystroke init\n// substitutes {{catalog:*}} from this map without reading the monorepo pnpm-workspace.yaml.\nexport const INIT_CATALOG_DEPS = [\"zod\", \"oxlint\", \"typescript\", \"vitest\", \"@types/node\"] as const;\n\nexport const INIT_CATALOG_VERSIONS = {\n zod: \"^4.4.3\",\n oxlint: \"^1.66.0\",\n typescript: \"^6.0.3\",\n vitest: \"^4.1.7\",\n \"@types/node\": \"^25.9.1\",\n} as const satisfies Record<(typeof INIT_CATALOG_DEPS)[number], string>;\n","import { readdir, readFile, stat, writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { INIT_CATALOG_VERSIONS } from \"./catalog-versions\";\n\nexport type TemplateVariables = {\n projectName: string;\n version: string;\n};\n\nfunction renderTemplate(content: string, variables: TemplateVariables): string {\n let rendered = content\n .replaceAll(\"{{projectName}}\", variables.projectName)\n .replaceAll(\"{{version}}\", variables.version);\n\n for (const [dep, version] of Object.entries(INIT_CATALOG_VERSIONS)) {\n rendered = rendered.replaceAll(`{{catalog:${dep}}}`, version);\n }\n\n return rendered;\n}\n\nasync function copyEntry(\n sourcePath: string,\n targetPath: string,\n variables: TemplateVariables,\n): Promise<void> {\n const info = await stat(sourcePath);\n\n if (info.isDirectory()) {\n await mkdir(targetPath, { recursive: true });\n const entries = await readdir(sourcePath);\n\n for (const entry of entries) {\n await copyEntry(join(sourcePath, entry), join(targetPath, entry), variables);\n }\n\n return;\n }\n\n await mkdir(dirname(targetPath), { recursive: true });\n const content = await readFile(sourcePath, \"utf8\");\n await writeFile(targetPath, renderTemplate(content, variables));\n}\n\nexport async function copyTemplate(\n templateDir: string,\n targetDir: string,\n variables: TemplateVariables,\n): Promise<void> {\n await copyEntry(templateDir, targetDir, variables);\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\n\nexport function resolveTemplateDir(templateName: string, fromModuleUrl = import.meta.url): string {\n const cliRoot = resolveCliRoot(fromModuleUrl);\n // Check source first so contributors editing `templates/` see their changes\n // without rebuilding the CLI. End users don't have `templates/` (only `dist/`\n // ships), so the fallback is what they hit.\n const candidates = [\n join(cliRoot, \"templates\", templateName),\n join(cliRoot, \"dist\", \"templates\", templateName),\n ];\n\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n\n throw new Error(`Template \"${templateName}\" not found`);\n}\n","import { readFile, unlink, writeFile } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\nimport { INIT_CATALOG_VERSIONS } from \"./catalog-versions\";\n\nexport const PROJECT_NPMRC = `@keystrokehq:registry=https://registry.npmjs.org\n`;\n\nexport const PROJECT_GITIGNORE = `node_modules/\ndist/\ndata/\ncoverage/\n.env\n.agent/\n`;\n\nfunction linkSpec(fromDir: string, toDir: string): string {\n const path = relative(fromDir, toDir);\n return `link:${path.startsWith(\".\") ? path : `./${path}`}`;\n}\n\n/** Monorepo playground only (`KEYSTROKE_DEV` + `playground/`). Distributed init uses copyTemplate. */\nfunction buildPlaygroundPackageJson(\n projectName: string,\n targetDir: string,\n monorepoRoot: string,\n): string {\n return `${JSON.stringify(\n {\n name: projectName,\n version: \"0.0.0\",\n private: true,\n type: \"module\",\n scripts: {\n dev: \"keystroke dev\",\n build: \"keystroke build\",\n start: \"keystroke start\",\n lint: \"oxlint .\",\n typecheck: \"tsc --noEmit\",\n \"test:unit\": \"vitest run --project unit\",\n \"test:int\": \"vitest run --project integration\",\n },\n dependencies: {\n \"@keystrokehq/action\": linkSpec(targetDir, join(monorepoRoot, \"packages/action\")),\n \"@keystrokehq/agent\": linkSpec(targetDir, join(monorepoRoot, \"packages/agent\")),\n \"@keystrokehq/config\": linkSpec(targetDir, join(monorepoRoot, \"packages/config\")),\n \"@keystrokehq/google\": linkSpec(\n targetDir,\n join(monorepoRoot, \"packages/integrations/google\"),\n ),\n \"@keystrokehq/slack\": linkSpec(\n targetDir,\n join(monorepoRoot, \"packages/integrations/slack\"),\n ),\n \"@keystrokehq/workflow\": linkSpec(targetDir, join(monorepoRoot, \"packages/workflow\")),\n zod: INIT_CATALOG_VERSIONS.zod,\n },\n devDependencies: {\n \"@keystrokehq/cli\": linkSpec(targetDir, join(monorepoRoot, \"apps/cli\")),\n \"@keystrokehq/tsconfig\": linkSpec(targetDir, join(monorepoRoot, \"packages/tsconfig\")),\n \"@types/node\": INIT_CATALOG_VERSIONS[\"@types/node\"],\n oxlint: INIT_CATALOG_VERSIONS.oxlint,\n typescript: INIT_CATALOG_VERSIONS.typescript,\n vitest: INIT_CATALOG_VERSIONS.vitest,\n },\n },\n null,\n 2,\n )}\\n`;\n}\n\n/** Patch hello-world scaffold for monorepo playground/ (link deps, no GitHub Packages). */\nexport async function applyPlaygroundManifest(\n targetDir: string,\n projectName: string,\n monorepoRoot: string,\n): Promise<void> {\n await writeFile(\n join(targetDir, \"package.json\"),\n buildPlaygroundPackageJson(projectName, targetDir, monorepoRoot),\n );\n\n try {\n await unlink(join(targetDir, \".npmrc\"));\n } catch {\n // Existing dirs may have a consumer .npmrc from an earlier scaffold.\n }\n\n const tsconfigPath = join(targetDir, \"tsconfig.json\");\n const tsconfig = JSON.parse(await readFile(tsconfigPath, \"utf8\")) as {\n include?: string[];\n compilerOptions?: { rootDir?: string };\n };\n tsconfig.include = [\"src\", \"keystroke.config.ts\"];\n if (tsconfig.compilerOptions) {\n tsconfig.compilerOptions.rootDir = \".\";\n }\n await writeFile(tsconfigPath, `${JSON.stringify(tsconfig, null, 2)}\\n`);\n}\n","import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\n\nconst SKILLS_BUNDLE = \"skills-bundle\";\n\nexport function resolveSkillsBundleDir(fromModuleUrl = import.meta.url): string {\n const cliRoot = resolveCliRoot(fromModuleUrl);\n // The real skills source lives in `packages/skills/`. Check it first so\n // contributor edits are picked up without rebuilding the CLI. End users\n // don't have those paths — they get the bundled copy under `dist/`.\n const candidates = [\n join(cliRoot, \"..\", \"..\", \"packages\", \"skills\", \"bundled\"),\n join(cliRoot, \"..\", \"..\", \"packages\", \"skills\", \"dist\"),\n join(cliRoot, \"dist\", SKILLS_BUNDLE),\n join(cliRoot, SKILLS_BUNDLE),\n ];\n\n for (const candidate of candidates) {\n if (existsSync(join(candidate, \"_AGENTS.md\"))) {\n return candidate;\n }\n }\n\n throw new Error(\n \"Bundled keystroke skills not found — run `pnpm --filter @keystrokehq/cli build`\",\n );\n}\n","import { cp, lstat, mkdir, readFile, rm, symlink, writeFile } from \"node:fs/promises\";\nimport { platform } from \"node:os\";\nimport { dirname, join, relative } from \"node:path\";\nimport { readCliVersion } from \"../version\";\nimport { resolveSkillsBundleDir } from \"./resolve-skills-bundle-dir\";\n\nexport const BUNDLE_VERSION_FILENAME = \".bundle-version\";\n\nexport function agentsSkillsDir(projectRoot: string): string {\n return join(projectRoot, \".agents\", \"skills\");\n}\n\nexport function bundleVersionPath(projectRoot: string): string {\n return join(agentsSkillsDir(projectRoot), BUNDLE_VERSION_FILENAME);\n}\n\nexport async function readBundleVersion(projectRoot: string): Promise<string | null> {\n try {\n return (await readFile(bundleVersionPath(projectRoot), \"utf8\")).trim();\n } catch {\n return null;\n }\n}\n\nasync function ensureSymlink(\n target: string,\n linkPath: string,\n kind: \"dir\" | \"file\",\n): Promise<void> {\n await mkdir(dirname(linkPath), { recursive: true });\n await rm(linkPath, { recursive: true, force: true });\n const type = platform() === \"win32\" && kind === \"dir\" ? \"junction\" : kind;\n await symlink(target, linkPath, type);\n}\n\n/** Overwrites `.agents/skills/`, AGENTS.md, and recreates `.claude` symlinks from the CLI bundle. */\nexport async function syncBundledSkills(\n projectRoot: string,\n fromModuleUrl = import.meta.url,\n): Promise<void> {\n const bundleDir = resolveSkillsBundleDir(fromModuleUrl);\n const skillsDir = agentsSkillsDir(projectRoot);\n const agentsMdPath = join(projectRoot, \"AGENTS.md\");\n\n await mkdir(join(projectRoot, \".agents\"), { recursive: true });\n\n const skillsStat = await lstat(skillsDir).catch(() => null);\n if (skillsStat?.isSymbolicLink()) {\n await rm(skillsDir, { force: true });\n await cp(join(bundleDir, \"skills\"), skillsDir, { recursive: true });\n } else {\n await mkdir(skillsDir, { recursive: true });\n await cp(join(bundleDir, \"skills\"), skillsDir, { recursive: true, force: true });\n }\n\n const agentsStat = await lstat(agentsMdPath).catch(() => null);\n if (agentsStat?.isSymbolicLink()) {\n await rm(agentsMdPath, { force: true });\n }\n // Overwrite AGENTS.md from the bundle — bundled agent docs are the source of truth for now.\n await writeFile(agentsMdPath, await readFile(join(bundleDir, \"_AGENTS.md\"), \"utf8\"));\n\n await ensureSymlink(\n relative(dirname(join(projectRoot, \".claude\", \"skills\")), skillsDir),\n join(projectRoot, \".claude\", \"skills\"),\n \"dir\",\n );\n await ensureSymlink(\n relative(dirname(join(projectRoot, \"CLAUDE.md\")), agentsMdPath),\n join(projectRoot, \"CLAUDE.md\"),\n \"file\",\n );\n\n await writeFile(bundleVersionPath(projectRoot), `${readCliVersion()}\\n`);\n}\n","import { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nconst EMPTY_SRC_DIRS = [\"files\", \"skills\", \"triggers\"] as const;\n\n/** Ensure standard empty `src/` folders exist (git does not track empty directories). */\nexport async function scaffoldEmptySrcDirs(targetDir: string): Promise<void> {\n await Promise.all(\n EMPTY_SRC_DIRS.map((dir) => mkdir(join(targetDir, \"src\", dir), { recursive: true })),\n );\n}\n","import { writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { PROJECT_GITIGNORE, PROJECT_NPMRC } from \"./project-files\";\n\n/** Write dotfiles npm/pnpm deploy omits from bundled templates. */\nexport async function scaffoldProjectDotfiles(targetDir: string): Promise<void> {\n await writeFile(join(targetDir, \".npmrc\"), PROJECT_NPMRC);\n await writeFile(join(targetDir, \".gitignore\"), PROJECT_GITIGNORE);\n}\n","import { existsSync } from \"node:fs\";\nimport { access, copyFile, readdir } from \"node:fs/promises\";\nimport { basename, isAbsolute, join, relative, resolve } from \"node:path\";\nimport {\n buildPlaygroundWorkspace,\n installDependencies,\n installPlaygroundDependencies,\n resolvePackageManager,\n} from \"./package-manager\";\nimport { assertProjectName, projectNameFromDirectory } from \"./project-name\";\nimport { confirmTargetDir, promptInitOptions } from \"./prompts\";\nimport { copyTemplate } from \"./copy-template\";\nimport { resolveTemplateDir } from \"./resolve-template-dir\";\nimport { applyPlaygroundManifest } from \"./project-files\";\nimport { syncBundledSkills } from \"../skills/sync-bundled-skills\";\nimport { scaffoldEmptySrcDirs } from \"./scaffold-empty-src-dirs\";\nimport { scaffoldProjectDotfiles } from \"./scaffold-project-dotfiles\";\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\nimport type { InitOptions } from \"./types\";\n\nexport type RunInitOptions = InitOptions & {\n version: string;\n};\n\nfunction monorepoRoot(): string | null {\n const root = join(resolveCliRoot(import.meta.url), \"..\", \"..\");\n return existsSync(join(root, \"pnpm-workspace.yaml\")) ? root : null;\n}\n\nfunction resolvePlaygroundRoot(targetDir: string): string | null {\n if (process.env.KEYSTROKE_DEV !== \"1\") {\n return null;\n }\n\n const root = monorepoRoot();\n if (!root) {\n return null;\n }\n\n const rel = relative(join(root, \"playground\"), resolve(targetDir));\n return rel.length > 0 && !rel.startsWith(\"..\") && !isAbsolute(rel) ? root : null;\n}\n\nasync function directoryExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function directoryIsEmpty(path: string): Promise<boolean> {\n if (!(await directoryExists(path))) {\n return true;\n }\n\n const entries = await readdir(path);\n return entries.length === 0;\n}\n\nfunction resolveHeadlessOptions(options: RunInitOptions): {\n projectName: string;\n targetDir: string;\n} {\n const targetDir = resolve(options.directory ?? options.name ?? \"my-keystroke\");\n const projectName = assertProjectName(\n options.name ?? projectNameFromDirectory(basename(targetDir)),\n );\n\n return { projectName, targetDir };\n}\n\nexport async function runInit(\n options: RunInitOptions,\n): Promise<{ targetDir: string; projectName: string }> {\n const interactive = !options.yes && process.stdin.isTTY;\n const resolved = interactive ? await promptInitOptions(options) : resolveHeadlessOptions(options);\n const { projectName, targetDir } = resolved;\n const playgroundRoot = resolvePlaygroundRoot(targetDir);\n\n if (!(await directoryIsEmpty(targetDir))) {\n if (interactive) {\n const ok = await confirmTargetDir(targetDir);\n if (!ok) {\n throw new Error(\"Init cancelled\");\n }\n } else if (!options.yes) {\n throw new Error(\n `Directory \"${targetDir}\" is not empty. Pass --yes to merge or choose an empty directory.`,\n );\n }\n }\n\n await copyTemplate(resolveTemplateDir(options.template ?? \"hello-world\"), targetDir, {\n projectName,\n version: options.version,\n });\n await scaffoldEmptySrcDirs(targetDir);\n\n if (playgroundRoot) {\n await applyPlaygroundManifest(targetDir, projectName, playgroundRoot);\n } else {\n await scaffoldProjectDotfiles(targetDir);\n }\n\n await syncBundledSkills(targetDir);\n await copyFile(join(targetDir, \".env.example\"), join(targetDir, \".env\"));\n\n if (!options.skipInstall) {\n if (playgroundRoot) {\n installPlaygroundDependencies(targetDir);\n // `link:` deps consume each package's built dist/; build so `keystroke dev`\n // works immediately instead of failing with ERR_MODULE_NOT_FOUND.\n buildPlaygroundWorkspace(playgroundRoot);\n } else {\n const manager = resolvePackageManager(options.packageManager);\n installDependencies(targetDir, manager);\n }\n }\n\n return { targetDir, projectName };\n}\n","import type { Command } from \"commander\";\nimport { runInit } from \"../init/run-init\";\nimport { readCliVersion } from \"../version\";\n\nexport function registerInitCommand(program: Command): void {\n program\n .command(\"init\")\n .description(\"Create a new keystroke project from a template\")\n .argument(\"[directory]\", \"Directory to create the project in\")\n .option(\"--name <name>\", \"Project name (kebab-case)\")\n .option(\"--template <name>\", \"Template to use\", \"hello-world\")\n .option(\"-y, --yes\", \"Skip prompts (headless mode for scripts and AI agents)\")\n .option(\"--skip-install\", \"Skip dependency installation\")\n .option(\"--pm <manager>\", \"Package manager: npm, pnpm, yarn, or bun\")\n .action(async (directory: string | undefined, options) => {\n try {\n const result = await runInit({\n directory,\n name: options.name,\n template: options.template,\n yes: options.yes,\n skipInstall: options.skipInstall,\n packageManager: options.pm,\n version: readCliVersion(),\n });\n\n process.stdout.write(\n `Created keystroke project \"${result.projectName}\" at ${result.targetDir}\\n`,\n );\n process.stdout.write(\"\\nNext steps:\\n\");\n process.stdout.write(` cd ${result.targetDir}\\n`);\n process.stdout.write(\" # set ANTHROPIC_API_KEY and integration keys in .env\\n\");\n process.stdout.write(\" keystroke dev\\n\");\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Init failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import type Conf from \"conf\";\nimport type { UpdateOrganizationRequest } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"../../config\";\nimport { withActivePlatformClient } from \"../project/run-project\";\n\nexport async function runOrganizationUpdate(\n config: Conf<CliConfig>,\n input: Pick<UpdateOrganizationRequest, \"name\">,\n): Promise<void> {\n await withActivePlatformClient(config, async (platform) => {\n const organization = await platform.organizations.update(input);\n process.stdout.write(`${JSON.stringify({ organization }, null, 2)}\\n`);\n });\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig, getPlatformUrl, getWebUrl } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { runOrganizationUpdate } from \"./run-organization\";\n\nexport function registerOrganizationCommand(program: Command): void {\n const organization = program\n .command(\"organization\")\n .description(\"Manage the active organization\");\n\n organization\n .command(\"update\")\n .description(\"Update the active organization's display name\")\n .requiredOption(\"--name <name>\", \"Organization display name\")\n .action(async (options: { name: string }) => {\n const config = createCliConfig();\n try {\n await runOrganizationUpdate(config, { name: options.name });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Update organization failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig, getPlatformUrl, getWebUrl } from \"../../config\";\nimport { formatCliError } from \"../../errors/format-cli-error\";\nimport { resolveActiveProjectId } from \"../../resolve-project-target\";\nimport { getCliTargetOptions } from \"../../target-options\";\nimport {\n runProjectCreate,\n runProjectList,\n runProjectMetrics,\n runProjectDeploymentsList,\n runProjectUpdate,\n runProjectDelete,\n} from \"./run-project\";\n\nexport function registerProjectCommand(program: Command): void {\n const project = program\n .command(\"project\")\n .description(\"List, create, update, and delete platform projects\");\n\n project\n .command(\"list\")\n .description(\"List projects in the active organization\")\n .action(async () => {\n const config = createCliConfig();\n try {\n await runProjectList(config);\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"List projects failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n project\n .command(\"metrics\")\n .description(\"List rollup metrics for projects in the active organization\")\n .option(\"--project <slug>\", \"Return metrics for a single project\")\n .action(async (options: { project?: string }) => {\n const config = createCliConfig();\n try {\n await runProjectMetrics(config, {\n ...(options.project ? { projectRef: options.project } : {}),\n });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"List project metrics failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n const deployments = project\n .command(\"deployments\")\n .description(\"View deployment history for platform projects\");\n\n deployments\n .command(\"list\")\n .description(\"List deployment history for a project\")\n .option(\"--project <slug>\", \"Project slug\")\n .action(async (options: { project?: string }) => {\n const config = createCliConfig();\n try {\n const projectRef =\n options.project ?? getCliTargetOptions().projectId ?? config.get(\"activeProjectId\");\n if (!projectRef) {\n throw new Error(\"Usage: keystroke project deployments list --project <slug>\");\n }\n\n await runProjectDeploymentsList(config, { projectRef });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"List deployments failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n project\n .command(\"create\")\n .description(\"Create a platform project in the active organization\")\n .requiredOption(\"--name <name>\", \"Project name\")\n .option(\"--description <description>\", \"Project description\")\n .action(async (options: { name: string; description?: string }) => {\n const config = createCliConfig();\n try {\n await runProjectCreate(config, {\n name: options.name,\n ...(options.description ? { description: options.description } : {}),\n });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Create project failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n project\n .command(\"update\")\n .description(\"Update a platform project's name and/or description\")\n .option(\"--name <name>\", \"Project name\")\n .option(\"--description <description>\", \"Project description\")\n .action(async (options: { name?: string; description?: string }) => {\n const config = createCliConfig();\n try {\n const projectId = await resolveActiveProjectId(config);\n if (!projectId) {\n throw new Error(\"Usage: keystroke --project <slug> project update --name <name>\");\n }\n\n if (!options.name && options.description === undefined) {\n throw new Error(\"At least one of --name or --description is required\");\n }\n\n await runProjectUpdate(config, {\n projectId,\n ...(options.name ? { name: options.name } : {}),\n ...(options.description !== undefined ? { description: options.description } : {}),\n });\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Update project failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n\n project\n .command(\"delete\")\n .description(\"Delete a platform project\")\n .option(\"-y, --yes\", \"Skip confirmation prompt\")\n .action(async (options: { yes?: boolean }) => {\n const config = createCliConfig();\n try {\n const projectId = await resolveActiveProjectId(config);\n if (!projectId) {\n throw new Error(\"Usage: keystroke --project <slug> project delete\");\n }\n\n if (!options.yes) {\n throw new Error(\"Pass --yes to confirm project deletion\");\n }\n\n await runProjectDelete(config, projectId);\n } catch (error) {\n process.stderr.write(\n `${formatCliError(error, \"Delete project failed\", {\n serverUrl: getPlatformUrl(config),\n webUrl: getWebUrl(config),\n })}\\n`,\n );\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { createCliConfig, getServerUrl } from \"../config\";\nimport { resolveBootstrapRun } from \"../project/bootstrap-run\";\nimport { resolveCliRoot } from \"../project/resolve-cli-root\";\nimport { resolveProjectRoot } from \"../project/resolve-project-root\";\nimport { runUntilExit, spawnNodeScript, type ManagedProcess } from \"../process/run-processes\";\nimport { ensureNativeDeps } from \"../runtime/ensure-native-deps\";\nimport { resolveCliRuntimeNodeModules } from \"../runtime/resolve-runtime-node-modules\";\n\ntype StartOptions = {\n dir: string;\n port?: number;\n};\n\nfunction resolveStartServerUrl(portOverride?: number): string {\n const url = new URL(getServerUrl(createCliConfig()));\n if (portOverride !== undefined) {\n url.port = String(portOverride);\n }\n return url.origin;\n}\n\nexport async function runStart(options: StartOptions): Promise<void> {\n const root = resolveProjectRoot(options.dir);\n const serverUrl = resolveStartServerUrl(options.port);\n const apiPort = Number(new URL(serverUrl).port || 80);\n\n const runtimeNodeModules = resolveCliRuntimeNodeModules(resolveCliRoot(import.meta.url));\n ensureNativeDeps(runtimeNodeModules);\n const { buildApp } = await import(\"@keystrokehq/build\");\n await buildApp({ root, clean: false });\n\n const bootstrap = await resolveBootstrapRun({\n root,\n runtimeNodeModules,\n apiPort,\n });\n\n const processes: ManagedProcess[] = [\n {\n name: \"api\",\n child: spawnNodeScript(bootstrap),\n },\n ];\n\n process.stdout.write(`API: ${serverUrl}\\n`);\n\n await runUntilExit(processes);\n}\n\nexport function registerStartCommand(program: Command): void {\n program\n .command(\"start\")\n .description(\"Build and run the API server\")\n .option(\"--dir <path>\", \"Project directory\", process.cwd())\n .option(\"--port <number>\", \"API port\", (value) => Number(value))\n .action(async (options) => {\n try {\n await runStart({\n dir: options.dir,\n port: options.port,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Start failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nexport function registerTriggerListCommand(trigger: Command): void {\n trigger\n .command(\"list\")\n .description(\"List discovered triggers\")\n .option(\"--endpoint <endpoint>\", \"Only webhook triggers on this shared endpoint\")\n .action((options: { endpoint?: string }) =>\n runProjectCliCommand(\"List triggers failed\", async ({ client }) => {\n const result = await client.triggers.list(\n options.endpoint ? { endpoint: options.endpoint } : undefined,\n );\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n\nexport function registerTriggerGetCommand(trigger: Command): void {\n trigger\n .command(\"get\")\n .description(\"Get a trigger by key, or all webhook triggers on a shared endpoint\")\n .argument(\"<id>\", \"Trigger key or shared webhook endpoint\")\n .action((id: string) =>\n runProjectCliCommand(\"Get trigger failed\", async ({ client }) => {\n const result = await client.triggers.get(id);\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n\nexport function registerTriggerUrlCommand(trigger: Command): void {\n trigger\n .command(\"url\")\n .description(\"Print the webhook URL for a trigger\")\n .argument(\"<id>\", \"Attachment key or webhook route\")\n .action((id: string) =>\n runProjectCliCommand(\"Resolve webhook URL failed\", async ({ client }) => {\n const url = await client.triggers.webhookUrl(id);\n process.stdout.write(`${url}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nexport function registerTriggerPollCommand(trigger: Command): void {\n trigger\n .command(\"poll\")\n .description(\"Run a poll trigger on demand\")\n .argument(\"<id>\", \"Poll attachment key, or poll source id with --group\")\n .option(\"--group\", \"Run all attachments that share this poll source id\")\n .option(\"--workflow <key>\", \"Only trigger this workflow (repeatable)\", collect, [])\n .option(\"--attachment <key>\", \"Only trigger this attachment (repeatable)\", collect, [])\n .action((id: string, options: { group?: boolean; workflow: string[]; attachment: string[] }) =>\n runProjectCliCommand(\"Poll trigger failed\", async ({ client }) => {\n const result = await client.triggers.poll(id, {\n ...(options.group ? { group: true } : {}),\n ...(options.workflow.length > 0 ? { workflows: options.workflow } : {}),\n ...(options.attachment.length > 0 ? { attachments: options.attachment } : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nexport function registerTriggerRunsCommand(trigger: Command): void {\n const runs = trigger.command(\"runs\").description(\"List and inspect trigger runs\");\n\n runs\n .command(\"list\")\n .description(\"List runs for a trigger attachment\")\n .argument(\"<attachmentId>\", \"Trigger attachment key\")\n .option(\"--limit <n>\", \"Page size (1–100)\", \"20\")\n .option(\"--cursor <cursor>\", \"Pagination cursor from a previous page\")\n .option(\"--trigger-type <type>\", \"Filter by trigger type (cron, webhook, poll)\")\n .action((attachmentId: string, options: Record<string, string | undefined>) =>\n runProjectCliCommand(\"List trigger runs failed\", async ({ client }) => {\n const result = await client.triggers.listRuns(attachmentId, {\n limit: Number(options.limit),\n ...(options.cursor ? { cursor: options.cursor } : {}),\n ...(options.triggerType\n ? { triggerType: options.triggerType as \"cron\" | \"webhook\" | \"poll\" }\n : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n\n runs\n .command(\"get\")\n .description(\"Get full details for a trigger run\")\n .argument(\"<attachmentId>\", \"Trigger attachment key\")\n .argument(\"<runId>\", \"Trigger run id\")\n .option(\"--include <parts>\", \"Comma-separated: workflows, trace\")\n .action((attachmentId: string, runId: string, options: { include?: string }) =>\n runProjectCliCommand(\"Get trigger run failed\", async ({ client }) => {\n const result = await client.triggers.getRun(attachmentId, runId, {\n include: options.include,\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport {\n registerTriggerGetCommand,\n registerTriggerListCommand,\n registerTriggerUrlCommand,\n} from \"./list\";\nimport { registerTriggerPollCommand } from \"./poll\";\nimport { registerTriggerRunsCommand } from \"./runs\";\n\nexport function registerTriggerCommand(program: Command): void {\n const trigger = program.command(\"trigger\").description(\"Invoke and inspect triggers\");\n\n registerTriggerListCommand(trigger);\n registerTriggerGetCommand(trigger);\n registerTriggerUrlCommand(trigger);\n registerTriggerPollCommand(trigger);\n registerTriggerRunsCommand(trigger);\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../../config\";\nimport { runCliCommand } from \"../../errors\";\nimport { ensureActiveOrganization } from \"../../organization/active-organization\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { resolveActiveProjectId } from \"../../resolve-project-target\";\n\nexport function registerWorkflowListCommand(workflow: Command): void {\n workflow\n .command(\"list\")\n .description(\"List workflows in the active organization\")\n .action(() =>\n runCliCommand(\n \"List workflows failed\",\n async () => {\n const config = createCliConfig();\n const client = createCliPlatformClient(config);\n await ensureActiveOrganization(config);\n const projectId = await resolveActiveProjectId(config);\n const result = await client.workflows.list(projectId ? { projectId } : undefined);\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n },\n undefined,\n { orgScoped: true },\n ),\n );\n}\n","import { isQueuedRunResponse } from \"@keystrokehq/sdk\";\nimport type { Command } from \"commander\";\nimport { cliBinaryName, parseJsonOption, runProjectCliCommand } from \"../../errors\";\n\nexport function registerWorkflowRunCommand(workflow: Command): void {\n workflow\n .command(\"run\")\n .description(\"Invoke a workflow\")\n .argument(\"<workflowId>\", \"Workflow key / route id\")\n .option(\"--input <json>\", \"JSON request body (defaults to {})\", \"{}\")\n .addHelpText(\n \"after\",\n `\nExamples:\n ${cliBinaryName()} workflow run math --input '{\"first\":1,\"second\":2}'\n ${cliBinaryName()} workflow run incoming-message --input '{\"message\":\"Hi\",\"sender\":\"you\"}'\n`,\n )\n .action((workflowId: string, options: { input: string }) =>\n runProjectCliCommand(\n \"Workflow run failed\",\n async ({ client }) => {\n const input = parseJsonOption(options.input, \"--input\");\n const result = await client.workflows.run(workflowId, input);\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n\n if (isQueuedRunResponse(result)) {\n process.stderr.write(\n `Run queued. Track progress:\\n` +\n ` ${cliBinaryName()} workflow runs get ${workflowId} ${result.runId} --include steps,trace\\n`,\n );\n }\n },\n {\n usage: {\n command: `${cliBinaryName()} workflow run ${workflowId}`,\n flag: \"--input\",\n },\n },\n ),\n );\n}\n","import type { Command } from \"commander\";\nimport { runProjectCliCommand } from \"../../errors\";\n\nexport function registerWorkflowRunsCommand(workflow: Command): void {\n const runs = workflow.command(\"runs\").description(\"List and inspect workflow runs\");\n\n runs\n .command(\"list\")\n .description(\"List runs for a workflow\")\n .argument(\"<workflowId>\", \"Workflow key / route id\")\n .option(\"--limit <n>\", \"Page size (1–100)\", \"20\")\n .option(\"--cursor <cursor>\", \"Pagination cursor from a previous page\")\n .option(\"--status <status>\", \"Filter by status\")\n .option(\"--trigger <trigger>\", \"Filter by trigger kind\")\n .action((workflowId: string, options: Record<string, string | undefined>) =>\n runProjectCliCommand(\"List workflow runs failed\", async ({ client }) => {\n const result = await client.workflows.listRuns(workflowId, {\n limit: Number(options.limit),\n ...(options.cursor ? { cursor: options.cursor } : {}),\n ...(options.status\n ? { status: options.status as \"pending\" | \"running\" | \"completed\" | \"failed\" }\n : {}),\n ...(options.trigger\n ? { trigger: options.trigger as \"api\" | \"cron\" | \"webhook\" | \"poll\" | \"retry\" }\n : {}),\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n\n runs\n .command(\"get\")\n .description(\"Get full details for a workflow run\")\n .argument(\"<workflowId>\", \"Workflow key / route id\")\n .argument(\"<runId>\", \"Workflow run id\")\n .option(\"--include <parts>\", \"Comma-separated: trigger, steps, trace\")\n .action((workflowId: string, runId: string, options: { include?: string }) =>\n runProjectCliCommand(\"Get workflow run failed\", async ({ client }) => {\n const result = await client.workflows.getRun(workflowId, runId, {\n include: options.include,\n });\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n }),\n );\n}\n","import type { Command } from \"commander\";\nimport { registerWorkflowListCommand } from \"./list\";\nimport { registerWorkflowRunCommand } from \"./run\";\nimport { registerWorkflowRunsCommand } from \"./runs\";\n\nexport function registerWorkflowCommand(program: Command): void {\n const workflow = program.command(\"workflow\").description(\"Invoke and inspect workflows\");\n\n registerWorkflowListCommand(workflow);\n registerWorkflowRunCommand(workflow);\n registerWorkflowRunsCommand(workflow);\n}\n","import type Conf from \"conf\";\nimport type { Project } from \"@keystrokehq/shared\";\n\nimport type { CliConfig } from \"../../config\";\nimport { cliBinaryName } from \"../../errors/command-input\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { formatProjectLabel, resolveProjectRef } from \"../../resolve-resource-ref\";\n\nexport type ConfigUseProjectResult = {\n stdout: string;\n stderr?: string;\n};\n\nasync function fetchProjectInOrg(config: Conf<CliConfig>, projectRef: string): Promise<Project> {\n const platform = createCliPlatformClient(config);\n return resolveProjectRef(platform, projectRef);\n}\n\nfunction assertProjectReadyForConfig(project: Project): void {\n const label = formatProjectLabel(project);\n\n if (project.status === \"failed\") {\n throw new Error(\n project.lastError\n ? `Project ${label} deploy failed: ${project.lastError}`\n : `Project ${label} deploy failed`,\n );\n }\n\n if (project.status === \"starting\") {\n throw new Error(\n `Project ${label} is still starting. Wait for deploy to finish, then run \\`keystroke config use project ${label}\\`.`,\n );\n }\n}\n\nexport async function runConfigUseProject(\n config: Conf<CliConfig>,\n projectRef: string,\n): Promise<ConfigUseProjectResult> {\n const project = await fetchProjectInOrg(config, projectRef);\n assertProjectReadyForConfig(project);\n\n config.set(\"activeProjectId\", project.id);\n config.set(\"apiTarget\", \"platform\");\n\n const label = formatProjectLabel(project);\n const stdout =\n project.status === \"active\"\n ? `Using platform project ${label}\\n`\n : `Using platform project ${label} (${project.status})\\n`;\n\n const stderr =\n project.status === \"inactive\"\n ? `Project is not active yet. Deploy with: ${cliBinaryName()} deploy --project ${label}\\n`\n : undefined;\n\n return { stdout, stderr };\n}\n","import { UserPreferencesPatchSchema, type UserPreferencesPatch } from \"@keystrokehq/shared\";\n\nexport function parsePreferenceValue(rawValue: string): unknown {\n try {\n return JSON.parse(rawValue);\n } catch {\n return rawValue;\n }\n}\n\nexport function buildPreferencesPatchFromKeyValue(\n key: string,\n rawValue: string,\n): UserPreferencesPatch {\n const trimmedKey = key.trim();\n if (!trimmedKey) {\n throw new Error(\"Preference key is required\");\n }\n\n const value = parsePreferenceValue(rawValue);\n const segments = trimmedKey.split(\".\").filter(Boolean);\n if (segments.length === 0) {\n throw new Error(\"Preference key is required\");\n }\n\n let patch: Record<string, unknown> = { [segments.at(-1)!]: value };\n\n for (let index = segments.length - 2; index >= 0; index -= 1) {\n patch = { [segments[index]!]: patch };\n }\n\n const parsed = UserPreferencesPatchSchema.safeParse(patch);\n if (!parsed.success) {\n const message = parsed.error.issues[0]?.message ?? \"invalid value\";\n throw new Error(`Invalid preference ${trimmedKey}: ${message}`);\n }\n\n return parsed.data;\n}\n","import type { Command } from \"commander\";\nimport type { PlatformClient } from \"@keystrokehq/sdk/platform\";\n\nimport { createCliConfig } from \"../../config\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { buildPreferencesPatchFromKeyValue } from \"./preferences-patch\";\n\nexport async function runConfigPreferencesGet(platform: PlatformClient): Promise<string> {\n const preferences = await platform.userPreferences.get();\n return `${JSON.stringify(preferences, null, 2)}\\n`;\n}\n\nexport async function runConfigPreferencesSet(\n platform: PlatformClient,\n key: string,\n value: string,\n): Promise<string> {\n const patch = buildPreferencesPatchFromKeyValue(key, value);\n const preferences = await platform.userPreferences.update(patch);\n return `${JSON.stringify(preferences, null, 2)}\\n`;\n}\n\nexport function registerConfigPreferencesCommand(config: Command): void {\n const preferences = config.command(\"preferences\").description(\"Manage user preferences\");\n\n preferences\n .command(\"get\")\n .description(\"Show current user preferences as JSON\")\n .action(async () => {\n const cliConfig = createCliConfig();\n const platform = createCliPlatformClient(cliConfig);\n process.stdout.write(await runConfigPreferencesGet(platform));\n });\n\n preferences\n .command(\"set\")\n .description(\"Update a user preference by dot-path key\")\n .argument(\"<key>\", \"Preference key, e.g. interfaceTheme or sidebar.navIconVisibility\")\n .argument(\"<value>\", \"Preference value (JSON or plain string)\")\n .action(async (key: string, value: string) => {\n const cliConfig = createCliConfig();\n const platform = createCliPlatformClient(cliConfig);\n process.stdout.write(await runConfigPreferencesSet(platform, key, value));\n });\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig, getConfigDir, getEffectiveApiTarget, getPlatformUrl } from \"../../config\";\nimport { readDevSession } from \"../../dev-session\";\nimport {\n listOrganizations,\n selectActiveOrganization,\n} from \"../../organization/active-organization\";\nimport { runConfigUseProject } from \"./use-project\";\nimport { registerConfigPreferencesCommand } from \"./preferences\";\n\nexport function registerConfigCommand(program: Command): void {\n const config = program.command(\"config\").description(\"Manage CLI configuration\");\n\n registerConfigPreferencesCommand(config);\n\n config\n .command(\"show\")\n .description(\"Show CLI configuration\")\n .action(() => {\n const cliConfig = createCliConfig();\n const configDir = getConfigDir(cliConfig);\n process.stdout.write(\n `${JSON.stringify(\n {\n serverUrl: cliConfig.get(\"serverUrl\"),\n webUrl: cliConfig.get(\"webUrl\"),\n platformUrl: getPlatformUrl(cliConfig),\n activeOrganizationId: cliConfig.get(\"activeOrganizationId\"),\n activeProjectId: cliConfig.get(\"activeProjectId\"),\n apiTarget: getEffectiveApiTarget(cliConfig),\n devSession: readDevSession(configDir) ?? null,\n },\n null,\n 2,\n )}\\n`,\n );\n });\n\n config\n .command(\"use\")\n .description(\"Switch API target (local/cloud/project) or active organization\")\n .argument(\"[mode]\", \"local, cloud, project, or org\")\n .argument(\"[id]\", \"Project or organization id when switching cloud target or org\")\n .action(async (mode?: string, id?: string) => {\n const cliConfig = createCliConfig();\n\n if (!mode || mode === \"local\") {\n cliConfig.set(\"apiTarget\", \"local\");\n const activeProjectId = cliConfig.get(\"activeProjectId\");\n process.stdout.write(\n activeProjectId\n ? `Using local keystroke server (cloud project ${activeProjectId} unchanged)\\n`\n : \"Using local keystroke server\\n\",\n );\n return;\n }\n\n if (mode === \"org\") {\n const membership = await selectActiveOrganization(cliConfig, { organizationRef: id });\n process.stdout.write(`Using organization ${membership.organization.name}\\n`);\n return;\n }\n\n if (mode === \"cloud\") {\n cliConfig.set(\"apiTarget\", \"platform\");\n const activeProjectId = cliConfig.get(\"activeProjectId\");\n process.stdout.write(\n activeProjectId\n ? `Using platform API (default project ${activeProjectId} for project-scoped commands)\\n`\n : \"Using platform API\\n\",\n );\n return;\n }\n\n if (mode !== \"project\") {\n throw new Error(\"Usage: keystroke config use [local|cloud|project [slug]|org [slug]]\");\n }\n\n const targetProjectId = id ?? cliConfig.get(\"activeProjectId\");\n if (!targetProjectId) {\n throw new Error(\"Usage: keystroke config use project <slug>\");\n }\n\n const result = await runConfigUseProject(cliConfig, targetProjectId);\n process.stdout.write(result.stdout);\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n });\n\n config\n .command(\"org\")\n .description(\"List organizations you belong to\")\n .action(async () => {\n const cliConfig = createCliConfig();\n const organizations = await listOrganizations(cliConfig);\n process.stdout.write(`${JSON.stringify({ organizations }, null, 2)}\\n`);\n });\n}\n","import type { Command } from \"commander\";\n\nimport { createCliConfig } from \"../../config\";\nimport { runCliCommand } from \"../../errors\";\nimport { ensureActiveOrganization } from \"../../organization/active-organization\";\nimport { createCliPlatformClient } from \"../../platform-client\";\nimport { resolveActiveProjectId } from \"../../resolve-project-target\";\n\nexport function registerSkillCommand(program: Command): void {\n const skill = program.command(\"skill\").description(\"Inspect platform skills\");\n\n skill\n .command(\"list\")\n .description(\"List skills in the active organization\")\n .action(() =>\n runCliCommand(\n \"List skills failed\",\n async () => {\n const config = createCliConfig();\n const client = createCliPlatformClient(config);\n await ensureActiveOrganization(config);\n const projectId = await resolveActiveProjectId(config);\n const result = await client.skills.list(projectId ? { projectId } : undefined);\n process.stdout.write(`${JSON.stringify(result, null, 2)}\\n`);\n },\n undefined,\n { orgScoped: true },\n ),\n );\n}\n","import type { Command } from \"commander\";\nimport { resolveProjectRoot } from \"../project/resolve-project-root\";\nimport { syncBundledSkills } from \"../skills/sync-bundled-skills\";\n\nexport function registerSkillsCommand(program: Command): void {\n const skills = program.command(\"skills\").description(\"Manage bundled agent skills\");\n\n skills\n .command(\"sync\")\n .description(\"Overwrite bundled skills and AGENTS.md with the CLI version\")\n .option(\"--dir <path>\", \"Project directory\", process.cwd())\n .action(async (options) => {\n try {\n const root = resolveProjectRoot(options.dir);\n await syncBundledSkills(root);\n process.stdout.write(`Synced bundled skills at ${root}\\n`);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Skills sync failed\";\n process.stderr.write(`${message}\\n`);\n process.exitCode = 1;\n }\n });\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\n\nconst KEYSTROKE_CONFIG = \"keystroke.config.ts\";\n\n/** Walk up from `fromDir` and return the directory containing `keystroke.config.ts`, if any. */\nexport function resolveKeystrokeConfigRoot(fromDir = process.cwd()): string | null {\n let dir = resolve(fromDir);\n\n while (dir !== dirname(dir)) {\n if (existsSync(join(dir, KEYSTROKE_CONFIG))) {\n return dir;\n }\n\n dir = dirname(dir);\n }\n\n if (existsSync(join(dir, KEYSTROKE_CONFIG))) {\n return dir;\n }\n\n return null;\n}\n","import { existsSync, lstatSync } from \"node:fs\";\nimport type { Command } from \"commander\";\nimport { resolveKeystrokeConfigRoot } from \"../project/resolve-keystroke-config-root\";\nimport { readCliVersion } from \"../version\";\nimport { agentsSkillsDir, readBundleVersion, syncBundledSkills } from \"./sync-bundled-skills\";\n\nfunction commandPath(command: Command): string[] {\n const names: string[] = [];\n\n for (let current: Command | null = command; current; current = current.parent) {\n const name = current.name();\n if (name && name !== \"keystroke\") {\n names.unshift(name);\n }\n }\n\n return names;\n}\n\nfunction shouldSkipAutoSync(command: Command): boolean {\n if (process.env.CI === \"true\" || process.env.CI === \"1\") {\n return true;\n }\n\n const path = commandPath(command);\n if (path[0] === \"init\") {\n return true;\n }\n\n if (path[0] === \"skills\") {\n return true;\n }\n\n return false;\n}\n\nfunction resolveAutoSyncRoot(command: Command): string | null {\n const opts = command.opts<{ dir?: string }>();\n return resolveKeystrokeConfigRoot(opts.dir ?? process.cwd());\n}\n\n/** Sync bundled skills when stale; no-op when not in a project or already up to date. */\nexport async function syncSkills(command: Command): Promise<void> {\n if (shouldSkipAutoSync(command)) {\n return;\n }\n\n const projectRoot = resolveAutoSyncRoot(command);\n if (!projectRoot) {\n return;\n }\n\n const skillsDir = agentsSkillsDir(projectRoot);\n if (!existsSync(skillsDir)) {\n return;\n }\n\n // Monorepo example projects symlink bundled skills for live edits — skip auto-sync.\n if (lstatSync(skillsDir).isSymbolicLink()) {\n return;\n }\n\n const currentVersion = readCliVersion();\n const bundledVersion = await readBundleVersion(projectRoot);\n if (bundledVersion === currentVersion) {\n return;\n }\n\n await syncBundledSkills(projectRoot);\n process.stderr.write(`Synced bundled skills to ${currentVersion}\\n`);\n}\n","import { Command } from \"commander\";\nimport { registerAgentCommand } from \"./commands/agent\";\nimport { registerAppCommand } from \"./commands/app\";\nimport { registerConnectCommand } from \"./commands/connect\";\nimport { registerCredentialsCommand } from \"./commands/credentials\";\nimport { registerAuthCommand } from \"./commands/auth\";\nimport { registerBuildCommand } from \"./commands/build\";\nimport { registerDeployCommand } from \"./commands/deploy\";\nimport { registerDevCommand } from \"./commands/dev\";\nimport { registerHistoryCommand } from \"./commands/history\";\nimport { registerHealthCommand } from \"./commands/health\";\nimport { registerInitCommand } from \"./commands/init\";\nimport { registerOrganizationCommand } from \"./commands/organization\";\nimport { registerProjectCommand } from \"./commands/project\";\nimport { registerStartCommand } from \"./commands/start\";\nimport { registerTriggerCommand } from \"./commands/trigger\";\nimport { registerWorkflowCommand } from \"./commands/workflow\";\nimport { registerConfigCommand } from \"./commands/config\";\nimport { registerSkillCommand } from \"./commands/skill\";\nimport { registerSkillsCommand } from \"./commands/skills\";\nimport { syncSkills } from \"./skills/sync-skills\";\nimport { readCliVersion } from \"./version\";\nimport { setCliTargetOptions } from \"./target-options\";\n\nexport function createProgram(): Command {\n const program = new Command()\n .name(\"keystroke\")\n .description(\"Build, run, and manage keystroke projects\")\n .version(readCliVersion())\n .option(\"--project <slug>\", \"Platform project slug (deploy target or one-off API target)\")\n .option(\"--local\", \"Force local keystroke server URL\")\n .hook(\"preAction\", async (thisCommand, actionCommand) => {\n const opts = thisCommand.opts<{ project?: string; local?: boolean }>();\n setCliTargetOptions({\n projectId: opts.project,\n local: opts.local,\n });\n await syncSkills(actionCommand);\n });\n\n registerAuthCommand(program);\n registerConnectCommand(program);\n registerConfigCommand(program);\n registerOrganizationCommand(program);\n registerProjectCommand(program);\n registerHistoryCommand(program);\n registerCredentialsCommand(program);\n registerHealthCommand(program);\n registerInitCommand(program);\n registerSkillsCommand(program);\n registerSkillCommand(program);\n registerBuildCommand(program);\n registerDeployCommand(program);\n registerDevCommand(program);\n registerStartCommand(program);\n registerAgentCommand(program);\n registerAppCommand(program);\n registerWorkflowCommand(program);\n registerTriggerCommand(program);\n return program;\n}\n\nexport async function runCli(argv: string[]): Promise<void> {\n const { maybeAutoUpdate } = await import(\"./update/maybe-auto-update\");\n await maybeAutoUpdate(argv);\n createProgram().parse(argv);\n}\n","import { runCli } from \"./program\";\n\nawait runCli(process.argv);\n"],"x_google_ignoreList":[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49],"mappings":";;;;;;;;;;;;;;;;AAEA,MAAa,kBAAkB;AAC/B,MAAa,uBAAuB;AAEpC,MAAa,qBAAqB;AAQlC,SAAS,iBAAiB,QAAwB;CAChD,OAAO,oBAAoB,QAAQ,OAAO,QAAQ,QAAQ,EAAE,CAAC;AAC/D;;AAGA,SAAgB,0BAA0B,QAAoC;CAC5E,MAAM,YAAY,iBAAiB,MAAM;CAEzC,IAAI,cAAA,2BAA+B,cAAc,yBAC/C,OAAO;CAGT,IAAI,cAAA,4BACF,OAAO;AAIX;AAEA,SAAgB,4BACd,QACA,UAAqC,CAAC,GAC9B;CACR,MAAM,WAAW,QAAQ,aAAa,KAAK;CAC3C,IAAI,UACF,OAAO,SAAS,QAAQ,QAAQ,EAAE;CAGpC,MAAM,QAAQ,0BAA0B,MAAM;CAC9C,IAAI,OACF,OAAO;CAIT,QADiB,QAAQ,UAAU,KAAK,KAAA,4BACxB,QAAQ,QAAQ,EAAE;AACpC;;;AC1BA,SAAgB,gBAAgB,MAAM,KAAK,QAAQ,GAAG,YAAY,GAAW;CAC3E,OAAO;AACT;AAEA,SAAgB,aAAa,QAAiC;CAC5D,OAAO,QAAQ,OAAO,IAAI;AAC5B;AAEA,SAAgB,sBAAsB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B;EAChB,aAAa;EACb,SAAS;EACT,UAAU;EACV,kBAAkB,CAAC;EACnB,cAAc;GACb,UAAU;GACV,WAAW;GACX,OAAO;GACP,QAAQ;GACR,WAAW;GACX,KAAK;EACN;EACA,gBAAgB;GACf;GACA;GACA;EACD;EACA,cAAc;GACb,UAAU;GACV,QAAQ;EACT;EACA,iBAAiB;EACjB,0BAA0B;EAC1B,SAAS;CACV;CACA;EACC,KAAK;EACL,MAAM;EACN,WAAW;EACX,gBAAgB;EAChB,aAAa;EACb,SAAS;EACT,UAAU;EACV,kBAAkB;GACjB;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,UAAU;IACV,MAAM;IACN,UAAU;GACX;GACA;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,MAAM;IACN,UAAU;GACX;GACA;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,UAAU;IACV,MAAM;IACN,UAAU;GACX;EACD;EACA,cAAc;GACb,UAAU;GACV,WAAW;GACX,OAAO;GACP,QAAQ;GACR,WAAW;GACX,KAAK;EACN;EACA,gBAAgB;GACf;GACA;GACA;EACD;EACA,cAAc;GACb,UAAU;GACV,QAAQ;EACT;EACA,iBAAiB;EACjB,0BAA0B;EAC1B,SAAS;CACV;CACA;EACC,KAAK;EACL,MAAM;EACN,WAAW;EACX,gBAAgB;EAChB,aAAa;EACb,SAAS;EACT,UAAU;EACV,kBAAkB,CAAC;GAClB,KAAK;GACL,OAAO;GACP,aAAa;GACb,UAAU;GACV,MAAM;GACN,UAAU;EACX,GAAG;GACF,KAAK;GACL,OAAO;GACP,aAAa;GACb,MAAM;GACN,UAAU;GACV,QAAQ;EACT,CAAC;EACD,cAAc;GACb,UAAU;GACV,WAAW;GACX,OAAO;GACP,QAAQ;GACR,WAAW;GACX,KAAK;EACN;EACA,gBAAgB;GACf;GACA;GACA;EACD;EACA,cAAc;GACb,UAAU;GACV,QAAQ;EACT;EACA,iBAAiB;EACjB,0BAA0B;EAC1B,SAAS;CACV;CACA;EACC,KAAK;EACL,MAAM;EACN,WAAW;EACX,gBAAgB;EAChB,aAAa;EACb,SAAS;EACT,UAAU;EACV,kBAAkB;GACjB;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,MAAM;IACN,UAAU;GACX;GACA;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,MAAM;IACN,UAAU;GACX;GACA;IACC,KAAK;IACL,OAAO;IACP,aAAa;IACb,MAAM;IACN,UAAU;GACX;EACD;EACA,cAAc;GACb,UAAU;GACV,WAAW;GACX,OAAO;GACP,QAAQ;GACR,WAAW;GACX,KAAK;EACN;EACA,gBAAgB;GACf;GACA;GACA;EACD;EACA,cAAc;GACb,UAAU;GACV,QAAQ;EACT;EACA,iBAAiB;EACjB,0BAA0B;EAC1B,SAAS;CACV;CACA;EACC,KAAK;EACL,MAAM;EACN,WAAW;EACX,gBAAgB;EAChB,aAAa;EACb,SAAS;EACT,UAAU;EACV,kBAAkB,CAAC;GAClB,KAAK;GACL,OAAO;GACP,aAAa;GACb,UAAU;GACV,MAAM;GACN,UAAU;EACX,GAAG;GACF,KAAK;GACL,OAAO;GACP,aAAa;GACb,MAAM;GACN,UAAU;EACX,CAAC;EACD,cAAc;GACb,UAAU;GACV,WAAW;GACX,OAAO;GACP,QAAQ;GACR,WAAW;GACX,KAAK;EACN;EACA,gBAAgB;GACf;GACA;GACA;EACD;EACA,cAAc;GACb,UAAU;GACV,QAAQ;EACT;EACA,iBAAiB;EACjB,0BAA0B;EAC1B,SAAS;CACV;AACD;AACA,SAAS,mBAAmB,KAAK;CAChC,OAAO,kBAAkB,MAAM,aAAa,SAAS,QAAQ,GAAG;AACjE;AACA,MAAM,oBAAoB;CACzB,OAAO;EACN;GACC,IAAI;GACJ,MAAM;GACN,MAAM;GACN,aAAa;EACd;EACA;GACC,IAAI;GACJ,MAAM;GACN,MAAM;GACN,aAAa;EACd;EACA;GACC,IAAI;GACJ,MAAM;GACN,MAAM;GACN,aAAa;EACd;EACA;GACC,IAAI;GACJ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