@kanyun-ai-infra/agenthub 0.1.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../contracts/dist/chunk-DDAAVRWG.js","../../contracts/src/run.ts","../../contracts/src/legacy-model-alias.ts","../../contracts/src/default-model-resolver.ts","../../contracts/src/bedrock-compatible-model.ts","../../contracts/src/modelgate-vendor.ts","../../contracts/src/agent.ts","../../contracts/src/artifact.ts","../../contracts/src/api.ts","../../contracts/src/events.ts","../../contracts/src/recovery.ts","../../contracts/src/project.ts","../../contracts/src/webhook-context.ts","../../contracts/src/sandbox-types.ts","../../contracts/src/merge-request.ts","../../contracts/src/runtime-profile.ts","../../contracts/src/shell-safe.ts","../../contracts/src/summarize.ts","../../contracts/src/workspace-diff.ts","../../contracts/src/agent-push.ts","../../contracts/src/agent-worker-bundle-release.ts","../../contracts/src/credential-reload.ts","../../contracts/src/pilot-v2-credentials-broker.ts","../../contracts/src/pod-agent-git-push.ts","../../contracts/src/wecom.ts","../../contracts/src/wecom-config.ts","../../contracts/src/wecom-push.ts","../../contracts/src/user-git-credential.ts","../../contracts/src/scope.ts","../../contracts/src/platform-token.ts","../../contracts/src/sdk-message.ts","../../contracts/src/sdk-api.ts","../../contracts/src/mcp.ts","../../contracts/src/skill.ts","../../contracts/src/api-version.ts","../../contracts/src/cli-wire.ts","../../contracts/src/message-normalize.ts","../../contracts/src/pilot-v2-delivery-result.ts","../../contracts/src/pilot-v2-events.ts","../../contracts/src/pilot-v2-worker-protocol-events.ts","../../contracts/src/worker-protocol-provider.ts","../../contracts/src/runtime-provider.ts","../../contracts/src/pilot-v2-session.ts","../../contracts/src/pilot-v2-runtime-template.ts","../../contracts/src/pilot-v2-vault.ts","../../contracts/src/schedules.ts","../../contracts/src/pilot-v2-managed-agent-profile.ts","../../contracts/src/pilot-v2-workload-manifest.ts","../../contracts/src/pilot-platform-sdk.ts","../../contracts/src/pilot-coder-prompt-payload.ts","../../contracts/src/pilot-v2-gateway.ts","../../contracts/src/outbound-webhook.ts","../../contracts/src/session-prewarming.ts","../../contracts/src/session-lifecycle-config.ts","../../contracts/src/resource-cleanup.ts","../src/errors.ts","../src/resources/projects.ts","../src/resources/sessions.ts","../src/resources/workloads.ts","../src/client.ts"],"sourcesContent":["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\nexport {\n __spreadValues,\n __spreadProps\n};\n//# sourceMappingURL=chunk-DDAAVRWG.js.map","import { z } from \"zod\";\n\n// RunStatus 保持现有 15 个状态\nexport const RunStatusSchema = z.enum([\n \"queued\",\n \"provisioning\",\n \"preparing\",\n \"running\",\n \"finalizing_prepare\",\n \"finalizing_uploading\",\n \"finalizing_verifying\",\n \"finalizing_metadata_commit\",\n \"finalized\",\n \"completed\",\n \"failed\",\n \"worker_unreachable\",\n \"finalizing_retryable_failed\",\n \"finalizing_timeout\",\n \"finalizing_manual_intervention\",\n]);\nexport type RunStatus = z.infer<typeof RunStatusSchema>;\n\n/**\n * V2 delivery-phase auxiliary enum (R-RSM-02-aux).\n *\n * Authoritative source: `specs/features/pilot-v2-run-state-machine.md`\n * § \"delivery_phase 辅助列\".\n *\n * Persisted in `runs.delivery_phase` for `pilot_api_version = 'v2'`\n * rows only. This enum is *semantically disjoint* from `RunStatus`\n * even though it shares the `\"completed\"` and `\"failed\"` literals:\n *\n * - It is NOT a substate of `running`; it is an orthogonal axis\n * describing what the agent-worker delivery handler observed.\n * - It MUST NOT be folded into `RunStatusSchema`, otherwise we\n * break the R-RSM-02 LOCK \"no new statuses on v2\" invariant.\n * - Wire-format terminal transitions\n * (`worker_protocol.{prompt,followup}.{completed,failed}`) continue\n * to drive `runs.status`. The delivery phase is reported separately\n * via the L1.3 mutation API (`POST /api/sessions/:id/runs/:runId/delivery-result`).\n *\n * The shared literals (`\"completed\"`, `\"failed\"`) are intentional:\n * per AGENTS.md § \"Same-name-different-meaning literals\", code-side\n * references always travel with a column qualifier\n * (`run.deliveryPhase === \"completed\"` vs `run.status === \"completed\"`),\n * making grep deterministic. Plan ref `plans/p3-pilot-coder-v2-full-migration.md`\n * L1.2 §\"命名 delivery_phase 而非 delivery_status …\".\n */\nexport const RunDeliveryPhaseSchema = z.enum([\"in_progress\", \"completed\", \"failed\"]);\nexport type RunDeliveryPhase = z.infer<typeof RunDeliveryPhaseSchema>;\n\nexport const TriggerSourceSchema = z.enum([\n \"user\",\n \"webhook\",\n \"alert\",\n \"cron\",\n \"wecom_chat\",\n \"jira\",\n]);\nexport type TriggerSource = z.infer<typeof TriggerSourceSchema>;\n\n/**\n * `ProviderType` enum.\n *\n * Phase 2 of `docs/proposals/pilot-multi-provider-via-modelgate.md`\n * extended this enum from the two legacy keys (`claude-code` / `codex`)\n * to cover every ModelGate `vendor_type` listed in proposal §3 row 3.\n *\n * **Vendor names follow ModelGate `owned_by`, not product brand.**\n * The 9 new entries match the empirical `/v1/models` superset\n * (probed via `scripts/probe-modelgate-chat-completions.mjs` on\n * 2026-06; see proposal §5.1 results). E.g. ModelGate emits\n * `\"google\"` for Gemini, `\"dashscope\"` for Qwen, `\"moonshot\"` for\n * Kimi, `\"volcengine\"` for Doubao — Pilot mirrors those values so\n * `vendorTypeToProvider()` round-trips bit-for-bit.\n *\n * **Backward compatibility.**\n * - `claude-code` / `codex` remain the canonical keys for the legacy\n * `anthropic` / `openai` runtime adapters. Persisted `runs.provider`\n * values stay valid bit-for-bit; no DB migration required (column\n * is `varchar(50)` with no CHECK constraint — see migration `0011`).\n * - The 9 new entries are accepted at persist time so RunSpec /\n * Schedule payloads can land vendor-specific selections from the\n * new dropdown (Phase 5). Runtime dispatch for the new keys is\n * **not yet** registered — `createProvider({type})` will throw\n * `Unsupported provider type` until Phase 3 ships its adapters.\n *\n * **Bridge to ModelGate.** Use `vendorTypeToProvider()` from\n * `./modelgate-vendor` to map `/v1/models` `owned_by` → this enum.\n * Pilot MUST NOT hardcode model-ID → vendor heuristics in product code;\n * ModelGate owns that relation.\n */\nexport const ProviderTypeSchema = z.enum([\n // Legacy runtime keys (do NOT reorder; preserves persisted values).\n \"claude-code\",\n \"codex\",\n // ModelGate vendor expansion (names mirror ModelGate `owned_by`).\n \"deepseek\",\n \"google\",\n \"zhipu\",\n \"volcengine\",\n \"tencent\",\n \"moonshot\",\n \"minimax\",\n \"dashscope\",\n \"xiaomi\",\n]);\nexport type ProviderType = z.infer<typeof ProviderTypeSchema>;\n\n/**\n * Default model identifiers per provider. Used for display when no\n * `modelOverride` is set on the Run.\n *\n * Legacy entries (`claude-code` / `codex`) keep the historical alias\n * values (`opus` / `gpt-5.3-codex`) for back-compat with rows already\n * persisted before Phase 6 lands the real-ID translation layer.\n *\n * New vendor entries point at a representative real ModelGate ID per\n * vendor (verified via `scripts/list-modelgate-inference-models.mjs`\n * on 2026-06). These are *best-effort defaults* used only when a\n * vendor-specific run is created without an explicit model — Phase 5\n * (server-driven dropdown) will replace these with the live\n * `/v1/models` lookup so the table can stay stale without harming UX,\n * but it MUST stay populated so that `RunSpec` building never produces\n * an undefined model string.\n */\nexport const PROVIDER_DEFAULT_MODELS: Record<ProviderType, string> = {\n \"claude-code\": \"opus\",\n codex: \"gpt-5.3-codex\",\n deepseek: \"deepseek-v4-pro\",\n google: \"gemini-3.1-pro-preview\",\n zhipu: \"glm-5\",\n volcengine: \"doubao-seed-2-0-pro-260215\",\n tencent: \"hy3-preview\",\n moonshot: \"kimi-k2.6\",\n minimax: \"minimax-m3\",\n dashscope: \"qwen3.7-max\",\n xiaomi: \"xiaomi/mimo-v2.5-pro\",\n};\n\n/** A selectable model option combining model ID, display label, and its provider. */\nexport interface ModelOption {\n id: string;\n label: string;\n provider: ProviderType;\n}\n\n/**\n * Legacy fallback dictionary of model options.\n *\n * **Status (post Phase 2):** This array is the *server-side fallback*\n * dictionary, NOT the canonical source of selectable models. The\n * canonical source is `GET /api/models` (Phase 1), which surfaces the\n * full ModelGate `/v1/models` catalogue (39 models as of 2026-06).\n *\n * Why it still exists:\n * - 14 sync server-side call sites (webhooks/github/gitlab/jira,\n * wecom message-handler, Portal/Automations pages, settings route)\n * use `MODEL_OPTIONS` / `getProviderForModel()` to reverse-lookup\n * a project's `default_model` → `ProviderType`. They cannot await\n * `/api/models` synchronously and must keep a local table.\n * - Phase 5 (server-driven dropdown) and Phase 7 (unified\n * `resolveDefaultModel`) will collapse all 14 sites onto a single\n * resolver and delete this array. Until those land, do NOT add\n * entries here for new ModelGate models — extending this table\n * re-introduces the white-list maintenance burden proposal §1\n * decided to eliminate.\n */\nexport const MODEL_OPTIONS: readonly ModelOption[] = [\n { id: \"opus\", label: \"Opus 4.6\", provider: \"claude-code\" },\n { id: \"gpt-5.3-codex\", label: \"Codex 5.3\", provider: \"codex\" },\n];\n\nexport const getModelLabel = (model: string, provider: ProviderType) => {\n const found = MODEL_OPTIONS.find((option) => option.id === model && option.provider === provider);\n return found?.label ?? model;\n};\n\n/**\n * Resolve a model ID to its declared provider in `MODEL_OPTIONS`.\n *\n * Used by automation entry points (webhooks + wecom message-handler) to\n * derive `provider` from the project's `default_model`. Hardcoding the\n * provider on those paths used to mis-pair codex models with the\n * claude-code runtime and fail the run with `400 The provided model\n * identifier is invalid`. See `specs/features/automations-page.md`\n * §自动化默认.\n *\n * Returns `null` for unknown model IDs so callers can fall back to a\n * sensible default rather than panicking.\n */\nexport const getProviderForModel = (modelId: string): ProviderType | null => {\n if (!modelId) return null;\n const fromStaticOptions = MODEL_OPTIONS.find((option) => option.id === modelId)?.provider;\n if (fromStaticOptions) return fromStaticOptions;\n\n // Keep a tiny compatibility fallback for high-frequency historical IDs.\n // This avoids mis-routing automation-triggered runs while the model catalogue\n // has moved to server-driven `/api/models`.\n if (modelId === \"gpt-5.3-codex\") return \"codex\";\n if (modelId === \"opus\" || modelId === \"sonnet\" || modelId === \"haiku\") return \"claude-code\";\n if (modelId.startsWith(\"claude-\")) return \"claude-code\";\n\n return null;\n};\n\n// Attachment metadata — stored in runs.attachments_json\nexport const AttachmentMetaSchema = z.object({\n /** OSS original URL (Agent Worker downloads via this) */\n ossUrl: z.string().min(1),\n /** Original filename */\n filename: z.string().min(1).max(255),\n /** File size in bytes */\n size: z.number().int().positive(),\n /** Media type classification */\n mediaType: z.enum([\"image\", \"document\", \"code\", \"notebook\"]),\n /** MIME type */\n mimeType: z.string(),\n});\nexport type AttachmentMeta = z.infer<typeof AttachmentMetaSchema>;\n\n// RunSpec - 基于 specs/architecture/runtime-profile.md RunSpec 字段\nexport const RunSpecSchema = z.object({\n prompt: z.string().min(1),\n projectId: z.string().uuid(),\n agentId: z.string().uuid().optional(),\n agentMode: z.enum([\"task\", \"chat\"]).optional(),\n repo: z.string().optional(),\n ref: z.string().optional(),\n model: z.string().optional(),\n provider: ProviderTypeSchema.optional().default(\"claude-code\"),\n runnerRequired: z.boolean().optional().default(false),\n triggerSource: TriggerSourceSchema.optional().default(\"user\"),\n triggerRef: z.string().optional(),\n githubInstallationId: z.string().optional(),\n attachments: z.array(AttachmentMetaSchema).max(5).optional(),\n /**\n * LDAP of the user whose action created this run. Populated by\n * Portal / 企微 entry points. Null / undefined for webhook / automation\n * triggers where we cannot identify a single human, in which case\n * prepareWorkspace falls back to the service-level Bedrock key.\n * See specs/features/user-bedrock-credentials.md.\n */\n triggerUserLdap: z.string().min(1).optional(),\n /**\n * Per-run override for the effective MCP / Skills enable list (spec\n * §6.3). Either field being present (including `[]`) writes into the\n * corresponding `runs.enabled_*` column; `undefined` leaves the\n * column NULL, in which case the runtime resolver falls through to\n * `agents.enabled_*`.\n *\n * Phase 1 has no Portal UI surface for this — the field is reserved\n * for SDK / webhook automations. See specs/features/mcp-and-skills.md.\n *\n * Element shape is validated by the API layer (Zod) — at the\n * RunService layer we accept already-validated arrays as opaque to\n * keep the service free of contracts re-imports.\n */\n // Element shape validated at the API layer; RunService accepts opaque arrays\n // (see comment above) so no further runtime check here.\n enabledMcpServers: z.array(z.any()).optional(),\n enabledSkills: z.array(z.any()).optional(),\n});\nexport type RunSpec = z.infer<typeof RunSpecSchema>;\n\n// Run 完整接口 - 基于 specs/architecture/data-model.md runs 表\nexport const RunSchema = z.object({\n id: z.string().uuid(),\n agentId: z.string().uuid(),\n parentRunId: z.string().uuid().nullable(),\n status: RunStatusSchema,\n prompt: z.string(),\n projectId: z.string().uuid(),\n repoUrl: z.string().nullable(),\n targetRef: z.string().nullable(),\n modelOverride: z.string().nullable(),\n runnerRequired: z.boolean(),\n runtimeProfileVersion: z.number().int().nullable(),\n runtimeProfileSnapshot: z.record(z.unknown()).nullable(),\n activeStreamId: z.string().nullable(),\n agentStreamId: z.string().nullable(),\n provider: ProviderTypeSchema.default(\"claude-code\"),\n triggerSource: TriggerSourceSchema,\n triggerRef: z.string().nullable(),\n githubInstallationId: z.string().nullable(),\n retryCount: z.number().int().default(0),\n maxRetries: z.number().int().default(3),\n pullRequestUrl: z.string().nullable(),\n errorMessage: z.string().nullable(),\n attachmentsJson: z.array(AttachmentMetaSchema).nullable(),\n /** LDAP of the triggering user; null when unknown (webhook / automation). */\n triggerUserLdap: z.string().nullable(),\n createdAt: z.date(),\n updatedAt: z.date(),\n startedAt: z.date().nullable(),\n completedAt: z.date().nullable(),\n});\nexport type Run = z.infer<typeof RunSchema>;\n\n// 合法的状态转换映射\nexport const VALID_RUN_TRANSITIONS: Record<RunStatus, RunStatus[]> = {\n queued: [\"provisioning\", \"failed\"],\n provisioning: [\"preparing\", \"failed\"],\n preparing: [\"running\", \"failed\"],\n running: [\"finalizing_prepare\", \"failed\", \"worker_unreachable\"],\n finalizing_prepare: [\"finalizing_uploading\", \"failed\", \"finalizing_retryable_failed\"],\n finalizing_uploading: [\"finalizing_verifying\", \"failed\", \"finalizing_retryable_failed\"],\n finalizing_verifying: [\"finalizing_metadata_commit\", \"failed\", \"finalizing_retryable_failed\"],\n finalizing_metadata_commit: [\"finalized\", \"failed\", \"finalizing_retryable_failed\"],\n finalized: [\"completed\"],\n completed: [],\n failed: [\"queued\"], // retry\n worker_unreachable: [\"failed\", \"running\"], // recovery or fail\n finalizing_retryable_failed: [\"finalizing_uploading\", \"finalizing_timeout\"],\n finalizing_timeout: [\"finalizing_manual_intervention\"],\n finalizing_manual_intervention: [\"failed\"],\n};\n\n/**\n * V2 run short chain (R-RSM-02).\n *\n * Source of truth: `specs/features/pilot-v2-run-state-machine.md` §R-RSM-02.\n *\n * v2 runs (`runs.pilot_api_version === 'v2'`) follow a strict 6-state\n * reachable subset: `queued → provisioning → preparing → running → completed | failed`.\n * The `finalizing_*` substate machine and `worker_unreachable` mid-state\n * are intentionally unreachable on v2 — those concerns are owned by the\n * managed_agent worker inside the sandbox, not by Pilot control-plane.\n *\n * The defensive empty-array entries for v1-only statuses make\n * `RunService.tryAdvanceStatus` deterministic-deny instead of throwing\n * an out-of-table key error if a v2 run ever observes a non-reachable\n * status (which would indicate a logic bug elsewhere).\n *\n * Cross-version invariant:\n * - Both tables share the same `RunStatus` 15-state enum. v2 does NOT\n * introduce new statuses; it just uses a strict subset.\n * - v1 runs continue to use `VALID_RUN_TRANSITIONS` verbatim.\n *\n * Reverse compat: any future v2 run that needs an additional reachable\n * status (e.g. abort terminal) MUST update this table + a matching test\n * in `__tests__/schemas.test.ts`; do NOT branch on `pilot_api_version`\n * inside `tryAdvanceStatus` beyond the table selection.\n */\nexport const VALID_V2_RUN_TRANSITIONS: Record<RunStatus, RunStatus[]> = {\n queued: [\"provisioning\", \"failed\"],\n provisioning: [\"preparing\", \"failed\"],\n preparing: [\"running\", \"failed\"],\n running: [\"completed\", \"failed\"],\n completed: [],\n failed: [], // v2 has NO automatic retry; failed is terminal (R-RSM-01)\n\n // unreachable on v2 — defensive empty arrays (R-RSM-02)\n finalizing_prepare: [],\n finalizing_uploading: [],\n finalizing_verifying: [],\n finalizing_metadata_commit: [],\n finalized: [],\n worker_unreachable: [],\n finalizing_retryable_failed: [],\n finalizing_timeout: [],\n finalizing_manual_intervention: [],\n};\n","/**\n * Legacy model-id alias translator — Phase 6 of\n * `docs/proposals/pilot-multi-provider-via-modelgate.md` §5.3.\n *\n * Pilot historically persisted Bedrock-style aliases (`opus`, `sonnet`,\n * `haiku`) in `runs.model_override` and `projects.default_model`. Those\n * names worked when claude-code went straight to AWS Bedrock (which has\n * its own alias layer), but ModelGate's `/v1/models` only knows real\n * model identifiers like `claude-opus-4-7`. Sending a Bedrock alias to\n * ModelGate is an \"unknown model\" 4xx waiting to happen.\n *\n * Per proposal §1 decision row 7:\n *\n * > 数据迁移: `runs.model = \"opus\"` 等历史 alias 在**读取时**翻译,\n * > 不做 DB backfill — 兜底逻辑简单,避免破坏历史归档可读性。\n *\n * Translation matrix (proposal §5.3):\n *\n * | input | output | reason |\n * |-------------|-------------------|-------------------|\n * | \"opus\" | \"claude-opus-4-7\" | Bedrock alias |\n * | \"sonnet\" | \"claude-sonnet-4-6\" | Bedrock alias |\n * | \"haiku\" | \"claude-haiku-4-5\" | Bedrock alias |\n * | any real id | unchanged | passthrough |\n * | unknown | system default + console.warn | safety net |\n *\n * `gpt-5.3-codex` is intentionally absent from the alias table — it is\n * already a real ModelGate id (proposal §5.3 row 4), so passthrough is\n * correct.\n *\n * Where this gets applied:\n * - `ClaudeCodeProvider.createModel(modelId)` — the moment the id\n * becomes a wire-level model id sent to the Anthropic SDK.\n * - `CodexProvider.createModel(modelId)` — symmetric defensive\n * translation. No-op for `gpt-5.3-codex`; future-proofs against\n * codex-side aliases the team might add.\n *\n * NOT applied at:\n * - DB write paths — `runs.model_override` and `projects.default_model`\n * keep whatever the caller passed (Portal will pass real ids post\n * Phase 5; webhooks/automations may still pass aliases until Phase 7).\n * - UI label resolution — `useModels.getModelLabel` and\n * `getModelLabel` from `contracts/run.ts` already handle the\n * `MODEL_OPTIONS` fallback for display.\n *\n * Why \"unknown → system default\" is safer than \"unknown → throw\":\n * The translator sits at the transport-output boundary; throwing would\n * take down a Run whose only fault is being created when a model id\n * was typo'd or has since been retired from ModelGate. Falling back to\n * the system default keeps the Run usable and surfaces the issue via\n * `console.warn` for observability.\n */\n\n/**\n * The system-default model id, used when an unknown alias is encountered.\n * Matches proposal §1 decision row 7 (`claude-opus-4-7`) — the current\n * \"first available Anthropic\" baseline.\n *\n * Exported so call sites can reference it consistently (e.g. unit tests\n * asserting fallback behavior) instead of duplicating the literal.\n */\nexport const SYSTEM_DEFAULT_MODEL_ID = \"claude-opus-4-7\";\n\n/**\n * Hard-coded alias → real-id map. Frozen to prevent drive-by additions\n * from re-introducing the white-list maintenance burden proposal §1\n * explicitly decided to eliminate.\n *\n * Treat additions to this map as a deliberate, spec-tracked migration\n * (each new alias is a new historical data-shape to support forever).\n */\nexport const LEGACY_MODEL_ALIASES: Readonly<Record<string, string>> = Object.freeze({\n opus: \"claude-opus-4-7\",\n sonnet: \"claude-sonnet-4-6\",\n haiku: \"claude-haiku-4-5\",\n});\n\n/**\n * Known-real-id allow-list — defines what counts as \"already resolved\"\n * for the {@link resolveLegacyModelAlias} fallback decision. Empty by\n * default because Pilot intentionally does NOT maintain a white-list of\n * valid ModelGate ids (proposal §1 row 2). Callers that need stricter\n * unknown-id handling can layer their own validation outside this\n * translator.\n *\n * Why this is exported as `null` rather than an empty Set:\n * The translator's contract is \"if it's not an alias, pass it\n * through\". An empty allow-list would force every non-alias id into\n * the warning path, which would spam logs with every legitimate\n * ModelGate id. `null` means \"trust the caller's id; only the\n * explicitly-listed aliases get translated\".\n */\nexport const KNOWN_REAL_MODEL_IDS: ReadonlySet<string> | null = null;\n\n/**\n * Result of one alias-translation attempt.\n *\n * `wasAlias`: true iff `input` was a key in {@link LEGACY_MODEL_ALIASES}.\n * Distinguishes \"I translated an alias\" from \"I passed your\n * id through unchanged\". Useful for callers that want to\n * log only when a translation actually happened (rather\n * than logging every model-id read).\n *\n * `wasFallback`: true iff the translator could not match an alias AND\n * the id was rejected by the optional allow-list. In\n * this case `resolved` is `SYSTEM_DEFAULT_MODEL_ID`.\n * Always false today because `KNOWN_REAL_MODEL_IDS` is\n * `null` (passthrough policy) — wired through so future\n * strict-mode callers don't need an API change.\n */\nexport interface ResolvedModelId {\n resolved: string;\n wasAlias: boolean;\n wasFallback: boolean;\n}\n\n/**\n * Translate a (possibly legacy) model id to its real ModelGate id.\n *\n * - alias hit → returns the mapped real id, `wasAlias: true`.\n * - passthrough → returns input unchanged, both flags false.\n * - empty / nullish → returns {@link SYSTEM_DEFAULT_MODEL_ID},\n * `wasFallback: true`. (No warning logged for this case — empty input\n * typically means \"no override, use whatever default is configured\",\n * which is a normal flow rather than a regression signal.)\n * - allow-list strict mode (future) → falls back to system default with\n * `console.warn`. Currently unreachable because the allow-list is\n * `null`; preserved as dead code on purpose to keep the contract\n * stable for Phase 7.\n *\n * Pure function — no I/O, no `Date.now()`, no globals other than\n * `console.warn` on the fallback path (which is intentional\n * observability, not state).\n */\nexport function resolveLegacyModelAlias(input: string | null | undefined): ResolvedModelId {\n if (!input || input.length === 0) {\n return { resolved: SYSTEM_DEFAULT_MODEL_ID, wasAlias: false, wasFallback: true };\n }\n\n const aliased = LEGACY_MODEL_ALIASES[input];\n if (aliased) {\n return { resolved: aliased, wasAlias: true, wasFallback: false };\n }\n\n if (KNOWN_REAL_MODEL_IDS !== null && !KNOWN_REAL_MODEL_IDS.has(input)) {\n // Defensive branch — currently unreachable because the allow-list\n // is `null`. Kept so a future \"strict mode\" toggle has somewhere to\n // land without an API change, and so the warning channel is\n // exercised in tests by temporarily swapping in a non-null set.\n console.warn(\n `[legacy-model-alias] Unknown model id \"${input}\" — falling back to ${SYSTEM_DEFAULT_MODEL_ID}.`,\n );\n return { resolved: SYSTEM_DEFAULT_MODEL_ID, wasAlias: false, wasFallback: true };\n }\n\n return { resolved: input, wasAlias: false, wasFallback: false };\n}\n\n/**\n * Thin convenience wrapper for the common \"just give me a usable id\"\n * call shape. Equivalent to `resolveLegacyModelAlias(input).resolved`.\n *\n * Use this in transport boundaries (e.g. inside\n * `Provider.createModel()`); use the full {@link resolveLegacyModelAlias}\n * when you also want to branch on `wasAlias` / `wasFallback` (e.g.\n * structured logging).\n */\nexport function resolveModelIdOrDefault(input: string | null | undefined): string {\n return resolveLegacyModelAlias(input).resolved;\n}\n","/**\n * Default-model fallback resolver — Phase 7 of\n * `docs/proposals/pilot-multi-provider-via-modelgate.md` §1 row 7.\n *\n * Webhook / wecom / automation entry points historically derived the\n * model id ad-hoc:\n *\n * const model = project.defaultModel ?? null;\n * const provider = model ? (getProviderForModel(model) ?? \"claude-code\") : \"claude-code\";\n *\n * That left two gaps the proposal called out:\n *\n * 1. `runs.model_override` was nullable on the webhook path, so\n * historical runs could not tell *which* default was in effect\n * (project default vs system default vs provider default vs\n * whatever agent-runtime happened to pick). Observability suffers.\n * 2. There was no central place to wire a future user-level default\n * (proposal §1 envisages run > project > user > system).\n *\n * This module fills both gaps with one pure function. It does NOT do\n * alias translation — keep that responsibility in\n * `legacy-model-alias.ts` so the two concerns can evolve independently.\n *\n * Composition order at the call site:\n *\n * const { resolved, source } = resolveDefaultModel({\n * projectDefault: project.defaultModel,\n * });\n * // Optionally feed `resolved` through `resolveLegacyModelAlias` if\n * // the call site writes to a wire boundary; for DB writes / RunSpec\n * // we keep the historical alias so audit logs stay grep-able.\n *\n * Why 4 priority tiers instead of the spec's \"3 tiers\":\n * Proposal §1 row 7 says `run > project > user > system`. There is no\n * `users.default_model` column today, but `userDefault` is accepted\n * as an optional input so a future schema migration can plug in\n * without an API change. Until then callers pass `undefined`.\n *\n * Why `source` is in the return value:\n * So the call site can structured-log \"model=X source=project\" for\n * the provisioning event. Without it, downstream observability would\n * have to re-derive the source from the inputs, defeating the point\n * of centralizing the fallback ladder.\n */\n\nimport { SYSTEM_DEFAULT_MODEL_ID } from \"./legacy-model-alias\";\n\n/**\n * Which tier of the fallback ladder produced {@link ResolvedDefaultModel.resolved}.\n *\n * - `\"run\"` — caller supplied a `runOverride` (the highest-priority slot,\n * used when a webhook payload carries an explicit `model` field\n * such as `@bot use opus`).\n * - `\"project\"` — `projects.default_model` was set.\n * - `\"user\"` — future: `users.default_model` was set. Currently unreachable\n * because the DB column does not exist yet; kept on the type\n * so callers can wire it in without changing this contract.\n * - `\"system\"` — none of the above provided a value, so the resolver fell\n * back to {@link SYSTEM_DEFAULT_MODEL_ID}.\n */\nexport type DefaultModelSource = \"run\" | \"project\" | \"user\" | \"system\";\n\nexport interface ResolvedDefaultModel {\n resolved: string;\n source: DefaultModelSource;\n}\n\n/**\n * Inputs for {@link resolveDefaultModel}.\n *\n * Every field is optional. `null` and `undefined` are treated identically\n * (both mean \"tier not provided\") — this matches how the inputs arrive\n * from Drizzle (`column | null`) and from optional payload fields\n * (`payload.model ?? undefined`) without forcing each call site to\n * normalize.\n *\n * `systemDefault` is overridable mostly for tests; production callers\n * should leave it `undefined` and let the resolver use\n * {@link SYSTEM_DEFAULT_MODEL_ID}.\n */\nexport interface ResolveDefaultModelInput {\n runOverride?: string | null;\n projectDefault?: string | null;\n userDefault?: string | null;\n systemDefault?: string;\n}\n\n/**\n * Walk the run → project → user → system fallback ladder, returning\n * the first non-empty model id together with the tier it came from.\n *\n * Empty-string is treated as \"not provided\" because Drizzle round-trips\n * empty varchar columns as `\"\"` rather than `null` on some platforms,\n * and a webhook payload `{ model: \"\" }` is semantically \"not provided\"\n * to a human reader.\n *\n * Pure function — no I/O, no globals, deterministic given inputs.\n */\nexport function resolveDefaultModel(input: ResolveDefaultModelInput): ResolvedDefaultModel {\n const { runOverride, projectDefault, userDefault, systemDefault } = input;\n\n if (runOverride && runOverride.length > 0) {\n return { resolved: runOverride, source: \"run\" };\n }\n if (projectDefault && projectDefault.length > 0) {\n return { resolved: projectDefault, source: \"project\" };\n }\n if (userDefault && userDefault.length > 0) {\n return { resolved: userDefault, source: \"user\" };\n }\n return {\n resolved: systemDefault ?? SYSTEM_DEFAULT_MODEL_ID,\n source: \"system\",\n };\n}\n","/**\n * Bedrock-compatibility check for `provider=claude-code` model IDs.\n *\n * **Why this exists:** Pilot historically supported a small set of model\n * aliases (`opus` / `sonnet` / `haiku`) that the Bedrock injection path\n * translates to ARN env vars (`ANTHROPIC_DEFAULT_OPUS_MODEL` etc.). When the\n * full ModelGate catalogue was introduced, users started selecting real\n * ModelGate IDs (e.g. `claude-sonnet-4-6`) which only exist on the ModelGate\n * inference proxy — Bedrock does NOT recognize them. If `decideModelGateInjection`\n * returns `use: false` for such a model the historical behavior was to silently\n * fall through to the Bedrock path, which then sent the unknown ID to Bedrock\n * and surfaced an opaque `400 The provided model identifier is invalid` error\n * to the end user, hiding the real root cause (missing TOKEN_ENCRYPTION_KEY /\n * USE_MODELGATE / approval account).\n *\n * This helper is the single source of truth for the \"can this model survive\n * a Bedrock fallback?\" question. Callers (currently `prepareWorkspace`) use\n * it to fail-fast when ModelGate is unavailable but the user picked a\n * ModelGate-only model — giving operators the typed skip reason (resolver-\n * not-wired / ldap-missing / etc.) instead of a misleading downstream error.\n *\n * Kept in `@pilot/contracts` (not control-plane) so SDKs / front-ends can\n * also gate UI affordances on the same set without taking a heavier dep.\n */\n\n/**\n * Model IDs that the Bedrock injection path can serve via the per-alias\n * `ANTHROPIC_DEFAULT_*_MODEL` env vars. **Adding entries is a deliberate\n * decision** — every new alias becomes a forever supported data shape.\n *\n * Synced with `LEGACY_MODEL_ALIASES` in `legacy-model-alias.ts`: that file\n * owns the *translation* direction (alias → real id for read-time\n * normalization); this file owns the *capability* direction (which aliases\n * the Bedrock path can actually serve). Today the two sets are identical\n * but the responsibilities are distinct enough to keep separate.\n */\nexport const BEDROCK_COMPATIBLE_MODEL_IDS: ReadonlySet<string> = Object.freeze(\n new Set<string>([\"opus\", \"sonnet\", \"haiku\"]),\n);\n\n/**\n * True iff this `modelOverride` value can be served by the Bedrock fallback\n * path. Pure predicate — no I/O, no allocations on the hot path.\n *\n * - `null` / `undefined` / `\"\"` → `true` (no override means \"use whatever\n * the project / system default is\"; that default is itself an alias today\n * so the run remains Bedrock-serviceable).\n * - alias hit (opus / sonnet / haiku) → `true`.\n * - any other string (real ModelGate id, typo, future vendor id) → `false`.\n */\nexport function isBedrockCompatibleModel(modelOverride: string | null | undefined): boolean {\n if (!modelOverride || modelOverride.length === 0) return true;\n return BEDROCK_COMPATIBLE_MODEL_IDS.has(modelOverride);\n}\n","/**\n * ModelGate vendor → Pilot ProviderType bridge.\n *\n * Source proposal: `docs/proposals/pilot-multi-provider-via-modelgate.md`\n * §3 (table row 3) — \"由 ModelGate `vendor_type` 直接决定 [provider],\n * Pilot 不再硬编码\".\n *\n * Phase 2 deliverable. This module is *new* in P2 and is **not yet\n * consumed** by the 14 legacy `MODEL_OPTIONS` / `getProviderForModel`\n * call sites in webhooks / wecom / Portal. P2's contract is \"behavior\n * unchanged\"; the 14 sites continue to use `MODEL_OPTIONS` (now\n * documented as the legacy fallback dictionary). Phase 3 (agent-runtime\n * vendor adapters) and Phase 4 (vendor-aware sandbox env injection) are\n * the first downstream consumers; Phase 5 (server-driven dropdown) will\n * route Portal UI through `vendorTypeToProvider()` as well.\n *\n * Design notes:\n * - **Why \"anthropic\" → \"claude-code\" and \"openai\" → \"codex\" instead\n * of new dedicated provider keys?** The runtime registry\n * (`packages/agent-runtime/src/registry.ts`) already dispatches on\n * `\"claude-code\"` and `\"codex\"`; renaming would force a coordinated\n * migration of `runs.provider`, schedule payloads, SDK types and DB\n * rows. We collapse the two generic vendors onto the existing keys\n * so legacy data stays valid bit-for-bit. New non-legacy vendors\n * (gemini / glm / qwen / …) get their own ProviderType slot so the\n * runtime registry can extend later without retroactive aliasing.\n *\n * - **Coverage policy.** `MODELGATE_VENDOR_TYPES` enumerates every\n * `owned_by` value Pilot is allowed to see on `/v1/models`. The\n * list mirrors proposal §3 row 3 verbatim. If ModelGate adds a\n * 16th vendor, `/api/models` will still surface it (the inference\n * client passes `owned_by` through untyped), but `RunSpec.provider`\n * would reject it until this enum is extended. That's intentional:\n * it forces an explicit contract review when a new vendor lands.\n *\n * - **Single source of truth.** Pilot MUST NOT layer its own\n * model-ID prefix heuristics (e.g. \"starts with `claude-` →\n * anthropic\") on top of this map. ModelGate owns the\n * `id ↔ vendor` relation; Pilot's job is to forward what `/v1/models`\n * returns and to map vendor → provider via this table only.\n */\n\nimport { z } from \"zod\";\nimport type { ProviderType } from \"./run\";\n\n/**\n * Every `owned_by` value Pilot accepts on `/v1/models`. The list is\n * the empirical superset returned by `GET /v1/models` against the\n * production ModelGate deployment (probed via\n * `scripts/probe-modelgate-chat-completions.mjs` on 2026-06; full\n * results in proposal §5.1). Adding a new entry requires updating\n * `VENDOR_TO_PROVIDER` below.\n *\n * Why these exact strings and not friendlier product labels (e.g.\n * `gemini` / `qwen` / `kimi` / `doubao`): ModelGate stamps `owned_by`\n * with the *vendor infrastructure* name (`google`, `dashscope`,\n * `moonshot`, `volcengine`), not the product brand. Pilot's contract\n * is \"follow ModelGate's source of truth\" (proposal §1 decision row 4),\n * so we mirror those values verbatim — anything else would silently\n * drop matches when `/v1/models` data flows through\n * `vendorTypeToProvider()`.\n *\n * ModelGate's `别名模型` (a Chinese-named internal alias group\n * routing anthropic models through volcengine ark) is intentionally\n * excluded; those entries surface to the dropdown via `/api/models`\n * passthrough but `RunSpec.provider` requires a real vendor — callers\n * are expected to switch to the underlying canonical model ID.\n */\nexport const MODELGATE_VENDOR_TYPES = [\n \"anthropic\",\n \"openai\",\n \"deepseek\",\n \"google\",\n \"zhipu\",\n \"volcengine\",\n \"tencent\",\n \"moonshot\",\n \"minimax\",\n \"dashscope\",\n \"xiaomi\",\n] as const;\n\nexport const ModelGateVendorTypeSchema = z.enum(MODELGATE_VENDOR_TYPES);\nexport type ModelGateVendorType = z.infer<typeof ModelGateVendorTypeSchema>;\n\n/**\n * Bridge table from ModelGate `vendor_type` (= OpenAI `owned_by`) to\n * Pilot `ProviderType`. The two legacy entries (`anthropic` /\n * `openai`) collapse onto the existing runtime keys; everything else\n * is one-to-one with the same string as `ProviderType`.\n *\n * Phase 3 ships a single `openai-compat` agent-runtime adapter that\n * serves every non-legacy entry — the §5.1 probe confirmed all 11\n * ModelGate vendors return the standard OpenAI `chat.completion`\n * envelope, so per-vendor adapters are not required. Until that\n * adapter lands, `createProvider()` throws\n * `Unsupported provider type: <vendor>` at L1.5 dispatch (not at\n * persist time).\n */\nconst VENDOR_TO_PROVIDER: Record<ModelGateVendorType, ProviderType> = {\n anthropic: \"claude-code\",\n openai: \"codex\",\n deepseek: \"deepseek\",\n google: \"google\",\n zhipu: \"zhipu\",\n volcengine: \"volcengine\",\n tencent: \"tencent\",\n moonshot: \"moonshot\",\n minimax: \"minimax\",\n dashscope: \"dashscope\",\n xiaomi: \"xiaomi\",\n};\n\n/**\n * Resolve a ModelGate `vendor_type` to the Pilot `ProviderType` the\n * runtime registry should dispatch on.\n *\n * Throws `TypeError` (rather than returning a default) if the vendor\n * is not in the bridge table — callers should validate via\n * `ModelGateVendorTypeSchema.safeParse` first when handling untrusted\n * input.\n */\nexport function vendorTypeToProvider(vendor: ModelGateVendorType): ProviderType {\n return VENDOR_TO_PROVIDER[vendor];\n}\n\n/**\n * Single model entry surfaced by `GET /api/models`. Mirrors the\n * subset of OpenAI `/v1/models` schema Pilot relies on; Phase 5 may\n * add a derived `provider` field to spare the frontend a separate\n * lookup, but for P2 we keep the wire shape minimal.\n */\nexport interface ModelGateInferenceModel {\n /** Canonical model identifier, e.g. `claude-opus-4-7`, `gpt-5.4`. */\n id: string;\n /** ModelGate vendor label; `undefined` only if upstream omitted the field. */\n ownedBy?: string;\n /** OpenAI envelope object kind, usually `\"model\"`. Passthrough; unused. */\n object?: string;\n /** Creation UNIX timestamp (seconds). Passthrough; unused. */\n created?: number;\n}\n","import { z } from \"zod\";\n\nexport const AgentModeSchema = z.enum([\"task\", \"chat\"]);\nexport type AgentMode = z.infer<typeof AgentModeSchema>;\n\nexport const AgentStatusSchema = z.enum([\"active\", \"closed\", \"deleted\"]);\nexport type AgentStatus = z.infer<typeof AgentStatusSchema>;\n\n/** External chat source that created this agent. null = web-created, \"wecom\" = WeCom aibot. */\nexport const ExternalChatSourceSchema = z.enum([\"wecom\"]);\nexport type ExternalChatSource = z.infer<typeof ExternalChatSourceSchema>;\n\nexport const AgentSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n sandboxId: z.string().nullable(),\n agentMode: AgentModeSchema,\n status: AgentStatusSchema,\n customTitle: z.string().max(200).nullable(),\n /**\n * Baseline git ref captured at agent (task) creation. Frozen for the\n * lifetime of the agent so follow-up runs always re-clone from the\n * branch the user originally selected. Nullable for chat-mode agents\n * and pre-migration rows; consumers fall back to project.defaultBranch.\n */\n baseRef: z.string().nullable(),\n /**\n * Per-agent system prompt (managed_agent profile Phase D). Seeded at\n * creation from the workload default and frozen for the agent's lifetime.\n * `null` → control-worker omits `PilotCoderRunConfigV1.systemPrompt` and\n * agent-worker falls back to the platform-level `SYSTEM_PROMPT`.\n */\n systemPrompt: z.string().nullable(),\n createdBy: z.string().nullable(),\n messagesJson: z.unknown().nullable(), // JSONB - lightweight snapshot\n lastCheckpointId: z.string().uuid().nullable(),\n activeStreamId: z.string().nullable(),\n /** External IM source that created this agent. See specs/features/wecom-chat-integration.md. */\n externalChatSource: ExternalChatSourceSchema.nullable(),\n /** External IM user identifier (e.g. WeCom userid). Unique per (project, source, chatid). */\n externalChatUserid: z.string().nullable(),\n /** External IM chat/conversation identifier. NULL for single chats; set to WeCom `chatid`\n * for group-chat conversations. Part of the composite uniqueness key (2026-04-22). */\n externalChatChatid: z.string().nullable(),\n createdAt: z.date(),\n updatedAt: z.date(),\n lastActiveAt: z.date(),\n});\nexport type Agent = z.infer<typeof AgentSchema>;\n","import { z } from \"zod\";\n\nexport const ArtifactKindSchema = z.enum([\n \"diff\",\n \"patch\",\n \"log\",\n \"screenshot\",\n \"video\",\n \"build\",\n \"report\",\n]);\nexport type ArtifactKind = z.infer<typeof ArtifactKindSchema>;\n\nexport const ArtifactManifestSchema = z.object({\n path: z.string(),\n kind: ArtifactKindSchema,\n contentType: z.string(),\n size: z.number().int().nonnegative(),\n checksum: z.string(),\n required: z.boolean(),\n});\nexport type ArtifactManifest = z.infer<typeof ArtifactManifestSchema>;\n\nexport const ArtifactSchema = z.object({\n id: z.string().uuid(),\n runId: z.string().uuid(),\n kind: ArtifactKindSchema,\n path: z.string(),\n storagePath: z.string(),\n contentType: z.string(),\n size: z.number().int().nonnegative(),\n checksum: z.string(),\n createdAt: z.date(),\n});\nexport type Artifact = z.infer<typeof ArtifactSchema>;\n","import { z } from \"zod\";\nimport { RunSpecSchema } from \"./run\";\n\nexport const CreateRunRequestSchema = RunSpecSchema;\nexport type CreateRunRequest = z.infer<typeof CreateRunRequestSchema>;\n\nexport const CreateRunResponseSchema = z.object({\n runId: z.string().uuid(),\n agentId: z.string().uuid(),\n isNewAgent: z.boolean(),\n});\nexport type CreateRunResponse = z.infer<typeof CreateRunResponseSchema>;\n\nexport const ApiResponseSchema = z.object({\n success: z.boolean(),\n data: z.unknown().optional(),\n error: z.string().optional(),\n code: z.string().optional(),\n message: z.string().optional(),\n});\nexport type ApiResponse<T = unknown> = {\n success: boolean;\n data?: T;\n error?: string;\n code?: string;\n message?: string;\n};\n\n// FollowUp 请求\nexport const FollowUpRequestSchema = z.object({\n runId: z.string().uuid(),\n message: z.string().min(1),\n});\nexport type FollowUpRequest = z.infer<typeof FollowUpRequestSchema>;\n\n// Abort 请求\nexport const AbortRequestSchema = z.object({\n runId: z.string().uuid(),\n reason: z.string().optional(),\n});\nexport type AbortRequest = z.infer<typeof AbortRequestSchema>;\n","import { z } from \"zod\";\nimport { RecoveryTypeSchema, DegradedReasonSchema } from \"./recovery\";\n\n// === UIMessageChunk 类型(AI SDK 原生格式,端到端使用) ===\nexport const UIMessageChunkTypeSchema = z.enum([\n \"text-start\",\n \"text-delta\",\n \"text-end\",\n \"reasoning-start\",\n \"reasoning-delta\",\n \"reasoning-end\",\n \"tool-input-start\",\n \"tool-input-delta\",\n \"tool-input-available\",\n \"tool-output-available\",\n \"tool-output-error\",\n \"start\",\n \"finish\",\n \"error\",\n \"start-step\",\n \"finish-step\",\n]);\nexport type UIMessageChunkType = z.infer<typeof UIMessageChunkTypeSchema>;\n\n// UIMessageChunk - 发送到浏览器的事件块\nexport const UIMessageChunkSchema = z.object({\n type: UIMessageChunkTypeSchema,\n id: z.string().optional(),\n content: z.string().optional(),\n delta: z.string().optional(),\n toolCallId: z.string().optional(),\n toolName: z.string().optional(),\n input: z.unknown().optional(),\n output: z.string().optional(),\n errorText: z.string().optional(),\n reason: z.string().optional(),\n preliminary: z.boolean().optional(),\n});\nexport type UIMessageChunk = z.infer<typeof UIMessageChunkSchema>;\n\n// === 存储层 RunEvent ===\nexport const RunEventSchema = z.object({\n id: z.string().uuid(),\n runId: z.string().uuid(),\n eventType: z.string(),\n payload: z.unknown(),\n cursor: z.number().int(),\n createdAt: z.date(),\n});\nexport type RunEvent = z.infer<typeof RunEventSchema>;\n\n// === Agent Recovery Events ===\nexport const AgentRecoveryStartedEventSchema = z.object({\n type: z.literal(\"agent_recovery_started\"),\n agentId: z.string(),\n sandboxId: z.string(),\n degradedRecovery: z.boolean(),\n degradedReason: DegradedReasonSchema.optional(),\n recoveryType: RecoveryTypeSchema,\n});\nexport type AgentRecoveryStartedEvent = z.infer<typeof AgentRecoveryStartedEventSchema>;\n\nexport const AgentRecoveryHydratedEventSchema = z.object({\n type: z.literal(\"agent_recovery_hydrated\"),\n agentId: z.string(),\n checkpointId: z.string().nullable(),\n messagesCount: z.number(),\n degradedRecovery: z.boolean(),\n});\nexport type AgentRecoveryHydratedEvent = z.infer<typeof AgentRecoveryHydratedEventSchema>;\n\nexport const RecoveredFromCheckpointEventSchema = z.object({\n type: z.literal(\"recovered_from_checkpoint\"),\n checkpointId: z.string(),\n lastEventCursor: z.number().int().nullable(),\n});\nexport type RecoveredFromCheckpointEvent = z.infer<typeof RecoveredFromCheckpointEventSchema>;\n\nexport const AgentRecoveryCompletedEventSchema = z.object({\n type: z.literal(\"agent_recovery_completed\"),\n agentId: z.string(),\n degradedRecovery: z.boolean(),\n});\nexport type AgentRecoveryCompletedEvent = z.infer<typeof AgentRecoveryCompletedEventSchema>;\n\nexport const AgentRecoveryFailedEventSchema = z.object({\n type: z.literal(\"agent_recovery_failed\"),\n agentId: z.string(),\n errorStage: z.string(),\n errorMessage: z.string(),\n degradedReason: DegradedReasonSchema.optional(),\n contextExpected: z.number().optional(),\n contextActual: z.number().optional(),\n});\nexport type AgentRecoveryFailedEvent = z.infer<typeof AgentRecoveryFailedEventSchema>;\n","import { z } from \"zod\";\nimport { ProjectKindSchema } from \"./project\";\nimport { AttachmentMetaSchema, ProviderTypeSchema } from \"./run\";\nimport { WebhookTriggerContextSchema } from \"./webhook-context\";\n\n// Checkpoint 状态\nexport const CheckpointStatusSchema = z.enum([\"in_progress\", \"completed\", \"failed\"]);\nexport type CheckpointStatus = z.infer<typeof CheckpointStatusSchema>;\n\n// 恢复类型\nexport const RecoveryTypeSchema = z.enum([\n \"normal\", // 正常恢复(有 checkpoint)\n \"zero_context\", // 零起点恢复(无 checkpoint,预期)\n \"context_loss\", // 上下文丢失(有 checkpoint 但丢失,异常)\n]);\nexport type RecoveryType = z.infer<typeof RecoveryTypeSchema>;\n\n// 降级原因\nexport const DegradedReasonSchema = z.enum([\n \"no_checkpoint\", // 无 checkpoint\n \"context_mismatch\", // 上下文不一致\n \"checkpoint_corrupt\", // Checkpoint 损坏\n \"checkpoint_storage_unavailable\", // 对象存储 checkpoint 不可用(Phase 2 未实现)\n]);\nexport type DegradedReason = z.infer<typeof DegradedReasonSchema>;\n\n// Checkpoint 触发来源\nexport const CheckpointTriggerSourceSchema = z.enum([\n \"finalization\", // Run Finalization 后(Phase 1)\n \"turn_count\", // Turn 计数触发(Phase 2)\n \"time_interval\", // 定时器触发(Phase 2)\n \"critical_tool\", // 关键工具调用触发(Phase 2)\n \"idle\", // Sandbox idle 前触发(Phase 2)\n]);\nexport type CheckpointTriggerSource = z.infer<typeof CheckpointTriggerSourceSchema>;\n\n// RunCheckpoint - 基于 specs/architecture/data-model.md run_checkpoints 表\nexport const RunCheckpointSchema = z.object({\n id: z.string().uuid(),\n agentId: z.string().uuid(),\n runId: z.string().uuid().nullable(),\n checkpointStatus: CheckpointStatusSchema,\n messagesSnapshot: z.array(z.unknown()).nullable(),\n messagesSnapshotRef: z.string().nullable(),\n lastEventCursor: z.number().int().nullable(),\n pendingToolCalls: z.unknown().nullable(),\n workspaceDeltaManifestRef: z.string().nullable(),\n runtimeProfileSnapshot: z.record(z.unknown()).nullable(),\n triggerSource: CheckpointTriggerSourceSchema.nullable().optional(),\n degradedRecovery: z.boolean().default(false),\n createdAt: z.date(),\n});\nexport type RunCheckpoint = z.infer<typeof RunCheckpointSchema>;\n\n// Agent Restore 请求(发送给 Agent Worker)\nexport const AgentRestoreRequestSchema = z.object({\n runId: z.string(),\n agentId: z.string(),\n messages: z.array(z.unknown()),\n messagesHash: z.string(),\n lastEventId: z.number().int().optional(),\n pendingToolCalls: z.array(z.unknown()).optional(),\n workspaceHydrationRef: z.string().optional(),\n runtimeProfileSnapshot: z.record(z.unknown()).optional(),\n degradedRecovery: z.boolean().optional(),\n});\nexport type AgentRestoreRequest = z.infer<typeof AgentRestoreRequestSchema>;\n\n// Agent Restore 响应(Agent Worker 返回)\nexport const AgentRestoreResponseSchema = z.object({\n success: z.boolean(),\n recovered: z.boolean(),\n messagesHash: z.string().optional(),\n messagesCount: z.number().int().optional(),\n degradedRecovery: z.boolean().optional(),\n error: z.string().optional(),\n});\nexport type AgentRestoreResponse = z.infer<typeof AgentRestoreResponseSchema>;\n\n/**\n * Wire-format MCP server entry, identical to what Claude Code SDK expects in\n * `.mcp.json` (`mcpServers[name]`) — discriminated by presence of `command`\n * (stdio) vs `url` (sse / http).\n *\n * Carrying this in `PromptRequest` / `FollowupRequest` lets control-worker\n * inject MCP servers **directly into the SDK** (`createClaudeCode({\n * defaultSettings: { mcpServers } })`) instead of writing\n * `<workspace>/.mcp.json` to the sandbox disk. SDK direct-injection has two\n * concrete wins over the file path: (a) tokens never land on the sandbox\n * filesystem, (b) bootstrap path (workspace permissions, `.mcp.json` file\n * write) is bypassed — the file route stays as a fallback for older\n * provisioning paths.\n *\n * Permissive at the schema layer (`z.unknown()` for nested values) — the\n * provider does the structural check at call time. We do this because\n * Claude Code SDK accepts a wider union than what `@pilot/mcp` renders\n * today (e.g. `createSdkMcpServer` instances), and we don't want\n * contracts to lag SDK changes.\n */\nexport const McpServerEntrySchema = z.union([\n // stdio entry\n z\n .object({\n command: z.string().min(1),\n args: z.array(z.string()).optional(),\n env: z.record(z.string()).optional(),\n })\n .passthrough(),\n // http / sse entry\n z\n .object({\n type: z.enum([\"http\", \"sse\"]),\n url: z.string().url(),\n headers: z.record(z.string()).optional(),\n })\n .passthrough(),\n]);\nexport type McpServerEntry = z.infer<typeof McpServerEntrySchema>;\n\n/**\n * Map from server name (e.g. `\"shimo-cli\"`) to its wire-format config.\n * Same key/value shape as `mcpServers` inside Claude's `.mcp.json`.\n */\nexport const McpServersMapSchema = z.record(McpServerEntrySchema);\nexport type McpServersMap = z.infer<typeof McpServersMapSchema>;\n\nexport const PromptRequestSchema = z.object({\n runId: z.string().optional(),\n agentId: z.string().optional(),\n prompt: z.string().min(1),\n provider: ProviderTypeSchema.optional(),\n model: z.string().optional(),\n workspacePath: z.string().optional(),\n /**\n * Directory holding the bootstrap-rendered `.mcp.json`. Decoupled from\n * `workspacePath` (which is the agent CWD = user repo) so MCP config never\n * lands inside the user's project tree. When omitted, agent-worker falls\n * back to `workspacePath` for backwards compatibility.\n */\n mcpConfigDir: z.string().optional(),\n attachments: z.array(AttachmentMetaSchema).max(5).optional(),\n /**\n * Runtime-derived context for webhook-triggered runs. When present, Agent\n * Worker injects a set of read-only provider tools so the agent can pull\n * Issue/PR body / history / diff on demand. See `webhook-context.ts`.\n */\n triggerContext: WebhookTriggerContextSchema.optional(),\n /**\n * Resolved MCP servers to inject directly into the SDK (preferred over\n * `<mcpConfigDir>/.mcp.json`). When omitted, the agent-worker falls back\n * to reading `.mcp.json` from `mcpConfigDir` / `workspacePath` (the legacy\n * bootstrap path).\n */\n mcpServers: McpServersMapSchema.optional(),\n /**\n * Run-scoped environment variables to inject into the AI CLI subprocess\n * spawned by agent-worker (e.g. `MCP_<NAME>_BEARER_TOKEN` referenced by\n * codex `config.toml`'s `bearer_token_env_var`). Pilot keeps these out\n * of the on-disk config files so tokens never land on the sandbox FS.\n * Merged into `ProviderConfig.env` by agent-worker.\n */\n env: z.record(z.string(), z.string()).optional(),\n projectKind: ProjectKindSchema.optional().default(\"coding\"),\n});\nexport type PromptRequest = z.infer<typeof PromptRequestSchema>;\n\n// Followup 请求(发送给 Agent Worker)\nexport const FollowupRequestSchema = z.object({\n runId: z.string().optional(),\n agentId: z.string().optional(),\n message: z.string(),\n provider: ProviderTypeSchema.optional(),\n model: z.string().optional(),\n workspacePath: z.string().optional(),\n /** See `PromptRequestSchema.mcpConfigDir`. */\n mcpConfigDir: z.string().optional(),\n expectedMessagesHash: z.string().optional(),\n expectedMessagesCount: z.number().int().optional(),\n attachments: z.array(AttachmentMetaSchema).max(5).optional(),\n /** See `PromptRequestSchema.mcpServers` — same semantics for follow-ups. */\n mcpServers: McpServersMapSchema.optional(),\n /** See `PromptRequestSchema.env` — same semantics for follow-ups. */\n env: z.record(z.string(), z.string()).optional(),\n projectKind: ProjectKindSchema.optional().default(\"coding\"),\n});\nexport type FollowupRequest = z.infer<typeof FollowupRequestSchema>;\n\n// Runner 恢复策略\nexport const RunnerRestorePolicySchema = z.enum([\"restart\", \"lazy-start\", \"skip\"]);\nexport type RunnerRestorePolicy = z.infer<typeof RunnerRestorePolicySchema>;\n\n// Hydration Manifest 分类\nexport const HydrationCategorySchema = z.enum([\n \"conversation\",\n \"workspace\",\n \"runtimeEnv\",\n \"runner\",\n \"attachments\",\n \"artifactsRef\",\n]);\nexport type HydrationCategory = z.infer<typeof HydrationCategorySchema>;\n\nexport const HydrationManifestEntrySchema = z.object({\n category: HydrationCategorySchema,\n ref: z.string(),\n checksum: z.string().optional(),\n size: z.number().int().optional(),\n});\nexport type HydrationManifestEntry = z.infer<typeof HydrationManifestEntrySchema>;\n","import { z } from \"zod\";\n\n/**\n * Built-in \"Platform Default\" project UUID.\n *\n * Holds workloads / runtime_templates / sandboxes that existed before\n * project-scoped resources (see plans/admin-ui-project-namespacing.md L1).\n * Marked with `is_system = true` so it is visible to every authenticated user\n * (read-only). MUST NOT be deleted while any row references it.\n *\n * Authoritative source: `plans/admin-ui-project-namespacing.md` §L1.1.\n */\nexport const PLATFORM_DEFAULT_PROJECT_ID = \"00000000-0000-0000-0000-000000000001\";\n\nexport const GitProviderSchema = z.enum([\"gitlab\", \"github\"]);\nexport type GitProvider = z.infer<typeof GitProviderSchema>;\nexport const ProjectKindSchema = z.enum([\"coding\", \"general\"]);\nexport type ProjectKind = z.infer<typeof ProjectKindSchema>;\n\nexport const ProjectSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1),\n kind: ProjectKindSchema.default(\"coding\"),\n /**\n * `true` for the built-in `Platform Default` project (id =\n * `PLATFORM_DEFAULT_PROJECT_ID`). System projects are visible to every\n * authenticated user but read-only at the UI layer.\n *\n * See plans/admin-ui-project-namespacing.md §L1.1 (C3).\n */\n isSystem: z.boolean().default(false),\n gitProvider: GitProviderSchema.nullable(),\n gitlabProjectId: z.string().nullable(),\n gitlabProjectPath: z.string().nullable(),\n githubRepoFullName: z.string().nullable(),\n githubRepoId: z.string().nullable(),\n /** Cached installation id for follow-up runs; authoritative value is on runs. */\n githubInstallationId: z.string().nullable(),\n repoUrl: z.string().nullable(),\n defaultBranch: z.string().default(\"main\"),\n defaultModel: z.string().nullable(),\n description: z.string().nullable(),\n webhookEnabled: z.boolean().default(false),\n webhookTriggerLabel: z.string().default(\"pilot\"),\n webhookSecret: z.string().nullable(),\n webhookPromptTemplate: z.string().nullable(),\n /** WeCom aibot long-connection integration toggle. See specs/features/wecom-chat-integration.md. */\n wecomEnabled: z.boolean().default(false),\n /** WeCom aibot ID; unique across projects, reverse-lookup from incoming messages. */\n wecomBotId: z.string().nullable(),\n /** Reference to `credential_bindings.name` holding the long-connection SDK secret. */\n wecomSecretRef: z.string().nullable(),\n /** Optional prompt prefix prepended to user message when creating a wecom_chat Run. */\n wecomPromptTemplate: z.string().nullable(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type Project = z.infer<typeof ProjectSchema>;\n","import { z } from \"zod\";\n\n/**\n * Runtime-derived context passed from Control Worker to Agent Worker when a\n * run was triggered by a webhook (Issue/PR/MR @mention or label).\n *\n * Used by Agent Worker to build a focused set of read-only provider tools so\n * the agent can pull Issue/PR body, historical comments, PR diff, etc.\n * on demand without forcing Control Worker to prefetch everything.\n *\n * Discriminated on `provider`. Tokens are short-lived / run-scoped and should\n * never be persisted beyond the lifetime of the run.\n */\nexport const WebhookTriggerContextSchema = z.discriminatedUnion(\"provider\", [\n z.object({\n provider: z.literal(\"github\"),\n /** `owner/repo`, e.g. `pilot-ai/pilot` */\n repoFullName: z.string().min(1),\n /** Issue or Pull Request number. */\n number: z.number().int().positive(),\n /** True when the trigger came from a PR (GitHub issue_comment fires for both). */\n isPr: z.boolean(),\n /** Id of the @mention comment that triggered the run (if applicable). */\n commentId: z.number().int().positive().optional(),\n /**\n * Installation token minted by Control Worker (GitHub App). TTL ≤ 1h;\n * Agent Worker uses this to back `GitHubClient` directly.\n */\n installationToken: z.string().min(1),\n /** Custom GitHub API base URL (GitHub Enterprise). */\n apiUrl: z.string().url().optional(),\n }),\n z.object({\n provider: z.literal(\"gitlab\"),\n /** `group/subgroup/project`. */\n projectPath: z.string().min(1),\n /** Issue IID or Merge Request IID. */\n iid: z.number().int().positive(),\n /** True when the trigger came from an MR note. */\n isMr: z.boolean(),\n /** Id of the note that triggered the run (if applicable). */\n noteId: z.number().int().positive().optional(),\n /** Decrypted OAuth / PAT token used to build `GitLabClient`. */\n accessToken: z.string().min(1),\n /** GitLab instance URL (e.g. `https://gitlab.example.com`). */\n instanceUrl: z.string().url(),\n }),\n]);\nexport type WebhookTriggerContext = z.infer<typeof WebhookTriggerContextSchema>;\n\n// ---------------------------------------------------------------------------\n// triggerRef parser\n// ---------------------------------------------------------------------------\n\n/** Trigger event kinds encoded in `runs.triggerRef`. */\nexport type TriggerRefKind =\n | \"issue\"\n | \"pr\"\n | \"issue_comment\"\n | \"pr_comment\"\n | \"issue_note\"\n | \"mr_note\";\n\nexport interface ParsedTriggerRef {\n provider: \"github\" | \"gitlab\";\n kind: TriggerRefKind;\n /** Issue number (GitHub) or IID (GitLab). */\n number: number;\n /** Comment/note id, when the triggerRef encodes one. */\n commentId?: number;\n}\n\nconst KIND_MAP: Record<string, TriggerRefKind | undefined> = {\n issue: \"issue\",\n pr: \"pr\",\n issue_comment: \"issue_comment\",\n pr_comment: \"pr_comment\",\n issue_note: \"issue_note\",\n mr_note: \"mr_note\",\n};\n\n/**\n * Parse a webhook triggerRef string into its components.\n *\n * Recognised shapes:\n * - `github#issue#<N>` / `gitlab#issue#<iid>`\n * - `github#pr#<N>`\n * - `github#issue_comment#<N>#<commentId>` / `github#pr_comment#<N>#<commentId>`\n * - `gitlab#issue_note#<iid>#<noteId>` / `gitlab#mr_note#<iid>#<noteId>`\n *\n * Returns `null` when the triggerRef is missing or malformed.\n */\nexport function parseTriggerRef(triggerRef: string | null | undefined): ParsedTriggerRef | null {\n if (!triggerRef) return null;\n const parts = triggerRef.split(\"#\");\n if (parts.length < 3) return null;\n\n const providerRaw = parts[0];\n const provider: ParsedTriggerRef[\"provider\"] | null =\n providerRaw === \"github\" || providerRaw === \"gitlab\" ? providerRaw : null;\n if (!provider) return null;\n\n const kind = KIND_MAP[parts[1]];\n if (!kind) return null;\n\n const number = Number(parts[2]);\n if (!Number.isInteger(number) || number <= 0) return null;\n\n const result: ParsedTriggerRef = { provider, kind, number };\n\n if (parts[3] !== undefined) {\n const cid = Number(parts[3]);\n if (Number.isInteger(cid) && cid > 0) {\n result.commentId = cid;\n }\n }\n\n return result;\n}\n","import { z } from \"zod\";\n\nexport const SandboxStatusSchema = z.enum([\n \"creating\",\n \"running\",\n \"idle\",\n \"destroying\",\n \"destroyed\",\n \"error\",\n]);\nexport type SandboxStatus = z.infer<typeof SandboxStatusSchema>;\n\n/**\n * Public endpoint as reported by the sandbox provider (Kanyun sandbox v2 SDK\n * `PublicEndpoint`). Raw provider shape — `url` is the sandbox-actual ingress\n * URL (e.g. `https://{hostPrefix}-{claimName}.rush-dev.zhenguanyu.com`).\n *\n * GAP 3 (preview URL transit): stored verbatim so the Session read path can\n * surface the sandbox-actual URL instead of re-deriving it from a formula.\n * Transform to the business-facing `AgentPublicEndpoint` (name-joined back to\n * `ingresses[]` for `backendPort` / `pathType`) happens downstream in the\n * control-plane Session snapshot layer, not here.\n */\nexport const SandboxPublicEndpointSchema = z.object({\n name: z.string(),\n url: z.string(),\n host: z.string(),\n path: z.string(),\n});\nexport type SandboxPublicEndpoint = z.infer<typeof SandboxPublicEndpointSchema>;\n\nexport const SandboxInfoSchema = z.object({\n id: z.string(),\n status: SandboxStatusSchema,\n podIp: z.string().nullable(),\n agentEndpoint: z.string().nullable(),\n createdAt: z.date(),\n ttlSeconds: z.number().int().optional(),\n templateName: z.string().optional(),\n labels: z.record(z.string()).optional(),\n /**\n * GAP 3 — sandbox-actual public endpoints transited from the provider SDK.\n * Optional/absent for providers that do not report them (and for legacy\n * call sites); downstream consumers MUST treat absence as \"no transit data\"\n * and fall back to declaration-derived URLs.\n */\n publicEndpoints: z.array(SandboxPublicEndpointSchema).optional(),\n});\nexport type SandboxInfo = z.infer<typeof SandboxInfoSchema>;\n\nexport const CreateSandboxOptionsSchema = z.object({\n templateName: z.string(),\n /**\n * Caller-supplied stable claim name. When omitted, the provider lets the\n * sandbox control plane generate a per-sandbox id (`claim-<nanoTS>`), which\n * changes on every create — so the derived public ingress host\n * (`<hostPrefix>-<claimName>.<baseDomain>`) drifts across recreate.\n *\n * Supplying a stable, caller-controlled value (e.g. a project-scoped key)\n * keeps the ingress host stable across abort→recreate cycles (GAP 1 = B:\n * scale-to-zero is abort + recreate, not pause/wake). MUST be DNS-label safe\n * (lowercase alphanumeric + hyphen); the control plane truncates the\n * `<hostPrefix>-<claimName>` first label to 63 chars, so callers must ensure\n * the distinguishing portion fits within budget.\n */\n claimName: z.string().optional(),\n image: z.string().optional(),\n env: z.record(z.string()).optional(),\n ttlSeconds: z.number().int().positive().optional(),\n metadata: z.record(z.string()).optional(),\n labels: z.record(z.string()).optional(),\n});\nexport type CreateSandboxOptions = z.infer<typeof CreateSandboxOptionsSchema>;\n\nexport const ExecResultSchema = z.object({\n exitCode: z.number().int(),\n stdout: z.string(),\n stderr: z.string(),\n});\nexport type ExecResult = z.infer<typeof ExecResultSchema>;\n","import { z } from \"zod\";\n\nexport const MergeRequestStatusSchema = z.enum([\"creating\", \"open\", \"merged\", \"closed\", \"failed\"]);\nexport type MergeRequestStatus = z.infer<typeof MergeRequestStatusSchema>;\n\nexport const MergeRequestSchema = z.object({\n id: z.string().uuid(),\n runId: z.string().uuid(),\n projectId: z.string().uuid(),\n externalId: z.string().nullable(),\n externalUrl: z.string().nullable(),\n sourceBranch: z.string(),\n targetBranch: z.string(),\n title: z.string(),\n description: z.string().nullable(),\n status: MergeRequestStatusSchema,\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type MergeRequest = z.infer<typeof MergeRequestSchema>;\n","import { z } from \"zod\";\n\nexport const HealthCheckConfigSchema = z.object({\n type: z.enum([\"http\", \"tcp\", \"command\"]),\n port: z.number().int().optional(),\n path: z.string().optional(),\n command: z.string().optional(),\n intervalMs: z.number().int().positive().default(5000),\n timeoutMs: z.number().int().positive().default(3000),\n retries: z.number().int().nonnegative().default(3),\n});\nexport type HealthCheckConfig = z.infer<typeof HealthCheckConfigSchema>;\n\nexport const RuntimeProfileSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n version: z.number().int().positive(),\n env: z.record(z.string()).default({}),\n secretRefs: z.record(z.string()).default({}),\n workingDirectory: z.string().default(\"/workspace\"),\n runnerCommand: z.string().optional(),\n runnerPorts: z.array(z.number().int().positive()).optional(),\n healthCheck: HealthCheckConfigSchema.optional(),\n prepareCommands: z.array(z.string()).optional(),\n status: z.enum([\"active\", \"archived\"]).default(\"active\"),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type RuntimeProfile = z.infer<typeof RuntimeProfileSchema>;\n","/**\n * Shell-safety utilities for sandbox command construction.\n *\n * These are in @pilot/contracts (zero-dependency package) so they can be\n * shared by both control-plane and control-worker without creating a\n * circular dependency.\n */\n\nconst MAX_GIT_REF_LEN = 255;\n\n/** Conservative: branch/tag names from Pilot UI (avoids shell metacharacters). */\nconst SAFE_GIT_REF = /^[A-Za-z0-9/._+@-]+$/;\n\n/**\n * Validates values interpolated into sandbox shell commands for `git clone`.\n * Defense-in-depth: exec() passes a single string to the remote shell.\n */\nexport function assertSafeGitRefForShell(ref: string): void {\n if (ref.length > MAX_GIT_REF_LEN) {\n throw new Error(\"targetRef exceeds maximum length\");\n }\n if (!SAFE_GIT_REF.test(ref)) {\n throw new Error(\"targetRef contains invalid characters for a git branch or tag\");\n }\n}\n\n/**\n * Single-quote for sh, preserving literal content (POSIX shell).\n *\n * Wraps `arg` in single quotes, escaping embedded single quotes with the\n * standard `'\\''` idiom. Safe for use in sandbox exec() commands.\n */\nexport function quoteShellSingle(arg: string): string {\n return `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n","import { z } from \"zod\";\n\n/** Maximum characters for the user prompt in a summarize request. */\nexport const MAX_SUMMARIZE_PROMPT_CHARS = 10_000;\n\n/** Maximum characters for diff truncation (model context limit). */\nexport const MAX_DIFF_CHARS = 100_000;\n\n/** Maximum characters for a single tool output in agentic summarize. */\nexport const MAX_TOOL_OUTPUT_CHARS = 50_000;\n\n// ---------------------------------------------------------------------------\n// Summarize Request / Response schemas (shared between agent-worker & control-worker)\n// ---------------------------------------------------------------------------\n\nexport const SummarizeRequestSchema = z\n .object({\n /** Full diff text (legacy mode). Optional when repoDir is provided. */\n diff: z.string().min(1).optional(),\n /** Workspace repo directory path (agentic mode). Must be an absolute path. */\n repoDir: z.string().startsWith(\"/\", { message: \"repoDir must be an absolute path\" }).optional(),\n /** Git diff reference, e.g. \"--cached\" or \"origin/main...HEAD\". */\n diffRef: z\n .string()\n .regex(/^(--cached|[a-zA-Z0-9_.\\-\\/~^]+(\\.\\.\\.?[a-zA-Z0-9_.\\-\\/~^]+)?)$/, {\n message:\n \"diffRef must be '--cached' or a valid git ref (e.g. 'origin/main..HEAD', 'origin/main...HEAD')\",\n })\n .optional(),\n prompt: z.string().max(MAX_SUMMARIZE_PROMPT_CHARS).optional(),\n model: z.string().optional(),\n })\n .refine((data) => data.diff || data.repoDir, {\n message: \"Either 'diff' or 'repoDir' must be provided\",\n });\nexport type SummarizeRequest = z.infer<typeof SummarizeRequestSchema>;\n\nexport const SummarizeResponseSchema = z.object({\n commitMessage: z\n .string()\n .min(1)\n .max(200)\n .describe(\n \"Single-line commit message in conventional commits format: <type>(<scope>): <description>\",\n ),\n prTitle: z\n .string()\n .min(1)\n .max(256)\n .describe(\n \"Pull request title, descriptive. Aim for under 72 characters but the schema accepts up to 256 (GitHub/GitLab hard limit) to tolerate model overshoot.\",\n ),\n prDescription: z\n .string()\n .min(1)\n .describe(\n \"Pull request description in markdown. Start with ## Changes, then list key changes as bullet points.\",\n ),\n});\nexport type SummarizeResponse = z.infer<typeof SummarizeResponseSchema>;\n\n/**\n * Truncate a diff at the nearest hunk boundary to stay within size limits.\n * Prefers cutting at `diff --git` boundaries to keep hunks complete.\n */\nexport function truncateDiff(diff: string, maxChars = MAX_DIFF_CHARS): string {\n if (diff.length <= maxChars) return diff;\n\n const truncated = diff.slice(0, maxChars);\n const lastHunkBoundary = truncated.lastIndexOf(\"\\ndiff --git \");\n\n if (lastHunkBoundary > 0) {\n return `${truncated.slice(0, lastHunkBoundary)}\\n\\n[Diff truncated — remaining files omitted]`;\n }\n\n // Fallback: truncate at last newline\n const lastNewline = truncated.lastIndexOf(\"\\n\");\n return `${truncated.slice(0, lastNewline > 0 ? lastNewline : maxChars)}\\n\\n[Diff truncated]`;\n}\n","import { z } from \"zod\";\n\n/**\n * Hard upper bound on the raw `git diff HEAD` size that Control Worker is\n * willing to buffer + upload as an OSS artifact. Exceeding this triggers the\n * `finalization_snapshot_degraded` audit event with reason=`oversize` and\n * finalization proceeds without the diff artifact.\n *\n * Sized generously to fit almost any reasonable human-authored change set\n * while still protecting control-worker memory from runaway generated output.\n */\nexport const MAX_WORKSPACE_DIFF_BYTES = 20 * 1024 * 1024; // 20 MB\n\n/**\n * Response shape of Agent Worker `GET /workspace/diff/stat`.\n *\n * Values come from `git diff <ref> --numstat`:\n * - `filesChanged`: number of entries in numstat output.\n * - `insertions` / `deletions`: sum across all files. Binary files report\n * `-` in numstat and are counted as 0 here (we don't attempt to estimate\n * binary size at this layer).\n * - `estimatedBytes`: coarse estimate used by Control Worker to decide\n * whether to even attempt the streaming fetch. Derived from numstat as\n * `(insertions + deletions) * 80` — ~80 bytes/line is a conservative\n * average including diff metadata overhead.\n */\nexport const WorkspaceDiffStatResponseSchema = z.object({\n filesChanged: z.number().int().nonnegative(),\n insertions: z.number().int().nonnegative(),\n deletions: z.number().int().nonnegative(),\n estimatedBytes: z.number().int().nonnegative(),\n});\nexport type WorkspaceDiffStatResponse = z.infer<typeof WorkspaceDiffStatResponseSchema>;\n","import { z } from \"zod\";\n\n/**\n * Contract for Agent Worker `POST /workspace/push`.\n *\n * Motivation — the finalization-phase `git push` historically ran via\n * Control Worker's `sandboxProvider.exec` (Kanyun `shell.execCommand`),\n * which suffers from two independent problems:\n *\n * 1. stdout/stderr buffer cap: a long push can return `exit -1` with\n * empty stderr when the Kanyun shell RPC truncates output (same\n * class of failure as the workspace-diff migration solved).\n * 2. GnuTLS transient network errors (errno 110 / \"TLS connection was\n * non-properly terminated\") show up as `exit 128` with the error\n * message split across stdout/stderr in ways that are hard to\n * classify from the outside, and cannot be retried cheaply.\n *\n * Running the push inside the Agent Worker process (which already lives\n * inside the sandbox container) gives us full control over stdout/stderr\n * capture, transient-error classification, and retry backoff — mirroring\n * the 2026-04-22 workspace-diff migration.\n *\n * See `specs/features/agent-worker-git-push.md` for the full behavior\n * contract.\n */\n\n/**\n * Upper bound we truncate stdout/stderr to in the HTTP response, in\n * bytes. Large enough to keep meaningful diagnostics (git's own failure\n * message + a handful of `remote:` lines) while protecting the\n * Control Worker from runaway output in pathological cases (hook\n * misconfigurations that spray MB of logs, etc.).\n *\n * Truncation keeps the head and the tail (the tail is where the\n * actionable error usually lives) with an explicit placeholder in the\n * middle. See `agent-worker`'s `runGitPush` for the exact truncation\n * algorithm.\n */\nexport const AGENT_PUSH_OUTPUT_TRUNCATE_BYTES = 8 * 1024;\n\n/**\n * Maximum number of attempts `runGitPush` will make, counting the\n * initial attempt. Retries only happen on transient network errors\n * (see `AgentPushRetryReason`).\n */\nexport const AGENT_PUSH_MAX_ATTEMPTS = 3;\n\n/**\n * Discriminated retry-reason classification. Populated on the response\n * only when `attempts > 1` and records **why the last retry was\n * triggered**. Used for observability — Control Worker does not branch\n * on this value.\n */\nexport const AgentPushRetryReasonSchema = z.enum([\n \"gnutls_recv_error\",\n \"rpc_failed\",\n \"connection_reset\",\n \"timeout\",\n \"broken_pipe\",\n \"early_eof\",\n \"dns\",\n]);\nexport type AgentPushRetryReason = z.infer<typeof AgentPushRetryReasonSchema>;\n\n/**\n * Auth bundle. Token is forwarded in the HTTP request body and lives\n * only in Agent Worker memory for the duration of the push — it is\n * never persisted to disk. Agent Worker passes the token to `git` via\n * a one-shot `GIT_ASKPASS` script written to an ephemeral tmp dir that\n * is unlinked in `finally`.\n *\n * `kind === \"github\"`: username is the caller's choice (`x-access-token`\n * for GitHub App installation tokens, or the user's login for user\n * PATs — the finalization code already makes this decision upstream).\n *\n * `kind === \"gitlab\"`: username is always `oauth2` per GitLab's OAuth\n * password-auth convention — the Agent Worker hardcodes this so\n * callers cannot accidentally pass the wrong username.\n */\nexport const AgentPushAuthSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"github\"),\n username: z.string().min(1),\n token: z.string().min(1),\n }),\n z.object({\n kind: z.literal(\"gitlab\"),\n token: z.string().min(1),\n }),\n]);\nexport type AgentPushAuth = z.infer<typeof AgentPushAuthSchema>;\n\nexport const AgentPushRequestSchema = z.object({\n /** Absolute path inside the sandbox to the git working directory. */\n repoDir: z.string().refine((s) => s.startsWith(\"/\"), {\n message: \"repoDir must be an absolute path\",\n }),\n /** Remote name, typically `origin`. */\n remote: z.string().min(1).default(\"origin\"),\n /** Branch to push. */\n branch: z.string().min(1),\n /** When true, appends `--force`. Default `false`. */\n force: z.boolean().default(false),\n auth: AgentPushAuthSchema,\n});\nexport type AgentPushRequest = z.infer<typeof AgentPushRequestSchema>;\n\nexport const AgentPushResponseSchema = z.object({\n /** Convenience flag — equivalent to `exitCode === 0`. */\n ok: z.boolean(),\n /**\n * Final `git push` process exit code (from the last attempt if\n * retries happened). `0` on success. Non-zero values follow git's\n * own conventions (e.g. `128` for fatal errors).\n */\n exitCode: z.number().int(),\n /** Captured stdout, truncated per AGENT_PUSH_OUTPUT_TRUNCATE_BYTES. */\n stdout: z.string(),\n /** Captured stderr, truncated per AGENT_PUSH_OUTPUT_TRUNCATE_BYTES. */\n stderr: z.string(),\n /** Total wall time across all attempts, in milliseconds. */\n durationMs: z.number().int().nonnegative(),\n /**\n * Number of attempts actually made. Always ≥ 1 and\n * ≤ AGENT_PUSH_MAX_ATTEMPTS.\n */\n attempts: z.number().int().min(1).max(AGENT_PUSH_MAX_ATTEMPTS),\n /**\n * Reason for the most recent retry. Present only when `attempts > 1`.\n * Absent when the initial attempt succeeded or when the failure was\n * classified as non-transient (auth failure, non-fast-forward, etc.).\n */\n lastRetryReason: AgentPushRetryReasonSchema.optional(),\n});\nexport type AgentPushResponse = z.infer<typeof AgentPushResponseSchema>;\n","export const AGENT_WORKER_BUNDLE_OSS_PREFIX = \"pilot/agent-worker\";\n\nexport interface AgentWorkerBundleObjectKeys {\n versionedKey: string;\n latestKey: string;\n}\n\nexport function buildAgentWorkerBundleObjectKeys({\n env,\n gitSha,\n}: {\n env: string;\n gitSha: string;\n}): AgentWorkerBundleObjectKeys {\n const keyPrefix = `${AGENT_WORKER_BUNDLE_OSS_PREFIX}/${env}`;\n return {\n versionedKey: `${keyPrefix}/bundle-${gitSha}.tar.gz`,\n latestKey: `${keyPrefix}/bundle-latest.tar.gz`,\n };\n}\n","import { z } from \"zod\";\n\n/**\n * ModelGate credential hot-reload protocol — two-way contract between\n * `apps/agent-worker` (inside sandbox) and `apps/control-worker`.\n *\n * Authoritative design: `docs/proposals/pilot-modelgate-migration.md` §4.3.\n *\n * Flow\n * ----\n *\n * 1. agent-worker observes a 401 from the CLI subprocess (Anthropic /\n * OpenAI gateway rejected the per-user API key — likely rotated /\n * revoked upstream).\n * 2. agent-worker POSTs `{control-worker}/internal/keys/invalidate` with\n * `InvalidateKeysRequest` (this file). The request body identifies\n * the session + LDAP whose key needs refresh.\n * 3. control-worker authenticates the request by checking the\n * `X-Pilot-Pod-Agent-Token` header against `pilot_v2_sessions.pod_agent_token`\n * for the supplied `sessionId`.\n * 4. control-worker invalidates the ModelGate resolver cache (drop DB row\n * + redis entry), re-resolves a fresh API key, then POSTs the new env\n * back to `{agent-worker}/internal/reload-credentials` with\n * `ReloadCredentialsRequest`. Authentication on the inbound side uses\n * the same `X-Pilot-Pod-Agent-Token` header, with agent-worker holding\n * the token in `process.env.PILOT_POD_AGENT_TOKEN` (injected by the\n * sandbox at start time).\n * 5. agent-worker applies the new env via `applyOverrides(env)` —\n * `apps/agent-worker/src/credential-overrides.ts`. The next CLI\n * subprocess started by `createProvider` picks up the override.\n *\n * v1 Run path\n * -----------\n *\n * Per §4.4 of the proposal, v1 Run sandboxes do NOT receive a\n * `PILOT_POD_AGENT_TOKEN` env (token only lives on `pilot_v2_sessions`).\n * Both endpoints MUST reject requests when no token is configured:\n *\n * - agent-worker `/internal/reload-credentials` returns `404` with\n * `{ error: \"not_supported_in_v1\" }` if `PILOT_POD_AGENT_TOKEN` env\n * is missing.\n * - control-worker `/internal/keys/invalidate` returns `404` with the\n * same error when the supplied `sessionId` is not found in\n * `pilot_v2_sessions`.\n *\n * v1 callers MUST fall back to \"Run retry\" (re-create the Run, which\n * walks the 4-layer resolver from scratch and naturally rotates the key).\n *\n * Security notes\n * --------------\n *\n * - Both directions use the SAME `pod_agent_token` value (per-session,\n * 64 hex chars, generated `crypto.randomBytes(32).toString(\"hex\")` at\n * session creation). Comparison MUST use `crypto.timingSafeEqual` to\n * prevent timing-channel leakage of the token.\n * - Token is treated as a bearer credential at this protocol layer.\n * Higher layers (TLS / mosn sidecar) MAY add transport-level auth on\n * top; this contract makes no claims about it.\n * - The env map carried by `ReloadCredentialsRequest.env` is limited to\n * the known ModelGate-related env keys at runtime (server-side\n * allowlist enforced inside the handler). The schema permits an open\n * `Record<string, string>` so the protocol can grow without a contract\n * rev; allowlist enforcement keeps it safe.\n */\n\n/**\n * agent-worker → control-worker.\n *\n * agent-worker tells control-worker \"I just got a 401 from the upstream\n * inference gateway; please rotate the key for `ldap` and push the new\n * value back to me\".\n *\n * Fields:\n * - `sessionId` — v2 Session id; control-worker uses this to look up\n * `pod_agent_token` and `runtime_bindings.worker_endpoint`.\n * - `runId` — optional, included for observability / audit log\n * correlation. The protocol does NOT branch on it.\n * - `ldap` — the user identity whose ModelGate key needs invalidation.\n * - `provider` — which CLI provider observed the 401. Determines\n * which env keys (`ANTHROPIC_*` vs `OPENAI_*`) control-worker\n * writes into the reload-credentials response.\n * - `observedAt` — ISO-8601 timestamp of when agent-worker observed\n * the 401. Used only for logging; control-worker MUST NOT use it for\n * idempotency or ordering.\n * - `reason` — optional free-text classification (e.g. \"401 from\n * /v1/messages\"); for audit logs.\n */\nexport const InvalidateKeysRequestSchema = z.object({\n sessionId: z.string().uuid(),\n runId: z.string().uuid().optional(),\n ldap: z.string().min(1).max(255),\n provider: z.enum([\"claude-code\", \"codex\"]),\n observedAt: z.string().datetime({ offset: true }),\n reason: z.string().max(500).optional(),\n});\n\nexport type InvalidateKeysRequest = z.infer<typeof InvalidateKeysRequestSchema>;\n\n/**\n * control-worker → control-worker response body for `/internal/keys/invalidate`.\n *\n * The response is deliberately minimal — its purpose is to ack the\n * invalidation. The new env is delivered via the SEPARATE reverse call to\n * agent-worker (see `ReloadCredentialsRequest`), NOT as part of this\n * response. Splitting the two avoids round-tripping the new API key\n * through the agent-worker → control-worker request's response body,\n * keeping the credential out of the agent-worker request log surface.\n *\n * `pushed`:\n * - `true` — control-worker invalidated upstream + successfully POSTed\n * the new env to agent-worker's `/internal/reload-credentials`.\n * - `false` — invalidation succeeded but the reverse push failed (e.g.\n * agent-worker unreachable). Caller MAY retry the original invalidate\n * call after a delay; the next call also re-runs the resolver layers,\n * which is idempotent.\n */\nexport const InvalidateKeysResponseSchema = z.object({\n pushed: z.boolean(),\n /** Optional sub-status; useful for clients to surface diagnostic detail\n * without parsing prose. */\n reasonCode: z.string().max(100).optional(),\n});\n\nexport type InvalidateKeysResponse = z.infer<typeof InvalidateKeysResponseSchema>;\n\n/**\n * control-worker → agent-worker.\n *\n * Carries the freshly-resolved env that agent-worker should merge into\n * its credential override store. Keys included in `env` MUST be limited\n * by the agent-worker handler's allowlist:\n *\n * - `ANTHROPIC_API_KEY`, `ANTHROPIC_BASE_URL` (claude-code path)\n * - `OPENAI_API_KEY`, `OPENAI_BASE_URL` (codex path)\n *\n * The schema does NOT encode the allowlist so the protocol can extend\n * later without a contract rev; the server applies the policy.\n *\n * Empty `env` is REJECTED — there must be at least one key to apply.\n */\nexport const ReloadCredentialsRequestSchema = z.object({\n env: z.record(z.string().min(1), z.string()).refine((rec) => Object.keys(rec).length > 0, {\n message: \"env must contain at least one entry\",\n }),\n});\n\nexport type ReloadCredentialsRequest = z.infer<typeof ReloadCredentialsRequestSchema>;\n\nexport const ReloadCredentialsResponseSchema = z.object({\n applied: z.array(z.string()),\n});\n\nexport type ReloadCredentialsResponse = z.infer<typeof ReloadCredentialsResponseSchema>;\n\n// Header name used by both directions is `POD_AGENT_TOKEN_HEADER`, exported\n// from `pilot-v2-credentials-broker` (kept there because that's where the\n// header was first introduced — see specs/features/pilot-v2-pod-agent-oci-runtime-layer.md\n// §podAgentToken). Import it from the same module rather than re-defining\n// here so the spelling stays in sync across the codebase.\nexport { POD_AGENT_TOKEN_HEADER } from \"./pilot-v2-credentials-broker\";\n","/**\n * Contracts for the P3 L1.4 control-plane credentials broker.\n *\n * The broker vends short-lived credentials over three internal endpoints:\n * POST /api/internal/credentials/git-provider\n * POST /api/internal/credentials/llm\n * POST /api/internal/credentials/oss\n *\n * Callers: **Pod Agent only** (two-factor auth: `Authorization: Bearer\n * <PILOT_SESSION_TOKEN>` + `X-Pilot-Pod-Agent-Token: <podAgentToken>`).\n * The Worker process never holds the second factor and therefore can\n * never invoke these endpoints directly.\n *\n * Wire shapes (request body + response body) live here so all consumers\n * — broker implementation, Next route handlers, Pod-Agent local proxy,\n * tests — agree on a single source of truth. Test points for the\n * underlying behavior live in\n * `specs/features/pilot-v2-credentials-broker.md`.\n */\n\nimport { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Shared request shape (all three endpoints take an empty body today; the\n// session id is derived from the verified session token, so callers cannot\n// influence which Session's credentials are issued.)\n// ---------------------------------------------------------------------------\n\nexport const CredentialsBrokerRequestSchema = z.object({}).strict();\nexport type CredentialsBrokerRequest = z.infer<typeof CredentialsBrokerRequestSchema>;\n\n// ---------------------------------------------------------------------------\n// git-provider — installation token (GitHub App) or refreshed OAuth token\n// (GitLab). The Pod Agent uses this to clone / push on behalf of the\n// Session's project.\n// ---------------------------------------------------------------------------\n\nexport const GitProviderCredentialSchema = z.object({\n /** Git hosting provider name. */\n provider: z.enum([\"github\", \"gitlab\"]),\n /**\n * Short-lived access token. For GitHub App, this is an installation\n * token (~1 hour TTL). For GitLab OAuth, this is the just-refreshed\n * access token.\n */\n accessToken: z.string().min(1),\n /** ISO-8601 expiry; callers MUST NOT use the token beyond this. */\n expiresAt: z.string().datetime(),\n /**\n * Monotonic rotation counter. The Pod Agent uses this to invalidate\n * its in-memory cache on refresh; bumps every time the broker hands\n * out a token (so two consecutive calls return different versions\n * even if the upstream provider returned the same string).\n */\n rotationVersion: z.number().int().nonnegative(),\n /** GitLab only: the instance base URL the token was minted for. */\n instanceUrl: z.string().url().optional(),\n});\nexport type GitProviderCredential = z.infer<typeof GitProviderCredentialSchema>;\n\n// ---------------------------------------------------------------------------\n// llm — per-LDAP Bedrock (default) or fallback proxy headers. The Pod\n// Agent injects these into the Worker process's LLM proxy at startup.\n// ---------------------------------------------------------------------------\n\nexport const LlmCredentialSchema = z.object({\n /** LLM provider name. `bedrock` covers the per-LDAP AK/SK path. */\n provider: z.enum([\"bedrock\", \"anthropic\"]),\n /** Base URL the Worker / proxy should target. */\n baseUrl: z.string().url(),\n /**\n * HTTP headers the proxy must send upstream. May contain the\n * Bedrock-related AWS overrides (encoded as headers consumed by the\n * Pod-Agent local proxy, not as bare AWS sig v4 yet — see proposal in\n * `docs/proposals/pilot-v2-llm-proxy.md`).\n */\n headers: z.record(z.string(), z.string()),\n /**\n * Optional expiry. Bedrock AK/SK are long-lived; this is present only\n * when the underlying credential issuer (e.g. STS-backed Bedrock\n * adapter in the future) returns a TTL.\n */\n expiresAt: z.string().datetime().optional(),\n});\nexport type LlmCredential = z.infer<typeof LlmCredentialSchema>;\n\n// ---------------------------------------------------------------------------\n// oss — Aliyun OSS access. Phase 1 returns a presigned upload URL rather\n// than an STS triple (the repo has no STS issuer today; see P3 plan\n// §L1.4 OSS-strategy decision). The Pod Agent forwards the URL to the\n// Worker; the Worker uploads directly without ever holding AK/SK.\n//\n// The schema leaves room for a future `stsAccessKeyId/stsSecretAccessKey/\n// stsSessionToken` variant: those fields are optional. Phase 2 / a\n// dedicated STS PR can add a discriminated union or simply populate\n// those alongside `presignedUploadUrl`.\n// ---------------------------------------------------------------------------\n\nexport const OssCredentialSchema = z.object({\n /** OSS region (e.g. `oss-cn-beijing`). */\n region: z.string().min(1),\n /** Target bucket. */\n bucket: z.string().min(1),\n /**\n * Per-session prefix the Worker MUST stay within (the presigned URL\n * is scoped to a single object key, but the prefix is exposed so the\n * client can compose multi-key flows by requesting fresh URLs).\n */\n prefix: z.string().min(1),\n /**\n * Pre-signed PUT URL for the Session's default artifact object key\n * (`${prefix}artifact.bin` by convention). Phase 1 fallback in place\n * of true STS credentials. Single-use semantics: callers needing a\n * different object key MUST call this endpoint again.\n */\n presignedUploadUrl: z.string().url(),\n /** ISO-8601 expiry of the presigned URL. */\n expiresAt: z.string().datetime(),\n // Reserved for the future STS variant. Optional today.\n stsAccessKeyId: z.string().optional(),\n stsSecretAccessKey: z.string().optional(),\n stsSessionToken: z.string().optional(),\n});\nexport type OssCredential = z.infer<typeof OssCredentialSchema>;\n\n// ---------------------------------------------------------------------------\n// Error codes returned by the broker. Routes map these to HTTP statuses\n// (see `apps/web/app/api/internal/credentials/*`).\n// ---------------------------------------------------------------------------\n\nexport const CredentialsBrokerErrorCodeSchema = z.enum([\n // 401 — authentication failures\n \"MISSING_SESSION_TOKEN\",\n \"MISSING_POD_AGENT_TOKEN\",\n \"SESSION_TOKEN_INVALID\",\n \"SESSION_TOKEN_REVOKED\",\n \"SESSION_TOKEN_EXPIRED\",\n \"POD_AGENT_TOKEN_INVALID\",\n // 403 — authorization failures\n \"SESSION_TOKEN_SESSION_MISMATCH\",\n // 404 — session does not exist\n \"SESSION_NOT_FOUND\",\n // 503 — upstream credential issuer (GitHub App / Vault / OSS) is down\n \"GIT_PROVIDER_NOT_CONFIGURED\",\n \"GIT_TOKEN_UNAVAILABLE\",\n \"LLM_CREDENTIAL_UNAVAILABLE\",\n \"OSS_STS_UNAVAILABLE\",\n // 500 — fallthrough\n \"INTERNAL_ERROR\",\n]);\nexport type CredentialsBrokerErrorCode = z.infer<typeof CredentialsBrokerErrorCodeSchema>;\n\n/**\n * HTTP status the route layer SHOULD return for each broker error code.\n * Kept here (not in the route file) so a future refactor of the routes\n * cannot drift from the broker's intent.\n */\nexport const CREDENTIALS_BROKER_ERROR_STATUS: Record<CredentialsBrokerErrorCode, number> = {\n MISSING_SESSION_TOKEN: 401,\n MISSING_POD_AGENT_TOKEN: 401,\n SESSION_TOKEN_INVALID: 401,\n SESSION_TOKEN_REVOKED: 401,\n SESSION_TOKEN_EXPIRED: 401,\n POD_AGENT_TOKEN_INVALID: 401,\n SESSION_TOKEN_SESSION_MISMATCH: 403,\n SESSION_NOT_FOUND: 404,\n GIT_PROVIDER_NOT_CONFIGURED: 503,\n GIT_TOKEN_UNAVAILABLE: 503,\n LLM_CREDENTIAL_UNAVAILABLE: 503,\n OSS_STS_UNAVAILABLE: 503,\n INTERNAL_ERROR: 500,\n};\n\n/**\n * Canonical name of the Pod-Agent second-factor auth header. Kept as a\n * constant so routes, broker, Pod-Agent client, and tests all agree.\n */\nexport const POD_AGENT_TOKEN_HEADER = \"x-pilot-pod-agent-token\";\n","/**\n * Contract for pod-agent `POST /pilot/git/push`.\n *\n * Motivation — the v2 delivery pipeline (`apps/agent-worker/src/v2/delivery/\n * push.ts`) originally read a token from `process.env.PILOT_GIT_PUSH_TOKEN`,\n * but that env injection path was never wired (no code in pod-agent /\n * control-worker / control-plane writes those variables). Every v2 push\n * therefore failed with `auth_missing` and the L3.2 classifier turned the\n * message into `reason=unknown`.\n *\n * This endpoint moves the `git push` execution into pod-agent so the\n * worker never observes the credential. Pod-agent fetches a one-shot\n * token via its existing `/api/internal/credentials/git-provider` broker\n * (same path used by `WorkspaceManager.clone`), then runs `runGitPush`\n * in-process and forwards a sanitized result back to the worker.\n *\n * Boundary:\n * - Request carries `leaseToken` + `workspaceDir` for correlation\n * (matches `/pilot/workspace/clone`); pod-agent validates the\n * directory against the registered workspace entry before invoking\n * git.\n * - Response is a discriminated union — `kind: \"ok\"` means git ran\n * (exitCode may still be non-zero, classified by the caller);\n * `kind: \"failed\"` means pod-agent could not start git (auth\n * fetch failed, workspace not registered, etc).\n *\n * See `specs/features/pilot-v2-delivery-pipeline.md` DP-INV-4 and\n * `apps/pod-agent/src/server.ts` for the wiring.\n */\nimport { z } from \"zod\";\nimport { AGENT_PUSH_MAX_ATTEMPTS, AgentPushRetryReasonSchema } from \"./agent-push\";\n\nexport const PodAgentGitPushRequestSchema = z\n .object({\n /** Lease token issued by pod-agent at worker startup; same value used by clone. */\n leaseToken: z.string().min(1),\n /** Absolute workspace path returned by an earlier `/pilot/workspace/clone`. */\n workspaceDir: z.string().refine((s) => s.startsWith(\"/\"), {\n message: \"workspaceDir must be an absolute path\",\n }),\n /** Remote name. Defaults to `origin`. */\n remote: z.string().min(1).default(\"origin\"),\n /** Branch to push. */\n branch: z.string().min(1),\n /** Whether to add `--force`. Default `false`. */\n force: z.boolean().default(false),\n })\n .strict();\nexport type PodAgentGitPushRequest = z.infer<typeof PodAgentGitPushRequestSchema>;\n\nexport const PodAgentGitPushResponseSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"ok\"),\n /** Final `git push` process exit code (0 = success). */\n exitCode: z.number().int(),\n /** Captured stdout, truncated per AGENT_PUSH_OUTPUT_TRUNCATE_BYTES. */\n stdout: z.string(),\n /** Captured stderr, truncated per AGENT_PUSH_OUTPUT_TRUNCATE_BYTES. */\n stderr: z.string(),\n /** Total wall time across all attempts, in milliseconds. */\n durationMs: z.number().int().nonnegative(),\n /** Number of attempts actually made (1..AGENT_PUSH_MAX_ATTEMPTS). */\n attempts: z.number().int().min(1).max(AGENT_PUSH_MAX_ATTEMPTS),\n /** Reason for the most recent retry; present only when attempts > 1. */\n lastRetryReason: AgentPushRetryReasonSchema.optional(),\n }),\n z.object({\n kind: z.literal(\"failed\"),\n /** Human-readable failure reason; safe to surface in delivery audit row. */\n reason: z.string().min(1),\n /** Coarse failure category for caller branching. */\n code: z\n .enum([\"AUTH_FETCH_FAILED\", \"INVALID_WORKSPACE\", \"INTERNAL\", \"TRANSPORT_FAILED\"])\n .optional(),\n }),\n]);\nexport type PodAgentGitPushResponse = z.infer<typeof PodAgentGitPushResponseSchema>;\n","import { z } from \"zod\";\n\n/**\n * WeCom aibot long-connection message contracts.\n *\n * Derived from the \"接收消息\" spec\n * (https://developer.work.weixin.qq.com/document/path/100719) and\n * refined per `specs/features/wecom-chat-integration.md`. Only the\n * subset used by Pilot is modeled here: message envelope + text /\n * image / file / mixed / voice / video / stream / quote fragments.\n *\n * Field names intentionally mirror WeCom's JSON payload (snake_case)\n * so SDK payloads can be parsed with minimal transformation.\n */\n\nexport const WecomMsgTypeSchema = z.enum([\n \"text\",\n \"image\",\n \"file\",\n \"mixed\",\n \"voice\",\n \"video\",\n \"stream\",\n]);\nexport type WecomMsgType = z.infer<typeof WecomMsgTypeSchema>;\n\nexport const WecomChatTypeSchema = z.enum([\"single\", \"group\"]);\nexport type WecomChatType = z.infer<typeof WecomChatTypeSchema>;\n\nexport const WecomSenderSchema = z.object({\n userid: z.string().min(1),\n});\nexport type WecomSender = z.infer<typeof WecomSenderSchema>;\n\n// ---- Content fragment schemas ----\n\nexport const WecomTextContentSchema = z.object({\n content: z.string(),\n});\nexport type WecomTextContent = z.infer<typeof WecomTextContentSchema>;\n\nexport const WecomImageContentSchema = z.object({\n url: z.string().url(),\n /** AES-256-CBC key (Base64) tied to this specific payload. Present in\n * long-connection mode — use with SDK `decryptFile(buffer, aesKey)`. */\n aeskey: z.string().optional(),\n});\nexport type WecomImageContent = z.infer<typeof WecomImageContentSchema>;\n\nexport const WecomFileContentSchema = z.object({\n url: z.string().url(),\n /** AES-256-CBC key (Base64) tied to this specific payload. */\n aeskey: z.string().optional(),\n});\nexport type WecomFileContent = z.infer<typeof WecomFileContentSchema>;\n\nexport const WecomVoiceContentSchema = z.object({\n /** Voice transcribed to text by WeCom (not a URL). */\n content: z.string(),\n});\nexport type WecomVoiceContent = z.infer<typeof WecomVoiceContentSchema>;\n\nexport const WecomVideoContentSchema = z.object({\n url: z.string().url(),\n /** AES-256-CBC key (Base64) tied to this specific payload. */\n aeskey: z.string().optional(),\n});\nexport type WecomVideoContent = z.infer<typeof WecomVideoContentSchema>;\n\n// ---- Mixed message (text + image interleaved) ----\n\nexport const WecomMixedItemSchema = z.discriminatedUnion(\"msgtype\", [\n z.object({ msgtype: z.literal(\"text\"), text: WecomTextContentSchema }),\n z.object({ msgtype: z.literal(\"image\"), image: WecomImageContentSchema }),\n]);\nexport type WecomMixedItem = z.infer<typeof WecomMixedItemSchema>;\n\nexport const WecomMixedContentSchema = z.object({\n msg_item: z.array(WecomMixedItemSchema).min(1),\n});\nexport type WecomMixedContent = z.infer<typeof WecomMixedContentSchema>;\n\n// ---- Quote: any of the above fragments may appear, gated by msgtype ----\n\nexport const WecomQuoteSchema = z.object({\n msgtype: z.enum([\"text\", \"image\", \"mixed\", \"voice\", \"file\", \"video\"]),\n text: WecomTextContentSchema.optional(),\n image: WecomImageContentSchema.optional(),\n mixed: WecomMixedContentSchema.optional(),\n voice: WecomVoiceContentSchema.optional(),\n file: WecomFileContentSchema.optional(),\n video: WecomVideoContentSchema.optional(),\n});\nexport type WecomQuote = z.infer<typeof WecomQuoteSchema>;\n\n// ---- Stream refresh pull ----\n\nexport const WecomStreamRefSchema = z.object({\n id: z.string().min(1),\n});\nexport type WecomStreamRef = z.infer<typeof WecomStreamRefSchema>;\n\n// ---- Top-level message payload (normalized after SDK decryption) ----\n\n/** Common fields present on every WeCom message payload. */\nconst wecomBasePayload = {\n /** Unique message id for dedup (potential duplicate delivery). */\n msgid: z.string().min(1),\n /** WeCom aibot id, used to reverse-lookup which Pilot project owns this bot. */\n aibotid: z.string().min(1),\n /** Group chat id; only present when chattype === \"group\". */\n chatid: z.string().optional(),\n chattype: WecomChatTypeSchema,\n from: WecomSenderSchema,\n /** Temporary push URL for active replies (short-lived). Optional in stream frames. */\n response_url: z.string().optional(),\n /** Optional quote reference if the user quoted a prior message. */\n quote: WecomQuoteSchema.optional(),\n};\n\nexport const WecomMessagePayloadSchema = z.discriminatedUnion(\"msgtype\", [\n z.object({\n ...wecomBasePayload,\n msgtype: z.literal(\"text\"),\n text: WecomTextContentSchema,\n }),\n z.object({\n ...wecomBasePayload,\n msgtype: z.literal(\"image\"),\n image: WecomImageContentSchema,\n }),\n z.object({\n ...wecomBasePayload,\n msgtype: z.literal(\"file\"),\n file: WecomFileContentSchema,\n }),\n z.object({\n ...wecomBasePayload,\n msgtype: z.literal(\"mixed\"),\n mixed: WecomMixedContentSchema,\n }),\n z.object({\n ...wecomBasePayload,\n msgtype: z.literal(\"voice\"),\n voice: WecomVoiceContentSchema,\n }),\n z.object({\n ...wecomBasePayload,\n msgtype: z.literal(\"video\"),\n video: WecomVideoContentSchema,\n }),\n z.object({\n ...wecomBasePayload,\n msgtype: z.literal(\"stream\"),\n stream: WecomStreamRefSchema,\n }),\n]);\nexport type WecomMessagePayload = z.infer<typeof WecomMessagePayloadSchema>;\n","import { z } from \"zod\";\n\n/**\n * WeCom bot config-change pub/sub contract.\n *\n * Crosses the Web → Control Worker boundary through Redis channel\n * `wecom:config-changed`. Published by `PATCH /api/projects/:id/settings`\n * in `apps/web`, consumed by `WecomConfigWatcher` in\n * `apps/control-worker` which dispatches to\n * `WecomConnectionManager.reloadBot` / `removeBot`.\n *\n * See specs/features/wecom-chat-integration.md §阶段 5.\n *\n * Lives here (zero-dep `@pilot/contracts`) so publisher and subscriber\n * share one authoritative shape. A Zod schema rather than a bare TS\n * interface so the subscriber validates the payload at runtime\n * instead of trusting a `JSON.parse(…) as T` cast.\n */\n\nexport const WECOM_CONFIG_CHANNEL = \"wecom:config-changed\";\n\n/**\n * Action the subscriber should take on receipt:\n *\n * - `enable` — bot just turned on; spawn a fresh BotConnectionWorker.\n * - `update` — bot_id / secret_ref / prompt_template changed on an\n * already-enabled project; stop worker then spawn fresh.\n * - `disable` — bot turned off; stop worker and release leader lease.\n */\nexport const WecomConfigActionSchema = z.enum([\"enable\", \"update\", \"disable\"]);\nexport type WecomConfigAction = z.infer<typeof WecomConfigActionSchema>;\n\nexport const WecomConfigChangeEventSchema = z.object({\n projectId: z.string().min(1),\n action: WecomConfigActionSchema,\n /**\n * Current bot id post-change. `null` on disable when the operator\n * cleared it alongside the disable; absent when the patch didn't\n * touch bot_id.\n */\n botId: z.string().nullable().optional(),\n});\nexport type WecomConfigChangeEvent = z.infer<typeof WecomConfigChangeEventSchema>;\n","import { z } from \"zod\";\n\n/**\n * WeCom terminal-push cross-process routing contracts.\n *\n * Carries the addressing information needed to send a \"task completed\"\n * or \"task failed\" template card to WeCom **after** the originating WS\n * frame has long since been replied to and discarded. Two transport\n * channels share one set of schemas:\n *\n * 1. Persisted column: `runs.wecom_push_target` (jsonb)\n * Written by `WecomMessageHandler` at createRun time so the value\n * survives process restarts and is visible to whichever pod ends\n * up consuming the run's SSE stream.\n *\n * 2. Redis pub/sub: `wecom:push` channel\n * Published by the SSE stream-end handler (whichever pod consumed\n * the stream); subscribed by every bot leader pod's\n * `WecomPushDispatcher`. Subscribers load the persisted target by\n * `runId`, filter by `target.projectId == owned bot projectId`,\n * and send the card via the local `WSClient.sendMessage`.\n *\n * The split between persisted target and pub/sub trigger is deliberate:\n * the trigger is small and replayable, the routing context is large\n * (and references credential tier metadata) and only resolved on\n * demand by the dispatcher.\n *\n * See specs/features/wecom-silent-execution.md §跨进程推送通道.\n */\n\n/** Pub/sub channel name. Single global channel — subscribers filter. */\nexport const WECOM_PUSH_CHANNEL = \"wecom:push\";\n\n/**\n * Credential tier the run's Git access was resolved through. Mirrors\n * `ResolvedCredential[\"layer\"]` in `@pilot/control-plane` but re-declared\n * here so `@pilot/contracts` keeps its zero-runtime-dependency stance.\n *\n * Used by the dispatcher to pick the layered error-card variant on\n * failure (`user_cred` / `owner_cred` / `project_cred` / `service_cred`).\n *\n * `\"owner\"` was added when the resolver gained a layer 4.5 owner-PAT\n * fallback (see specs/features/wecom-user-git-credentials.md §Token\n * 解析链 layer 4.5). It surfaces on `wecom_push_target.credentialLayer`\n * so the dispatcher can distinguish \"owner's PAT used to clone for a\n * member's request\" from a true user-tier hit when something goes\n * wrong downstream.\n */\nexport const WecomCredentialLayerSchema = z.enum([\"user\", \"owner\", \"project\", \"service\"]);\nexport type WecomCredentialLayer = z.infer<typeof WecomCredentialLayerSchema>;\n\n/**\n * Routing context persisted on `runs.wecom_push_target`. Everything the\n * dispatcher needs to render and address the terminal card without\n * re-resolving credentials, agents, or chat metadata.\n */\nexport const WecomPushTargetSchema = z.object({\n /** Project that owns the bot — used by dispatcher subscribers to\n * filter messages addressed to bots this pod doesn't lead. */\n projectId: z.string().min(1),\n /** Agent id the run belongs to. Rendered into the card's `card_action`\n * Portal link so the user can jump to `/agents/<agentId>` to read\n * the result. */\n agentId: z.string().min(1),\n /** \"single\" or \"group\" — chooses whether the dispatcher prefixes the\n * outbound card with a `<@triggerUserid>` markdown so the original\n * sender gets a real @ notification (template_card cannot carry\n * inline mentions). */\n chatType: z.enum([\"single\", \"group\"]),\n /** Destination passed verbatim to `wsClient.sendMessage`. Userid for\n * single chats, chatid for group chats. */\n chatTarget: z.string().min(1),\n /** Userid that triggered the run. Used (a) to build the `<@userid>`\n * markdown in group-chat pushes and (b) by future audit / logging. */\n triggerUserid: z.string().min(1),\n /** Layer the layered Git-credential resolver landed on, when the\n * resolver was wired and produced a hit. Absent → `null` semantically:\n * resolver wired but no tier matched (user should configure a PAT)\n * iff `credentialResolverEnabled` is true; otherwise legacy\n * pre-resolver deployment (env PAT path). */\n credentialLayer: WecomCredentialLayerSchema.optional(),\n /** True iff the resolver was wired into the message handler. Lets\n * the dispatcher distinguish \"no PAT in any tier → user-actionable\n * error card\" from \"legacy deployment, env PAT was the intended\n * path → generic error card\". */\n credentialResolverEnabled: z.boolean(),\n});\nexport type WecomPushTarget = z.infer<typeof WecomPushTargetSchema>;\n\n/**\n * Pub/sub payload published by the SSE stream-end handler. The\n * dispatcher uses `runId` to look up the persisted target, then renders\n * either the success card or the layered error card per `success`.\n *\n * Reasons for splitting trigger and target:\n * - The pub/sub payload is small and bounded — every replica receives\n * every event, so we keep it lean.\n * - The target is large and credential-context-laden — reading it\n * from the DB on demand keeps secrets out of Redis broadcast traffic.\n */\nexport const WecomPushEventSchema = z.object({\n runId: z.string().uuid(),\n success: z.boolean(),\n /** Optional human-readable error reason. Only meaningful when\n * `success === false`; ignored otherwise. */\n reason: z.string().optional(),\n});\nexport type WecomPushEvent = z.infer<typeof WecomPushEventSchema>;\n","import { z } from \"zod\";\nimport { GitProviderSchema } from \"./project\";\n\n/**\n * Shared schema for plaintext PAT inputs.\n *\n * Real PATs from GitLab (`glpat-…`) and GitHub (`ghp_…`, `github_pat_…`) are\n * strictly visible-ASCII with no whitespace. We enforce that here because:\n *\n * 1. Paste hygiene — users routinely paste a token that leaked in whitespace,\n * a trailing newline, or (seen in the wild) a Braille spinner glyph from\n * terminal output. A stray `⣷` (U+28F7) would reach the probe step and\n * explode with \"Cannot convert argument to a ByteString because the\n * character at index N has a value of M which is greater than 255\" when\n * fetch tries to build `Authorization: Bearer <token>`. Failing fast at\n * the schema surfaces a clean validation error instead.\n *\n * 2. Security — silently trimming or passing through non-ASCII content\n * makes it possible to store a mangled token that then fails at runtime\n * behind the WeCom bot, by which point the user has long since left the\n * UI. Rejecting at the edge keeps the failure mode next to the action\n * that caused it.\n *\n * Leading/trailing whitespace is trimmed automatically — that's by far the\n * most common paste artefact and not worth rejecting — but any whitespace or\n * non-printable byte *inside* the token is a hard error.\n */\nexport const GitTokenSchema = z\n .string()\n .transform((s) => s.trim())\n .pipe(\n z\n .string()\n .min(1, \"token must not be empty\")\n .max(1024)\n .regex(\n /^[\\x21-\\x7e]+$/,\n \"token must contain only printable ASCII characters (no whitespace or special symbols)\",\n ),\n );\n\n/**\n * Zod contracts for the WeCom user-git-credentials feature.\n *\n * Three schema families:\n *\n * 1. `UserGitCredentialMetadataSchema` — GET view: metadata about a\n * stored PAT, *never* including the plaintext or encrypted token.\n * Safe to return from `/api/user-credentials` GET.\n *\n * 2. `UpsertUserGitCredentialSchema` — PUT body: plaintext token +\n * key fields (`provider`, `instanceUrl`) + optional `tokenScope`\n * and `expiresAt` hints. The Web layer encrypts before writing.\n *\n * 3. `UserGitCredentialKeySchema` — DELETE / lookup key: just the\n * composite key columns.\n *\n * 4. `ProjectSharedCredentialMetadataSchema` — GET view for project\n * settings: boolean configured flags for each provider, never the\n * encrypted ciphertext.\n *\n * 5. `UpsertProjectSharedCredentialSchema` — PUT body for project\n * owner/admin to configure the per-project fallback PAT.\n *\n * See specs/features/wecom-user-git-credentials.md §Portal 改动.\n *\n * Security invariants enforced here:\n * - Metadata schemas never declare `token` / `encryptedToken` fields.\n * Zod strips unknown keys by default so stray tokens passed to\n * `parse()` are silently dropped rather than leaked downstream.\n * - Token length is capped at 1024 characters, matching the DB column\n * width for `user_git_credentials.encrypted_token`. An 1024-char\n * plaintext yields a ciphertext that comfortably fits (AES-256-GCM\n * + base64 overhead for a PAT is well below 2x).\n */\n\n/**\n * Metadata view of a stored user credential. No plaintext or encrypted\n * token fields — callers must not surface those to the browser.\n */\nexport const UserGitCredentialMetadataSchema = z.object({\n provider: GitProviderSchema,\n instanceUrl: z.string().url(),\n tokenScope: z.string().nullable(),\n expiresAt: z.coerce.date().nullable(),\n lastValidatedAt: z.coerce.date(),\n createdAt: z.coerce.date(),\n updatedAt: z.coerce.date(),\n});\nexport type UserGitCredentialMetadata = z.infer<typeof UserGitCredentialMetadataSchema>;\n\n/**\n * Upsert payload for `PUT /api/user-credentials`. Contains the plaintext\n * token; the API layer encrypts with `TOKEN_ENCRYPTION_KEY` before\n * writing to DB and must not log this value.\n */\nexport const UpsertUserGitCredentialSchema = z.object({\n provider: GitProviderSchema,\n instanceUrl: z.string().url(),\n token: GitTokenSchema,\n tokenScope: z.string().optional(),\n expiresAt: z.coerce.date().optional(),\n});\nexport type UpsertUserGitCredential = z.infer<typeof UpsertUserGitCredentialSchema>;\n\n/**\n * Composite key used by DELETE `/api/user-credentials?provider=…&instanceUrl=…`\n * and by lookups. Narrower than the full metadata schema so accidental\n * over-fetching can't widen the surface.\n */\nexport const UserGitCredentialKeySchema = z.object({\n provider: GitProviderSchema,\n instanceUrl: z.string().url(),\n});\nexport type UserGitCredentialKey = z.infer<typeof UserGitCredentialKeySchema>;\n\n/**\n * Metadata view returned by `GET /api/projects/:id/shared-credentials`.\n * Only booleans — ciphertext stays server-side.\n *\n * Defaults both flags to `false` so a brand-new project without any\n * shared credentials configured still parses cleanly.\n */\nexport const ProjectSharedCredentialMetadataSchema = z.object({\n sharedGitlabTokenConfigured: z.boolean().default(false),\n sharedGithubTokenConfigured: z.boolean().default(false),\n});\nexport type ProjectSharedCredentialMetadata = z.infer<typeof ProjectSharedCredentialMetadataSchema>;\n\n/**\n * Upsert payload for `PUT /api/projects/:id/shared-credentials`. Only\n * owner/admin callers are authorized by the API layer.\n */\nexport const UpsertProjectSharedCredentialSchema = z.object({\n provider: GitProviderSchema,\n token: GitTokenSchema,\n});\nexport type UpsertProjectSharedCredential = z.infer<typeof UpsertProjectSharedCredentialSchema>;\n","import { z } from \"zod\";\n\n/**\n * Platform-token scope identifiers. See `specs/features/pilot-sdk-auth.md`\n * §Scope 体系 for the authoritative catalog.\n *\n * Kept as a zod enum so downstream SDK consumers get narrow string-literal\n * types without importing `@pilot/db` (which pulls in Drizzle at runtime).\n */\nexport const PlatformScopeSchema = z.enum([\n // Project-level (clamped by target_project_ids ∩ ACL)\n \"project:read\",\n \"project:settings\",\n \"agents:write\",\n \"runs:create\",\n \"runs:stream\",\n \"runs:abort\",\n \"runs:merge\",\n \"files:upload\",\n \"pool:acquire\",\n // User-level (not clamped by project allowlist)\n \"user:credentials\",\n \"integrations:git:read\",\n // Admin-only (separate approval)\n \"sessions:terminate\",\n \"resources:cleanup\",\n \"pool:admin\",\n \"admin:bedrock-sync\",\n]);\nexport type PlatformScope = z.infer<typeof PlatformScopeSchema>;\n\n/**\n * Scope template names. Stored on `platform_tokens.scope_template` for\n * audit, and surfaced in the UI. `custom` means the user ticked scopes\n * manually in the \"advanced\" section.\n */\nexport const ScopeTemplateSchema = z.enum([\n \"read_only\",\n \"ci_automation\",\n \"trigger_only\",\n \"full_automation\",\n \"custom\",\n]);\nexport type ScopeTemplate = z.infer<typeof ScopeTemplateSchema>;\n\n/**\n * Canonical scope set for each preset template. `custom` has no preset\n * membership — consumers should look at the token's `scopes` field.\n *\n * Keep this aligned with spec §Scope 体系 §预设模板. If you change a\n * template, bump the contracts minor version.\n */\nexport const SCOPE_TEMPLATE_SCOPES: Record<\n Exclude<ScopeTemplate, \"custom\">,\n readonly PlatformScope[]\n> = {\n read_only: [\"project:read\", \"runs:stream\"],\n trigger_only: [\"project:read\", \"runs:create\"],\n ci_automation: [\n \"project:read\",\n \"runs:create\",\n \"runs:stream\",\n \"runs:abort\",\n \"files:upload\",\n \"pool:acquire\",\n ],\n full_automation: [\n \"project:read\",\n \"runs:create\",\n \"runs:stream\",\n \"runs:abort\",\n \"files:upload\",\n \"agents:write\",\n \"runs:merge\",\n \"pool:acquire\",\n ],\n};\n\n/**\n * Reserved token name used for the \"Pilot 跑 Pilot\" proxy-delegated\n * token. The Web proxy creates / reuses this on behalf of the Pilot\n * Agent account. Users see it in their token list but cannot delete\n * it — a revoke triggers an automatic rebuild on next request.\n */\nexport const PILOT_AGENT_AUTO_TOKEN_NAME = \"__pilot_agent_auto\";\n","import { z } from \"zod\";\n\n/**\n * JWT payload carried by platform tokens. Matches the Node-runtime helper\n * in `apps/web/lib/auth/platform-token.ts` — kept here so SDK consumers\n * can type-check token metadata without importing web-only modules.\n *\n * The JWT intentionally carries *only identity*: scopes and\n * target_project_ids are resolved per-request from the `platform_tokens`\n * table so that revoke / scope-edit / ACL changes propagate without\n * re-issuing the token.\n */\nexport const PlatformTokenPayloadSchema = z.object({\n /** Discriminator. Rejects cross-system JWTs (reskill-api, summarization-api, ...). */\n type: z.literal(\"platform-api\"),\n /** Owner LDAP. */\n sub: z.string().min(1),\n /** Corresponds to `platform_tokens.id`. */\n jti: z.string().uuid(),\n /** Issued-at (seconds). */\n iat: z.number().int().nonnegative(),\n /** Expiry (seconds). Omit for never-expiring tokens. */\n exp: z.number().int().positive().optional(),\n});\nexport type PlatformTokenPayload = z.infer<typeof PlatformTokenPayloadSchema>;\n","import { z } from \"zod\";\nimport { RunStatusSchema } from \"./run\";\n\n/**\n * `SDKMessage` is the stable wrapper type exposed by `@kanyun-ai-infra/pilot`\n * `runs.stream()`. See spec §流式契约版本化.\n *\n * The server continues to emit raw `UIMessageChunk` events over SSE;\n * the SDK *re-projects* those chunks into `SDKMessage` so that minor\n * UIMessage field churn (e.g. the reasoning/checkpoint additions from\n * #242) does not break downstream code.\n *\n * Rules:\n * - Any new field here MUST be optional so older SDK consumers keep\n * working against newer servers.\n * - Removing or reshaping an existing field is a minor-version bump\n * of `@pilot/contracts` + `@kanyun-ai-infra/pilot`.\n * - The `type` discriminant is intentionally narrow: unknown types are\n * rejected at parse time so callers cannot silently latch onto an\n * event the SDK's projection layer has not yet learned about. Adding\n * a new `type` is always a contracts release. Non-discriminant fields\n * DO pass through additively (see `.passthrough()` below).\n */\n\nexport const SDKMessageTypeSchema = z.enum([\n // Assistant text output.\n \"text-delta\",\n // Assistant reasoning (when the model supports it).\n \"reasoning\",\n // A tool invocation by the agent (input available).\n \"tool-use\",\n // A tool result (output available).\n \"tool-result\",\n // A tool failure.\n \"tool-error\",\n // Finalize-stage progress (preparing / uploading / verifying / ...).\n \"finalize-progress\",\n // Terminal error from the run.\n \"error\",\n // Stream completed successfully (run finalized).\n \"done\",\n // Step boundaries (used by multi-step agents).\n \"step-start\",\n \"step-end\",\n]);\nexport type SDKMessageType = z.infer<typeof SDKMessageTypeSchema>;\n\nexport const SDKMessageSchema = z\n .object({\n type: SDKMessageTypeSchema,\n /** Monotonically increasing stream cursor from the server. Usable for resume. */\n cursor: z.number().int().nonnegative().optional(),\n /** Stable per-message identifier when the server provides one. */\n id: z.string().optional(),\n /** Raw text for `text-delta` / `reasoning`. */\n text: z.string().optional(),\n /** Tool invocation details when `type === 'tool-use' | 'tool-result' | 'tool-error'`. */\n tool: z\n .object({\n name: z.string(),\n callId: z.string().optional(),\n input: z.unknown().optional(),\n output: z.string().optional(),\n error: z.string().optional(),\n })\n .optional(),\n /** Finalize progress snapshot for `type === 'finalize-progress'`. */\n progress: z\n .object({\n stage: z.string(),\n detail: z.string().optional(),\n })\n .optional(),\n /** Error detail for `type === 'error'`. */\n error: z\n .object({\n message: z.string(),\n code: z.string().optional(),\n })\n .optional(),\n /**\n * Terminal run status for `type === 'done'`. Mirrors the DB\n * run-status enum so callers can branch without another fetch.\n */\n runStatus: RunStatusSchema.optional(),\n })\n .passthrough();\nexport type SDKMessage = z.infer<typeof SDKMessageSchema>;\n","import { z } from \"zod\";\nimport { EnabledMcpEntryListSchema } from \"./mcp\";\nimport { GitProviderSchema, ProjectKindSchema } from \"./project\";\nimport {\n AttachmentMetaSchema,\n ProviderTypeSchema,\n RunStatusSchema,\n TriggerSourceSchema,\n} from \"./run\";\nimport { PlatformScopeSchema, ScopeTemplateSchema } from \"./scope\";\nimport { EnabledSkillEntryListSchema } from \"./skill\";\n\n/**\n * SDK-facing request / response **DTOs** (spec §SDK 契约).\n *\n * These schemas describe the shapes `@kanyun-ai-infra/pilot` exposes to callers.\n * They are not always identical to what `apps/web/app/api/*` serves on\n * the wire today: T5 (resource method bodies) is allowed to add a thin\n * projection layer so the SDK surface stays stable even when the web\n * routes change shape. The server responses that T5 cannot reshape\n * this way will be addressed in T3 / T5 by widening the route\n * response. Either way, this file is the authoritative SDK contract.\n *\n * Design principles:\n * - New fields MUST be optional so older SDKs keep working.\n * - Timestamps travel as ISO-8601 strings; schemas use `datetime()`.\n * - No imports from `@pilot/db` — scope / status enums stay as literal\n * string unions so the contracts package stays cheap.\n */\n\n// ============================================================\n// Agents\n// ============================================================\n\n/**\n * Compact agent representation returned by list endpoints. The full\n * `AgentSchema` (see `agent.ts`) is the DB row; this summary shape is\n * what SDK callers typically consume.\n */\nexport const SdkAgentSummarySchema = z.object({\n agentId: z.string().uuid(),\n title: z.string(),\n project: z.object({\n id: z.string().uuid(),\n name: z.string(),\n gitProvider: GitProviderSchema.nullable(),\n }),\n agentMode: z.enum([\"task\", \"chat\"]),\n productStatus: z.enum([\"idle\", \"running\", \"needs_attention\", \"completed\"]),\n model: z.string().nullable(),\n isAutomation: z.boolean(),\n latestRun: z\n .object({\n runId: z.string().uuid(),\n promptSummary: z.string(),\n status: z.string(),\n updatedAt: z.string().datetime(),\n startedAt: z.string().datetime().nullable(),\n completedAt: z.string().datetime().nullable(),\n hasArtifacts: z.boolean(),\n hasReview: z.boolean(),\n hasDiff: z.boolean(),\n hasCommits: z.boolean(),\n hasPullRequest: z.boolean(),\n })\n .nullable(),\n lastActiveAt: z.string().datetime(),\n});\nexport type SdkAgentSummary = z.infer<typeof SdkAgentSummarySchema>;\n\nexport const ListAgentsQuerySchema = z.object({\n projectId: z.string().uuid().optional(),\n limit: z.number().int().min(1).max(100).optional(),\n});\nexport type ListAgentsQuery = z.infer<typeof ListAgentsQuerySchema>;\n\nexport const ListAgentsResponseSchema = z.object({\n items: z.array(SdkAgentSummarySchema),\n nextCursor: z.string().nullable(),\n});\nexport type ListAgentsResponse = z.infer<typeof ListAgentsResponseSchema>;\n\n/**\n * Pilot runtime API version selector for a single run.\n *\n * - `\"v1\"` — legacy three-stage Run + Agent + Sandbox lifecycle (the\n * default until v2 reaches stability).\n * - `\"v2\"` — `managed_agent` Worker Protocol path (PR-WP-1 / PR-WP-2 /\n * #434 milestone).\n *\n * **Three-layer LOCK** (per Task #1 SDK PR scope, v0.3-A reframe\n * `default → server-decided`):\n * L1 SDK `SdkCreateRunRequestSchema.pilotApiVersion` — this file\n * `SdkCreateAgentRequestSchema.pilotApiVersion` — this file (Phase 1 T1)\n * L2 API `apps/web/app/api/runs/route.ts` — `CreateRunRequestSchema.pilotApiVersion`\n * `apps/web/app/api/agents/route.ts` — body field (Phase 1 T2)\n * L3 RT `packages/control-plane/src/run-service.ts` line 99 — `runs.pilot_api_version` DB col (varchar(20), default `\"v1\"`)\n *\n * Routing precedence (`run-service.ts` line 105-114, locked by\n * PR-TS-1 D5 explicit-wins test\n * `run-service-pilot-api-version.test.ts` line 134-149):\n * 1. caller-explicit `options.pilotApiVersion` wins\n * 2. else `decideRoute()` traffic-split decision (PR-TS-1 D5/D6) —\n * reads `kill_switch_enabled` + `traffic_split_v2_percentage`\n * ConfigService snapshot, emits `traffic_split.decision.*` log\n * 3. else default `\"v1\"`\n *\n * Naming note: there are TWO unrelated `PilotApiVersion` types in this\n * codebase. The wire-handshake `X_PILOT_API_VERSION = \"v1\"` (single\n * literal, see `api-version.ts`) is for SDK ↔ server compatibility and\n * has nothing to do with this per-run selector. We deliberately keep\n * the literal name `pilotApiVersion` end-to-end (SDK + Wire + DB\n * snake_case `pilot_api_version`) for traceability with PR-TS-1 D5/D6\n * and the runs-table column. Do not rename one without renaming all\n * three.\n */\nexport const PilotApiVersionSchema = z.enum([\"v1\", \"v2\"]);\nexport type PilotApiVersionRef = z.infer<typeof PilotApiVersionSchema>;\n\n/**\n * SDK-shaped agent creation request. Simpler than the internal\n * `CreateAgentRequestSchema` exposed by `/api/agents` POST: SDK callers\n * typically already know the `projectId` (they list projects first),\n * so we accept that directly and let the server resolve repo metadata\n * from the project record.\n *\n * Backward-compatible with the web UI flow by allowing either `projectId`\n * or the git-provider tuple (gitlabProjectPath / githubRepoFullName).\n */\nexport const SdkCreateAgentRequestSchema = z\n .object({\n projectId: z.string().uuid().optional(),\n gitProvider: GitProviderSchema.optional(),\n gitlabProjectPath: z.string().trim().min(1).optional(),\n githubRepoFullName: z.string().trim().min(1).optional(),\n repoUrl: z.string().min(1).optional(),\n /**\n * Baseline git ref frozen on the agent for the lifetime of follow-up\n * runs. Optional — server falls back to project.defaultBranch.\n */\n baseRef: z.string().optional(),\n prompt: z.string().min(1),\n agentMode: z.enum([\"task\", \"chat\"]).optional(),\n model: z.string().optional(),\n provider: ProviderTypeSchema.optional(),\n githubInstallationId: z.string().optional(),\n attachments: z.array(AttachmentMetaSchema).max(5).optional(),\n /**\n * Optional MCP / Skill enable lists frozen on the new agent at\n * creation time.\n *\n * Both fields accept the same union the home-composer\n * pre-edit and `PUT /api/agents/:id/mcp-skills` accept (see\n * `EnabledMcpEntrySchema` / `EnabledSkillEntrySchema`):\n * full snapshot **OR** ref into the global credential store.\n *\n * `POST /api/agents` semantics (Pilot Web):\n * - Omitted lists + no CLI seed header → new agent starts with empty\n * `enabled_*` (interactive / SDK default; spec §4.3).\n * - Omitted lists + Pilot CLI request (`x-pilot-cli-seed-from-project: 1`) →\n * server seeds from `projects.enabled_mcp_servers` / `enabled_skills`.\n * - Either list provided → explicit caller choice; omitted dimension\n * still follows the seed rule above; `agents.mcp_skills_customized = true`\n * when any list is caller-supplied.\n *\n * See `specs/features/mcp-and-skills.md` §4.4.\n */\n enabledMcpServers: EnabledMcpEntryListSchema.optional(),\n enabledSkills: EnabledSkillEntryListSchema.optional(),\n /**\n * Caller-explicit per-run lifecycle selector. Same semantics as\n * `SdkCreateRunRequestSchema.pilotApiVersion` — see `PilotApiVersionSchema`\n * JSDoc for the three-layer LOCK and routing precedence.\n *\n * Three-layer LOCK (agents):\n * L1 SDK `SdkCreateAgentRequestSchema.pilotApiVersion` — this file\n * L2 API `apps/web/app/api/agents/route.ts` — body field\n * L3 RT `packages/control-plane/src/run-service.ts` — `runs.pilot_api_version`\n *\n * Optional; when omitted, server falls through to `decideRoute()` then\n * default `\"v1\"`.\n */\n pilotApiVersion: PilotApiVersionSchema.optional(),\n })\n .superRefine((data, ctx) => {\n const hasProjectId = typeof data.projectId === \"string\" && data.projectId.length > 0;\n const hasGitlabPath = !!data.gitlabProjectPath;\n const hasGithubRepo = !!data.githubRepoFullName;\n const hasGitProvider = !!data.gitProvider;\n\n if (hasProjectId) {\n // projectId is authoritative — any repo-tuple field is ambiguous.\n if (hasGitProvider || hasGitlabPath || hasGithubRepo || data.repoUrl) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"projectId is exclusive with gitProvider / gitlabProjectPath / githubRepoFullName / repoUrl.\",\n path: [\"projectId\"],\n });\n }\n return;\n }\n\n if (!hasGitProvider) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"Provide either projectId, or (gitProvider + gitlabProjectPath) / (gitProvider + githubRepoFullName).\",\n path: [\"gitProvider\"],\n });\n return;\n }\n\n if (data.gitProvider === \"gitlab\") {\n if (!hasGitlabPath) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"gitProvider=gitlab requires gitlabProjectPath.\",\n path: [\"gitlabProjectPath\"],\n });\n }\n if (hasGithubRepo) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"gitProvider=gitlab must not carry githubRepoFullName.\",\n path: [\"githubRepoFullName\"],\n });\n }\n } else if (data.gitProvider === \"github\") {\n if (!hasGithubRepo) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"gitProvider=github requires githubRepoFullName.\",\n path: [\"githubRepoFullName\"],\n });\n }\n if (hasGitlabPath) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"gitProvider=github must not carry gitlabProjectPath.\",\n path: [\"gitlabProjectPath\"],\n });\n }\n }\n });\nexport type SdkCreateAgentRequest = z.infer<typeof SdkCreateAgentRequestSchema>;\n\nexport const SdkCreateAgentResponseSchema = z.object({\n agentId: z.string().uuid(),\n runId: z.string().uuid(),\n isNewAgent: z.boolean(),\n});\nexport type SdkCreateAgentResponse = z.infer<typeof SdkCreateAgentResponseSchema>;\n\n/**\n * Follow-up message posted to an existing agent. Mirrors the shape\n * accepted by `POST /api/agents/:id/runs` (internal) and\n * `POST /api/runs` (public). Server creates a fresh run and threads\n * it onto the agent's message history.\n */\nexport const SdkMergeAgentRequestSchema = z.object({\n /** Optional custom commit message. Server falls back to the model output. */\n commitMessage: z.string().min(1).max(200).optional(),\n /** Optional PR title override. */\n prTitle: z.string().min(1).max(256).optional(),\n /** Optional PR description override. */\n prDescription: z.string().optional(),\n});\nexport type SdkMergeAgentRequest = z.infer<typeof SdkMergeAgentRequestSchema>;\n\nexport const SdkMergeAgentResponseSchema = z.object({\n mergeRequestId: z.string().uuid(),\n externalUrl: z.string(),\n externalId: z.string(),\n});\nexport type SdkMergeAgentResponse = z.infer<typeof SdkMergeAgentResponseSchema>;\n\nexport const SdkPatchAgentRequestSchema = z.object({\n customTitle: z.string().max(200).nullable().optional(),\n status: z.enum([\"active\", \"closed\"]).optional(),\n});\nexport type SdkPatchAgentRequest = z.infer<typeof SdkPatchAgentRequestSchema>;\n\n// ============================================================\n// Runs\n// ============================================================\n\n/**\n * SDK-shaped run creation request. Mirrors the body accepted by\n * `POST /api/runs` today: `projectId` is required, `agentId` optional\n * (server creates a fresh agent when absent). T5 is free to add a\n * thin SDK convenience that derives `projectId` from an existing\n * agent, but the wire shape stays this one.\n *\n * Note: the server currently hard-codes `triggerSource: \"user\"` on\n * SDK-originated runs — there is no wire field to override it. When\n * the route grows a caller-driven trigger source (spec §CI 场景 token\n * 注入约定) this schema will gain `triggerSource` / `triggerRef`.\n */\nexport const SdkCreateRunRequestSchema = z.object({\n projectId: z.string().uuid(),\n prompt: z.string().min(1),\n agentId: z.string().uuid().optional(),\n parentRunId: z.string().uuid().optional(),\n repo: z.string().optional(),\n ref: z.string().optional(),\n model: z.string().optional(),\n provider: ProviderTypeSchema.optional(),\n attachments: z.array(AttachmentMetaSchema).max(5).optional(),\n /**\n * Per-run override of the MCP / Skill enable lists.\n *\n * When omitted, the run inherits whatever lives on the agent (Portal /\n * SDK create without MCP/Skill body and without CLI seed header → empty\n * lists on the agent; see `SdkCreateAgentRequestSchema`).\n *\n * Same union shape as the create-agent fields: snapshot OR ref.\n * Useful for one-off runs that need a different toolset than the\n * conversational defaults baked onto the agent.\n *\n * See `specs/features/mcp-and-skills.md` §6.3 (per-run override).\n */\n enabledMcpServers: EnabledMcpEntryListSchema.optional(),\n enabledSkills: EnabledSkillEntryListSchema.optional(),\n /**\n * Caller-explicit Pilot runtime API version override for this run.\n *\n * Defaults to **server-decided**: when omitted, the server consults\n * the traffic-split router (PR-TS-1 D5/D6) for the v1/v2 routing\n * decision and persists it to `runs.pilot_api_version`. When passed\n * explicitly, the caller value wins regardless of the router state\n * (see `run-service.ts` line 99-114 and PR-TS-1 D5 explicit-wins\n * test `run-service-pilot-api-version.test.ts` line 134-149).\n *\n * Use this opt-in carefully — it bypasses the canary / kill-switch\n * gates. Most callers should leave this unset and trust the router.\n */\n pilotApiVersion: PilotApiVersionSchema.optional(),\n});\nexport type SdkCreateRunRequest = z.infer<typeof SdkCreateRunRequestSchema>;\n\n/**\n * Response envelope returned by `POST /api/runs` — `{ run }` today.\n * The SDK unwraps the envelope and returns the run object directly\n * in T5.\n */\nexport const SdkCreateRunResponseSchema = z.object({\n run: z.lazy(() => SdkRunSummarySchema),\n});\nexport type SdkCreateRunResponse = z.infer<typeof SdkCreateRunResponseSchema>;\n\nexport const SdkAbortRunRequestSchema = z.object({\n reason: z.string().max(500).optional(),\n});\nexport type SdkAbortRunRequest = z.infer<typeof SdkAbortRunRequestSchema>;\n\nexport const SdkAbortRunResponseSchema = z.object({\n aborted: z.boolean(),\n status: RunStatusSchema,\n});\nexport type SdkAbortRunResponse = z.infer<typeof SdkAbortRunResponseSchema>;\n\nexport const SdkRunSummarySchema = z.object({\n runId: z.string().uuid(),\n agentId: z.string().uuid(),\n projectId: z.string().uuid(),\n status: RunStatusSchema,\n prompt: z.string(),\n model: z.string().nullable(),\n provider: ProviderTypeSchema,\n triggerSource: TriggerSourceSchema,\n pullRequestUrl: z.string().nullable(),\n errorMessage: z.string().nullable(),\n createdAt: z.string().datetime(),\n startedAt: z.string().datetime().nullable(),\n completedAt: z.string().datetime().nullable(),\n});\nexport type SdkRunSummary = z.infer<typeof SdkRunSummarySchema>;\n\n/**\n * Query parameters for `runs.stream()`. `lastCursor` powers SSE② resume:\n * the SDK persists the last seen cursor and replays from there when the\n * connection drops.\n */\nexport const SdkStreamRunQuerySchema = z.object({\n lastCursor: z.number().int().nonnegative().optional(),\n});\nexport type SdkStreamRunQuery = z.infer<typeof SdkStreamRunQuerySchema>;\n\n// ============================================================\n// Projects\n// ============================================================\n\n/**\n * Project list-item shape returned by `GET /api/projects`. Stays a\n * subset — the server deliberately omits member rosters and optional\n * descriptive fields from the list response. Detail / settings\n * endpoints fill in the rest.\n */\nexport const SdkProjectSummarySchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n // `kind` is now `NOT NULL DEFAULT 'coding'` in the DB (migration\n // 0034), so the server always emits a concrete value — `.default()`\n // would silently mask a missing-field bug instead of surfacing it.\n // Keep the field strict so SDK consumers can rely on the union\n // without runtime fallbacks.\n kind: ProjectKindSchema,\n gitProvider: GitProviderSchema.nullable(),\n repoUrl: z.string().nullable(),\n gitlabProjectPath: z.string().nullable(),\n githubRepoFullName: z.string().nullable(),\n webhookEnabled: z.boolean(),\n webhookTriggerLabel: z.string(),\n jiraEnabled: z.boolean(),\n wecomEnabled: z.boolean(),\n ownerLdap: z.string().nullable(),\n role: z.enum([\"owner\", \"member\", \"admin\"]),\n});\nexport type SdkProjectSummary = z.infer<typeof SdkProjectSummarySchema>;\n\nexport const ListProjectsRequestSchema = z.object({\n kind: ProjectKindSchema.optional(),\n});\nexport type ListProjectsRequest = z.infer<typeof ListProjectsRequestSchema>;\n\nexport const CreateGeneralProjectRequestSchema = z.object({\n name: z.string().trim().min(1).max(255),\n kind: z.literal(\"general\"),\n description: z.string().trim().max(2000).optional(),\n});\nexport type CreateGeneralProjectRequest = z.infer<typeof CreateGeneralProjectRequestSchema>;\n\nexport const CreateGeneralProjectResponseSchema = z.object({\n projectId: z.string().uuid(),\n});\nexport type CreateGeneralProjectResponse = z.infer<typeof CreateGeneralProjectResponseSchema>;\n\nexport const ListProjectsResponseSchema = z.object({\n items: z.array(SdkProjectSummarySchema),\n});\nexport type ListProjectsResponse = z.infer<typeof ListProjectsResponseSchema>;\n\n/**\n * Settings payload surfaced by `GET /api/projects/:id/settings`. Tracks\n * the automation toggles (webhook / WeCom / Jira) — core metadata such\n * as name / description lives elsewhere.\n */\nexport const SdkProjectSettingsSchema = z.object({\n id: z.string().uuid(),\n webhookEnabled: z.boolean(),\n webhookTriggerLabel: z.string(),\n webhookPromptTemplate: z.string().nullable(),\n wecomEnabled: z.boolean(),\n wecomBotId: z.string().nullable(),\n wecomPromptTemplate: z.string().nullable(),\n jiraEnabled: z.boolean().optional(),\n jiraBaseUrl: z.string().nullable().optional(),\n jiraProjectKey: z.string().nullable().optional(),\n jiraTriggerLabel: z.string().optional(),\n jiraPromptTemplate: z.string().nullable().optional(),\n});\nexport type SdkProjectSettings = z.infer<typeof SdkProjectSettingsSchema>;\n\n/**\n * PATCH body accepted by `PATCH /api/projects/:id/settings`. Partial\n * update — any omitted field is left untouched. `runs:merge`-level\n * config changes are routed here rather than via a dedicated endpoint.\n */\nexport const UpdateProjectSettingsRequestSchema = z.object({\n webhookEnabled: z.boolean().optional(),\n webhookTriggerLabel: z.string().min(1).max(100).optional(),\n webhookPromptTemplate: z.string().nullable().optional(),\n wecomEnabled: z.boolean().optional(),\n wecomBotId: z.string().min(1).max(100).nullable().optional(),\n wecomPromptTemplate: z.string().nullable().optional(),\n jiraEnabled: z.boolean().optional(),\n jiraBaseUrl: z.string().url().nullable().optional(),\n jiraProjectKey: z.string().min(1).max(64).nullable().optional(),\n jiraTriggerLabel: z.string().min(1).max(100).optional(),\n jiraPromptTemplate: z.string().nullable().optional(),\n});\nexport type UpdateProjectSettingsRequest = z.infer<typeof UpdateProjectSettingsRequestSchema>;\n\n// ============================================================\n// Automations\n// ============================================================\n\nexport const SdkAutomationRunSchema = z.object({\n runId: z.string().uuid(),\n agentId: z.string().uuid(),\n projectId: z.string().uuid(),\n projectName: z.string(),\n gitProvider: GitProviderSchema.nullable(),\n repoFullName: z.string().nullable(),\n status: z.string(),\n productStatus: z.enum([\"idle\", \"running\", \"needs_attention\", \"completed\"]),\n promptSummary: z.string(),\n triggerRef: z.string().nullable(),\n triggerType: z.enum([\"label\", \"mention\", \"wecom\", \"jira\"]),\n issueUrl: z.string().nullable(),\n pullRequestUrl: z.string().nullable(),\n errorMessage: z.string().nullable(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n startedAt: z.string().datetime().nullable(),\n completedAt: z.string().datetime().nullable(),\n});\nexport type SdkAutomationRun = z.infer<typeof SdkAutomationRunSchema>;\n\nexport const ListAutomationRunsQuerySchema = z.object({\n projectId: z.string().uuid().optional(),\n limit: z.number().int().min(1).max(100).optional(),\n cursor: z.string().optional(),\n});\nexport type ListAutomationRunsQuery = z.infer<typeof ListAutomationRunsQuerySchema>;\n\nexport const ListAutomationRunsResponseSchema = z.object({\n items: z.array(SdkAutomationRunSchema),\n nextCursor: z.string().nullable(),\n});\nexport type ListAutomationRunsResponse = z.infer<typeof ListAutomationRunsResponseSchema>;\n\n// ============================================================\n// Platform tokens (Web UI / CLI approve flow)\n// ============================================================\n\nexport const CreatePlatformTokenRequestSchema = z.object({\n name: z.string().min(1).max(200),\n description: z.string().max(2000).optional(),\n scopes: z.array(PlatformScopeSchema).min(1),\n scopeTemplate: ScopeTemplateSchema,\n /** NULL means \"all projects I currently have access to\". */\n targetProjectIds: z.array(z.string().uuid()).nullable(),\n /** ISO-8601 string. Omit for never-expire. */\n expiresAt: z.string().datetime().optional(),\n});\nexport type CreatePlatformTokenRequest = z.infer<typeof CreatePlatformTokenRequestSchema>;\n\nexport const CreatePlatformTokenResponseSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n /** The **only** time the full token is returned. */\n token: z.string(),\n tokenPrefix: z.string(),\n scopes: z.array(PlatformScopeSchema),\n scopeTemplate: ScopeTemplateSchema,\n targetProjectIds: z.array(z.string().uuid()).nullable(),\n createdAt: z.string().datetime(),\n expiresAt: z.string().datetime().nullable(),\n});\nexport type CreatePlatformTokenResponse = z.infer<typeof CreatePlatformTokenResponseSchema>;\n\n/**\n * Audit-only metadata returned by list / detail endpoints. Does *not*\n * include the raw token body.\n */\nexport const PlatformTokenInfoSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n description: z.string().nullable(),\n tokenPrefix: z.string(),\n scopes: z.array(PlatformScopeSchema),\n scopeTemplate: ScopeTemplateSchema.nullable(),\n targetProjectIds: z.array(z.string().uuid()).nullable(),\n createdAt: z.string().datetime(),\n expiresAt: z.string().datetime().nullable(),\n lastUsedAt: z.string().datetime().nullable(),\n revokedAt: z.string().datetime().nullable(),\n revokedReason: z.string().nullable(),\n});\nexport type PlatformTokenInfo = z.infer<typeof PlatformTokenInfoSchema>;\n\nexport const ListPlatformTokensResponseSchema = z.object({\n items: z.array(PlatformTokenInfoSchema),\n});\nexport type ListPlatformTokensResponse = z.infer<typeof ListPlatformTokensResponseSchema>;\n\nexport const PatchPlatformTokenRequestSchema = z.object({\n name: z.string().min(1).max(200).optional(),\n description: z.string().max(2000).nullable().optional(),\n /**\n * Allowed to *shrink* the scope set (for tightening); forbidden to\n * widen. Server enforces `new_scopes ⊆ old_scopes`.\n */\n scopes: z.array(PlatformScopeSchema).min(1).optional(),\n});\nexport type PatchPlatformTokenRequest = z.infer<typeof PatchPlatformTokenRequestSchema>;\n","import { z } from \"zod\";\n\n/**\n * Wire-format MCP server config — corresponds 1:1 with the entries written\n * to `.mcp.json` (claude-code) and `config.toml` (codex).\n *\n * The discriminator is the literal `type` field. Three transports are\n * supported, mirroring Claude Code SDK and Codex CLI:\n *\n * - `stdio` — subprocess launched with `command` + `args`; env is passed\n * via process env vars\n * - `sse` — server-sent-events endpoint\n * - `http` — streamable HTTP endpoint\n *\n * `${var}` placeholders may appear in `headers` / `env` value strings;\n * the `@pilot/mcp` `mergeTemplate` helper substitutes from\n * `EnabledMcpServer.extraConfigValues`. URL / command / args are passed\n * through verbatim — historically too many legitimate `${...}` shell\n * interpolations exist there to substitute safely.\n *\n * See `specs/features/mcp-and-skills.md` §3.3.\n */\nexport const McpStdioConfigSchema = z.object({\n type: z.literal(\"stdio\"),\n command: z.string().min(1),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n});\n\nexport const McpSseConfigSchema = z.object({\n type: z.literal(\"sse\"),\n url: z.string().url(),\n headers: z.record(z.string(), z.string()).optional(),\n});\n\nexport const McpHttpConfigSchema = z.object({\n type: z.literal(\"http\"),\n url: z.string().url(),\n headers: z.record(z.string(), z.string()).optional(),\n});\n\nexport const MCPServerConfigSchema = z.discriminatedUnion(\"type\", [\n McpStdioConfigSchema,\n McpSseConfigSchema,\n McpHttpConfigSchema,\n]);\nexport type MCPServerConfig = z.infer<typeof MCPServerConfigSchema>;\nexport type McpStdioConfig = z.infer<typeof McpStdioConfigSchema>;\nexport type McpSseConfig = z.infer<typeof McpSseConfigSchema>;\nexport type McpHttpConfig = z.infer<typeof McpHttpConfigSchema>;\n\n/**\n * Snapshot of the rush MCP template at the moment the user enabled it.\n *\n * Frozen in `EnabledMcpServer` so sandbox bootstrap is decoupled from\n * upstream rush changes — once enabled, the server config the user\n * approved is what runs, even if rush updates the template later.\n *\n * `requiredVars` lists the placeholders the user must fill in via\n * `extraConfigValues` (UI form is driven by this list).\n */\nexport const McpTemplateSnapshotSchema = z.object({\n transportType: z.enum([\"stdio\", \"sse\", \"http\"]),\n serverConfig: MCPServerConfigSchema,\n requiredVars: z.array(z.string()).optional(),\n version: z.string().optional(),\n});\nexport type McpTemplateSnapshot = z.infer<typeof McpTemplateSnapshotSchema>;\n\n/**\n * One enabled MCP server, persisted in `projects.enabled_mcp_servers` /\n * `agents.enabled_mcp_servers` / `runs.enabled_mcp_servers` jsonb arrays.\n *\n * Naming: jsonb internal fields use camelCase (mirrors Zod schema);\n * surrounding DB columns use snake_case (see spec §3.1).\n *\n * `toolFilter` is reserved for a future agent-worker-side allowlist —\n * Phase 1 does not enforce it. Stored in DB so we don't have to migrate\n * existing rows when the runtime check is added.\n *\n * `disabled` is a soft-off flag: the entry stays in the array (so the\n * user-typed `extraConfigValues` survives), but the resolver filters it\n * out before sandbox bootstrap consumes the list. Toggling on flips it\n * back without re-prompting the placeholder form. Absent / `false` →\n * effectively enabled. See spec §3.3 / §4.2.\n */\nexport const EnabledMcpServerSchema = z.object({\n rushMcpId: z.string().min(1),\n displayName: z.string().min(1),\n templateSnapshot: McpTemplateSnapshotSchema,\n extraConfigValues: z.record(z.string(), z.string()).optional(),\n toolFilter: z.array(z.string()).optional(),\n disabled: z.boolean().optional(),\n});\nexport type EnabledMcpServer = z.infer<typeof EnabledMcpServerSchema>;\n\n/** Array of enabled MCP servers — used as the jsonb column shape. */\nexport const EnabledMcpServerListSchema = z.array(EnabledMcpServerSchema);\nexport type EnabledMcpServerList = z.infer<typeof EnabledMcpServerListSchema>;\n\n/**\n * Reference-only entry for the **global credential** model — what\n * `projects.enabled_mcp_servers` / `agents.enabled_mcp_servers` /\n * `runs.enabled_mcp_servers` jsonb arrays will hold once the\n * `user_mcp_installs` table is the source of truth for credentials and\n * template snapshots.\n *\n * Resolution flow at sandbox bootstrap:\n *\n * ref ─► user_mcp_installs[ldap, ref.rushMcpId] ─► extraConfigValues\n * └► rushRegistry.getMcpServer(ref.rushMcpId) ─► templateSnapshot\n *\n * Both halves are merged into a runtime `EnabledMcpServer`, then\n * persisted verbatim into `run_mcp_snapshots` so the bootstrap\n * decision is auditable / replayable even if the user later rotates\n * the token or rush updates the template.\n *\n * `extraConfigValuesOverride` is the escape hatch for the\n * \"project service-account token ≠ personal token\" case — when set,\n * it wins over the user's personal credential record. Most refs leave\n * it absent.\n *\n * `disabled` mirrors the soft-off semantics of `EnabledMcpServer` —\n * keeps the entry around so the UI toggle can flip back without\n * losing the (now refless) per-row state.\n *\n * Schema is intentionally NOT `.passthrough()` — unknown fields are\n * stripped on parse, so a future server-side rename never leaks an\n * extra field into the wire payload that consumers might\n * accidentally rely on.\n *\n * See `docs/proposals/mcp-global-config-model.md` §3.3.\n */\nexport const EnabledMcpRefSchema = z.object({\n rushMcpId: z.string().min(1),\n disabled: z.boolean().optional(),\n extraConfigValuesOverride: z.record(z.string(), z.string()).optional(),\n});\nexport type EnabledMcpRef = z.infer<typeof EnabledMcpRefSchema>;\n\n/** Array form for the jsonb column. */\nexport const EnabledMcpRefListSchema = z.array(EnabledMcpRefSchema);\nexport type EnabledMcpRefList = z.infer<typeof EnabledMcpRefListSchema>;\n\n/**\n * Union accepted by the agent / project / run write endpoints during\n * the ref-rollout transition. Each element is **either** a legacy\n * `EnabledMcpServer` snapshot (still used by existing rows pre-Phase 3\n * backfill) **or** a new `EnabledMcpRef` (what new writes should look\n * like). The union order matters: snapshot has more required fields,\n * so it's checked first; refs match the looser shape and serve as\n * fallback. Bootstrap discriminates structurally at runtime via\n * `templateSnapshot` presence.\n *\n * Per-element validation rather than a homogeneous list — mixing\n * both shapes in a single array is legal during double-write phases\n * (an agent might still hold legacy entries while the user adds new\n * ones via the ref path).\n */\nexport const EnabledMcpEntrySchema = z.union([EnabledMcpServerSchema, EnabledMcpRefSchema]);\nexport type EnabledMcpEntry = z.infer<typeof EnabledMcpEntrySchema>;\nexport const EnabledMcpEntryListSchema = z.array(EnabledMcpEntrySchema);\nexport type EnabledMcpEntryList = z.infer<typeof EnabledMcpEntryListSchema>;\n","import { z } from \"zod\";\n\n/**\n * Source type for a Skill artifact.\n *\n * Phase 1 supports only `github` and `gitlab` — both fetch a tarball\n * archive from the platform's repository archive endpoint. Other source\n * types (registry / local / oss_url / custom_url) are reserved in the\n * union for future expansion but rejected by the installer with\n * `SkillSourceUnsupportedError`. See `specs/features/mcp-and-skills.md`\n * §1 (out-of-scope) and §9.1.\n */\nexport const SkillSourceTypeSchema = z.enum([\n \"github\",\n \"gitlab\",\n \"registry\",\n \"local\",\n \"oss_url\",\n \"custom_url\",\n]);\nexport type SkillSourceType = z.infer<typeof SkillSourceTypeSchema>;\n\n/**\n * Frozen artifact metadata captured from rush at the moment a Skill is\n * enabled on a project / agent.\n *\n * `integrity` is an SRI-format string (`sha256-<base64>`). Empty or\n * absent means best-effort — installer skips integrity check (matches\n * rush installer's behaviour on older publishes). When present and the\n * downloaded bytes don't match, installer throws `SkillIntegrityError`.\n *\n * `skillPath` lets a single repo host multiple skills in subdirectories;\n * the installer fetches the whole archive but extracts only that subtree.\n *\n * Naming: camelCase inside jsonb (Zod parse boundary). DB column wrappers\n * are snake_case.\n */\nexport const ResolvedSkillArtifactSchema = z.object({\n sourceType: SkillSourceTypeSchema,\n /**\n * Direct repo / file URL for `github` / `gitlab` source types. For\n * `registry` / `oss_url` / `local` / `custom_url`, rush stores the\n * actual download artifact in `skill_versions` (different per\n * version) so this field is empty / unused at install time — the\n * installer goes through `RushRegistryClient.resolveDownloadUrl`\n * instead.\n */\n sourceUrl: z.string().optional().default(\"\"),\n skillPath: z.string().optional(),\n integrity: z.string().optional(),\n version: z.string().optional(),\n});\nexport type ResolvedSkillArtifact = z.infer<typeof ResolvedSkillArtifactSchema>;\n\n/**\n * One enabled Skill, persisted in `projects.enabled_skills` /\n * `agents.enabled_skills` / `runs.enabled_skills` jsonb arrays.\n *\n * `rushSkillName` may be a scoped name (e.g. `@kanyun/rush-find-skills`).\n * The on-disk directory name is derived via `extractSkillDirName` which\n * takes only the last `/`-separated segment (see installer safety helpers\n * in `@pilot/skills`). Validation here is permissive — strict char-set\n * checks happen at install time so the API can still surface \"rejected\n * for safety reasons\" with a clear message.\n */\nexport const EnabledSkillSchema = z.object({\n rushSkillName: z.string().min(1),\n displayName: z.string().min(1),\n resolvedArtifact: ResolvedSkillArtifactSchema,\n});\nexport type EnabledSkill = z.infer<typeof EnabledSkillSchema>;\n\nexport const EnabledSkillListSchema = z.array(EnabledSkillSchema);\nexport type EnabledSkillList = z.infer<typeof EnabledSkillListSchema>;\n\n/**\n * Reference-only Skill entry for the **global credential** model.\n *\n * Skills don't carry user-supplied credentials, so the ref is\n * essentially just the rush skill name. The `resolvedArtifact`\n * snapshot is reconstructed at bootstrap time from the user's\n * `user_skill_installs` row + a live rush registry lookup.\n *\n * Why the indirection if there's no credential? Three reasons:\n *\n * 1. Symmetry with `EnabledMcpRef` — uniform resolver code path\n * 2. rush updates (skill version bumps, source URL changes,\n * integrity rotations) flow to old conversations automatically\n * instead of being stuck on the snapshot taken at enable time\n * 3. The user's per-LDAP \"what skills do I have installed\" set\n * becomes a single queryable table for cross-conversation UI\n *\n * See `docs/proposals/mcp-global-config-model.md` §3.3.\n */\nexport const EnabledSkillRefSchema = z.object({\n rushSkillName: z.string().min(1),\n});\nexport type EnabledSkillRef = z.infer<typeof EnabledSkillRefSchema>;\n\n/** Array form for the jsonb column. */\nexport const EnabledSkillRefListSchema = z.array(EnabledSkillRefSchema);\nexport type EnabledSkillRefList = z.infer<typeof EnabledSkillRefListSchema>;\n\n/**\n * Union accepted by the write endpoints during the ref-rollout\n * transition (mirrors `EnabledMcpEntrySchema`). Bootstrap uses\n * structural detection (`resolvedArtifact` presence) to pick the\n * legacy-vs-ref code path at runtime.\n */\nexport const EnabledSkillEntrySchema = z.union([EnabledSkillSchema, EnabledSkillRefSchema]);\nexport type EnabledSkillEntry = z.infer<typeof EnabledSkillEntrySchema>;\nexport const EnabledSkillEntryListSchema = z.array(EnabledSkillEntrySchema);\nexport type EnabledSkillEntryList = z.infer<typeof EnabledSkillEntryListSchema>;\n","/**\n * Pilot API version handshake. See `specs/features/pilot-sdk-auth.md`\n * §流式契约版本化.\n *\n * Server attaches `x-pilot-api-version: v1` to every `/api/*` response.\n * SDK clients check the prefix on first response and refuse to interpret\n * bodies if the server has moved to an incompatible major (`v2+`). A\n * missing header is tolerated with a warning — older server builds are\n * assumed to be v1.\n *\n * SemVer policy for `@pilot/contracts`:\n * - **patch** — add optional fields, widen enum unions with additive\n * literals, tighten validation without excluding existing valid\n * payloads. No SDK rebuild required.\n * - **minor** — rename / reshape / narrow an existing field, remove an\n * optional field, add a new required field to an existing schema.\n * Downstream consumers should retest.\n * - **major** — bump `X_PILOT_API_VERSION` to `v2+`. This is a wire\n * break; old SDKs will throw `VersionMismatchError` until upgraded.\n */\n\n/**\n * HTTP header carrying the major API version.\n *\n * - **Response side** (server → SDK): server attaches the wire major it\n * actually serves. Set in `apps/web/middleware.ts`.\n * - **Request side** (SDK → server, Phase 2 T4): SDK announces the wire\n * major it expects. Defaults to `X_PILOT_API_VERSION` (\"v1\"); callers\n * opt into `v2` via `new PilotClient({ pilotApiVersion: \"v2\" })`. The\n * server may use this to 403 with `API_VERSION_REQUIRED` if it cannot\n * satisfy the requested major.\n */\nexport const X_PILOT_API_VERSION_HEADER = \"x-pilot-api-version\";\n\n/**\n * Current major API version actually served by the Pilot web tier.\n * Bump to `v2+` ONLY for breaking wire changes (servers and SDKs roll\n * forward together).\n */\nexport const X_PILOT_API_VERSION = \"v1\" as const;\n\n/**\n * Wire-format majors the SDK is allowed to declare as its expected\n * server response shape. Includes the future `v2` slot so SDK callers\n * can opt into the next major before server-side rollout (Phase 2 T4).\n *\n * Distinct from `runs.pilot_api_version` (per-run lifecycle) — see\n * `pilot-sdk-auth.md` §流式契约版本化 rule 8 for the boundary.\n */\nexport const SUPPORTED_PILOT_API_VERSIONS = [\"v1\", \"v2\"] as const;\nexport type PilotApiVersion = (typeof SUPPORTED_PILOT_API_VERSIONS)[number];\n\n/**\n * Extract the major-version prefix (`v1`, `v2`, ...) from a raw header\n * value. Header values may include well-formed suffixes (`v1.2`,\n * `v1-beta`) that we ignore for compatibility checks. Malformed inputs\n * like `v1junk` or `v1 v2` are rejected — they fall through to the\n * legacy-tolerance warning path so we don't silently treat garbage\n * as a matched major.\n */\nexport function parsePilotApiVersion(header: string | null | undefined): string | null {\n if (!header) return null;\n const trimmed = header.trim();\n if (!trimmed) return null;\n // Match only strict boundaries: end-of-string, dot, or dash.\n const match = /^(v\\d+)(?:$|[.-])/i.exec(trimmed);\n return match ? match[1].toLowerCase() : null;\n}\n\n/**\n * Check whether a server-reported version is compatible with the SDK's\n * expected major.\n *\n * - `null` → caller saw no header at all; treat as compatible with a\n * warning (legacy servers predate T9).\n * - exact match → compatible.\n * - mismatch → incompatible; caller should raise `VersionMismatchError`.\n */\nexport function isPilotApiVersionCompatible(\n serverVersion: string | null | undefined,\n clientVersion: PilotApiVersion = X_PILOT_API_VERSION,\n): { compatible: boolean; serverMajor: string | null } {\n const serverMajor = parsePilotApiVersion(serverVersion ?? undefined);\n if (serverMajor === null) {\n return { compatible: true, serverMajor: null };\n }\n return { compatible: serverMajor === clientVersion, serverMajor };\n}\n","/**\n * Optional wire hints for Pilot tooling (currently only the official Pilot\n * CLI sends them). Browsers and generic SDK callers do not send these —\n * server behaviour stays unchanged unless the header is present with the\n * exact expected value.\n *\n * IMPORTANT — these headers are **hints**, not authorization. Any caller\n * holding a platform token MAY set them; the server-side effect is\n * limited to choosing seeding defaults that the same caller could\n * already produce by passing explicit `enabledMcpServers` /\n * `enabledSkills` in the body. The `cli` infix is naming intent\n * (the official CLI is the only known sender), not an auth gate.\n */\n\n/**\n * Sent by the Pilot CLI on `POST /api/agents`.\n *\n * Server contract:\n * - Header value MUST equal {@link X_PILOT_CLI_SEED_FROM_PROJECT_VALUE}\n * (literal `\"1\"`). Any other value (`\"0\"`, `\"true\"`, empty, missing)\n * is treated as \"not set\" → server keeps the default\n * `seedFromProject = false` behaviour. Strict equality is intentional\n * — keeps the wire signal unambiguous and forward-compatible.\n * - When the header is honoured AND the body omits\n * `enabledMcpServers` / `enabledSkills`, the new agent's enable\n * lists are deep-copied from `projects.enabled_*`.\n *\n * See `specs/features/mcp-and-skills.md` §4.3.\n */\nexport const X_PILOT_CLI_SEED_FROM_PROJECT_HEADER = \"x-pilot-cli-seed-from-project\";\n\n/** Only value the server treats as \"on\". See header docstring above. */\nexport const X_PILOT_CLI_SEED_FROM_PROJECT_VALUE = \"1\";\n","/**\n * Restore-time normalization for assistant messages so the upstream\n * Anthropic / Bedrock API accepts every turn.\n *\n * When extended thinking is enabled the API requires every assistant\n * message to start with a `reasoning` block — not just the final one.\n * Multi-turn conversations restored via `/agent/restore` (control-worker\n * → agent-worker) would otherwise 400 on earlier assistant messages.\n *\n * Normalization rules (applied to assistant messages only; user / tool\n * messages pass through unchanged):\n * - String content (`{ content: \"text\" }` from legacy checkpoints\n * written before reasoning events were preserved) becomes\n * `[{ type: \"reasoning\", text: \"\" }, { type: \"text\", text }]`.\n * - `thinking` blocks are remapped to `reasoning` blocks, preserving\n * the thought text.\n * - `redacted_thinking` blocks become empty `reasoning` blocks (we\n * cannot recover the redacted content; an empty placeholder\n * satisfies the API contract).\n * - Assistant arrays that don't already start with a `reasoning`\n * block get an empty one prepended.\n * - Empty arrays (`content: []`) are left alone — there is no text\n * to wrap and prepending a phantom reasoning block on a no-content\n * assistant turn would be misleading rather than restorative.\n *\n * This used to live in two near-identical copies (control-worker's\n * `normalizeRestoreMessagesForModelSchema` and agent-worker's\n * `ensureThinkingBlocks`). Both call sites flow into the same restore\n * path, so the duplication was defensive but invited drift —\n * kris-dong-dong's review on PR #369 recommended consolidating into\n * `@pilot/contracts`.\n *\n * The function is shape-only (no Zod schema, no runtime imports), so\n * it stays inside the \"zero runtime dependencies\" boundary that\n * `packages/contracts` enforces.\n */\nexport function normalizeAssistantMessagesForReasoning(messages: unknown[]): unknown[] {\n return messages.map((rawMessage) => {\n const message = rawMessage as { role?: string; content?: unknown };\n if (message.role !== \"assistant\") return rawMessage;\n\n if (typeof message.content === \"string\") {\n return {\n ...message,\n content: [\n { type: \"reasoning\", text: \"\" },\n { type: \"text\", text: message.content },\n ],\n };\n }\n\n if (Array.isArray(message.content) && message.content.length > 0) {\n const normalizedContent = message.content.map((part) => {\n const p = part as { type?: string; text?: unknown; thinking?: unknown };\n if (p.type === \"thinking\") {\n return { type: \"reasoning\", text: typeof p.thinking === \"string\" ? p.thinking : \"\" };\n }\n if (p.type === \"redacted_thinking\") {\n return { type: \"reasoning\", text: \"\" };\n }\n return part;\n });\n\n const first = normalizedContent[0] as { type?: string } | undefined;\n if (first?.type === \"reasoning\") {\n return {\n ...message,\n content: normalizedContent,\n };\n }\n return {\n ...message,\n content: [{ type: \"reasoning\", text: \"\" }, ...normalizedContent],\n };\n }\n\n return rawMessage;\n });\n}\n","/**\n * Contracts for the P3 L1.3a delivery-result mutation API.\n *\n * Exposed as a single Worker-callable endpoint:\n *\n * POST /api/sessions/:id/delivery-result\n * Authorization: Bearer <PILOT_SESSION_TOKEN>\n *\n * Authoritative behavior: `specs/features/pilot-v2-delivery-result.md`.\n * Rationale for the route shape, why it doesn't go through the wire\n * event taxonomy, and the relationship to L1.2 `recordDeliveryPhase`:\n * `plans/p3-pilot-coder-v2-full-migration.md` §L1.3a (revised).\n *\n * Scope (Phase 1):\n * - 4 mutation fields backed by existing L1.2 columns / helpers:\n * `pullRequestUrl`, `phase`, `failedReason`, `incrementAttempts`.\n * - `artifacts[]` append via the `artifacts` table; idempotency uses\n * the `unique(run_id, path)` constraint added by migration 0048.\n *\n * Deferred to L3.1 (NOT supported by this contract yet):\n * - `pullRequestProvider` — requires new `runs.pull_request_provider`\n * column; deferred until Phase 3 delivery code actually distinguishes\n * providers in the result payload.\n * - `checkpoint` — plan-internal inconsistency (§L1.3a describes\n * `{ version, payload }` while §L4.5 refers to the v1 `run_checkpoints`\n * table). Needs a separate design pass; routes will reject the\n * field with `VALIDATION_ERROR` until then via `.strict()`.\n */\n\nimport { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Phase enum — mirrors `RunDeliveryPhaseSchema` from `./run`. We re-declare\n// here (a) to avoid forcing every delivery-result consumer to pull in the\n// full Run schema and (b) to make the API surface review-able from a single\n// file. The two enums MUST stay in sync; tests in\n// `packages/control-plane/src/__tests__/delivery-result-service.test.ts`\n// assert the broker accepts every member of `RunDeliveryPhaseSchema`.\n// ---------------------------------------------------------------------------\n\nexport const DeliveryResultPhaseSchema = z.enum([\"in_progress\", \"completed\", \"failed\"]);\nexport type DeliveryResultPhase = z.infer<typeof DeliveryResultPhaseSchema>;\n\n// ---------------------------------------------------------------------------\n// Artifact item — mirrors the `artifacts` DB schema for fields that the\n// Worker controls. `id` / `createdAt` are server-assigned and intentionally\n// omitted; `runId` is derived from the URL `:id` so the Worker can never\n// cross-write.\n// ---------------------------------------------------------------------------\n\nexport const DeliveryResultArtifactItemSchema = z\n .object({\n /** Artifact category. Workers MAY add new kinds; storage is opaque. */\n kind: z.enum([\"diff\", \"log\", \"general\"]),\n /**\n * Logical path inside the sandbox workspace (used as the idempotency\n * key together with `runId`). Two writes with the same `(runId, path)`\n * pair collapse to a single row via `ON CONFLICT DO NOTHING`.\n */\n path: z.string().min(1).max(1024),\n /** Object key inside the OSS bucket where the artifact was uploaded. */\n storagePath: z.string().min(1).max(1024),\n /** Reported byte size of the upload. */\n size: z.number().int().nonnegative(),\n /**\n * SHA-256 digest in the form `sha256:<hex>`. Workers compute this\n * before upload so a later integrity check can cross-verify the\n * stored object. Length cap 128 mirrors the `artifacts.checksum`\n * column width.\n */\n checksum: z.string().min(1).max(128),\n /** MIME content type recorded for downloads / preview. */\n contentType: z.string().min(1).max(255),\n })\n .strict();\nexport type DeliveryResultArtifactItem = z.infer<typeof DeliveryResultArtifactItemSchema>;\n\n// ---------------------------------------------------------------------------\n// Top-level request — all fields optional, all fields handled idempotently.\n// `.strict()` rejects unknown keys so deferred fields (`pullRequestProvider`\n// / `checkpoint`) produce a 400 VALIDATION_ERROR instead of being silently\n// ignored, giving the Worker a clean signal to roll forward to the L3.1\n// contract once it ships.\n// ---------------------------------------------------------------------------\n\nexport const DeliveryResultUpdateSchema = z\n .object({\n /**\n * The PR / MR URL the agent created. First-write-wins per spec\n * (`UPDATE ... WHERE pull_request_url IS NULL`); subsequent writes\n * are recorded in the response as \"skipped\" rather than as an error\n * so Worker retries stay idempotent.\n */\n pullRequestUrl: z.string().url().max(1024).optional(),\n /**\n * Append-set of artifacts uploaded for this run. Each item is\n * upserted independently via the `unique(run_id, path)` constraint;\n * the response indicates how many of the submitted items resulted\n * in a new row.\n */\n artifacts: z.array(DeliveryResultArtifactItemSchema).max(64).optional(),\n /**\n * Drive the `runs.delivery_phase` column via the L1.2\n * `RunService.recordDeliveryPhase` helper. `failed` requires\n * `failedReason`; the service throws `INVALID_INPUT` otherwise.\n */\n phase: DeliveryResultPhaseSchema.optional(),\n /** Non-empty failure reason; required iff `phase === \"failed\"`. */\n failedReason: z.string().min(1).max(2048).optional(),\n /**\n * When `true`, increment `runs.delivery_attempts` by 1 alongside\n * the phase write. Workers SHOULD set this on every delivery\n * (re)attempt so the audit row reflects retry count.\n */\n incrementAttempts: z.boolean().optional(),\n })\n .strict()\n .refine(\n (data) =>\n data.pullRequestUrl !== undefined ||\n data.artifacts !== undefined ||\n data.phase !== undefined ||\n data.failedReason !== undefined ||\n data.incrementAttempts !== undefined,\n {\n message:\n \"At least one of pullRequestUrl / artifacts / phase / failedReason / incrementAttempts MUST be provided\",\n },\n );\nexport type DeliveryResultUpdate = z.infer<typeof DeliveryResultUpdateSchema>;\n\n// ---------------------------------------------------------------------------\n// Response — echoes which side-effects actually applied, so the Worker\n// can distinguish \"first write\" from \"idempotent replay\" without a\n// follow-up read. `applied` is the list of fields that produced a state\n// change; `artifactsInserted` counts new artifact rows (omitted items\n// were duplicates).\n// ---------------------------------------------------------------------------\n\nexport const DeliveryResultUpdateResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n /** Subset of the request fields whose persisted state actually\n * changed. `pullRequestUrl` is omitted on second-write (PR URL\n * already set) so callers can detect idempotent replays. */\n applied: z.array(\n z.enum([\"pullRequestUrl\", \"artifacts\", \"phase\", \"failedReason\", \"incrementAttempts\"]),\n ),\n /** Number of newly inserted artifact rows. Always 0 when `artifacts`\n * wasn't in the request. */\n artifactsInserted: z.number().int().nonnegative(),\n }),\n});\nexport type DeliveryResultUpdateResponse = z.infer<typeof DeliveryResultUpdateResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// Error codes returned by the route. Mirrors the credentials-broker\n// pattern (status table lives next to the enum so the route layer can\n// never drift from the contract).\n// ---------------------------------------------------------------------------\n\nexport const DeliveryResultErrorCodeSchema = z.enum([\n // 400 — request was malformed or schema-invalid\n \"VALIDATION_ERROR\",\n // 401 — Authorization header missing or session token invalid/expired\n \"MISSING_SESSION_TOKEN\",\n \"SESSION_TOKEN_INVALID\",\n \"SESSION_TOKEN_EXPIRED\",\n \"SESSION_TOKEN_REVOKED\",\n // 403 — the session token belongs to a different session than the URL\n \"SESSION_TOKEN_SESSION_MISMATCH\",\n // 404 — the URL session id / corresponding run does not exist\n \"SESSION_NOT_FOUND\",\n \"RUN_NOT_FOUND\",\n // 500 — fallthrough\n \"INTERNAL_ERROR\",\n]);\nexport type DeliveryResultErrorCode = z.infer<typeof DeliveryResultErrorCodeSchema>;\n\nexport const DELIVERY_RESULT_ERROR_STATUS: Record<DeliveryResultErrorCode, number> = {\n VALIDATION_ERROR: 400,\n MISSING_SESSION_TOKEN: 401,\n SESSION_TOKEN_INVALID: 401,\n SESSION_TOKEN_EXPIRED: 401,\n SESSION_TOKEN_REVOKED: 401,\n SESSION_TOKEN_SESSION_MISMATCH: 403,\n SESSION_NOT_FOUND: 404,\n RUN_NOT_FOUND: 404,\n INTERNAL_ERROR: 500,\n};\n","/**\n * Pilot v2 Event Taxonomy — Standardized `{domain}.{action}` enum.\n *\n * Spec: `specs/features/pilot-v2-event-taxonomy.md` (Issue #443, PR #516).\n *\n * 6 wire-stable domains (append-only, MUST NOT delete/rename):\n * user | agent | session | span | worker_protocol | vault\n *\n * 9+ standard event types with strict Zod payload schemas.\n * Event types outside this list are accepted as opaque by ingest;\n * SDK parsers emit non-blocking warnings for unknown types.\n */\n\nimport { z } from \"zod\";\nimport {\n WorkerProtocolAcceptedPayloadSchema,\n WorkerProtocolCompletedPayloadSchema,\n WorkerProtocolFailedPayloadSchema,\n WorkerProtocolRejectedPayloadSchema,\n} from \"./pilot-v2-worker-protocol-events\";\nimport {\n WorkerProtocolAbortRequestSchema,\n WorkerProtocolFollowupRequestSchema,\n WorkerProtocolPromptRequestSchema,\n WorkerProtocolRestoreRequestSchema,\n} from \"./worker-protocol-provider\";\n\n// ─── INV-1: Canonical event_type regex ──────────────────────────────────────\n// domain segment: lowercase + snake_case (allows underscore for worker_protocol)\n// action: lowercase + snake_case, max one sub-action level (a.b.c)\nexport const EVENT_TYPE_REGEX = /^([a-z][a-z0-9_]*)\\.([a-z][a-z0-9_]*(?:\\.[a-z][a-z0-9_]*)?)$/;\n\nexport const EventTypeSchema = z\n .string()\n .min(1)\n .max(100, \"event_type must not exceed SESSION_EVENT_TYPE_MAX_LENGTH (100)\")\n .regex(EVENT_TYPE_REGEX, \"event_type must be {domain}.{action} in lowercase snake_case\");\n\n// ─── INV-1: 6 wire-stable domains ────────────────────────────────────────────\n\nexport const EVENT_DOMAINS = [\n \"user\",\n \"agent\",\n \"session\",\n \"span\",\n \"worker_protocol\",\n \"vault\",\n] as const;\nexport type EventDomain = (typeof EVENT_DOMAINS)[number];\nexport const EVENT_DOMAIN_SET = new Set<string>(EVENT_DOMAINS);\n\n// ─── §1.1 user.* — inbound events from business callers ──────────────────────\n\nexport const UserMessagePayloadSchema = z\n .object({\n content: z.array(\n z.union([\n z.object({ type: z.literal(\"text\"), text: z.string() }).strict(),\n z.object({ type: z.literal(\"image\"), source: z.unknown() }).strict(),\n z.object({ type: z.literal(\"file\"), source: z.unknown() }).strict(),\n ]),\n ),\n })\n .strict();\nexport type UserMessagePayload = z.infer<typeof UserMessagePayloadSchema>;\n\nexport const UserInterruptPayloadSchema = z.object({}).strict();\nexport type UserInterruptPayload = z.infer<typeof UserInterruptPayloadSchema>;\n\nexport const UserToolConfirmationPayloadSchema = z\n .object({\n toolUseId: z.string().min(1),\n result: z.enum([\"allow\", \"deny\"]),\n denyMessage: z.string().optional(),\n })\n .strict();\nexport type UserToolConfirmationPayload = z.infer<typeof UserToolConfirmationPayloadSchema>;\n\nexport const UserToolResultPayloadSchema = z\n .object({\n toolUseId: z.string().min(1),\n content: z.array(z.unknown()),\n })\n .strict();\nexport type UserToolResultPayload = z.infer<typeof UserToolResultPayloadSchema>;\n\n// ─── §1.2 agent.* — events emitted by business Worker / Agent ────────────────\n\nexport const AgentMessagePayloadSchema = z\n .object({\n content: z.array(\n z.union([\n z.object({ type: z.literal(\"text\"), text: z.string() }).strict(),\n z.object({ type: z.literal(\"image\"), source: z.unknown() }).strict(),\n ]),\n ),\n })\n .strict();\nexport type AgentMessagePayload = z.infer<typeof AgentMessagePayloadSchema>;\n\nexport const AgentToolUsePayloadSchema = z\n .object({\n toolUseId: z.string().min(1),\n toolName: z.string().min(1),\n input: z.record(z.unknown()),\n })\n .strict();\nexport type AgentToolUsePayload = z.infer<typeof AgentToolUsePayloadSchema>;\n\nexport const AgentToolResultPayloadSchema = z\n .object({\n toolUseId: z.string().min(1),\n content: z.array(z.unknown()),\n isError: z.boolean().optional(),\n })\n .strict();\nexport type AgentToolResultPayload = z.infer<typeof AgentToolResultPayloadSchema>;\n\nexport const AgentMcpToolUsePayloadSchema = z\n .object({\n toolUseId: z.string().min(1),\n mcpServerName: z.string().min(1),\n toolName: z.string().min(1),\n input: z.record(z.unknown()),\n })\n .strict();\nexport type AgentMcpToolUsePayload = z.infer<typeof AgentMcpToolUsePayloadSchema>;\n\n// agent.completed is business-extensible — NOT .strict() per INV-3 exception\nexport const AgentCompletedPayloadSchema = z.object({}).passthrough();\nexport type AgentCompletedPayload = z.infer<typeof AgentCompletedPayloadSchema>;\n\n// agent.session_reset — R-ASB-09 / MF-1.\n//\n// Emitted by the control-plane (NOT the worker) into the OLD sessionId's\n// `session_events` stream every time R-ASB-06 re-provision completes:\n// the agent's `session_id` was just rewritten from `oldSessionId` to a\n// freshly-created `newSessionId`. Portal threads use this row as the\n// stitching point between two sessions belonging to the same agent —\n// the user-visible \"sandbox 已重启\" card renders at this position so\n// the next turn (cold start, no prior conversation history) is framed\n// rather than appearing as a confusing context drop.\n//\n// Reason enum mirrors the five R-ASB-05 unhealthy dimensions (a-e) plus\n// the `agent.session_id IS NULL` fast-path before dimension (a) runs.\n//\n// See `specs/features/pilot-v2-agent-session-binding.md` § R-ASB-09.\nexport const AGENT_SESSION_RESET_REASONS = [\n \"session_terminal\", // R-ASB-05 dim (a) — session.status === \"failed\"\n \"session_lifecycle_terminal\", // ready session whose lifecycle_phase is terminating/terminated\n \"binding_missing\", // dim (b) — no alive runtime_binding row\n \"ttl_expired\", // dim (c) — ttl_expires_at within REPROVISION_BUFFER_MS\n \"keepalive_unhealthy\", // dim (d) — MF-4 mark-unhealthy latch tripped\n \"max_lifetime\", // dim (e) — MF-5 24h+ session age\n \"agent_session_null\", // pre-dim — agent.session_id was NULL on dispatch\n] as const;\nexport const AgentSessionResetReasonSchema = z.enum(AGENT_SESSION_RESET_REASONS);\nexport type AgentSessionResetReason = z.infer<typeof AgentSessionResetReasonSchema>;\n\nexport const AgentSessionResetPayloadSchema = z\n .object({\n oldSessionId: z.string().uuid(),\n newSessionId: z.string().uuid(),\n reason: AgentSessionResetReasonSchema,\n triggeredByRunId: z.string().uuid(),\n triggeredAt: z.string().datetime(),\n })\n .strict();\nexport type AgentSessionResetPayload = z.infer<typeof AgentSessionResetPayloadSchema>;\n\n// ─── §1.2.x agent.recovery_* — Pilot v2 Agent Recovery (path A) ──────────────\n//\n// `pilot-v2-session-revival.md` REV-INV-6 / R-REV-07. Emitted onto the\n// SAME `session_events` log the original session already owns, since\n// path-A revival keeps `sessionId` invariant across recovery.\n//\n// These schemas are intentionally NOT a copy of the v1 RunEvent\n// `AgentRecoveryStartedEventSchema` (in `events.ts`): v1 carries an\n// `agentId` field that has no v2 equivalent (v2 has no long-lived\n// `agent` entity; the `session` IS the long-lived entity). Sharing\n// schema across the two layers would force every v2 emit site to fake\n// an `agentId`, leaking v1 vocabulary into v2 wire payloads.\n//\n// REV-INV-5 also relies on these payloads carrying `attemptId` so the\n// SDK / observability pipeline can correlate the four lifecycle events\n// (started → hydrated → completed | failed) emitted within a single\n// revival pipeline — multiple revivals on the same session over its\n// lifetime get distinct `attemptId`s.\n\nexport const AGENT_RECOVERY_ERROR_STAGES = [\"provision\", \"startup\", \"hydrate\", \"dispatch\"] as const;\nexport const AgentRecoveryErrorStageSchema = z.enum(AGENT_RECOVERY_ERROR_STAGES);\nexport type AgentRecoveryErrorStage = z.infer<typeof AgentRecoveryErrorStageSchema>;\n\nexport const AgentRecoveryStartedV2PayloadSchema = z\n .object({\n /** 1-based attempt counter (first revive of this session = 1). */\n revivalAttempts: z.number().int().min(1),\n /**\n * REV-INV-7 cap for the chain (typically 3). Optional for backward\n * compatibility with events emitted before the same-session retry\n * landed; consumers MUST treat absence as \"unknown\" rather than\n * \"no cap\" — they can fall back to `revivalAttempts >= 3` as the\n * default budget if they need a UI cue.\n */\n maxRevivalAttempts: z.number().int().min(1).optional(),\n /** `runtime_bindings.id` of the row this revival is superseding. */\n predecessorBindingId: z.string().uuid(),\n /** UUID of this revival pipeline run; correlates the 4 lifecycle events. */\n attemptId: z.string().uuid(),\n })\n .strict();\nexport type AgentRecoveryStartedV2Payload = z.infer<typeof AgentRecoveryStartedV2PayloadSchema>;\n\nexport const AgentRecoveryHydratedV2PayloadSchema = z\n .object({\n messagesCount: z.number().int().nonnegative(),\n /** Canonical SHA-256 hex of restored messages (see `pilot-v2-restore-envelope.md` R-RES-03). */\n messagesHash: z.string().min(1),\n degradedRecovery: z.boolean(),\n })\n .strict();\nexport type AgentRecoveryHydratedV2Payload = z.infer<typeof AgentRecoveryHydratedV2PayloadSchema>;\n\nexport const AgentRecoveryCompletedV2PayloadSchema = z\n .object({\n degradedRecovery: z.boolean(),\n /** Raw `session_events` rows scanned before any cap-trim. */\n eventsSeen: z.number().int().nonnegative(),\n attemptId: z.string().uuid(),\n })\n .strict();\nexport type AgentRecoveryCompletedV2Payload = z.infer<typeof AgentRecoveryCompletedV2PayloadSchema>;\n\nexport const AgentRecoveryFailedV2PayloadSchema = z\n .object({\n errorStage: AgentRecoveryErrorStageSchema,\n /** Human-readable, MUST NOT include credentials / PII. */\n error: z.string().min(1),\n attemptId: z.string().uuid(),\n })\n .strict();\nexport type AgentRecoveryFailedV2Payload = z.infer<typeof AgentRecoveryFailedV2PayloadSchema>;\n\n// ─── §1.3 session.* — platform lifecycle events ──────────────────────────────\n// INV-2: session.status_* strictly maps to SessionStatus 5 states\n// MUST NOT include session.status_terminated\n\nexport const SessionStatusCreatedPayloadSchema = z\n .object({ sessionId: z.string().uuid(), createdAt: z.string() })\n .strict();\nexport type SessionStatusCreatedPayload = z.infer<typeof SessionStatusCreatedPayloadSchema>;\n\nexport const SessionStatusProvisioningPayloadSchema = z\n .object({\n sessionId: z.string().uuid(),\n runtimeBindingId: z.string().optional(),\n provisionStartedAt: z.string(),\n })\n .strict();\nexport type SessionStatusProvisioningPayload = z.infer<\n typeof SessionStatusProvisioningPayloadSchema\n>;\n\nexport const SessionStatusStartingPayloadSchema = z\n .object({\n sessionId: z.string().uuid(),\n runtimeBindingId: z.string(),\n sandboxId: z.string(),\n workerEndpoint: z.string(),\n })\n .strict();\nexport type SessionStatusStartingPayload = z.infer<typeof SessionStatusStartingPayloadSchema>;\n\nexport const SessionStatusReadyPayloadSchema = z\n .object({\n sessionId: z.string().uuid(),\n readyAt: z.string(),\n gateAggregate: z.object({ worker: z.literal(true) }).passthrough(),\n })\n .strict();\nexport type SessionStatusReadyPayload = z.infer<typeof SessionStatusReadyPayloadSchema>;\n\nexport const SessionStatusFailedPayloadSchema = z\n .object({\n sessionId: z.string().uuid(),\n failedAt: z.string(),\n primaryFailure: z.object({\n source: z.string(),\n code: z.string(),\n message: z.string().optional(),\n }),\n })\n .strict();\nexport type SessionStatusFailedPayload = z.infer<typeof SessionStatusFailedPayloadSchema>;\n\n// session.idle — NOT a status_* event (INV-2: MUST NOT use status_ prefix)\nexport const SessionIdlePayloadSchema = z\n .object({\n sessionId: z.string().uuid(),\n stopReason: z.object({\n type: z.enum([\"requires_action\", \"end_turn\"]),\n eventIds: z.array(z.string()).optional(),\n }),\n })\n .strict();\nexport type SessionIdlePayload = z.infer<typeof SessionIdlePayloadSchema>;\n\n// INV-2 subschema: ONLY the 5 valid session.status_* literals\nexport const EventTypeSessionStatusSchema = z.enum([\n \"session.status_created\",\n \"session.status_provisioning\",\n \"session.status_starting\",\n \"session.status_ready\",\n \"session.status_failed\",\n]);\nexport type EventTypeSessionStatus = z.infer<typeof EventTypeSessionStatusSchema>;\n\n// ─── §1.4 span.* — sub-task nesting ──────────────────────────────────────────\n\nexport const SpanStartPayloadSchema = z\n .object({\n spanId: z.string().min(1),\n parentSpanId: z.string().optional(),\n name: z.string().min(1),\n startedAt: z.string(),\n attributes: z.record(z.unknown()).optional(),\n })\n .strict();\nexport type SpanStartPayload = z.infer<typeof SpanStartPayloadSchema>;\n\nexport const SpanEndPayloadSchema = z\n .object({\n spanId: z.string().min(1),\n endedAt: z.string(),\n status: z.enum([\"ok\", \"error\"]).optional(),\n })\n .strict();\nexport type SpanEndPayload = z.infer<typeof SpanEndPayloadSchema>;\n\nexport const SpanEventPayloadSchema = z\n .object({\n spanId: z.string().min(1),\n eventName: z.string().min(1),\n attributes: z.record(z.unknown()).optional(),\n })\n .strict();\nexport type SpanEventPayload = z.infer<typeof SpanEventPayloadSchema>;\n\n// ─── §1.5 worker_protocol.* — Platform worker protocol events ────────────────\n// 4 kinds × 5 suffixes = 20 standard event types.\n// Payload schemas for accepted/rejected/completed/failed bridge to\n// packages/contracts/src/pilot-v2-worker-protocol-events.ts (already shipped).\n\nexport const WORKER_PROTOCOL_KINDS = [\"prompt\", \"followup\", \"abort\", \"restore\"] as const;\nexport type WorkerProtocolKind = (typeof WORKER_PROTOCOL_KINDS)[number];\nexport const WORKER_PROTOCOL_SUFFIXES = [\n \"dispatched\",\n \"accepted\",\n \"rejected\",\n \"completed\",\n \"failed\",\n] as const;\nexport type WorkerProtocolSuffix = (typeof WORKER_PROTOCOL_SUFFIXES)[number];\n\n// worker_protocol.{kind}.dispatched — control-plane writer emits the full\n// request envelope as payload (per SessionWorkerProtocolProvider).\n// Per-kind schemas match the actual writer output to avoid strict-rejection\n// of production emits when ingest validation is wired up.\nexport {\n WorkerProtocolAbortRequestSchema as WorkerProtocolAbortDispatchedPayloadSchema,\n WorkerProtocolFollowupRequestSchema as WorkerProtocolFollowupDispatchedPayloadSchema,\n WorkerProtocolPromptRequestSchema as WorkerProtocolPromptDispatchedPayloadSchema,\n WorkerProtocolRestoreRequestSchema as WorkerProtocolRestoreDispatchedPayloadSchema,\n};\n\n// Re-export bridged schemas for caller convenience\nexport {\n WorkerProtocolAcceptedPayloadSchema,\n WorkerProtocolCompletedPayloadSchema,\n WorkerProtocolFailedPayloadSchema,\n WorkerProtocolRejectedPayloadSchema,\n};\n\n// ─── §1.6 vault.* — Vault credential lifecycle (#441 + #518) ─────────────────\n\nexport const VaultArchivedPayloadSchema = z\n .object({ vaultId: z.string().min(1), archivedAt: z.string() })\n .strict();\nexport type VaultArchivedPayload = z.infer<typeof VaultArchivedPayloadSchema>;\n\nexport const VaultDeletedPayloadSchema = z\n .object({ vaultId: z.string().min(1), deletedAt: z.string() })\n .strict();\nexport type VaultDeletedPayload = z.infer<typeof VaultDeletedPayloadSchema>;\n\nexport const VaultCredentialArchivedPayloadSchema = z\n .object({\n vaultId: z.string().min(1),\n credentialId: z.string().min(1),\n archivedAt: z.string(),\n })\n .strict();\nexport type VaultCredentialArchivedPayload = z.infer<typeof VaultCredentialArchivedPayloadSchema>;\n\nexport const VaultCredentialDeletedPayloadSchema = z\n .object({\n vaultId: z.string().min(1),\n credentialId: z.string().min(1),\n deletedAt: z.string(),\n })\n .strict();\nexport type VaultCredentialDeletedPayload = z.infer<typeof VaultCredentialDeletedPayloadSchema>;\n\nexport const VaultCredentialRefreshFailedPayloadSchema = z\n .object({\n vaultId: z.string().min(1),\n credentialId: z.string().min(1),\n failedStatus: z.enum([\"invalid\", \"unknown\"]),\n lastRefreshedAt: z.string(),\n })\n .strict();\nexport type VaultCredentialRefreshFailedPayload = z.infer<\n typeof VaultCredentialRefreshFailedPayloadSchema\n>;\n\nexport const VaultCredentialTargetNotAllowedPayloadSchema = z\n .object({\n sessionId: z.string().uuid(),\n vaultId: z.string().optional(),\n credentialId: z.string().optional(),\n mcpServerUrl: z.string(),\n reason: z.literal(\"target_not_in_revision_allowlist\"),\n recoverable: z.literal(false),\n occurredAt: z.string(),\n })\n .strict();\nexport type VaultCredentialTargetNotAllowedPayload = z.infer<\n typeof VaultCredentialTargetNotAllowedPayloadSchema\n>;\n\n// ─── Standard event type → payload schema map ─────────────────────────────────\n// INV-3: Each standard event_type MUST have a payload schema.\n// worker_protocol.* schemas live in pilot-v2-worker-protocol-events.ts (already shipped).\n\nexport const STANDARD_EVENT_PAYLOAD_SCHEMAS = {\n \"user.message\": UserMessagePayloadSchema,\n \"user.interrupt\": UserInterruptPayloadSchema,\n \"user.tool_confirmation\": UserToolConfirmationPayloadSchema,\n \"user.tool_result\": UserToolResultPayloadSchema,\n \"agent.message\": AgentMessagePayloadSchema,\n \"agent.tool_use\": AgentToolUsePayloadSchema,\n \"agent.tool_result\": AgentToolResultPayloadSchema,\n \"agent.mcp_tool_use\": AgentMcpToolUsePayloadSchema,\n \"agent.completed\": AgentCompletedPayloadSchema,\n \"agent.session_reset\": AgentSessionResetPayloadSchema,\n \"agent.recovery_started\": AgentRecoveryStartedV2PayloadSchema,\n \"agent.recovery_hydrated\": AgentRecoveryHydratedV2PayloadSchema,\n \"agent.recovery_completed\": AgentRecoveryCompletedV2PayloadSchema,\n \"agent.recovery_failed\": AgentRecoveryFailedV2PayloadSchema,\n \"session.status_created\": SessionStatusCreatedPayloadSchema,\n \"session.status_provisioning\": SessionStatusProvisioningPayloadSchema,\n \"session.status_starting\": SessionStatusStartingPayloadSchema,\n \"session.status_ready\": SessionStatusReadyPayloadSchema,\n \"session.status_failed\": SessionStatusFailedPayloadSchema,\n \"session.idle\": SessionIdlePayloadSchema,\n \"span.start\": SpanStartPayloadSchema,\n \"span.end\": SpanEndPayloadSchema,\n \"span.event\": SpanEventPayloadSchema,\n \"vault.archived\": VaultArchivedPayloadSchema,\n \"vault.deleted\": VaultDeletedPayloadSchema,\n \"vault.credential_archived\": VaultCredentialArchivedPayloadSchema,\n \"vault.credential_deleted\": VaultCredentialDeletedPayloadSchema,\n \"vault.credential_refresh_failed\": VaultCredentialRefreshFailedPayloadSchema,\n \"vault.credential_target_not_allowed\": VaultCredentialTargetNotAllowedPayloadSchema,\n // §1.5 worker_protocol.* — 4 kinds × 5 suffixes = 20 standard event types\n \"worker_protocol.prompt.dispatched\": WorkerProtocolPromptRequestSchema,\n \"worker_protocol.prompt.accepted\": WorkerProtocolAcceptedPayloadSchema,\n \"worker_protocol.prompt.rejected\": WorkerProtocolRejectedPayloadSchema,\n \"worker_protocol.prompt.completed\": WorkerProtocolCompletedPayloadSchema,\n \"worker_protocol.prompt.failed\": WorkerProtocolFailedPayloadSchema,\n \"worker_protocol.followup.dispatched\": WorkerProtocolFollowupRequestSchema,\n \"worker_protocol.followup.accepted\": WorkerProtocolAcceptedPayloadSchema,\n \"worker_protocol.followup.rejected\": WorkerProtocolRejectedPayloadSchema,\n \"worker_protocol.followup.completed\": WorkerProtocolCompletedPayloadSchema,\n \"worker_protocol.followup.failed\": WorkerProtocolFailedPayloadSchema,\n \"worker_protocol.abort.dispatched\": WorkerProtocolAbortRequestSchema,\n \"worker_protocol.abort.accepted\": WorkerProtocolAcceptedPayloadSchema,\n \"worker_protocol.abort.rejected\": WorkerProtocolRejectedPayloadSchema,\n \"worker_protocol.abort.completed\": WorkerProtocolCompletedPayloadSchema,\n \"worker_protocol.abort.failed\": WorkerProtocolFailedPayloadSchema,\n \"worker_protocol.restore.dispatched\": WorkerProtocolRestoreRequestSchema,\n \"worker_protocol.restore.accepted\": WorkerProtocolAcceptedPayloadSchema,\n \"worker_protocol.restore.rejected\": WorkerProtocolRejectedPayloadSchema,\n \"worker_protocol.restore.completed\": WorkerProtocolCompletedPayloadSchema,\n \"worker_protocol.restore.failed\": WorkerProtocolFailedPayloadSchema,\n} as const;\n\nexport type StandardEventType = keyof typeof STANDARD_EVENT_PAYLOAD_SCHEMAS;\n\nexport const STANDARD_EVENT_TYPES = Object.keys(\n STANDARD_EVENT_PAYLOAD_SCHEMAS,\n) as StandardEventType[];\n\nexport const StandardEventTypeSchema = z.enum(STANDARD_EVENT_TYPES as [string, ...string[]]);\n\n// ─── INV-4: Legacy aliases (backward compat, v0.x emit) ──────────────────────\n\nexport const LEGACY_EVENT_TYPE_ALIASES: Record<string, StandardEventType> = {\n \"session.created\": \"session.status_created\",\n \"worker.ready\": \"session.status_ready\",\n};\n\n// ─── parseEventType helper ────────────────────────────────────────────────────\n// Non-throwing — returns a structured result for SDK warning emission.\n\nexport type ParseEventTypeResult =\n | { kind: \"standard\"; eventType: StandardEventType; domain: EventDomain; action: string }\n | {\n kind: \"legacy_alias\";\n originalType: string;\n resolvedType: StandardEventType;\n domain: EventDomain;\n }\n | { kind: \"unknown_domain\"; eventType: string; domain: string; action: string }\n | { kind: \"non_standard_action\"; eventType: string; domain: EventDomain; action: string }\n | { kind: \"invalid_format\"; eventType: string };\n\nexport function parseEventType(typeStr: string): ParseEventTypeResult {\n const match = typeStr.match(EVENT_TYPE_REGEX);\n if (!match) return { kind: \"invalid_format\", eventType: typeStr };\n\n const domain = match[1];\n const action = match[2];\n\n // Check legacy alias first\n if (typeStr in LEGACY_EVENT_TYPE_ALIASES) {\n const resolved = LEGACY_EVENT_TYPE_ALIASES[typeStr];\n const resolvedMatch = resolved.match(EVENT_TYPE_REGEX);\n const resolvedDomain = resolvedMatch ? (resolvedMatch[1] as EventDomain) : \"session\";\n return {\n kind: \"legacy_alias\",\n originalType: typeStr,\n resolvedType: resolved,\n domain: resolvedDomain,\n };\n }\n\n if (!EVENT_DOMAIN_SET.has(domain)) {\n return { kind: \"unknown_domain\", eventType: typeStr, domain, action };\n }\n\n if (typeStr in STANDARD_EVENT_PAYLOAD_SCHEMAS) {\n return {\n kind: \"standard\",\n eventType: typeStr as StandardEventType,\n domain: domain as EventDomain,\n action,\n };\n }\n\n return { kind: \"non_standard_action\", eventType: typeStr, domain: domain as EventDomain, action };\n}\n","import { z } from \"zod\";\n\nimport {\n WP_FAILURE_REASON_KINDS,\n WorkerProtocolAbortReasonSchema,\n WorkerProtocolVersionSchema,\n} from \"./worker-protocol-provider\";\n\n/**\n * R-SWS-09b — pilot-v2 worker protocol event payload schemas.\n *\n * Source-of-truth Zod schemas for `worker_protocol.${kind}.{accepted,rejected,completed,failed}`\n * event payloads emitted by the sdk-worker `ManagedAgentServer` (R-SWS-09) and\n * by handlers per P0a R-MAH-05 / R-MAH-08 / R-MAH-09 ownership rules.\n *\n * Cross-references:\n * - `specs/features/pilot-v2-sdk-worker-substrate-api.md` §Event payloads (R-SWS-09b)\n * - `specs/features/pilot-v2-managed-agent-handler-contract.md` §R-MAH-04b / R-MAH-08 / R-MAH-09\n *\n * Namespace boundary (consumer MUST distinguish):\n * - `WP_FAILURE_REASON_KINDS` (6-arm, wire-level) — used by `DispatchOutcome.rejected.reason`\n * and by `worker_protocol.${kind}.rejected` event payload.\n * - `WorkerProtocolFailedReasonSchema` (5-arm, event-local sub-enum) — used ONLY by\n * `worker_protocol.${kind}.failed` event payload. Literal values may overlap with\n * the wire-level set, but consumers MUST route by `event_type` suffix /\n * `DispatchOutcome.kind`, not by the bare reason string.\n */\n\nexport const WorkerProtocolAcceptedPayloadSchema = z\n .object({\n turnId: z.string().min(1),\n protocolVersion: WorkerProtocolVersionSchema,\n })\n .strict();\nexport type WorkerProtocolAcceptedPayload = z.infer<typeof WorkerProtocolAcceptedPayloadSchema>;\n\nexport const WorkerProtocolRejectedPayloadSchema = z\n .object({\n reason: z.enum(WP_FAILURE_REASON_KINDS),\n message: z.string().min(1).optional(),\n })\n .strict();\nexport type WorkerProtocolRejectedPayload = z.infer<typeof WorkerProtocolRejectedPayloadSchema>;\n\nexport const WorkerProtocolFailedReasonSchema = z.enum([\n \"wp_handshake_timeout\",\n \"wp_aborted_by_signal\",\n \"wp_protocol_violation\",\n \"wp_replay_lost\",\n \"wp_session_terminated\",\n]);\nexport type WorkerProtocolFailedReason = z.infer<typeof WorkerProtocolFailedReasonSchema>;\n\nexport const WorkerProtocolFailedPayloadSchema = z\n .object({\n reason: WorkerProtocolFailedReasonSchema,\n message: z.string().min(1).optional(),\n abortContext: z\n .object({\n reason: WorkerProtocolAbortReasonSchema,\n requestedAt: z.string().min(1).optional(),\n })\n .strict()\n .optional(),\n })\n .strict()\n .refine((p) => p.reason !== \"wp_aborted_by_signal\" || p.abortContext !== undefined, {\n message: \"abortContext required when reason = wp_aborted_by_signal\",\n });\nexport type WorkerProtocolFailedPayload = z.infer<typeof WorkerProtocolFailedPayloadSchema>;\n\n/**\n * `completed` event is handler-emit only (P0a R-MAH-05, R-MAH-09 ownership).\n *\n * Business-extensible — spec deliberately leaves the field set open (no `.strict()`).\n * ManagedAgentServer MUST NOT narrow the payload before forwarding to SessionEventsClient.\n */\nexport const WorkerProtocolCompletedPayloadSchema = z.record(z.unknown());\nexport type WorkerProtocolCompletedPayload = z.infer<typeof WorkerProtocolCompletedPayloadSchema>;\n","import { z } from \"zod\";\n\nimport {\n FAILURE_REASON_KINDS,\n type FailureReasonRef,\n TraceContextSchema,\n} from \"./runtime-provider\";\n\n/**\n * WorkerProtocolProvider v2 frozen-contract surface.\n *\n * Cohort-canonical 4-method narrow adapter boundary for the Pilot v2\n * `managed_agent` Worker Protocol — Pilot's outbox-only path that\n * dispatches prompts, follow-ups, aborts, and restores into a Worker\n * process. This is the **sister API** to `RuntimeProvider`:\n *\n * - `RuntimeProvider` (runtime-provider.ts) governs Pod/Sandbox\n * provisioning lifecycle (provision /\n * getReadyState / getHealth / cancel).\n * - `WorkerProtocolProvider` (this file) governs the Worker-process\n * business protocol — dispatching prompts\n * and follow-ups into a Worker that has\n * already been provisioned and reached\n * `ReadyState.ready`.\n *\n * PR-WP-1 form LOCK (per @TL `57179693`):\n * - First-class iface ship + ZERO production wire-up. Callsite\n * migration (KanyunWorkerProtocolClient + RunService dual-path) is a\n * follow-up PR cohort-anchored to PR-WP-1b.\n * - D5 §17 outbox-only path. This iface NEVER writes `runs.*` — the\n * RunService remains the single writer of the runs table; the\n * WorkerProtocol surface only emits dispatch envelopes via the\n * outbox row owned by RunService callers.\n * - R-WP-02 BLOCK enforce D7. PR-WP-1 is review-time gated:\n * callsite-wiring PRs (PR-WP-1b endpoint DTOs + later\n * KanyunWorkerProtocolClient PR) MUST cite this iface verbatim and\n * MUST NOT widen the 4-method shape.\n *\n * R-WP-01..05 (shape-agnostic invariants for the iface; spec parity in\n * `specs/features/pilot-v2-worker-runtime-contract.md`):\n * 01 zero v1 primitives — no `runId` / `agentId` / `projectId` /\n * `provider` legacy on the iface (those live in RunService scope).\n * The iface speaks only `sessionId` + `runtimeBindingId` (the v2\n * Session/RuntimeBinding identifiers locked in PR #408 / PR #407).\n * 02 WorkerProtocolPromptRequest / WorkerProtocolFollowupRequest / WorkerProtocolAbortRequest / WorkerProtocolRestoreRequest\n * are readonly DTOs (TS Readonly<>).\n * 03 idempotencyKey REQUIRED on every method (crash-safe re-dispatch;\n * mirrors `RuntimeProvider.provision`'s R-IF-04 invariant).\n * 04 promptText / followupText opaque pass-through bytes — Pilot\n * treats Worker-business prompt content as opaque (mirrors\n * ProvisionRequest's R-IF-05 env opacity).\n * 05 21-arm `FailureReasonRef` LOCK reused verbatim — failure shape\n * stays cohort-canonical 14 baseline + 1 traffic-split + 6 wp_*\n * (no new failure arm shipped by this iface; the 6 `wp_*` arms\n * already locked in PR-WP-2 #468 / PR-TS-1 D5 are precisely the\n * ones this iface reports).\n *\n * Naming-collision warning (mirrors the `pilotApiVersion` Task #1 SDK\n * disambiguation): TWO unrelated identifiers exist in the cohort:\n * - `WorkerProtocolProvider` (this file) — the v2 4-method iface.\n * - `WorkerProtocolClient` / `KanyunWorkerProtocolClient` (future\n * PR-WP-1b+ implementations) — the production wiring against the\n * real Worker HTTP surface.\n * The iface has zero production deps; PR-WP-1b ships endpoint DTOs and\n * a Kanyun-specific client lands later. This file MUST stay zero-runtime-deps\n * compatible with the @pilot/contracts package invariant (per AGENTS.md).\n *\n * See also:\n * - `specs/features/pilot-v2-worker-runtime-contract.md` §\n * \"WorkerProtocolProvider Iface\" (v0.x spec parity, PR-WP-1a).\n * - `runtime-provider.ts` for the sister 4-method narrow boundary\n * and the 21-arm `FailureReasonRef` LOCK source-of-truth.\n */\n\n/**\n * Worker Protocol semver: locked to `\"v1\"` for PR-WP-1.\n *\n * The iface itself is intentionally non-versioned (the 4-method shape\n * is the contract). `WorkerProtocolVersion` is the *wire* version of\n * the dispatch envelope that PR-WP-1b will materialise; it appears on\n * the iface as the response field `protocolVersion` so callers can\n * detect a mismatched Worker without parsing the body.\n *\n * Forward extension: a future \"v2\" wire format would land in PR-WP-N\n * with a synchronous dual-track convention (cohort-canonical) — never\n * by silently bumping the literal here.\n */\nexport const WorkerProtocolVersionSchema = z.enum([\"v1\"]);\nexport type WorkerProtocolVersion = z.infer<typeof WorkerProtocolVersionSchema>;\n\n/**\n * SessionRef — the addressable v2 Session identifier the iface speaks.\n *\n * Mirrors PR #408 `session_tokens.session_id` and PR #407\n * `PodAgentStartWorkerRequest.sessionId`. The iface MUST NOT speak v1\n * `runId` / `agentId` (R-WP-01).\n */\nexport const SessionRefSchema = z\n .object({\n sessionId: z.string().min(1),\n runtimeBindingId: z.string().min(1),\n })\n .strict();\nexport type SessionRef = z.infer<typeof SessionRefSchema>;\n\n/**\n * WorkerProtocolPromptRequest — initial prompt dispatch into a ready Worker.\n *\n * Wire shape mirrors v1 `POST /prompt` (`apps/agent-worker/src/server.ts`)\n * but stripped of v1 primitives: no `runId` / `provider`. The v2 Session\n * identifies the conversation, and `protocolVersion` lets the Worker\n * reject a mismatched wire format synchronously (instead of failing\n * mid-stream).\n *\n * `promptText` is opaque pass-through bytes (R-WP-04). Pilot does NOT\n * inspect or transform prompt content; the Worker owns business\n * semantics (consistent with Substrate § Worker SDK auto-read scope —\n * Pilot only governs the env / token / port surface, not Worker\n * business protocol).\n */\n/**\n * Forward-compat policy for envelope schemas (R-WP-02 refinement):\n *\n * The 4 dispatch envelopes use `.passthrough()` + an explicit v1-primitive\n * blacklist refinement, NOT `.strict()`. Rationale:\n *\n * - `.strict()` historically rejected *all* unknown keys to enforce\n * R-WP-01 (no v1 primitives on the iface). The side effect: any\n * forward-compat extension (e.g. `idleTimeoutMs`, `hardCapMs`) added on\n * the dispatcher side becomes an immediate breaking change for every\n * deployed worker bundle that has not yet rolled forward — the worker\n * rejects the entire envelope as `wp_invalid_envelope`, the run hangs\n * indefinitely (poller writes job.outcome but does not advance\n * run.status today; see worker-protocol-job-poller.ts).\n *\n * - `.passthrough()` preserves R-WP-02 intent (the iface shape is the\n * contract) AND satisfies the proper forward-compat invariant:\n * adding a new OPTIONAL field on a newer dispatcher MUST never\n * break an older worker.\n *\n * - R-WP-01 (no v1 primitives) is preserved by an explicit refinement\n * below: the dispatcher MUST NOT inject `runId / agentId / projectId\n * / provider` even though `.passthrough()` would otherwise tolerate\n * them. Misconfigured callers still fail loudly.\n */\nconst FORBIDDEN_V1_PRIMITIVE_KEYS = [\"runId\", \"agentId\", \"projectId\", \"provider\"] as const;\nfunction forbidV1Primitives(val: Record<string, unknown>, ctx: z.RefinementCtx): void {\n for (const k of FORBIDDEN_V1_PRIMITIVE_KEYS) {\n if (k in val) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [k],\n message: `R-WP-01: v1 primitive '${k}' is forbidden on v2 dispatch envelopes`,\n });\n }\n }\n}\n\nexport const WorkerProtocolPromptRequestSchema = z\n .object({\n idempotencyKey: z.string().min(1),\n session: SessionRefSchema,\n protocolVersion: WorkerProtocolVersionSchema,\n promptText: z.string().min(1),\n trace: TraceContextSchema,\n // Legacy wall-clock deadline. Kept for back-compat with workers/dispatchers\n // that have not yet adopted the idle/hardCap split. NEW behavior:\n // - When `idleTimeoutMs` is supplied, framework uses idle-based deadline\n // (reset on each ctx.events.append success) plus optional `hardCapMs`\n // absolute upper bound; the legacy `deadlineMs` is ignored.\n // - When only `deadlineMs` is supplied, framework falls back to the\n // original wall-clock behavior (single setTimeout = deadlineMs).\n deadlineMs: z.number().int().positive(),\n // Idle timeout: framework fails the turn with `wp_handshake_timeout` if no\n // `ctx.events.append` succeeds within this many ms. Reset each time the\n // handler emits a session_event chunk — long-running but actively-streaming\n // handlers are NOT killed by the wall-clock alone.\n idleTimeoutMs: z.number().int().positive().optional(),\n // Hard upper bound that fires regardless of activity (defense against\n // infinite-loop handlers that keep emitting). Optional companion to\n // `idleTimeoutMs`; when omitted, no hard cap is armed.\n hardCapMs: z.number().int().positive().optional(),\n })\n .passthrough()\n .superRefine(forbidV1Primitives);\nexport type WorkerProtocolPromptRequest = Readonly<\n z.infer<typeof WorkerProtocolPromptRequestSchema>\n>;\n\n/**\n * WorkerProtocolFollowupRequest — follow-up turn dispatch on an existing Session.\n *\n * Mirrors v1 `POST /followup`. `parentTurnId` is the prior turn the\n * follow-up extends; the Worker is responsible for conversation-state\n * continuity (Substrate § `managed_agent` Worker responsibilities).\n */\nexport const WorkerProtocolFollowupRequestSchema = z\n .object({\n idempotencyKey: z.string().min(1),\n session: SessionRefSchema,\n protocolVersion: WorkerProtocolVersionSchema,\n parentTurnId: z.string().min(1),\n followupText: z.string().min(1),\n trace: TraceContextSchema,\n // See `WorkerProtocolPromptRequestSchema.deadlineMs` for the legacy /\n // idle / hardCap precedence rules; same semantics apply for follow-up.\n deadlineMs: z.number().int().positive(),\n idleTimeoutMs: z.number().int().positive().optional(),\n hardCapMs: z.number().int().positive().optional(),\n })\n .passthrough()\n .superRefine(forbidV1Primitives);\nexport type WorkerProtocolFollowupRequest = Readonly<\n z.infer<typeof WorkerProtocolFollowupRequestSchema>\n>;\n\n/**\n * WorkerProtocolAbortRequest — abort an in-flight turn.\n *\n * Mirrors v1 `POST /abort`. Idempotent first-wins: a second abort on\n * the same turn MUST NOT throw (mirrors `RuntimeProvider.cancel`'s\n * idempotency invariant). Provenance arm is locked to `user / timeout\n * / system`, identical to `RuntimeProvider.CancelReason`, to keep the\n * cohort-canonical cancel shape uniform across the two providers.\n */\nexport const WorkerProtocolAbortReasonSchema = z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"user\"), userId: z.string().min(1).optional() }).strict(),\n z.object({ kind: z.literal(\"timeout\") }).strict(),\n z.object({ kind: z.literal(\"system\"), hint: z.string().min(1) }).strict(),\n]);\nexport type WorkerProtocolAbortReason = z.infer<typeof WorkerProtocolAbortReasonSchema>;\n\nexport const WorkerProtocolAbortRequestSchema = z\n .object({\n idempotencyKey: z.string().min(1),\n session: SessionRefSchema,\n protocolVersion: WorkerProtocolVersionSchema,\n turnId: z.string().min(1),\n reason: WorkerProtocolAbortReasonSchema,\n trace: TraceContextSchema,\n })\n .passthrough()\n .superRefine(forbidV1Primitives);\nexport type WorkerProtocolAbortRequest = Readonly<z.infer<typeof WorkerProtocolAbortRequestSchema>>;\n\n/**\n * WorkerProtocolRestoreRequest — rehydrate Worker conversation state from a prior\n * Session / turn boundary.\n *\n * Mirrors v1 `POST /agent/restore`. Used after a Worker crash + restart\n * sequence (Pod Agent restarts the Worker subprocess, then Pilot\n * re-issues `restore` to bring the Worker back to the last persisted\n * turn). `replayCursor` is opaque to Pilot; the Worker owns its\n * persistence model.\n */\nexport const WorkerProtocolRestoreRequestSchema = z\n .object({\n idempotencyKey: z.string().min(1),\n session: SessionRefSchema,\n protocolVersion: WorkerProtocolVersionSchema,\n replayCursor: z.string().min(1).optional(),\n trace: TraceContextSchema,\n // See `WorkerProtocolPromptRequestSchema.deadlineMs` for the legacy /\n // idle / hardCap precedence rules.\n deadlineMs: z.number().int().positive(),\n idleTimeoutMs: z.number().int().positive().optional(),\n hardCapMs: z.number().int().positive().optional(),\n })\n .passthrough()\n .superRefine(forbidV1Primitives);\nexport type WorkerProtocolRestoreRequest = Readonly<\n z.infer<typeof WorkerProtocolRestoreRequestSchema>\n>;\n\n/**\n * DispatchOutcome 4-arm:\n *\n * - `accepted` — the Worker accepted the dispatch and is now\n * producing events on the outbox/event stream.\n * - `rejected` — the Worker rejected the dispatch synchronously\n * (e.g. unsupported `protocolVersion`, malformed\n * envelope). `reason` is one of the `wp_*`\n * FailureReasonRef arms.\n * - `idempotent_replay` — the iface saw an existing entry for this\n * `idempotencyKey` and returned the prior\n * outcome instead of re-dispatching.\n * - `transport_failed` — the iface could not reach the Worker; the\n * caller MAY retry. `reason` is one of the\n * `wp_*` arms (e.g. `wp_handshake_timeout`).\n *\n * Every dispatch method returns the same arm shape — uniformity keeps\n * the contract test surface flat (one matcher per arm, not 4×4).\n */\nexport type DispatchOutcome =\n | {\n readonly kind: \"accepted\";\n readonly turnId: string;\n readonly protocolVersion: WorkerProtocolVersion;\n readonly observedAt: string;\n }\n | {\n readonly kind: \"rejected\";\n readonly reason: WpFailureReasonRef;\n readonly observedAt: string;\n readonly message?: string;\n }\n | {\n readonly kind: \"idempotent_replay\";\n readonly turnId: string;\n readonly priorOutcome: \"accepted\" | \"rejected\";\n readonly observedAt: string;\n }\n | {\n readonly kind: \"transport_failed\";\n readonly reason: WpFailureReasonRef;\n readonly observedAt: string;\n readonly message?: string;\n };\n\n/**\n * The 6 wp_* failure arms an iface implementation MAY emit. Subset of\n * the 21-arm `FAILURE_REASON_KINDS`; carried here as a typed view so\n * tests can assert that `rejected.reason` / `transport_failed.reason`\n * stay within the wp_* slice without leaking provisioning arms.\n *\n * NOT an enum re-declaration — this is a derived view that re-uses\n * `FAILURE_REASON_KINDS` to guarantee no drift. R-WP-05 LOCK.\n */\nexport const WP_FAILURE_REASON_KINDS = [\n \"wp_protocol_violation\",\n \"wp_handshake_timeout\",\n \"wp_unsupported_version\",\n \"wp_invalid_envelope\",\n \"wp_stream_terminated\",\n \"wp_replay_lost\",\n] as const satisfies ReadonlyArray<FailureReasonRef>;\n\nexport type WpFailureReasonRef = (typeof WP_FAILURE_REASON_KINDS)[number];\n\n/**\n * Compile-time guarantee that every wp_* literal is contained in the\n * canonical 21-arm union. If a future PR changes the wp_* slice\n * without updating `FAILURE_REASON_KINDS`, this assertion fails the\n * `tsc` build before tests even run.\n */\nconst _wpKindsAreSubsetOfFailureReasonRef: ReadonlyArray<FailureReasonRef> =\n WP_FAILURE_REASON_KINDS;\nvoid _wpKindsAreSubsetOfFailureReasonRef;\nvoid FAILURE_REASON_KINDS; // silences unused-import on `dts` builds.\n\n/**\n * DispatchOutcomeSchema — runtime validator for the 4-arm DispatchOutcome\n * union (PR-WP-1b).\n *\n * PR-WP-1a shipped the TS type only. PR-WP-1b adds the zod runtime parser\n * so wire-incoming envelopes (and `FakeWorkerProtocolProvider` test\n * doubles) can validate against the same shape the iface declares.\n *\n * The schema's runtime-narrow shape is byte-identical with the TS union:\n * - `accepted` / `idempotent_replay` carry no `reason` field\n * - `rejected` / `transport_failed` MUST carry `reason: WpFailureReasonRef`\n * (R-WP-05 enforce-at-consumption — schema-layer + consumption-layer\n * dual-layer LOCK, same form the type uses)\n *\n * `.strict()` on every arm rejects v1 primitives (`runId` / `agentId` /\n * `provider`) and any forward-extension-without-dual-track field that\n * leaks into the wire (R-WP-01 + R-WP-02 BLOCK enforce D7).\n */\nconst WP_FAILURE_REASON_ENUM = z.enum(WP_FAILURE_REASON_KINDS);\n\nexport const DispatchOutcomeSchema = z.discriminatedUnion(\"kind\", [\n z\n .object({\n kind: z.literal(\"accepted\"),\n turnId: z.string().min(1),\n protocolVersion: WorkerProtocolVersionSchema,\n observedAt: z.string().min(1),\n })\n .strict(),\n z\n .object({\n kind: z.literal(\"rejected\"),\n reason: WP_FAILURE_REASON_ENUM,\n observedAt: z.string().min(1),\n message: z.string().min(1).optional(),\n })\n .strict(),\n z\n .object({\n kind: z.literal(\"idempotent_replay\"),\n turnId: z.string().min(1),\n priorOutcome: z.enum([\"accepted\", \"rejected\"]),\n observedAt: z.string().min(1),\n })\n .strict(),\n z\n .object({\n kind: z.literal(\"transport_failed\"),\n reason: WP_FAILURE_REASON_ENUM,\n observedAt: z.string().min(1),\n message: z.string().min(1).optional(),\n })\n .strict(),\n]);\n\n/**\n * Per-method Response DTO schemas (PR-WP-1b).\n *\n * Each method's wire response is the same `DispatchOutcome` 4-arm union\n * (uniformity per the iface — see L225-226 comment block \"Every dispatch\n * method returns the same arm shape — uniformity keeps the contract test\n * surface flat (one matcher per arm, not 4×4)\").\n *\n * The per-method aliases exist for two reasons:\n * 1. **Documentation site / SDK type-export ergonomics** — callsite\n * code that imports `WorkerProtocolPromptResponse` reads naturally\n * next to `WorkerProtocolPromptRequest`. PR-WP-1b ships the\n * symmetric pair for all 4 endpoints.\n * 2. **Forward extension hook** — if a future Worker Protocol version\n * ever needs per-method response narrowing (e.g. `restore` returns\n * a checkpoint object, not just `accepted`), the alias is the\n * anchor where that narrowing would land WITHOUT widening\n * `DispatchOutcome` (which is the wire shape).\n *\n * R-WP-05 enforce-at-consumption form is preserved — every Response\n * type's `rejected` / `transport_failed` arms inherit the 6-arm\n * `WpFailureReasonRef` narrow from `DispatchOutcomeSchema`.\n */\nexport const WorkerProtocolPromptResponseSchema = DispatchOutcomeSchema;\nexport const WorkerProtocolFollowupResponseSchema = DispatchOutcomeSchema;\nexport const WorkerProtocolAbortResponseSchema = DispatchOutcomeSchema;\nexport const WorkerProtocolRestoreResponseSchema = DispatchOutcomeSchema;\n\nexport type WorkerProtocolPromptResponse = Readonly<\n z.infer<typeof WorkerProtocolPromptResponseSchema>\n>;\nexport type WorkerProtocolFollowupResponse = Readonly<\n z.infer<typeof WorkerProtocolFollowupResponseSchema>\n>;\nexport type WorkerProtocolAbortResponse = Readonly<\n z.infer<typeof WorkerProtocolAbortResponseSchema>\n>;\nexport type WorkerProtocolRestoreResponse = Readonly<\n z.infer<typeof WorkerProtocolRestoreResponseSchema>\n>;\n\n/**\n * WorkerProtocolProvider — 4-method narrow adapter boundary.\n *\n * Cohort-canonical Path 2 (mirrors `RuntimeProvider`'s narrow boundary):\n * no v1 `RunService.dispatch(runId)` legacy on the iface. The iface\n * speaks Session/RuntimeBinding identifiers + opaque prompt bytes only.\n *\n * D5 §17 outbox-only path:\n * - Implementations MUST NOT write `runs.*`.\n * - Implementations emit dispatch envelopes via an outbox row owned\n * by the caller (RunService). The iface returns the synchronous\n * `DispatchOutcome` arm; the actual event stream flows via the\n * v2 Session events surface (PR #408 `POST /api/sessions/:id/events`).\n *\n * R-WP-02 BLOCK enforce D7 (review-time gate):\n * - Callsite-wiring PRs MUST cite this iface verbatim.\n * - Widening the 4-method shape requires a separate PR with\n * dual-track convention + cohort review.\n */\nexport interface WorkerProtocolProvider {\n /** Initial prompt dispatch. Idempotent on `idempotencyKey` (R-WP-03). */\n prompt(request: WorkerProtocolPromptRequest): Promise<DispatchOutcome>;\n /** Follow-up turn dispatch. Idempotent on `idempotencyKey` (R-WP-03). */\n followup(request: WorkerProtocolFollowupRequest): Promise<DispatchOutcome>;\n /** Idempotent first-wins abort. */\n abort(request: WorkerProtocolAbortRequest): Promise<DispatchOutcome>;\n /** Restore Worker state from `replayCursor`. Idempotent. */\n restore(request: WorkerProtocolRestoreRequest): Promise<DispatchOutcome>;\n}\n","import { z } from \"zod\";\n\n/**\n * RuntimeProvider v2 frozen-contract surface.\n *\n * Cohort-canonical 4-method narrow adapter boundary. Ships NEW types only;\n * production wiring (callsite migration + KanyunRuntimeProvider rewrite +\n * dual-track gate) lives in a follow-up PR.\n *\n * R-IF-01..05 (shape-agnostic invariants):\n * 01 zero v1 primitives (no runId/agentId/projectId/createOrBind legacy)\n * 02 ProvisionRequest readonly DTO (TS Readonly<>)\n * 03 repoCoordinates optional (idle / non-repo runs)\n * 04 idempotencyKey REQUIRED (crash-safe re-provision)\n * 05 env Record<string,string> opaque pass-through (I-ENV-01..05)\n *\n * See `specs/features/pilot-v2-runtime-provider-contract.md` for the full\n * contract (invariants, test layers, lifecycle, and 21-enum lock).\n */\n\n/**\n * 21-enum FailureReasonRef LOCK.\n * 14 baseline + 1 traffic-split + 6 Worker Protocol Phase B-1..B-6.\n */\nexport type FailureReasonRef =\n | \"provision_timeout\"\n | \"kanyun_unavailable\"\n | \"kanyun_quota_exceeded\"\n | \"kanyun_invalid_template\"\n | \"kanyun_invalid_resource_profile\"\n | \"kanyun_unauthorized\"\n | \"image_pull_failure\"\n | \"snapshot_unavailable\"\n | \"git_clone_failure\"\n | \"internal_error\"\n | \"cancelled\"\n | \"preempted\"\n | \"stale\"\n | \"unknown\"\n | \"traffic_split_kill_switch\"\n | \"wp_protocol_violation\"\n | \"wp_handshake_timeout\"\n | \"wp_unsupported_version\"\n | \"wp_invalid_envelope\"\n | \"wp_stream_terminated\"\n | \"wp_replay_lost\";\n\nexport const FAILURE_REASON_KINDS: readonly FailureReasonRef[] = [\n \"provision_timeout\",\n \"kanyun_unavailable\",\n \"kanyun_quota_exceeded\",\n \"kanyun_invalid_template\",\n \"kanyun_invalid_resource_profile\",\n \"kanyun_unauthorized\",\n \"image_pull_failure\",\n \"snapshot_unavailable\",\n \"git_clone_failure\",\n \"internal_error\",\n \"cancelled\",\n \"preempted\",\n \"stale\",\n \"unknown\",\n \"traffic_split_kill_switch\",\n \"wp_protocol_violation\",\n \"wp_handshake_timeout\",\n \"wp_unsupported_version\",\n \"wp_invalid_envelope\",\n \"wp_stream_terminated\",\n \"wp_replay_lost\",\n] as const;\n\nexport const ResourceProfileSchema = z\n .object({\n cpu: z.string().min(1),\n memory: z.string().min(1),\n disk: z.string().min(1).optional(),\n gpu: z.string().min(1).optional(),\n })\n .strict();\nexport type ResourceProfile = z.infer<typeof ResourceProfileSchema>;\n\nexport const TraceContextSchema = z\n .object({\n traceId: z.string().min(1),\n spanId: z.string().min(1),\n parentSpanId: z.string().min(1).optional(),\n })\n .strict();\nexport type TraceContext = z.infer<typeof TraceContextSchema>;\n\nexport const TemplateKindSchema = z.enum([\"claude-code\", \"codex\", \"amp\"]);\nexport type TemplateKind = z.infer<typeof TemplateKindSchema>;\n\nexport const RepoCoordinatesSchema = z\n .object({\n repoUrl: z.string().min(1),\n targetRef: z.string().min(1),\n })\n .strict();\nexport type RepoCoordinates = z.infer<typeof RepoCoordinatesSchema>;\n\n/**\n * ProvisionRequest — opaque-env DTO. Readonly per R-IF-02.\n *\n * `env` uses `z.record(z.string(), z.string())` so the schema is JSON\n * round-trip safe (cassettes, queues, future wire boundaries). The pilot\n * platform treats env entries as an opaque pass-through key/value bag.\n */\nexport const ProvisionRequestSchema = z\n .object({\n idempotencyKey: z.string().min(1),\n template: TemplateKindSchema,\n resourceProfile: ResourceProfileSchema,\n repoCoordinates: RepoCoordinatesSchema.optional(),\n env: z.record(z.string(), z.string()),\n trace: TraceContextSchema,\n deadlineMs: z.number().int().positive(),\n })\n .strict();\nexport type ProvisionRequest = Readonly<z.infer<typeof ProvisionRequestSchema>>;\n\n/** ReadyState 4-arm: provisioning → ready | failed | cancelled. */\nexport type ReadyState =\n | { readonly kind: \"provisioning\"; readonly since: string }\n | { readonly kind: \"ready\"; readonly since: string }\n | {\n readonly kind: \"failed\";\n readonly reason: FailureReasonRef;\n readonly since: string;\n readonly message?: string;\n }\n | { readonly kind: \"cancelled\"; readonly since: string };\n\n/** HealthSnapshot 3-arm: post-ready liveness. */\nexport type HealthSnapshot =\n | { readonly kind: \"healthy\"; readonly observedAt: string }\n | { readonly kind: \"degraded\"; readonly observedAt: string; readonly hint: string }\n | {\n readonly kind: \"terminated\";\n readonly observedAt: string;\n readonly reason: FailureReasonRef;\n readonly message?: string;\n };\n\n/** Readonly opaque handle returned by provision(). */\nexport interface ProvisionHandle {\n readonly runtimeId: string;\n readonly idempotencyKey: string;\n readonly createdAt: string;\n}\n\n/** Cancel provenance: user / timeout / system. */\nexport type CancelReason =\n | { readonly kind: \"user\"; readonly userId?: string }\n | { readonly kind: \"timeout\" }\n | { readonly kind: \"system\"; readonly hint: string };\n\n/**\n * RuntimeProvider — 4-method narrow adapter boundary.\n *\n * Cohort-canonical Path 2: no `createOrBind` legacy. v1 callsite migration\n * happens in a follow-up PR; this surface is intentionally decoupled from\n * production wiring so the contract can be reviewed in isolation.\n */\nexport interface RuntimeProvider {\n /** Idempotent on `idempotencyKey` (R-IF-04). */\n provision(request: ProvisionRequest): Promise<ProvisionHandle>;\n /** Read-only ReadyState lookup. MUST NOT mutate provider state. */\n getReadyState(handle: ProvisionHandle): Promise<ReadyState>;\n /** Read-only post-ready health probe. */\n getHealth(handle: ProvisionHandle): Promise<HealthSnapshot>;\n /** Idempotent first-wins. Post-cancel: ReadyState=cancelled, Health=terminated. */\n cancel(handle: ProvisionHandle, reason: CancelReason): Promise<void>;\n}\n","import { z } from \"zod\";\nimport { AgentPortSpecSchema, IngressSpecSchema } from \"./pilot-v2-runtime-template\";\n\nexport const WorkloadKindSchema = z.enum([\n \"managed_agent\",\n \"batch_task\",\n \"external_worker\",\n \"self_managed\",\n]);\nexport type WorkloadKind = z.infer<typeof WorkloadKindSchema>;\n\nexport const SessionStatusSchema = z.enum([\n \"created\",\n \"provisioning\",\n \"starting\",\n \"ready\",\n \"failed\",\n]);\nexport type SessionStatus = z.infer<typeof SessionStatusSchema>;\n\nexport const SessionUsageKindSchema = z.enum([\"run_scoped\", \"conversation\", \"prewarmed\"]);\nexport type SessionUsageKind = z.infer<typeof SessionUsageKindSchema>;\n\nexport const StartupGateStatusSchema = z.enum([\"true\", \"false\", \"unknown\", \"stale\"]);\nexport type StartupGateStatus = z.infer<typeof StartupGateStatusSchema>;\n\nexport const FailureReasonSourceSchema = z.enum([\n \"control_plane\",\n \"scheduler\",\n \"runtime_provider\",\n \"pod_agent\",\n \"worker\",\n]);\nexport type FailureReasonSource = z.infer<typeof FailureReasonSourceSchema>;\n\nexport const FailureReasonCodeSchema = z.enum([\n \"TEMPLATE_NOT_FOUND\",\n \"POOL_NOT_READY\",\n \"SANDBOX_CREATE_FAILED\",\n \"SANDBOX_CREATE_TIMEOUT\",\n \"POD_AGENT_UNREACHABLE\",\n \"WORKER_START_FAILED\",\n \"WORKER_PROCESS_EXITED\",\n \"WORKER_HEALTH_FAILED\",\n \"WORKER_INTERNAL_ERROR\",\n \"WORKER_HEALTH_TIMEOUT\",\n \"GATE_REPORTED_FAILED\",\n \"GATE_READY_TIMEOUT\",\n \"PERMISSION_DENIED\",\n \"UNKNOWN_STARTUP_FAILURE\",\n]);\nexport type FailureReasonCode = z.infer<typeof FailureReasonCodeSchema>;\n\nexport const WorkerHealthStateSchema = z.enum([\"heartbeat\", \"ready\", \"failed\"]);\nexport type WorkerHealthState = z.infer<typeof WorkerHealthStateSchema>;\n\nexport const WorkerHealthReasonCodeSchema = z.enum([\n \"WORKER_BOOTING\",\n \"WORKER_READY\",\n \"WORKER_PROCESS_EXITED\",\n \"WORKER_HEALTH_CHECK_FAILED\",\n \"WORKER_INTERNAL_ERROR\",\n]);\nexport type WorkerHealthReasonCode = z.infer<typeof WorkerHealthReasonCodeSchema>;\n\nexport const WorkerEndpointSpecSchema = z.object({\n port: z.number().int().positive(),\n basePath: z.string().optional(),\n});\nexport type WorkerEndpointSpec = z.infer<typeof WorkerEndpointSpecSchema>;\n\nexport const WorkerHealthSpecSchema = z.object({\n transport: z.literal(\"control_plane_pull\"),\n path: z.literal(\"/pilot/worker/health\"),\n pollIntervalSeconds: z.number().int().positive(),\n requestTimeoutSeconds: z.number().int().positive(),\n staleAfterSeconds: z.number().int().positive(),\n startupTimeoutSeconds: z.number().int().positive(),\n});\nexport type WorkerHealthSpec = z.infer<typeof WorkerHealthSpecSchema>;\n\nexport const P0_WORKER_HEALTH_SPEC: WorkerHealthSpec = {\n transport: \"control_plane_pull\",\n path: \"/pilot/worker/health\",\n pollIntervalSeconds: 5,\n requestTimeoutSeconds: 3,\n staleAfterSeconds: 15,\n startupTimeoutSeconds: 60,\n};\n\nexport const ImageDigestSchema = z\n .string()\n .min(1)\n .regex(/^sha256:[0-9a-fA-F]{64}$/, \"Image digest must be a sha256 digest\");\nexport type ImageDigest = z.infer<typeof ImageDigestSchema>;\n\nexport const ImageProvenanceSchema = z.discriminatedUnion(\"kind\", [\n z\n .object({\n kind: z.literal(\"image_asset\"),\n imageAssetId: z.string().min(1),\n imageRef: z.string().min(1).optional(),\n imageDigest: ImageDigestSchema,\n sourceCommit: z.string().min(1).optional(),\n sourceRef: z.string().min(1).optional(),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict(),\n z\n .object({\n kind: z.literal(\"platform_image\"),\n platformImageId: z.string().min(1),\n version: z.string().min(1),\n imageRef: z.string().min(1).optional(),\n imageDigest: ImageDigestSchema,\n metadata: z.record(z.unknown()).optional(),\n })\n .strict(),\n z\n .object({\n kind: z.literal(\"legacy_external_template\"),\n providerTemplateName: z.string().min(1),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict(),\n]);\nexport type ImageProvenance = z.infer<typeof ImageProvenanceSchema>;\nexport type PublishableImageProvenance = Exclude<\n ImageProvenance,\n { kind: \"legacy_external_template\" }\n>;\n\nexport type ImageProvenanceBindingResult =\n | { ok: true; imageProvenance: PublishableImageProvenance }\n | {\n ok: false;\n error: string;\n detail: { reason: string; image?: string; imageDigest?: string; provenanceDigest?: string };\n };\n\nexport type PublishableImageProvenanceValidationResult =\n | { ok: true; imageProvenance: PublishableImageProvenance }\n | {\n ok: false;\n error: string;\n detail: {\n reason: string;\n imageRef?: string;\n imageDigest?: string;\n provenanceDigest?: string;\n };\n };\n\nexport function validatePublishableImageProvenance(\n imageProvenance: ImageProvenance,\n): PublishableImageProvenanceValidationResult {\n if (imageProvenance.kind === \"legacy_external_template\") {\n return {\n ok: false,\n error: \"legacy_external_template provenance cannot be used for new Revision publish\",\n detail: { reason: \"legacy_provenance_not_allowed\" },\n };\n }\n\n const provenanceDigest = imageProvenance.imageDigest.toLowerCase();\n if (imageProvenance.imageRef) {\n const imageDigest = extractPinnedImageDigest(imageProvenance.imageRef);\n if (!imageDigest) {\n return {\n ok: false,\n error: \"imageProvenance.imageRef must be digest-pinned with @sha256:<digest>\",\n detail: { reason: \"image_ref_not_digest_pinned\", imageRef: imageProvenance.imageRef },\n };\n }\n if (imageDigest !== provenanceDigest) {\n return {\n ok: false,\n error: \"imageProvenance.imageRef digest must match imageProvenance.imageDigest\",\n detail: {\n reason: \"image_digest_mismatch\",\n imageRef: imageProvenance.imageRef,\n imageDigest,\n provenanceDigest,\n },\n };\n }\n }\n\n return {\n ok: true,\n imageProvenance: {\n ...imageProvenance,\n imageDigest: provenanceDigest,\n },\n };\n}\n\nexport function bindImageProvenanceToImage(\n image: string,\n imageProvenance: ImageProvenance,\n): ImageProvenanceBindingResult {\n const publishable = validatePublishableImageProvenance(imageProvenance);\n if (!publishable.ok) {\n return {\n ok: false,\n error: publishable.error,\n detail: publishable.detail,\n };\n }\n\n const imageDigest = extractPinnedImageDigest(image);\n if (!imageDigest) {\n return {\n ok: false,\n error: \"image must be digest-pinned with @sha256:<digest> when imageProvenance is provided\",\n detail: { reason: \"image_not_digest_pinned\", image },\n };\n }\n\n const provenanceDigest = publishable.imageProvenance.imageDigest;\n if (imageDigest !== provenanceDigest) {\n return {\n ok: false,\n error: \"imageProvenance.imageDigest must match the digest in image\",\n detail: { reason: \"image_digest_mismatch\", imageDigest, provenanceDigest },\n };\n }\n\n if (publishable.imageProvenance.imageRef && publishable.imageProvenance.imageRef !== image) {\n return {\n ok: false,\n error: \"imageProvenance.imageRef must match the image applied to Kanyun\",\n detail: { reason: \"image_ref_mismatch\", image },\n };\n }\n\n return {\n ok: true,\n imageProvenance: {\n ...publishable.imageProvenance,\n imageRef: image,\n imageDigest: provenanceDigest,\n },\n };\n}\n\nexport function createImageAssetProvenance(\n imageRef: string,\n imageAssetId: string,\n sourceCommit?: string,\n): PublishableImageProvenance {\n const imageDigest = extractPinnedImageDigest(imageRef);\n if (!imageDigest) {\n throw new Error(\n \"imageRef must be digest-pinned with @sha256:<digest>; tag refs cannot be used for U-pin RuntimeTemplate.create\",\n );\n }\n return {\n kind: \"image_asset\",\n imageAssetId,\n imageRef,\n imageDigest,\n ...(sourceCommit ? { sourceCommit } : {}),\n };\n}\n\nexport function extractPinnedImageDigest(imageRef: string): ImageDigest | undefined {\n return imageRef.match(/@(sha256:[0-9a-fA-F]{64})$/)?.[1]?.toLowerCase();\n}\n\nexport const RuntimeTemplateSnapshotSchema = z.object({\n provider: z.literal(\"kanyun\"),\n providerTemplateName: z.string().min(1),\n providerPoolName: z.string().min(1).optional(),\n imageProvenance: ImageProvenanceSchema.optional(),\n defaultWorkerEndpoint: WorkerEndpointSpecSchema,\n healthSpec: WorkerHealthSpecSchema.default(P0_WORKER_HEALTH_SPEC),\n /**\n * PR-E0 / §6 Wave 1 — business worker listen port (`POD_AGENT_WORKER_PORT`).\n * Defaults to 8787 in the auto-create API; persisted into the snapshot so a\n * published Revision freezes the value even if the source `runtime_templates`\n * row is later mutated.\n */\n workerPort: z.number().int().min(1).max(65535).optional(),\n /**\n * Internal-only additional business container ports. Strict — does NOT\n * carry expose/hostPrefix/path; public exposure is declared via `ingresses[]`.\n */\n agentPorts: z.array(AgentPortSpecSchema).optional(),\n /**\n * Independent public ingress rules. Each entry's `backendPort` MUST reference\n * `workerPort` or one of `agentPorts[].port`; cross-field validation is the\n * caller's responsibility via `validateRuntimeTemplateNetwork()` from\n * `@pilot/contracts` after `.parse(snapshot)`.\n */\n ingresses: z.array(IngressSpecSchema).optional(),\n /**\n * Per-workload sandbox TTL (seconds) — lets each business define how long its\n * runtime sandbox lives before the provider reclaims it. Read by\n * `SessionStartupService` when provisioning; when omitted, the platform\n * `DEFAULT_TTL_SECONDS` applies (backward-compatible). A keep-alive service\n * extends the TTL while the session is active, so this primarily governs how\n * long an *idle* sandbox persists. Capped at 30 days to bound resource usage.\n */\n ttlSeconds: z\n .number()\n .int()\n .positive()\n .max(30 * 24 * 60 * 60)\n .optional(),\n /**\n * Selects which set of handlers the agent-worker process registers\n * (`coder` for the JSON-payload pilot-coder loop, `echo` for the bare-text\n * managed_agent Default UI demo). Read by control-plane at startWorker\n * dispatch, forwarded via `PodAgentStartWorkerRequest.agentFlavor`,\n * eventually injected by pod-agent as `PILOT_AGENT_FLAVOR` env var.\n * Undefined → agent-worker defaults to coder (existing behavior,\n * backward-compatible for all existing snapshots).\n *\n * Locked enum: extend ONLY after the corresponding `FLAVOR_REGISTRY`\n * entry exists in `apps/agent-worker/src/v2/init.ts` (otherwise the\n * worker falls back to coder + console.warn).\n */\n agentFlavor: z.enum([\"coder\", \"echo\"]).optional(),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type RuntimeTemplateSnapshot = z.infer<typeof RuntimeTemplateSnapshotSchema>;\n\nexport const WorkerContractRefSchema = z.object({\n kind: WorkloadKindSchema,\n name: z.string().optional(),\n version: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type WorkerContractRef = z.infer<typeof WorkerContractRefSchema>;\n\nexport const SESSION_CONFIG_VALUE_KEY_MAX_LENGTH = 100;\nexport const SESSION_EVENT_ID_MAX_LENGTH = 100;\nexport const SESSION_EVENT_TYPE_MAX_LENGTH = 100;\nexport const RESERVED_SESSION_CONFIG_ENV_PREFIXES = [\"PILOT_\", \"SESSION_\", \"PLATFORM_\"] as const;\n\nexport function isReservedSessionConfigEnvKey(key: string): boolean {\n return RESERVED_SESSION_CONFIG_ENV_PREFIXES.some((prefix) => key.startsWith(prefix));\n}\n\nexport const SessionConfigValuesSchema = z.record(z.string()).superRefine((values, ctx) => {\n for (const key of Object.keys(values)) {\n if (key.length > SESSION_CONFIG_VALUE_KEY_MAX_LENGTH) {\n ctx.addIssue({\n code: z.ZodIssueCode.too_big,\n maximum: SESSION_CONFIG_VALUE_KEY_MAX_LENGTH,\n type: \"string\",\n inclusive: true,\n message: `Config value key must be at most ${SESSION_CONFIG_VALUE_KEY_MAX_LENGTH} characters`,\n path: [key],\n });\n }\n if (isReservedSessionConfigEnvKey(key)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Config value key ${key} uses a reserved Pilot platform prefix`,\n path: [key],\n });\n }\n }\n});\nexport type SessionConfigValues = z.infer<typeof SessionConfigValuesSchema>;\n\nexport const SessionEventSchema = z.object({\n id: z.string().uuid(),\n sessionId: z.string().uuid(),\n eventId: z.string().min(1).max(SESSION_EVENT_ID_MAX_LENGTH),\n eventType: z.string().min(1).max(SESSION_EVENT_TYPE_MAX_LENGTH),\n payload: z.unknown().optional(),\n createdAt: z.string(),\n});\nexport type SessionEvent = z.infer<typeof SessionEventSchema>;\n\nexport const SessionEventAppendRequestSchema = z.object({\n eventId: z.string().min(1).max(SESSION_EVENT_ID_MAX_LENGTH).optional(),\n eventType: z.string().min(1).max(SESSION_EVENT_TYPE_MAX_LENGTH),\n payload: z.unknown().optional(),\n});\nexport type SessionEventAppendRequest = z.infer<typeof SessionEventAppendRequestSchema>;\n\nexport const SessionTokenClaimsSchema = z.object({\n type: z.literal(\"pilot-session\"),\n jti: z.string().uuid(),\n session_id: z.string().uuid(),\n workload_id: z.string().uuid(),\n revision_id: z.string().uuid(),\n tenant_id: z.string().uuid(),\n iat: z.number().int().nonnegative(),\n exp: z.number().int().positive().optional(),\n});\nexport type SessionTokenClaims = z.infer<typeof SessionTokenClaimsSchema>;\n\nexport const WorkloadIdentityClaimSchema = z.object({\n type: z.literal(\"pilot-workload-identity\"),\n workload_id: z.string().uuid(),\n revision_id: z.string().uuid(),\n tenant_id: z.string().uuid(),\n});\nexport type WorkloadIdentityClaim = z.infer<typeof WorkloadIdentityClaimSchema>;\n\nexport const StartupGatePolicySchema = z.object({\n required: z.array(z.string().min(1)).min(1),\n optional: z.array(z.string().min(1)).optional(),\n});\nexport type StartupGatePolicy = z.infer<typeof StartupGatePolicySchema>;\n\nexport const P0_STARTUP_GATE_POLICY: StartupGatePolicy = {\n required: [\"worker\"],\n};\n\n/**\n * Startup gate policy for self_managed sessions with ingresses and a known\n * `workerPort`. Adds the built-in `ingress` gate: the session won't flip to\n * \"ready\" until the **API ingress** (workerPort-matched endpoint) is externally\n * reachable — not just worker-internal health. This closes the \"fake ready\"\n * gap where session-ready fires before ingress propagation completes (~2-5s).\n *\n * NOTE: Only auto-injected when `snapshot.workerPort` is defined, signaling a\n * self_managed workload whose API endpoint serves `/api/health`.\n */\nexport const P0_INGRESS_STARTUP_GATE_POLICY: StartupGatePolicy = {\n required: [\"worker\", \"ingress\"],\n};\n\nexport const StartupGateConditionSchema = z.object({\n gate: z.string().min(1),\n status: StartupGateStatusSchema,\n reasonCode: z.string().optional(),\n message: z.string().optional(),\n observedAt: z.string(),\n lastTransitionAt: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type StartupGateCondition = z.infer<typeof StartupGateConditionSchema>;\n\nexport const FailureReasonSchema = z.object({\n code: FailureReasonCodeSchema,\n source: FailureReasonSourceSchema,\n message: z.string(),\n observedAt: z.string(),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type FailureReason = z.infer<typeof FailureReasonSchema>;\n\nexport const FailureReasonCandidateSchema = z.object({\n code: z.string().min(1),\n message: z.string(),\n observedAt: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type FailureReasonCandidate = z.infer<typeof FailureReasonCandidateSchema>;\n\nexport const WorkerReportedConditionSchema = z.object({\n gate: z.string().min(1),\n status: StartupGateStatusSchema,\n reasonCode: z.string().optional(),\n message: z.string().optional(),\n observedAt: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n});\nexport type WorkerReportedCondition = z.infer<typeof WorkerReportedConditionSchema>;\n\nexport const WorkerHealthObservationSchema = z.object({\n state: WorkerHealthStateSchema,\n reasonCode: WorkerHealthReasonCodeSchema.optional(),\n message: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n conditions: z.array(WorkerReportedConditionSchema).optional(),\n});\nexport type WorkerHealthObservation = z.infer<typeof WorkerHealthObservationSchema>;\n\nexport const PodAgentHealthResponseSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"worker_health\"),\n observedAt: z.string(),\n worker: WorkerHealthObservationSchema,\n }),\n z.object({\n kind: z.literal(\"worker_start_failed\"),\n observedAt: z.string(),\n failureCandidate: FailureReasonCandidateSchema,\n }),\n]);\nexport type PodAgentHealthResponse = z.infer<typeof PodAgentHealthResponseSchema>;\n\nexport const PodAgentStartWorkerRequestSchema = z.object({\n sessionId: z.string().uuid(),\n workloadId: z.string().uuid(),\n revisionId: z.string().uuid(),\n runtimeBindingId: z.string().uuid(),\n workerContract: WorkerContractRefSchema,\n healthSpec: WorkerHealthSpecSchema,\n env: z.record(z.string()).optional(),\n metadata: z.record(z.unknown()).optional(),\n /**\n * Pod-Agent-only auth factor for upcoming Pilot v2 internal credentials API\n * (`POST /api/internal/credentials/*`). The token is generated by control-plane\n * at session creation time, stored on the session row, and delivered to\n * pod-agent **once** via this start request. Pod-agent MUST hold it in memory\n * only and MUST NOT forward it to the supervised worker process (neither via\n * env, file, nor IPC). See `specs/features/pilot-v2-pod-agent-oci-runtime-layer.md`\n * § \"podAgentToken (Pod-Agent Auth Factor)\" for the full contract.\n *\n * Backward-compat: optional in P3 Pre-P1 — pre-existing callers (legacy\n * control-worker, `--smoke` check) may omit it; pod-agent then operates in\n * `legacy` mode (no `podAgentToken` held, any future internal-credentials\n * API calls SHALL reject). P3 Phase 1 L1.4 will tighten control-plane to\n * always send this field; the schema may be promoted to required in a\n * separate spec PR after the v1 retirement window closes.\n */\n podAgentToken: z.string().min(32).optional(),\n /**\n * Optional agent-worker handler flavor selector. Pod-agent forwards this\n * verbatim into the spawned child as `PILOT_AGENT_FLAVOR` env var (see\n * `apps/pod-agent/src/process-manager.ts → buildWorkerEnv`). Undefined →\n * pod-agent omits the env var, agent-worker `resolveFlavor()` falls back\n * to coder. Source of truth lives in\n * `RuntimeTemplateSnapshot.agentFlavor`; control-plane is responsible\n * for projecting that into this field at `startWorker` call time.\n */\n agentFlavor: z.enum([\"coder\", \"echo\"]).optional(),\n /**\n * Optional agent-worker bundle tarball URL (v2 hot-deploy). When set,\n * pod-agent downloads + extracts this tarball over the baked\n * `/opt/pilot/agent-worker` dist BEFORE spawning the worker, so the\n * running binary matches the latest `apps/agent-worker` build rather\n * than whatever was baked into the Kanyun pod image. Mirrors the v1\n * `OrchestrationService.deployAgentWorker` mechanism (which has no v2\n * equivalent — see\n * `docs/handoff/2026-06-10-echo-runtime-coordinator-actions.md` §2).\n *\n * The URL is resolved by control-worker (`PodAgentHttpClient`) from\n * `AGENT_WORKER_BUNDLE_OSS_KEY` (presigned) / `AGENT_WORKER_BUNDLE_URL`\n * env — the same env contract v1 already uses. control-plane stays\n * OSS-agnostic and does NOT populate this field.\n *\n * Backward-compat: optional. Omitted → pod-agent skips hot-deploy and\n * runs the baked dist (legacy behavior). Old pod-agents that predate\n * this field ignore it (zod strip), also falling back to baked dist.\n */\n agentWorkerBundleUrl: z.string().url().optional(),\n});\nexport type PodAgentStartWorkerRequest = z.infer<typeof PodAgentStartWorkerRequestSchema>;\n\nexport const PodAgentStartWorkerResponseSchema = z.discriminatedUnion(\"kind\", [\n z.object({\n kind: z.literal(\"accepted\"),\n observedAt: z.string(),\n metadata: z.record(z.unknown()).optional(),\n }),\n z.object({\n kind: z.literal(\"worker_start_failed\"),\n observedAt: z.string(),\n failureCandidate: FailureReasonCandidateSchema,\n }),\n]);\nexport type PodAgentStartWorkerResponse = z.infer<typeof PodAgentStartWorkerResponseSchema>;\n\nexport const CreateSessionRequestSchema = z\n .object({\n /**\n * P4 Phase 1.5 — optional caller-supplied resource id. When present, the\n * control-plane uses this UUID as the new Session row's primary key\n * (caller-controlled pin); when omitted, the control-plane generates a\n * `randomUUID()` (legacy / backward-compat behavior).\n *\n * Naming note: the field is intentionally named `sessionId` (not `id`) to\n * align with `CreateSessionResponseSchema.sessionId`. Despite the same\n * name on request and response, the semantics differ:\n * - request.sessionId = caller-supplied PK pin (write-side)\n * - response.sessionId = the actual Session row id (read-side, equal to\n * the request pin when supplied, or to the control-plane-generated\n * UUID when omitted)\n *\n * Use case: portal `POST /api/agents` dispatches v2 runs via\n * `dispatchV2AgentSession` and needs `runId === sessionId ===\n * runtimeBindingId` per `pilot-v2-managed-agent-handler-contract.md`\n * § \"Managed-agent runtime binding cohort\". Caller pins this field to\n * the freshly created run id so the entire cohort shares one UUID.\n */\n sessionId: z.string().uuid().optional(),\n projectId: z.string().uuid(),\n workloadId: z.string().uuid(),\n revisionId: z.string().uuid().optional(),\n idempotencyScope: z.string().min(1).optional(),\n idempotencyKey: z.string().min(1).optional(),\n configValues: SessionConfigValuesSchema.optional(),\n metadata: z.record(z.unknown()).optional(),\n /**\n * GAP1-B (rush-app v2 migration) — optional caller-supplied stable runtime\n * claim name. Forwarded to the runtime provider's `create()` as the sandbox\n * `claimName`, which the sandbox control plane embeds in the public ingress\n * host (`<hostPrefix>-<claimName>.<baseDomain>`). Supplying a stable,\n * project-scoped value keeps preview URLs stable across abort→recreate\n * (scale-to-zero) cycles; omitted → control plane generates a per-sandbox\n * `claim-<nanoTS>` (host drifts on every recreate).\n *\n * MUST be DNS-label safe (lowercase alphanumeric + hyphen); the sandbox\n * control plane truncates the `<hostPrefix>-<claimName>` first label to 63\n * chars, so the distinguishing portion must fit within budget. Callers\n * (e.g. rush-app) typically derive it from a project-scoped key such as\n * `rush-<normalizedProjectId>`.\n */\n runtimeClaimName: z\n .string()\n .min(1)\n .max(48)\n // DNS-label safe: lowercase alphanumeric + internal hyphens, no leading/\n // trailing hyphen. Validated at the contract boundary so invalid shapes\n // (uppercase, underscores, spaces, e.g. \"Rush_App\") are rejected here\n // rather than producing an invalid ingress host / failing sandbox create.\n .regex(\n /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/,\n \"runtimeClaimName must be DNS-label safe (lowercase alphanumeric and hyphens, no leading/trailing hyphen)\",\n )\n .optional(),\n /**\n * PR-1 / §INV-2.1 — optional list of vault `public_id` values to bind to\n * this Session. The control plane resolves each `vlt_*` public_id to the\n * internal uuid, inserts `session_vault_bindings` rows, and freezes an\n * `allowedMcpTargets` snapshot from the active credentials' MCP URLs.\n *\n * Constraints (PR1-E):\n * - Each entry MUST match `^vlt_[a-z0-9]+$` (lowercase alphanumeric).\n * - Maximum 64 entries per request.\n * - Duplicates are rejected at the Zod layer (→ 400).\n * Requires `vaults:read` (or `vaults:admin`) scope (PR1-B → 403 if absent).\n */\n vault_ids: z\n .array(z.string().regex(/^vlt_[a-z0-9]+$/, \"vault_id must match vlt_[a-z0-9]+\"))\n .max(64, \"vault_ids must have at most 64 entries\")\n .optional(),\n })\n .strict()\n .refine(\n (data) => {\n if (!data.vault_ids) return true;\n return new Set(data.vault_ids).size === data.vault_ids.length;\n },\n {\n message: \"vault_ids must not contain duplicates\",\n path: [\"vault_ids\"],\n },\n );\nexport type CreateSessionRequest = z.infer<typeof CreateSessionRequestSchema>;\n\nexport const CreateSessionResponseSchema = z.object({\n sessionId: z.string().uuid(),\n status: SessionStatusSchema,\n /**\n * PR-1 / §INV-2.1 — MCP target URLs frozen at Session creation time.\n * Present only when the request supplied `vault_ids`; absent otherwise.\n * Each entry is a URL string (no internal uuids exposed — INV-1.1).\n */\n allowed_mcp_targets: z.array(z.string().url()).optional(),\n});\nexport type CreateSessionResponse = z.infer<typeof CreateSessionResponseSchema>;\n\nexport function aggregateStartupGates(\n policy: StartupGatePolicy,\n conditions: StartupGateCondition[],\n): \"ready\" | \"failed\" | \"pending\" {\n const byGate = new Map(conditions.map((condition) => [condition.gate, condition]));\n\n for (const gate of policy.required) {\n const condition = byGate.get(gate);\n if (condition?.status === \"false\") return \"failed\";\n }\n\n for (const gate of policy.required) {\n const condition = byGate.get(gate);\n if (!condition || condition.status === \"unknown\" || condition.status === \"stale\") {\n return \"pending\";\n }\n }\n\n return \"ready\";\n}\n","import { z } from \"zod\";\n\nexport const POD_AGENT_ENDPOINT_PORT = 8790;\n\nexport const AgentPortSpecSchema = z\n .object({\n name: z.string().min(1).max(63),\n port: z.number().int().min(1).max(65535),\n protocol: z.literal(\"TCP\"),\n })\n .strict();\n\nexport type AgentPortSpec = z.infer<typeof AgentPortSpecSchema>;\n\nexport const IngressPathTypeSchema = z.enum([\"prefix\", \"exact\"]);\nexport type IngressPathType = z.infer<typeof IngressPathTypeSchema>;\n\nexport const IngressSpecSchema = z\n .object({\n name: z.string().min(1).max(63),\n backendPort: z\n .number()\n .int()\n .min(1)\n .max(65535)\n .refine((p) => p !== POD_AGENT_ENDPOINT_PORT, {\n message: `backendPort ${POD_AGENT_ENDPOINT_PORT} is reserved for the platform pod-agent endpoint and MUST NOT be exposed via ingress.`,\n }),\n hostPrefix: z.string().min(1).max(63),\n path: z.string().min(1).startsWith(\"/\"),\n pathType: IngressPathTypeSchema,\n })\n .strict();\n\nexport type IngressSpec = z.infer<typeof IngressSpecSchema>;\n\nexport interface RuntimeTemplateNetworkInput {\n workerPort?: number;\n agentPorts?: AgentPortSpec[];\n ingresses?: IngressSpec[];\n}\n\nexport type RuntimeTemplateNetworkValidationError =\n | {\n code: \"duplicate_agent_port_name\";\n name: string;\n }\n | {\n code: \"duplicate_agent_port_value\";\n port: number;\n protocol: \"TCP\";\n }\n | {\n code: \"agent_port_reserved\";\n name: string;\n port: number;\n }\n | {\n code: \"worker_port_reserved\";\n port: number;\n }\n | {\n code: \"duplicate_ingress_name\";\n name: string;\n }\n | {\n code: \"duplicate_ingress_route\";\n hostPrefix: string;\n path: string;\n }\n | {\n code: \"ingress_backend_port_unreferenced\";\n ingressName: string;\n backendPort: number;\n };\n\nexport function validateRuntimeTemplateNetwork(\n input: RuntimeTemplateNetworkInput,\n): RuntimeTemplateNetworkValidationError | null {\n const { workerPort, agentPorts = [], ingresses = [] } = input;\n\n if (workerPort === POD_AGENT_ENDPOINT_PORT) {\n return { code: \"worker_port_reserved\", port: workerPort };\n }\n\n const agentPortNames = new Set<string>();\n const agentPortCombos = new Set<string>();\n for (const ap of agentPorts) {\n if (ap.port === POD_AGENT_ENDPOINT_PORT) {\n return { code: \"agent_port_reserved\", name: ap.name, port: ap.port };\n }\n if (agentPortNames.has(ap.name)) {\n return { code: \"duplicate_agent_port_name\", name: ap.name };\n }\n agentPortNames.add(ap.name);\n const combo = `${ap.port}/${ap.protocol}`;\n if (agentPortCombos.has(combo)) {\n return {\n code: \"duplicate_agent_port_value\",\n port: ap.port,\n protocol: ap.protocol,\n };\n }\n agentPortCombos.add(combo);\n }\n\n const referencablePorts = new Set<number>();\n if (workerPort !== undefined) referencablePorts.add(workerPort);\n for (const ap of agentPorts) referencablePorts.add(ap.port);\n\n const ingressNames = new Set<string>();\n const ingressRoutes = new Set<string>();\n for (const ing of ingresses) {\n if (ingressNames.has(ing.name)) {\n return { code: \"duplicate_ingress_name\", name: ing.name };\n }\n ingressNames.add(ing.name);\n const route = `${ing.hostPrefix}|${ing.path}`;\n if (ingressRoutes.has(route)) {\n return {\n code: \"duplicate_ingress_route\",\n hostPrefix: ing.hostPrefix,\n path: ing.path,\n };\n }\n ingressRoutes.add(route);\n if (!referencablePorts.has(ing.backendPort)) {\n return {\n code: \"ingress_backend_port_unreferenced\",\n ingressName: ing.name,\n backendPort: ing.backendPort,\n };\n }\n }\n\n return null;\n}\n\n/**\n * Public endpoint exposed back to business callers via\n * `GET /api/sessions/:id` as `agentPublicEndpoints[]`.\n *\n * **URL semantics — declaration-derived (best-effort)**: `url` is computed\n * from the declared `runtimeTemplateSnapshot.ingresses[]` and the platform\n * `KANYUN_INGRESS_BASE_DOMAIN` configuration. Sandbox-side endpoint\n * reachability verification is platform-internal (Wave 3 / P1 follow-up);\n * clients SHOULD treat the `url` as platform best-effort and validate\n * reachability through standard HTTP error handling.\n *\n * `pathType` is the Pilot business-facing lowercase value\n * (`\"prefix\"` / `\"exact\"`), matching `IngressSpec.pathType`. The Kanyun SDK\n * uppercase shape never leaks into this response.\n */\nexport const AgentPublicEndpointSchema = z\n .object({\n /** Stable name; matches the originating `IngressSpec.name`. */\n name: z.string().min(1).max(63),\n /** TCP port the ingress targets; equals `IngressSpec.backendPort`. */\n backendPort: z.number().int().min(1).max(65535),\n /**\n * Declaration-derived public URL (`https://{hostPrefix}.{baseDomain}{path}`).\n * Best-effort — clients MUST validate reachability via standard HTTP\n * error handling; sandbox-side reconciliation is platform-internal.\n */\n url: z.string().url(),\n /** Path prefix or exact match; must start with `/`. */\n path: z.string().min(1).startsWith(\"/\"),\n /** Business-facing pathType (lowercase). */\n pathType: IngressPathTypeSchema,\n })\n .strict();\n\nexport type AgentPublicEndpoint = z.infer<typeof AgentPublicEndpointSchema>;\n\n/**\n * Pure mapping from `ingresses[]` + a configured ingress base domain to the\n * `agentPublicEndpoints[]` field exposed in Session response.\n *\n * Per #604 §6 line 445 PR-B: derive from `snapshot.ingresses[]` rather than\n * reading sandbox v2 `publicEndpoints[]`, so the read path is independent of\n * the Kanyun SDK round-trip.\n *\n * Behaviour:\n * - `ingresses` undefined / empty → returns `[]` (legacy session\n * forward-compatibility).\n * - `baseDomain` empty / undefined / whitespace-only → returns `[]`.\n * Returning placeholder URLs is intentionally avoided — exposing\n * unreachable URLs would mislead business callers.\n * - `baseDomain` containing only dots (e.g. `\".\"`, `\"..\"`) also\n * normalises to empty and returns `[]`.\n * - Otherwise each ingress entry produces:\n * url = `https://{hostPrefix}.{baseDomain}{path}`\n * where `baseDomain` is trimmed and any leading / trailing `.` is stripped.\n *\n * Multiple ingresses pointing to the same `backendPort` (fan-out) each\n * produce a distinct entry — they only differ on `hostPrefix` / `name`.\n *\n * Callers SHOULD log a structured warn when this returns `[]` while\n * `ingresses` was non-empty (see `SessionStartupService` for the platform\n * implementation).\n */\nexport function mapIngressesToPublicEndpoints(input: {\n ingresses?: IngressSpec[];\n baseDomain?: string;\n}): AgentPublicEndpoint[] {\n const ingresses = input.ingresses ?? [];\n if (ingresses.length === 0) return [];\n\n const trimmed = input.baseDomain?.trim() ?? \"\";\n if (trimmed.length === 0) return [];\n\n const baseDomain = trimmed.replace(/^\\.+/, \"\").replace(/\\.+$/, \"\");\n if (baseDomain.length === 0) return [];\n\n return ingresses.map((ing) => ({\n name: ing.name,\n backendPort: ing.backendPort,\n url: `https://${ing.hostPrefix}.${baseDomain}${ing.path}`,\n path: ing.path,\n pathType: ing.pathType,\n }));\n}\n","/**\n * Pilot v2 Vault skeleton — contracts (PR-B of #441 implementation phase).\n *\n * Authoritative source: `specs/features/pilot-v2-vault-skeleton.md`\n * commit `eea8389` § 1.1 / § 1.2 / § 9.1 / INV-5.\n *\n * PR-B is contracts-only: VaultClient interface + Zod schemas +\n * RESERVED_HEADERS const + isReservedHeader helper. Implementation\n * (PR-D), encryption envelope (PR-C), REST endpoints (PR-E), refresh\n * worker (PR-F), and e2e (PR-G) ship subsequently.\n *\n * Field naming convention (per spec § 1.2): wire schemas default to\n * camelCase. `external_user_id` is the deliberate snake_case exception\n * — it aligns with the DB column name (`external_user_id varchar(200)`)\n * and the Claude Vault model `external_id` field semantics, so business\n * SDK consumers see the same identifier across yaml manifest, REST API,\n * and DB column.\n *\n * Schema unknown-key policy (per spec § 1.2 + § 9.1): all caller-facing\n * request schemas use `.strict()` so unknown keys raise\n * `ZodIssueCode.unrecognized_keys` rather than silently strip. Route\n * handlers (PR-E) map specific forbidden keys (`actorId` /\n * `mcpServerUrl` / `tokenEndpoint` / `clientId` / `auth.type`) to the\n * stable error codes documented in spec § 9.1; unknown keys not in the\n * forbidden mapping fall through to generic `validation_error` (400).\n *\n * INV summary (severed from spec for grep convenience; spec wins on\n * conflict):\n * - INV-1: workspace + actorId (Platform Token actor, server-derive)\n * + external_user_id (business-opaque) tri-layer ownership.\n * - INV-1.1: double-id — internal uuid PK + `vlt_*` / `vcrd_*`\n * public_id; API surface only exposes public_id.\n * - INV-2: at most one active credential per (vault, MCP server URL);\n * 409 conflict on duplicate; multi-vault first-vault-wins by\n * binding_order.\n * - INV-3: platform-managed lifecycle (synchronous + asynchronous\n * refresh, archive cascade, mcpServerUrl/tokenEndpoint/clientId\n * immutable after create).\n * - INV-4: MCP server runs its own OAuth flow; Vault stores\n * already-issued tokens — Vault MUST NOT include\n * authorize/consent/pkce_challenge endpoints.\n * - INV-5: customHeaders carries business-supplied wire headers in\n * `{ name: literal_value }` form; reserved-header filter (11 fixed\n * headers + `x-pilot-*` prefix) + 32 entries cap + key/value length\n * caps.\n */\nimport { z } from \"zod\";\n\n/**\n * INV-5 reserved headers — Pilot platform owns the wire shape for\n * these, so business `customHeaders` MUST NOT shadow them.\n *\n * Lookups MUST go through `isReservedHeader(name)`; the set holds\n * lowercase canonical names only. The `x-pilot-*` family is checked\n * separately via `startsWith` so future Pilot-internal header\n * extensions stay reserved without per-name maintenance.\n */\nexport const RESERVED_HEADERS: ReadonlySet<string> = new Set([\n \"authorization\",\n \"host\",\n \"content-length\",\n \"content-encoding\",\n \"transfer-encoding\",\n \"connection\",\n \"upgrade\",\n \"cookie\",\n \"set-cookie\",\n \"server\",\n \"date\",\n]);\n\n/**\n * Returns `true` when `name` matches one of the 11 fixed reserved\n * header names (case-insensitive) or starts with the `x-pilot-`\n * prefix. Used by `CustomHeadersSchema.refine` and by the route\n * handlers (PR-E) that need a single source of truth for the\n * reserved-header policy (per INV-5 + spec § 1.2 sub-rule 3 — avoid\n * annotation vs schema drift).\n */\nexport function isReservedHeader(name: string): boolean {\n const lower = name.toLowerCase();\n return RESERVED_HEADERS.has(lower) || lower.startsWith(\"x-pilot-\");\n}\n\n/**\n * Stable error code returned when the caller has access to multiple\n * workspaces but did not supply a `workspaceId` (per spec § 9, #531).\n * Exported so route handlers import the literal from contracts and the\n * string never drifts between the vault-actor resolver and the wire.\n */\nexport const VAULT_WORKSPACE_REQUIRED_CODE = \"vault_workspace_required\" as const;\nexport type VaultWorkspaceRequiredCode = typeof VAULT_WORKSPACE_REQUIRED_CODE;\n\n/**\n * Authentication type discriminator. Immutable after credential\n * creation; mutation in `UpdateCredentialRequestSchema` is rejected at\n * the route handler with `vault_credential_immutable_field_mutation`\n * (per spec § 9.1).\n */\nexport const VaultCredentialAuthTypeSchema = z.enum([\"mcp_oauth\", \"static_bearer\"]);\nexport type VaultCredentialAuthType = z.infer<typeof VaultCredentialAuthTypeSchema>;\n\n/**\n * `last_refresh_status` enumeration carried on `VaultCredentialRecord`.\n * `success` — last refresh wrote a new access_token successfully.\n * `failed_invalid` — refresh token rejected by upstream (likely\n * unrecoverable; business SHOULD re-authorize).\n * `failed_unknown` — refresh failed for other reasons (transient\n * network, upstream 5xx); refresh worker MAY retry.\n */\nexport const VaultCredentialRefreshStatusSchema = z.enum([\n \"success\",\n \"failed_invalid\",\n \"failed_unknown\",\n]);\nexport type VaultCredentialRefreshStatus = z.infer<typeof VaultCredentialRefreshStatusSchema>;\n\n/**\n * INV-5 customHeaders — business-supplied wire headers. Three\n * invariants enforced here at the contracts layer:\n *\n * 1. Reserved-header filter (11 fixed headers + `x-pilot-*` prefix)\n * via `isReservedHeader` to avoid annotation/schema drift.\n * 2. Entry cap (32) to bound DoS / payload growth.\n * 3. Key length ≤ 100 chars, value length ≤ 2048 chars.\n *\n * Failures map to spec § 9 stable error codes:\n * - reserved header → `vault_credential_reserved_header_conflict` (400)\n * - too many entries → `vault_credential_custom_headers_too_many_entries`\n * (400, generic `validation_error` channel)\n */\nexport const CustomHeadersSchema = z\n .record(z.string().min(1).max(100), z.string().min(0).max(2048))\n .refine((m) => Object.keys(m).length <= 32, {\n message: \"vault_credential_custom_headers_too_many_entries\",\n })\n .refine((m) => Object.keys(m).every((k) => !isReservedHeader(k)), {\n message: \"vault_credential_reserved_header_conflict\",\n });\nexport type CustomHeaders = z.infer<typeof CustomHeadersSchema>;\n\n/**\n * `mcp_oauth` credential — full OAuth client credential including\n * access_token + refresh metadata. Used by `CreateCredentialRequest`\n * `auth` discriminator.\n *\n * `refresh` is REQUIRED for the `mcp_oauth` variant per INV-3 + INV-4\n * (Vault stores already-issued access_token + refresh_token + refresh\n * metadata; the platform-managed refresh worker in PR-F depends on\n * `refreshToken` / `tokenEndpoint` / `clientId` being present). Static\n * bearer credentials live in their own discriminator arm\n * (`StaticBearerCredentialSchema`), so this variant does not need an\n * `optional` refresh — that was the codex catch on PR-B round 2.\n *\n * Each variant of the inner `tokenEndpointAuth` discriminated union\n * carries its own `.strict()` because top-level `.strict()` does not\n * cascade into discriminated-union variants (per spec § 1.2 sub-rule\n * 3.1 cascade lock).\n */\nexport const McpOAuthCredentialSchema = z\n .object({\n type: z.literal(\"mcp_oauth\"),\n mcpServerUrl: z.string().url(),\n /**\n * Initial access token; write-only after create — never returned\n * by `VaultCredentialRecord` (per INV-3 / Claude write-only\n * invariant).\n */\n accessToken: z.string().min(1),\n expiresAt: z.string().datetime(),\n customHeaders: CustomHeadersSchema.optional(),\n refresh: z\n .object({\n tokenEndpoint: z.string().url(),\n clientId: z.string().min(1),\n scope: z.string().optional(),\n /** Write-only; never returned. */\n refreshToken: z.string().min(1),\n tokenEndpointAuth: z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"none\") }).strict(),\n z\n .object({\n type: z.literal(\"client_secret_basic\"),\n clientSecret: z.string().min(1),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"client_secret_post\"),\n clientSecret: z.string().min(1),\n })\n .strict(),\n ]),\n })\n .strict(),\n })\n .strict();\nexport type McpOAuthCredential = z.infer<typeof McpOAuthCredentialSchema>;\n\n/**\n * `static_bearer` credential — single fixed bearer token, no refresh\n * metadata. The Pilot Gateway injects the token verbatim into the\n * upstream MCP request `Authorization` header.\n */\nexport const StaticBearerCredentialSchema = z\n .object({\n type: z.literal(\"static_bearer\"),\n mcpServerUrl: z.string().url(),\n accessToken: z.string().min(1),\n customHeaders: CustomHeadersSchema.optional(),\n })\n .strict();\nexport type StaticBearerCredential = z.infer<typeof StaticBearerCredentialSchema>;\n\n/**\n * `CreateVaultRequest` — caller side of `VaultClient.createVault`.\n *\n * `actorId` is intentionally absent — it is server-derived from the\n * Platform Token actor identity (Pilot side, IdP-agnostic per spec\n * round 6 `a140189` INV-1 framing block; not a terminal user, not\n * equivalent to `external_user_id`). Callers passing it explicitly\n * trip the `.strict()` rejection and the route handler maps the\n * unknown key to `vault_actor_id_forbidden` (per spec § 9.1).\n *\n * `external_user_id` is required — INV-1 mandates that the business\n * supply the terminal-user identifier opaquely; Pilot does not derive\n * or interpret it. The snake_case naming is deliberate (see\n * file-level comment).\n */\nexport const CreateVaultRequestSchema = z\n .object({\n workspaceId: z.string().uuid(),\n displayName: z.string().min(1).max(200),\n external_user_id: z.string().min(1).max(200),\n metadata: z.record(z.unknown()).optional(),\n })\n .strict();\nexport type CreateVaultRequest = z.infer<typeof CreateVaultRequestSchema>;\n\n/**\n * `VaultRecord` — API response shape for vault rows. Only public_id\n * (`vlt_*`) is exposed; the internal uuid PK stays out of the wire\n * shape (INV-1.1).\n *\n * `.strict()` makes the response schema a guard, not just a\n * projection — accidentally including the internal uuid (or any\n * other extra field) is caught at parse time rather than silently\n * stripped.\n */\nexport const VaultRecordSchema = z\n .object({\n type: z.literal(\"vault\"),\n /** INV-1.1 public_id, `vlt_*` prefix. */\n id: z.string().regex(/^vlt_[a-zA-Z0-9]+$/),\n workspaceId: z.string().uuid(),\n /**\n * INV-1 second ownership layer — Pilot Platform Token actor /\n * credential owner principal id (IdP-agnostic per spec round 6).\n * Set server-side at create time from the Platform Token actor\n * identity; immutable. NOT a terminal user; NOT equivalent to\n * `external_user_id`.\n */\n actorId: z.string().min(1),\n /** INV-1 third ownership layer — opaque business-side identifier. */\n external_user_id: z.string().min(1),\n displayName: z.string().min(1),\n metadata: z.record(z.unknown()).optional(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n archivedAt: z.string().datetime().nullable(),\n })\n .strict();\nexport type VaultRecord = z.infer<typeof VaultRecordSchema>;\n\n/**\n * `ListVaultsFilter` — optional filter for `VaultClient.listVaults`.\n *\n * `workspaceId` and `actorId` filtering happens server-side at the\n * RBAC layer (per spec § 10.2); this filter only narrows within the\n * caller's permitted scope.\n */\nexport const ListVaultsFilterSchema = z\n .object({\n /**\n * Business-opaque cohort filter. Pilot does not interpret the\n * value — it is matched verbatim against the stored\n * `external_user_id` column.\n */\n external_user_id: z.string().min(1).optional(),\n /** When true, archived rows are included; default `false`. */\n includeArchived: z.boolean().optional(),\n })\n .strict();\nexport type ListVaultsFilter = z.infer<typeof ListVaultsFilterSchema>;\n\n/**\n * `CreateCredentialRequest` — caller side of\n * `VaultClient.createCredential`. The `auth` discriminated union\n * branches by `type` to either `McpOAuthCredentialSchema` or\n * `StaticBearerCredentialSchema`, both of which carry their own\n * `.strict()` (per spec § 1.2 cascade lock).\n */\nexport const CreateCredentialRequestSchema = z\n .object({\n displayName: z.string().min(1).max(200),\n auth: z.discriminatedUnion(\"type\", [McpOAuthCredentialSchema, StaticBearerCredentialSchema]),\n })\n .strict();\nexport type CreateCredentialRequest = z.infer<typeof CreateCredentialRequestSchema>;\n\n/**\n * `UpdateCredentialRequest` — only mutable fields (per INV-3).\n *\n * Top-level `.strict()` rejects unknown keys (e.g. `mcpServerUrl` at\n * the top level); the inner `auth.strict()` rejects mutations to\n * immutable fields (`mcpServerUrl` / `tokenEndpoint` / `clientId` /\n * `type`). Route handlers map those specific keys to\n * `vault_credential_immutable_field_mutation` (per spec § 9.1).\n *\n * `auth.type` is deliberately omitted from the inner schema so that\n * any caller-supplied `type` (even a same-literal `\"mcp_oauth\"`) is\n * caught by the inner `.strict()` as `unrecognized_keys`. A\n * `z.literal(\"mcp_oauth\")` field would silently accept the\n * same-literal mutation and bypass the immutable-field error code —\n * that was the codex catch on PR-B round 2.\n *\n * `customHeaders` is mutable but follows whole-replace semantics (not\n * deep merge) per spec § 7.3.\n */\nexport const UpdateCredentialRequestSchema = z\n .object({\n displayName: z.string().min(1).max(200).optional(),\n customHeaders: CustomHeadersSchema.optional(),\n auth: z\n .object({\n accessToken: z.string().min(1).optional(),\n expiresAt: z.string().datetime().optional(),\n refresh: z\n .object({\n refreshToken: z.string().min(1).optional(),\n })\n .strict()\n .optional(),\n })\n .strict()\n .optional(),\n })\n .strict();\nexport type UpdateCredentialRequest = z.infer<typeof UpdateCredentialRequestSchema>;\n\n/**\n * `VaultCredentialRecord` — API response shape for credential rows.\n * Secret fields (`accessToken` / `refreshToken` / `clientSecret`) are\n * deliberately absent (INV-3 write-only invariant).\n *\n * `.strict()` enforces INV-3 at the schema layer rather than relying\n * on annotation only — if the implementation accidentally includes a\n * secret in the response, the parse fails (and contract tests catch\n * it) rather than silently stripping the leak.\n */\nexport const VaultCredentialRecordSchema = z\n .object({\n type: z.literal(\"vault_credential\"),\n /** INV-1.1 public_id, `vcrd_*` prefix. */\n id: z.string().regex(/^vcrd_[a-zA-Z0-9]+$/),\n /** INV-1.1 public_id reference to parent vault. */\n vaultId: z.string().regex(/^vlt_[a-zA-Z0-9]+$/),\n displayName: z.string().min(1),\n authType: VaultCredentialAuthTypeSchema,\n mcpServerUrl: z.string().url(),\n expiresAt: z.string().datetime().nullable(),\n lastRefreshedAt: z.string().datetime().nullable(),\n lastRefreshStatus: VaultCredentialRefreshStatusSchema.nullable(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n archivedAt: z.string().datetime().nullable(),\n })\n .strict();\nexport type VaultCredentialRecord = z.infer<typeof VaultCredentialRecordSchema>;\n\n/**\n * `ListCredentialsFilter` — optional filter for\n * `VaultClient.listCredentials`.\n */\nexport const ListCredentialsFilterSchema = z\n .object({\n /** Filter by upstream MCP server URL. */\n mcpServerUrl: z.string().url().optional(),\n includeArchived: z.boolean().optional(),\n })\n .strict();\nexport type ListCredentialsFilter = z.infer<typeof ListCredentialsFilterSchema>;\n\n/**\n * `ResolvedCredential` — returned by\n * `VaultClient.resolveCredentialForMcpUrl` (per session) for the\n * Pilot Gateway (#518) to inject into the outbound MCP request.\n *\n * `accessToken` here is the freshly-refreshed plaintext token; this\n * shape is intentionally NOT exposed to Pod Agent / Worker — only the\n * Gateway process holds it.\n *\n * `customHeaders` reuses `CustomHeadersSchema` so the resolver-side\n * shape carries the same INV-5 invariants as Create / Update\n * (reserved-header rejection, 32-entry cap, key/value length caps).\n * The resolver MUST normalize to `{}` rather than `undefined` so the\n * Gateway injection path does not need a null-check (per spec § 1.2\n * INV-5 normalization rule).\n *\n * `.strict()` keeps the response a guard — accidental extra fields\n * (e.g. internal uuid leak) fail at parse time.\n */\nexport const ResolvedCredentialSchema = z\n .object({\n vaultId: z.string().regex(/^vlt_[a-zA-Z0-9]+$/),\n credentialId: z.string().regex(/^vcrd_[a-zA-Z0-9]+$/),\n authType: VaultCredentialAuthTypeSchema,\n accessToken: z.string().min(1),\n expiresAt: z.string().datetime().nullable(),\n customHeaders: CustomHeadersSchema,\n })\n .strict();\nexport type ResolvedCredential = z.infer<typeof ResolvedCredentialSchema>;\n\n/**\n * `VaultCredentialValidation` — three-state diagnostic for the\n * `validateMcpOAuth` operation (forks Claude `/mcp_oauth_validate`):\n * - `valid` — the credential was successfully exchanged for a fresh\n * access token.\n * - `invalid` — refresh exchange returned a definitive error\n * (likely revoked / unauthorized; business SHOULD re-authorize).\n * - `unknown` — refresh exchange failed for other reasons\n * (transient network, upstream 5xx); diagnostic is inconclusive.\n */\nexport const VaultCredentialValidationSchema = z\n .object({\n status: z.enum([\"valid\", \"invalid\", \"unknown\"]),\n message: z.string().optional(),\n validatedAt: z.string().datetime(),\n })\n .strict();\nexport type VaultCredentialValidation = z.infer<typeof VaultCredentialValidationSchema>;\n\n/**\n * `VaultClient` — internal Pilot interface for vault CRUD + per-MCP\n * credential resolution. Lives in `packages/control-plane`; exposed\n * via the REST endpoints in PR-E.\n *\n * MUST NOT be a business-facing API — businesses interact via the\n * REST surface. The interface stays in `@pilot/contracts` so test\n * doubles (FakeVaultClient in PR-D) can be typed against the same\n * shape.\n */\nexport interface VaultClient {\n // --- Vault lifecycle ----------------------------------------------------\n\n /** Create a new vault. Returns the persisted `VaultRecord`. */\n createVault(request: CreateVaultRequest): Promise<VaultRecord>;\n\n /** Resolve a vault by public id; returns `null` on miss (no throw). */\n getVault(vaultId: string): Promise<VaultRecord | null>;\n\n /** List vaults visible to the caller per spec § 10.2 RBAC. */\n listVaults(filter?: ListVaultsFilter): Promise<VaultRecord[]>;\n\n /**\n * Archive a vault. Cascades to all `vault_credentials` (per INV-3);\n * running sessions are NOT interrupted, but the next credential\n * re-resolve fails authentication.\n */\n archiveVault(vaultId: string): Promise<void>;\n\n // --- Credential lifecycle ----------------------------------------------\n\n createCredential(\n vaultId: string,\n request: CreateCredentialRequest,\n ): Promise<VaultCredentialRecord>;\n\n getCredential(vaultId: string, credentialId: string): Promise<VaultCredentialRecord | null>;\n\n listCredentials(\n vaultId: string,\n filter?: ListCredentialsFilter,\n ): Promise<VaultCredentialRecord[]>;\n\n /**\n * Mutate the mutable fields of an existing credential (per INV-3).\n * Mutation of `mcpServerUrl` / `tokenEndpoint` / `clientId` /\n * `auth.type` is rejected by the schema and mapped to\n * `vault_credential_immutable_field_mutation` at the route layer.\n */\n updateCredential(\n vaultId: string,\n credentialId: string,\n request: UpdateCredentialRequest,\n ): Promise<VaultCredentialRecord>;\n\n archiveCredential(vaultId: string, credentialId: string): Promise<void>;\n\n // --- Per-session credential resolution ---------------------------------\n\n /**\n * Resolves the active credential for a given MCP server URL within a\n * session's bound vaults (first-vault-wins by `binding_order`, per\n * INV-2). Returns `null` when no vault binds the URL or all\n * candidates are archived.\n *\n * Signature pinned to `(sessionId, mcpServerUrl)` per spec § 1.1 to\n * align with the Pilot Gateway (#518) wire shape — the Gateway does\n * NOT pass `vault_ids` through; the resolver looks them up from\n * `pilot_v2_session_vault_bindings`.\n */\n resolveCredentialForMcpUrl(\n sessionId: string,\n mcpServerUrl: string,\n ): Promise<ResolvedCredential | null>;\n\n // --- OAuth refresh diagnostic ------------------------------------------\n\n /**\n * Triggers a one-shot OAuth refresh validation against the\n * configured `tokenEndpoint`; returns the three-state diagnostic\n * without mutating the credential row.\n */\n validateMcpOAuth(vaultId: string, credentialId: string): Promise<VaultCredentialValidation>;\n}\n","/**\n * Pilot v2 User Schedules — wire contracts.\n *\n * Authoritative behavioral spec:\n * `specs/features/pilot-v2-user-schedules.md`\n * (promoted from the draft at\n * `docs/proposals/pilot-v2-user-schedules-spec-draft.md` on 2026-05-27).\n *\n * P1.2 evolution sourced from:\n * `docs/proposals/pilot-v2-user-schedules-evolution-inline-and-projectless.md`\n *\n * Scope of this file:\n * - stable enums (target kind, version preference, lifecycle status,\n * trigger source, trigger status, skipped reason, failure code);\n * - core view objects (`ScheduleDefinition`, `ScheduleTrigger`,\n * `ScheduleView`);\n * - request / response shapes for the REST endpoints in spec\n * §API Surface;\n * - SDK-facing error code enum (`ScheduleApiErrorCode`).\n *\n * Out of scope (handled in Phase 2 service layer):\n * - cron-parser-driven `firedAt` computation (kept out of contracts to\n * avoid taking a runtime dependency in this universal package);\n * - DB CHECK enforcement (lives in migration SQL);\n * - concurrency / misfire / auto-disable runtime semantics;\n * - workload-slug → workloadId/revisionId resolution for `inline_v2`\n * (lives in `WorkloadResolver`, called by the dispatcher in P1.3).\n *\n * Cross-field invariants enforced here (mirror DB CHECKs as a\n * defense-in-depth client-side floor):\n * - INV-5 (extended in P1.2): `(targetKind, pilotApiVersionPreference)`\n * ∈ `{(workload, v2), (agent, v1), (inline_v1, v1), (inline_v2, v2)}`.\n * Other combos → zod fail.\n * - target-kind shape consistency:\n * - `workload` ⇒ `targetWorkloadId` present, agent fields absent.\n * - `agent` ⇒ `targetAgentId` present, workload fields absent.\n * - `inline_v1` / `inline_v2` ⇒ all three target-FK fields absent.\n * - `targetRevisionId` only meaningful for `targetKind=workload`.\n * - Project-or-owner anchor: at least one of `projectId` / `ownerLdap`\n * must be present. Inline kinds may have `projectId=null`; workload\n * and agent kinds keep `projectId` mandatory.\n * - `endAt > startAt` when both are set.\n */\nimport { z } from \"zod\";\nimport { EnabledMcpEntryListSchema } from \"./mcp\";\nimport { AttachmentMetaSchema, ProviderTypeSchema } from \"./run\";\nimport { EnabledSkillEntryListSchema } from \"./skill\";\n\n// --- Enums ------------------------------------------------------------------\n\n/**\n * P1.2: extended from `{workload, agent}` to also include `inline_v1`\n * and `inline_v2`. Inline kinds carry a self-contained dispatch spec in\n * the schedule's `payload` and create brand-new Run / Session per fire.\n */\nexport const ScheduleTargetKindSchema = z.enum([\"workload\", \"agent\", \"inline_v1\", \"inline_v2\"]);\nexport type ScheduleTargetKind = z.infer<typeof ScheduleTargetKindSchema>;\n\n/**\n * Lifecycle-routing preference. Static at create time per INV-5 — the\n * route is chosen once and never re-decided per-trigger. Distinct from\n * `X_PILOT_API_VERSION` (wire protocol header), which is unrelated.\n */\nexport const ScheduleApiVersionPreferenceSchema = z.enum([\"v1\", \"v2\"]);\nexport type ScheduleApiVersionPreference = z.infer<typeof ScheduleApiVersionPreferenceSchema>;\n\n/**\n * INV-2 — disjoint from `runs.status` / `sessions.status`. Adding a\n * fourth value here is a major-version contract change.\n */\nexport const ScheduleLifecycleStatusSchema = z.enum([\"active\", \"disabled\", \"deleted\"]);\nexport type ScheduleLifecycleStatus = z.infer<typeof ScheduleLifecycleStatusSchema>;\n\nexport const ScheduleConcurrencyPolicySchema = z.enum([\"allow\", \"forbid\"]);\nexport type ScheduleConcurrencyPolicy = z.infer<typeof ScheduleConcurrencyPolicySchema>;\n\nexport const ScheduleMisfirePolicySchema = z.enum([\"skip\", \"fire_once_immediately\"]);\nexport type ScheduleMisfirePolicy = z.infer<typeof ScheduleMisfirePolicySchema>;\n\nexport const ScheduleTriggerSourceSchema = z.enum([\"cron\", \"manual\"]);\nexport type ScheduleTriggerSource = z.infer<typeof ScheduleTriggerSourceSchema>;\n\nexport const ScheduleTriggerStatusSchema = z.enum([\n \"pending\",\n \"dispatched\",\n \"skipped\",\n \"failed_to_dispatch\",\n]);\nexport type ScheduleTriggerStatus = z.infer<typeof ScheduleTriggerStatusSchema>;\n\nexport const ScheduleSkippedReasonSchema = z.enum([\n \"misfire\",\n \"concurrency_forbidden\",\n \"schedule_disabled\",\n \"out_of_window\",\n]);\nexport type ScheduleSkippedReason = z.infer<typeof ScheduleSkippedReasonSchema>;\n\n/**\n * Spec §\"Failure Codes 矩阵\". Stable enum — new values may be added\n * (additive minor bump per `api-version.ts` SemVer policy), MUST NOT be\n * renamed or reused.\n */\nexport const ScheduleFailureReasonCodeSchema = z.enum([\n \"TARGET_NOT_FOUND\",\n \"TARGET_DISABLED\",\n \"REVISION_NOT_FOUND\",\n \"PERMISSION_DENIED\",\n \"UPSTREAM_UNAVAILABLE\",\n \"DOWNSTREAM_TIMEOUT\",\n \"ORPHANED_PENDING_TRIGGER\",\n \"UNKNOWN_DISPATCH_FAILURE\",\n]);\nexport type ScheduleFailureReasonCode = z.infer<typeof ScheduleFailureReasonCodeSchema>;\n\n/**\n * SDK-facing error code enum for `ScheduleApiErrorBody`. Only includes\n * codes the API layer can return on the create / update / run-now path\n * — distinct from `ScheduleFailureReasonCode` which is the *async*\n * dispatch failure enum stored on `schedule_triggers` rows.\n */\nexport const ScheduleApiErrorCodeSchema = z.enum([\n \"INVALID_CRON\",\n \"INVALID_TIMEZONE\",\n \"INVALID_TARGET\",\n \"UNSUPPORTED_VERSION_COMBO\",\n \"PROJECT_NOT_FOUND\",\n \"WORKLOAD_NOT_FOUND\",\n \"AGENT_NOT_FOUND\",\n \"REVISION_NOT_FOUND\",\n \"REVISION_NOT_FOR_TARGET_WORKLOAD\",\n \"TARGET_NOT_IN_PROJECT\",\n \"SCHEDULE_NOT_FOUND\",\n \"SCHEDULE_DISABLED\",\n \"CONCURRENCY_FORBIDDEN\",\n \"SCHEDULE_TRIGGER_CONFLICT\",\n \"FORBIDDEN_FIELD\",\n \"PERMISSION_DENIED\",\n // P1.2: inline_v2 schedule references a workload slug that cannot be\n // resolved to any (workloadId, revisionId). Distinct from\n // WORKLOAD_NOT_FOUND (which is keyed by ID) — slug resolution is\n // dispatcher-time and surfaces a different remediation path.\n \"WORKLOAD_SLUG_NOT_FOUND\",\n // P1.2: project-or-owner anchor missing — caller submitted neither\n // projectId nor ownerLdap (or ownerLdap was empty for an inline\n // kind). 400.\n \"MISSING_PROJECT_OR_OWNER\",\n // Server-side internal error (DB returned no row, dispatcher failed\n // synchronously, etc.). Surfaces as HTTP 500 / SDK ScheduleClientError\n // category=platform_error. Distinct from `PERMISSION_DENIED` which\n // signals \"the user is not authorized\" — internal errors are not the\n // caller's fault. Spec §\"API Error Codes\".\n \"INTERNAL_ERROR\",\n]);\nexport type ScheduleApiErrorCode = z.infer<typeof ScheduleApiErrorCodeSchema>;\n\n// --- Field-level helpers ----------------------------------------------------\n\n/** Length caps shared between API request schemas and the DB column. */\nexport const SCHEDULE_DISPLAY_NAME_MAX_LENGTH = 200;\nexport const SCHEDULE_DESCRIPTION_MAX_LENGTH = 1000;\nexport const SCHEDULE_CREATED_BY_MAX_LENGTH = 255;\nexport const SCHEDULE_FAILURE_REASON_MESSAGE_MAX_LENGTH = 2000;\n\n/** misfire grace window (spec §Data Model). */\nexport const SCHEDULE_MISFIRE_GRACE_SECONDS_MIN = 0;\nexport const SCHEDULE_MISFIRE_GRACE_SECONDS_MAX = 3600;\nexport const SCHEDULE_MISFIRE_GRACE_SECONDS_DEFAULT = 60;\n\n/** auto-disable threshold (spec §Auto-disable Policy). */\nexport const SCHEDULE_FAILURE_THRESHOLD_MIN = 1;\nexport const SCHEDULE_FAILURE_THRESHOLD_MAX = 100;\nexport const SCHEDULE_FAILURE_THRESHOLD_DEFAULT = 5;\n\n/**\n * IANA timezone validation via `Intl.DateTimeFormat`. Implementations\n * MUST throw on unknown identifiers (Node 22 + all evergreen browsers\n * comply). `Intl.supportedValuesOf(\"timeZone\")` is faster but Node 18-\n * lacks it, so we keep the constructor-throws approach for portability.\n */\nexport function isValidIanaTimezone(value: string): boolean {\n if (!value || value.length > 100) return false;\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: value });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Lightweight cron-expression structural validator (5 or 6 whitespace-\n * separated segments). Real semantic validation (range / step / `L|W|#`)\n * happens in the API layer via `cron-parser`; keeping the contracts\n * package zero-runtime-dep.\n */\nexport function isCronStructurallyValid(value: string): boolean {\n const trimmed = value.trim();\n if (!trimmed) return false;\n const segments = trimmed.split(/\\s+/);\n return segments.length === 5 || segments.length === 6;\n}\n\nconst TimezoneStringSchema = z\n .string()\n .min(1, \"timezone must be a non-empty IANA identifier\")\n .refine(isValidIanaTimezone, \"timezone must be a valid IANA identifier\");\n\nconst CronExpressionSchema = z\n .string()\n .min(1, \"cronExpression must be non-empty\")\n .max(200, \"cronExpression must be at most 200 characters\")\n .refine(isCronStructurallyValid, \"cronExpression must have 5 or 6 whitespace-separated segments\");\n\n/** ISO-8601 timestamp with timezone — matches DB `timestamp with time zone`. */\nconst IsoDatetimeSchema = z.string().datetime({ offset: true });\n\n// --- Dispatch payload -------------------------------------------------------\n\n/**\n * Per-schedule dispatch payload — the parameters Tick Worker forwards\n * to the upstream `RunService.createRun` (v1) / `SessionStartupService\n * .createSessionWithResult` (v2) call. Stored as opaque jsonb on\n * `schedule_definitions.payload_json` so payload schema can evolve\n * without DB migrations; validated at the API boundary.\n *\n * Length caps are intentionally tight (50 KB prompt, 64 char provider)\n * to keep `schedule_definitions` rows <100 KB — avoids `TOAST` on the\n * Tick Worker hot path.\n */\nexport const SCHEDULE_PAYLOAD_PROMPT_MAX_LENGTH = 50_000;\n\nexport const SchedulePayloadV1Schema = z\n .object({\n /** Required for v1 — `RunService.createRun` rejects empty prompts. */\n prompt: z.string().min(1).max(SCHEDULE_PAYLOAD_PROMPT_MAX_LENGTH),\n repo: z.string().max(2048).optional(),\n ref: z.string().max(255).optional(),\n model: z.string().max(255).optional(),\n /**\n * P1.6: tightened from `z.string().max(64).optional()` to\n * `ProviderTypeSchema.optional()`. Catches invalid provider strings\n * at schedule create / update time rather than letting the\n * dispatcher cast them through `RunSpec` and surface as a generic\n * Zod error on fire (P1.3 review [CONSIDER]).\n */\n provider: ProviderTypeSchema.optional(),\n /**\n * LDAP of the user whose action created this schedule. Forwarded\n * verbatim to `runs.triggerUserLdap` so per-user Bedrock credentials\n * (specs/features/user-bedrock-credentials.md) resolve correctly on\n * cron-triggered runs. Null / undefined falls back to the\n * service-level Bedrock key.\n */\n triggerUserLdap: z.string().min(1).max(255).optional(),\n })\n .strict();\nexport type SchedulePayloadV1 = z.infer<typeof SchedulePayloadV1Schema>;\n\nexport const SchedulePayloadV2Schema = z\n .object({\n /**\n * Sandbox-environment overrides forwarded to\n * `CreateSessionRequest.configValues`. Reserved-env-key sanitization\n * is enforced at the SessionStartupService boundary; the schema\n * here keeps the shape opaque to avoid duplicating that policy.\n */\n configValues: z.record(z.string(), z.string()).optional(),\n /** Free-form audit metadata; non-functional. */\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n .strict();\nexport type SchedulePayloadV2 = z.infer<typeof SchedulePayloadV2Schema>;\n\n// --- Inline payload (P1.2) --------------------------------------------------\n\n/**\n * Inline v1 payload — same wire shape as `SchedulePayloadV1`. The\n * dispatcher creates a fresh Agent per fire and sources the entire\n * RunSpec from this payload.\n *\n * `repo` / `ref` are **optional**: a schedule may target a Git repo\n * (repo-backed task) or omit it entirely (repo-less / \"general\" task,\n * mirroring the home composer where leaving the repo picker empty\n * creates a chat-mode Agent against a general project). When omitted,\n * the synthesised Agent is created with `baseRef = null` and the\n * RunSpec carries no `repo` / `ref`. The schedule's `projectId` (a\n * general project resolved at authoring time) anchors the new Agent.\n */\nexport const ScheduleInlineV1PayloadSchema = z\n .object({\n prompt: z.string().min(1).max(SCHEDULE_PAYLOAD_PROMPT_MAX_LENGTH),\n repo: z.string().min(1).max(2048).optional(),\n ref: z.string().min(1).max(255).optional(),\n model: z.string().max(255).optional(),\n /**\n * P1.6: see `SchedulePayloadV1Schema.provider` — same rationale.\n * Closes the unsafe `as RunSpec[\"provider\"]` cast in\n * `schedule-dispatcher.ts dispatchInlineV1` (P1.3 review [CONSIDER]).\n */\n provider: ProviderTypeSchema.optional(),\n triggerUserLdap: z.string().min(1).max(255).optional(),\n /**\n * Per-fire MCP / Skills enable lists — same wire shape the home\n * composer sends to `POST /api/agents` (run-level override, spec\n * §4.3 \"对话级别\"). The dispatcher forwards these onto the\n * synthesised `RunSpec` so each cron-created Run resolves the same\n * MCPs / skills the user would get by clicking \"新建任务\" with the\n * same toggles. Omitted ⇒ no customization (empty resolution).\n *\n * Stored verbatim in `payload_json`; refs are resolved against the\n * owner's global credential store at run start, so a schedule keeps\n * working as long as the owner keeps the referenced MCP/skill\n * installed.\n */\n enabledMcpServers: EnabledMcpEntryListSchema.optional(),\n enabledSkills: EnabledSkillEntryListSchema.optional(),\n /**\n * User-uploaded attachments — same wire shape the home composer\n * sends to `POST /api/agents` (`RunSpec.attachments`). Files are\n * uploaded once at schedule-authoring time to the owner's project\n * OSS space; the dispatcher forwards the stored `ossUrl` references\n * onto every synthesised `RunSpec`, so each cron-created Run sees\n * the same attachments. Capped at 5 to match `RunSpec.attachments`.\n */\n attachments: z.array(AttachmentMetaSchema).max(5).optional(),\n })\n .strict();\nexport type ScheduleInlineV1Payload = z.infer<typeof ScheduleInlineV1PayloadSchema>;\n\n/**\n * Globally-unique workload slug — same regex as\n * `pilot-v2-sessions.workloads.slug` (lowercase, dashes, alphanumerics).\n * Defense-in-depth: API and DB will both reject malformed slugs at\n * schedule-create time; the dispatcher only tries to resolve a\n * structurally valid slug.\n */\nexport const SCHEDULE_INLINE_V2_WORKLOAD_SLUG_REGEX = /^[a-z0-9][a-z0-9-]{0,127}$/;\n\n/**\n * Inline v2 payload — declarative reference to a workload by *slug*\n * plus an optional revision selector. The dispatcher resolves\n * `(workloadSlug, revisionSelector)` to `(workloadId, revisionId)`\n * at fire time so revisions published after the schedule was created\n * are picked up automatically when `revisionSelector === \"latest\"`.\n *\n * Why slug instead of ID:\n * - Workload IDs change on republish; slugs are stable.\n * - Lets users author a schedule that always targets the most\n * recently published revision of a known workload.\n *\n * `revisionSelector`:\n * - `\"latest\"` (default): resolve to the newest published revision\n * at fire time. New revisions auto-promote.\n * - `\"<uuid>\"`: pin to a specific revision; no auto-promotion.\n */\nexport const ScheduleInlineV2PayloadSchema = z\n .object({\n workloadSlug: z\n .string()\n .min(1)\n .max(128)\n .refine(\n (s) => SCHEDULE_INLINE_V2_WORKLOAD_SLUG_REGEX.test(s),\n \"workloadSlug must be lowercase alphanumeric / dashes (1..128 chars)\",\n ),\n /** Default `\"latest\"`; UUID strings are treated as revision pin. */\n revisionSelector: z.union([z.literal(\"latest\"), z.string().uuid()]).default(\"latest\"),\n configValues: z.record(z.string(), z.string()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n .strict();\nexport type ScheduleInlineV2Payload = z.infer<typeof ScheduleInlineV2PayloadSchema>;\n\n/**\n * Empty raw payload accepted only for v2 schedules whose workload's\n * `revision.runtimeTemplateSnapshot` already encodes everything the\n * session needs — equivalent to passing `{}` to `CreateSessionRequest`.\n * v1 / inline_v1 / inline_v2 schedules MUST NOT pass an empty payload.\n */\nconst RawPayloadSchema = z.record(z.string(), z.unknown());\n\n// --- Cross-field invariants -------------------------------------------------\n\ntype TargetFields = {\n targetKind: ScheduleTargetKind;\n targetWorkloadId?: string | null;\n targetRevisionId?: string | null;\n targetAgentId?: string | null;\n pilotApiVersionPreference: ScheduleApiVersionPreference;\n projectId?: string | null;\n ownerLdap?: string | null;\n};\n\n/**\n * INV-5 (extended) — admissible (targetKind, versionPref) tuples.\n * Mirrors the `schedule_definitions_target_version_combo_check` DB CHECK\n * (`0051_schedules_inline_and_projectless.sql`, extended by\n * `0057_schedules_inline_v1_v2_combo.sql`).\n *\n * `inline_v1` accepts BOTH `v1` and `v2`: the payload shape is identical\n * (ScheduleInlineV1PayloadSchema — a self-contained RunSpec), only the\n * dispatch lifecycle differs. `v2` routes each fire through the\n * \"new agent from prompt\" path (dispatchV2AgentSession: project.kind →\n * pre-seeded workload + prompt/attachments via session metadata); `v1`\n * keeps the legacy `run:execute` lifecycle. v2 is the default for new\n * schedules (v1 is being phased out).\n */\nconst ADMISSIBLE_TARGET_VERSION_COMBOS: ReadonlyArray<`${ScheduleTargetKind}:${ScheduleApiVersionPreference}`> =\n [\"workload:v2\", \"agent:v1\", \"inline_v1:v1\", \"inline_v1:v2\", \"inline_v2:v2\"];\n\n/**\n * Re-usable target / version cross-field validator. Used by the create\n * request and the full view schema (when a row is read back from DB).\n *\n * Enforces:\n * - shape consistency for each `targetKind` (which target-FK fields\n * must be present / absent);\n * - INV-5 (extended): `(targetKind, pilotApiVersionPreference)` must\n * be one of the 4 admissible combos;\n * - project-or-owner anchor: at least one of `projectId` / `ownerLdap`\n * is present;\n * - workload / agent kinds keep `projectId` non-null (project-less is\n * reserved for inline kinds in P1.2).\n */\nfunction refineTargetFields<T extends TargetFields>(\n schema: z.ZodType<T>,\n): z.ZodEffects<z.ZodType<T>, T, T> {\n return schema.superRefine((value, ctx) => {\n // 1. Shape consistency per targetKind.\n switch (value.targetKind) {\n case \"workload\": {\n if (!value.targetWorkloadId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"targetWorkloadId is required when targetKind is 'workload'\",\n path: [\"targetWorkloadId\"],\n });\n }\n if (value.targetAgentId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"targetAgentId must be omitted when targetKind is 'workload'\",\n path: [\"targetAgentId\"],\n });\n }\n break;\n }\n case \"agent\": {\n if (!value.targetAgentId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"targetAgentId is required when targetKind is 'agent'\",\n path: [\"targetAgentId\"],\n });\n }\n if (value.targetWorkloadId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"targetWorkloadId must be omitted when targetKind is 'agent'\",\n path: [\"targetWorkloadId\"],\n });\n }\n if (value.targetRevisionId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"targetRevisionId is only allowed when targetKind is 'workload'\",\n path: [\"targetRevisionId\"],\n });\n }\n break;\n }\n case \"inline_v1\":\n case \"inline_v2\": {\n if (value.targetWorkloadId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `targetWorkloadId must be omitted when targetKind is '${value.targetKind}'`,\n path: [\"targetWorkloadId\"],\n });\n }\n if (value.targetAgentId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `targetAgentId must be omitted when targetKind is '${value.targetKind}'`,\n path: [\"targetAgentId\"],\n });\n }\n if (value.targetRevisionId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `targetRevisionId must be omitted when targetKind is '${value.targetKind}' (use payload.revisionSelector for inline_v2)`,\n path: [\"targetRevisionId\"],\n });\n }\n break;\n }\n }\n\n // 2. INV-5 (extended) — only the 4 admissible combos.\n const combo = `${value.targetKind}:${value.pilotApiVersionPreference}` as const;\n if (!ADMISSIBLE_TARGET_VERSION_COMBOS.includes(combo)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Unsupported (targetKind, pilotApiVersionPreference) combination. Admissible: ${ADMISSIBLE_TARGET_VERSION_COMBOS.join(\n \", \",\n )}`,\n path: [\"pilotApiVersionPreference\"],\n });\n }\n\n // 3. workload / agent kinds keep projectId mandatory (P1.2 P0-compat).\n const isInline = value.targetKind === \"inline_v1\" || value.targetKind === \"inline_v2\";\n if (!isInline && !value.projectId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `projectId is required when targetKind is '${value.targetKind}'`,\n path: [\"projectId\"],\n });\n }\n\n // 4. Project-or-owner anchor: at least one of projectId / ownerLdap.\n const hasProject = Boolean(value.projectId);\n const hasOwner = Boolean(value.ownerLdap && value.ownerLdap.length > 0);\n if (!hasProject && !hasOwner) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"At least one of projectId / ownerLdap must be present (project-or-owner anchor)\",\n path: [\"ownerLdap\"],\n });\n }\n });\n}\n\n/** Validates `endAt > startAt` when both are present. */\nfunction refineLifecycleWindow<T extends { startAt?: string | null; endAt?: string | null }>(\n schema: z.ZodType<T>,\n): z.ZodEffects<z.ZodType<T>, T, T> {\n return schema.superRefine((value, ctx) => {\n if (value.startAt && value.endAt) {\n const start = Date.parse(value.startAt);\n const end = Date.parse(value.endAt);\n if (Number.isFinite(start) && Number.isFinite(end) && end <= start) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"endAt must be strictly later than startAt\",\n path: [\"endAt\"],\n });\n }\n }\n });\n}\n\n// --- Create request ---------------------------------------------------------\n\nconst CreateScheduleRequestBaseSchema = z\n .object({\n /**\n * Host project. Required for `targetKind ∈ {workload, agent}` (P0\n * shape); MAY be null for `inline_v1` / `inline_v2`. When null, the\n * `ownerLdap` field becomes the sole authorization anchor.\n */\n projectId: z.string().uuid().nullable().optional(),\n /**\n * LDAP of the schedule owner (P1.2). Distinct from the implicit\n * `createdBy` which is captured server-side from the auth context.\n * MUST be non-empty when `projectId` is null. The route handler is\n * authoritative for enforcing \"createdBy === ownerLdap\" on create\n * (delegation / ownership transfer is an explicit follow-up).\n */\n ownerLdap: z.string().min(1).max(255).optional(),\n displayName: z\n .string()\n .min(1, \"displayName must be non-empty\")\n .max(SCHEDULE_DISPLAY_NAME_MAX_LENGTH),\n description: z.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).optional(),\n cronExpression: CronExpressionSchema,\n timezone: TimezoneStringSchema,\n targetKind: ScheduleTargetKindSchema,\n targetWorkloadId: z.string().uuid().optional(),\n targetRevisionId: z.string().uuid().optional(),\n targetAgentId: z.string().uuid().optional(),\n pilotApiVersionPreference: ScheduleApiVersionPreferenceSchema,\n concurrencyPolicy: ScheduleConcurrencyPolicySchema.default(\"allow\"),\n misfirePolicy: ScheduleMisfirePolicySchema.default(\"skip\"),\n misfireGraceSeconds: z\n .number()\n .int()\n .min(SCHEDULE_MISFIRE_GRACE_SECONDS_MIN)\n .max(SCHEDULE_MISFIRE_GRACE_SECONDS_MAX)\n .default(SCHEDULE_MISFIRE_GRACE_SECONDS_DEFAULT),\n consecutiveFailureThreshold: z\n .number()\n .int()\n .min(SCHEDULE_FAILURE_THRESHOLD_MIN)\n .max(SCHEDULE_FAILURE_THRESHOLD_MAX)\n .default(SCHEDULE_FAILURE_THRESHOLD_DEFAULT),\n startAt: IsoDatetimeSchema.optional(),\n endAt: IsoDatetimeSchema.optional(),\n /**\n * Dispatch parameter payload. Shape is determined by\n * `pilotApiVersionPreference` and validated by `refinePayload` (see\n * below). Stored verbatim into `schedule_definitions.payload_json`.\n */\n payload: RawPayloadSchema,\n })\n .strict();\n\n/**\n * Branches `payload` validation on `targetKind`:\n * - `workload` → MUST match `SchedulePayloadV2Schema` (all fields\n * optional; `{}` is valid).\n * - `agent` → MUST match `SchedulePayloadV1Schema` (prompt required).\n * - `inline_v1` → MUST match `ScheduleInlineV1PayloadSchema` (prompt\n * required; repo / ref / model / mcp / skills / attachments optional —\n * a self-contained RunSpec mirroring the home composer).\n * - `inline_v2` → MUST match `ScheduleInlineV2PayloadSchema`\n * (workloadSlug required; revisionSelector defaults to \"latest\").\n *\n * Failures are re-pathed under `payload.*` so SDK error rendering can\n * point users at the offending sub-field.\n *\n * NOTE: payload schema is keyed off `targetKind`, NOT\n * `pilotApiVersionPreference`. INV-5 guarantees they are correlated, but\n * the dispatcher needs to look at the kind to pick the parsing strategy\n * (workload vs inline_v2 both have versionPref=v2 but different shapes).\n */\nfunction refinePayload<\n T extends {\n targetKind: ScheduleTargetKind;\n payload: Record<string, unknown>;\n },\n>(schema: z.ZodType<T>): z.ZodEffects<z.ZodType<T>, T, T> {\n return schema.superRefine((value, ctx) => {\n let payloadSchema: z.ZodTypeAny;\n switch (value.targetKind) {\n case \"workload\":\n payloadSchema = SchedulePayloadV2Schema;\n break;\n case \"agent\":\n payloadSchema = SchedulePayloadV1Schema;\n break;\n case \"inline_v1\":\n payloadSchema = ScheduleInlineV1PayloadSchema;\n break;\n case \"inline_v2\":\n payloadSchema = ScheduleInlineV2PayloadSchema;\n break;\n }\n const result = payloadSchema.safeParse(value.payload);\n if (!result.success) {\n for (const issue of result.error.issues) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: issue.message,\n path: [\"payload\", ...issue.path],\n });\n }\n }\n });\n}\n\nexport const CreateScheduleRequestSchema = refinePayload(\n refineLifecycleWindow(refineTargetFields(CreateScheduleRequestBaseSchema)),\n);\nexport type CreateScheduleRequest = z.input<typeof CreateScheduleRequestBaseSchema>;\nexport type ParsedCreateScheduleRequest = z.output<typeof CreateScheduleRequestSchema>;\n\n// --- Update (PATCH) request -------------------------------------------------\n\n/**\n * spec §API Surface — PATCH allows mutation of behavioral fields only.\n * Path-binding fields (`projectId / targetKind / targetWorkloadId /\n * targetAgentId / targetRevisionId / pilotApiVersionPreference`) MUST\n * NOT be patchable. We use `.strict()` so unknown / forbidden keys\n * surface as `unrecognized_keys` — route handlers translate the\n * forbidden-key set into `FORBIDDEN_FIELD` (400) for SDK readability.\n */\nconst UpdateScheduleRequestBaseSchema = z\n .object({\n displayName: z.string().min(1).max(SCHEDULE_DISPLAY_NAME_MAX_LENGTH).optional(),\n description: z.string().max(SCHEDULE_DESCRIPTION_MAX_LENGTH).nullable().optional(),\n /**\n * Convenience field — `true` ⇒ lifecycle_status='active',\n * `false` ⇒ lifecycle_status='disabled'. Cannot reach `deleted`\n * via PATCH (use DELETE).\n */\n enabled: z.boolean().optional(),\n cronExpression: CronExpressionSchema.optional(),\n timezone: TimezoneStringSchema.optional(),\n concurrencyPolicy: ScheduleConcurrencyPolicySchema.optional(),\n misfirePolicy: ScheduleMisfirePolicySchema.optional(),\n misfireGraceSeconds: z\n .number()\n .int()\n .min(SCHEDULE_MISFIRE_GRACE_SECONDS_MIN)\n .max(SCHEDULE_MISFIRE_GRACE_SECONDS_MAX)\n .optional(),\n consecutiveFailureThreshold: z\n .number()\n .int()\n .min(SCHEDULE_FAILURE_THRESHOLD_MIN)\n .max(SCHEDULE_FAILURE_THRESHOLD_MAX)\n .optional(),\n endAt: IsoDatetimeSchema.nullable().optional(),\n /**\n * Replaces the entire dispatch payload. Null is forbidden — to\n * \"clear\" optional sub-fields, send a payload object that omits\n * them. Payload shape (v1 vs v2) is fixed at create time per\n * INV-5; the route handler validates against the schedule's\n * stored `pilotApiVersionPreference` before persisting.\n */\n payload: RawPayloadSchema.optional(),\n })\n .strict();\n\nexport const UpdateScheduleRequestSchema = UpdateScheduleRequestBaseSchema.refine(\n (data) => Object.keys(data).length > 0,\n { message: \"PATCH body must contain at least one field\" },\n);\nexport type UpdateScheduleRequest = z.infer<typeof UpdateScheduleRequestSchema>;\n\n// --- Read shapes ------------------------------------------------------------\n\nconst ScheduleViewBaseSchema = z.object({\n id: z.string().uuid(),\n /**\n * Nullable since P1.2 — only inline kinds may have null projectId in\n * persisted form; workload / agent kinds keep it set (enforced at\n * create time and by DB shape CHECK).\n */\n projectId: z.string().uuid().nullable(),\n /**\n * Owner LDAP (P1.2). NOT NULL in DB; the read shape exposes it for\n * UI to render \"owned by\" labels and for permission checks on\n * project-less schedules.\n */\n ownerLdap: z.string(),\n displayName: z.string(),\n description: z.string().nullable(),\n cronExpression: z.string(),\n timezone: z.string(),\n targetKind: ScheduleTargetKindSchema,\n targetWorkloadId: z.string().uuid().nullable(),\n targetRevisionId: z.string().uuid().nullable(),\n targetAgentId: z.string().uuid().nullable(),\n pilotApiVersionPreference: ScheduleApiVersionPreferenceSchema,\n lifecycleStatus: ScheduleLifecycleStatusSchema,\n concurrencyPolicy: ScheduleConcurrencyPolicySchema,\n misfirePolicy: ScheduleMisfirePolicySchema,\n misfireGraceSeconds: z.number().int().nonnegative(),\n startAt: IsoDatetimeSchema.nullable(),\n endAt: IsoDatetimeSchema.nullable(),\n payload: RawPayloadSchema,\n consecutiveFailureCount: z.number().int().nonnegative(),\n consecutiveFailureThreshold: z.number().int().positive(),\n lastTriggerAt: IsoDatetimeSchema.nullable(),\n nextFireAt: IsoDatetimeSchema.nullable(),\n createdBy: z.string(),\n createdAt: IsoDatetimeSchema,\n updatedAt: IsoDatetimeSchema,\n deletedAt: IsoDatetimeSchema.nullable(),\n});\n\n/**\n * Full row view returned by `GET /api/schedules/:id`. Fields mirror\n * `schedule_definitions` columns 1:1; refinements re-apply the\n * cross-field invariants so a corrupt DB row would surface at the API\n * boundary rather than silently round-trip.\n */\nexport const ScheduleViewSchema = refineTargetFields(\n ScheduleViewBaseSchema as unknown as z.ZodType<\n z.input<typeof ScheduleViewBaseSchema> & TargetFields\n >,\n);\nexport type ScheduleView = z.infer<typeof ScheduleViewBaseSchema>;\n\n/** Compact form returned by `GET /api/schedules` list. */\nexport const ScheduleListItemSchema = ScheduleViewBaseSchema.pick({\n id: true,\n projectId: true,\n ownerLdap: true,\n displayName: true,\n cronExpression: true,\n timezone: true,\n targetKind: true,\n targetWorkloadId: true,\n targetAgentId: true,\n pilotApiVersionPreference: true,\n lifecycleStatus: true,\n lastTriggerAt: true,\n nextFireAt: true,\n createdAt: true,\n updatedAt: true,\n});\nexport type ScheduleListItem = z.infer<typeof ScheduleListItemSchema>;\n\nexport const ScheduleListResponseSchema = z.object({\n items: z.array(ScheduleListItemSchema),\n nextCursor: z.string().optional(),\n});\nexport type ScheduleListResponse = z.infer<typeof ScheduleListResponseSchema>;\n\n// --- Trigger view -----------------------------------------------------------\n\nexport const ScheduleTriggerViewSchema = z\n .object({\n id: z.string().uuid(),\n scheduleId: z.string().uuid(),\n firedAt: IsoDatetimeSchema,\n triggerSource: ScheduleTriggerSourceSchema,\n status: ScheduleTriggerStatusSchema,\n dispatchedAt: IsoDatetimeSchema.nullable(),\n dispatchedRunId: z.string().uuid().nullable(),\n dispatchedSessionId: z.string().uuid().nullable(),\n /**\n * Owning agent of the dispatched Run / Session, when one exists.\n * Resolved by joining `runs.agent_id` on the dispatched run/session id\n * (cohort invariant: `run.id === session.id`). Lets the UI deep-link\n * the trigger to `/agents/:agentId`. Null for pure-workload v2\n * dispatches (no agent) and for non-dispatched triggers.\n */\n dispatchedAgentId: z.string().uuid().nullable(),\n skippedReason: ScheduleSkippedReasonSchema.nullable(),\n failureReasonCode: ScheduleFailureReasonCodeSchema.nullable(),\n failureReasonMessage: z.string().max(SCHEDULE_FAILURE_REASON_MESSAGE_MAX_LENGTH).nullable(),\n idempotencyKey: z.string(),\n attemptCount: z.number().int().nonnegative(),\n blockingTriggerId: z.string().uuid().nullable(),\n createdAt: IsoDatetimeSchema,\n })\n .superRefine((trigger, ctx) => {\n // Mirror DB CHECK: dispatched ⇔ (dispatchedRunId XOR dispatchedSessionId).\n if (trigger.status === \"dispatched\") {\n if (!trigger.dispatchedAt) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"dispatchedAt is required when status is 'dispatched'\",\n path: [\"dispatchedAt\"],\n });\n }\n const hasRun = trigger.dispatchedRunId !== null;\n const hasSession = trigger.dispatchedSessionId !== null;\n if (hasRun === hasSession) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"Exactly one of dispatchedRunId / dispatchedSessionId must be set when status is 'dispatched'\",\n path: [\"dispatchedRunId\"],\n });\n }\n } else {\n if (trigger.dispatchedAt !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"dispatchedAt must be null when status is not 'dispatched'\",\n path: [\"dispatchedAt\"],\n });\n }\n }\n\n if (trigger.status === \"skipped\" && trigger.skippedReason === null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"skippedReason is required when status is 'skipped'\",\n path: [\"skippedReason\"],\n });\n }\n if (trigger.status !== \"skipped\" && trigger.skippedReason !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"skippedReason must be null when status is not 'skipped'\",\n path: [\"skippedReason\"],\n });\n }\n\n if (trigger.status === \"failed_to_dispatch\" && trigger.failureReasonCode === null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"failureReasonCode is required when status is 'failed_to_dispatch'\",\n path: [\"failureReasonCode\"],\n });\n }\n if (trigger.status !== \"failed_to_dispatch\" && trigger.failureReasonCode !== null) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"failureReasonCode must be null when status is not 'failed_to_dispatch'\",\n path: [\"failureReasonCode\"],\n });\n }\n\n if (\n trigger.blockingTriggerId !== null &&\n !(trigger.status === \"skipped\" && trigger.skippedReason === \"concurrency_forbidden\")\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"blockingTriggerId is only meaningful for skipped+concurrency_forbidden rows\",\n path: [\"blockingTriggerId\"],\n });\n }\n });\nexport type ScheduleTriggerView = z.infer<typeof ScheduleTriggerViewSchema>;\n\nexport const ScheduleTriggerListResponseSchema = z.object({\n items: z.array(ScheduleTriggerViewSchema),\n nextCursor: z.string().optional(),\n});\nexport type ScheduleTriggerListResponse = z.infer<typeof ScheduleTriggerListResponseSchema>;\n\n// --- POST /api/schedules/:id/run ------------------------------------------\n\nexport const RunScheduleResponseSchema = z\n .object({\n triggerId: z.string().uuid(),\n dispatchedRunId: z.string().uuid().optional(),\n dispatchedSessionId: z.string().uuid().optional(),\n })\n .superRefine((value, ctx) => {\n const hasRun = value.dispatchedRunId !== undefined;\n const hasSession = value.dispatchedSessionId !== undefined;\n if (hasRun === hasSession) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message:\n \"Exactly one of dispatchedRunId / dispatchedSessionId must be present in run-now response\",\n });\n }\n });\nexport type RunScheduleResponse = z.infer<typeof RunScheduleResponseSchema>;\n\n// --- Common error body ------------------------------------------------------\n\nexport const ScheduleApiErrorBodySchema = z.object({\n error: z.object({\n code: ScheduleApiErrorCodeSchema,\n message: z.string(),\n details: z.record(z.unknown()).optional(),\n }),\n});\nexport type ScheduleApiErrorBody = z.infer<typeof ScheduleApiErrorBodySchema>;\n\n// --- Idempotency key helper -------------------------------------------------\n\n/**\n * Spec §Idempotency Contract — wire-format key. Used by both cron-tick\n * and manual run-now paths; service layer passes this as\n * `idempotencyKey` to `SessionStartupService.createSessionWithResult`\n * (v2 path) or to the v1 cleanup-job orphan watcher.\n */\nexport function buildScheduleIdempotencyKey(scheduleId: string, firedAtIso: string): string {\n return `schedule:${scheduleId}:${firedAtIso}`;\n}\n","import { z } from \"zod\";\n\nimport { SessionConfigValuesSchema } from \"./pilot-v2-session\";\nimport {\n PILOT_WORKLOAD_MANIFEST_API_VERSION,\n PilotWorkloadManifestApiVersionSchema,\n type WorkloadManifest,\n WorkloadManifestDisplayNameSchema,\n WorkloadManifestModelSchema,\n WorkloadManifestNameSchema,\n WorkloadManifestObjectRefSchema,\n WorkloadManifestSystemPromptSchema,\n WorkloadManifestUiHintSchema,\n WorkloadManifestValidationError,\n} from \"./pilot-v2-workload-manifest\";\n\n/**\n * `ManagedAgentProfile` is the user-friendly authoring surface for the\n * v1-style managed_agent productization (proposal\n * `docs/proposals/pilot-v2-managed-agent-profile-schema.md`, Phase A).\n *\n * It is **not** a new WorkloadKind nor a new wire protocol — it is a\n * schema projection (`projectManagedAgentProfileToWorkloadManifest`)\n * onto the existing `WorkloadManifest` (`kind: \"Workload\"`,\n * `contract.kind: \"managed_agent\"`).\n *\n * Phase A exposed the **green-lit** fields that already had an\n * end-to-end consumer (§5 of the proposal):\n * - `metadata` → workload metadata\n * - `spec.runtimeTemplateRef` → `spec.defaults.runtimeTemplateRef`\n * - `spec.env` → `spec.defaults.configValues` (worker env passthrough)\n * - `spec.ui` → `spec.ui`\n *\n * Phase B adds:\n * - `spec.model` → `spec.defaults.model` (workload default model id),\n * injected at session creation into `sessions.metadata.model` when\n * the caller does not pin a model.\n *\n * Phase C adds:\n * - `spec.skills` (friendly rush skill name list) → projected to\n * `spec.defaults.enabledSkills` as `EnabledSkillRef[]`, resolved to\n * full snapshots at `POST /api/workloads` and seeded into\n * `agents.enabled_skills` at agent creation when the caller omits\n * skills.\n * - `spec.mcpServers` (friendly rush MCP id list, Phase C2/C3) → projected\n * to `spec.defaults.enabledMcpServers` as `EnabledMcpRef[]` and seeded\n * into `agents.enabled_mcp_servers` at agent creation when the caller\n * omits MCP servers. At `POST /api/workloads`, credential-free MCP\n * freeze into snapshots (C2) and credentialed MCP persist as refs\n * resolved per running user at bootstrap (C3). See\n * `specs/features/pilot-v2-managed-agent-profile.md` §\"Phase C\".\n *\n * Phase D adds:\n * - `spec.systemPrompt` → projected to `spec.defaults.systemPrompt`,\n * seeded onto `agents.system_prompt` at agent creation, and forwarded\n * per-run by control-worker as `PilotCoderRunConfigV1.systemPrompt`.\n * agent-worker uses it instead of the platform-level `SYSTEM_PROMPT`\n * fallback. See `specs/features/pilot-v2-managed-agent-profile.md`\n * §\"Phase D\".\n */\nexport const MANAGED_AGENT_PROFILE_KIND = \"ManagedAgentProfile\" as const;\n\nconst ManagedAgentProfileMetadataSchema = z\n .object({\n name: WorkloadManifestNameSchema,\n displayName: WorkloadManifestDisplayNameSchema,\n labels: z.record(z.string()).optional(),\n annotations: z.record(z.string()).optional(),\n })\n .strict();\n\nconst ManagedAgentProfileSpecSchema = z\n .object({\n runtimeTemplateRef: WorkloadManifestObjectRefSchema,\n env: SessionConfigValuesSchema.optional(),\n ui: WorkloadManifestUiHintSchema.optional(),\n // Phase B (🟡): workload-level default model id. Projected to\n // `manifest.spec.defaults.model`, persisted in\n // `workloads.manifest_defaults_json`, and read at session creation as\n // the default for `sessions.metadata.model` when the caller does not\n // pin one. See `specs/features/pilot-v2-managed-agent-profile.md`\n // §\"Phase B\" for the resolution order.\n model: WorkloadManifestModelSchema.optional(),\n // Phase C (🟡): workload-level default enabled skills as friendly rush\n // skill names (e.g. `@kanyun/data-analysis-skills`). Projected to\n // `manifest.spec.defaults.enabledSkills` as `EnabledSkillRef[]`,\n // resolved to full snapshots at `POST /api/workloads`, and seeded into\n // `agents.enabled_skills` at agent creation when the caller omits\n // skills. See `specs/features/pilot-v2-managed-agent-profile.md`\n // §\"Phase C\".\n skills: z.array(z.string().min(1)).optional(),\n // Phase C2/C3 (🟡): workload-level default MCP servers as friendly rush\n // MCP ids (e.g. `github`). Projected to\n // `manifest.spec.defaults.enabledMcpServers` as `EnabledMcpRef[]`. At\n // `POST /api/workloads` each ref resolves by credential need:\n // credential-free templates freeze into `EnabledMcpServer` snapshots\n // (C2); credentialed templates persist as bare refs resolved per running\n // user at bootstrap (C3). Seeded into `agents.enabled_mcp_servers` at\n // agent creation when the caller omits MCP servers. See\n // `specs/features/pilot-v2-managed-agent-profile.md` §\"Phase C\".\n mcpServers: z.array(z.string().min(1)).optional(),\n // Phase D: workload-level default system prompt. Projected to\n // `manifest.spec.defaults.systemPrompt`, seeded onto\n // `agents.system_prompt` at agent creation, and forwarded per-run as\n // `PilotCoderRunConfigV1.systemPrompt`. agent-worker uses it instead of\n // the platform-level `SYSTEM_PROMPT` fallback. See\n // `specs/features/pilot-v2-managed-agent-profile.md` §\"Phase D\".\n systemPrompt: WorkloadManifestSystemPromptSchema.optional(),\n })\n .strict();\n\nexport const ManagedAgentProfileSchema = z\n .object({\n apiVersion: PilotWorkloadManifestApiVersionSchema,\n kind: z.literal(MANAGED_AGENT_PROFILE_KIND),\n metadata: ManagedAgentProfileMetadataSchema,\n spec: ManagedAgentProfileSpecSchema,\n })\n .strict();\nexport type ManagedAgentProfile = z.infer<typeof ManagedAgentProfileSchema>;\n\n/**\n * Parse + validate a `ManagedAgentProfile`. Throws\n * `WorkloadManifestValidationError` (code `MANIFEST_VALIDATION_ERROR`)\n * with issue paths pointing at profile fields, so the API can surface\n * profile-shaped errors rather than projected manifest paths.\n */\nexport function parseManagedAgentProfile(input: unknown): ManagedAgentProfile {\n const result = ManagedAgentProfileSchema.safeParse(input);\n if (!result.success) {\n throw new WorkloadManifestValidationError(\n \"MANIFEST_VALIDATION_ERROR\",\n result.error.issues[0]?.message ?? \"Managed agent profile validation failed\",\n result.error.issues.map((issue) => ({ path: issue.path, message: issue.message })),\n );\n }\n return result.data;\n}\n\n/**\n * Project a parsed `ManagedAgentProfile` onto an equivalent\n * `WorkloadManifest` (`kind: \"Workload\"`, `contract.kind:\n * \"managed_agent\"`). The result is a valid `WorkloadManifest` that the\n * existing `applyWorkloadManifest` pipeline consumes unchanged — so\n * `dryRun`, error reporting, and persistence are all reused.\n */\nexport function projectManagedAgentProfileToWorkloadManifest(\n profile: ManagedAgentProfile,\n): WorkloadManifest {\n return {\n apiVersion: PILOT_WORKLOAD_MANIFEST_API_VERSION,\n kind: \"Workload\",\n metadata: {\n name: profile.metadata.name,\n displayName: profile.metadata.displayName,\n ...(profile.metadata.labels ? { labels: profile.metadata.labels } : {}),\n ...(profile.metadata.annotations ? { annotations: profile.metadata.annotations } : {}),\n },\n spec: {\n contract: { kind: \"managed_agent\" },\n defaults: {\n runtimeTemplateRef: profile.spec.runtimeTemplateRef,\n ...(profile.spec.env ? { configValues: profile.spec.env } : {}),\n ...(profile.spec.model ? { model: profile.spec.model } : {}),\n ...(profile.spec.skills && profile.spec.skills.length > 0\n ? { enabledSkills: profile.spec.skills.map((rushSkillName) => ({ rushSkillName })) }\n : {}),\n ...(profile.spec.mcpServers && profile.spec.mcpServers.length > 0\n ? { enabledMcpServers: profile.spec.mcpServers.map((rushMcpId) => ({ rushMcpId })) }\n : {}),\n ...(profile.spec.systemPrompt ? { systemPrompt: profile.spec.systemPrompt } : {}),\n },\n ...(profile.spec.ui ? { ui: profile.spec.ui } : {}),\n },\n };\n}\n\n/**\n * API entry helper (proposal §7 C1): given a raw, untyped manifest\n * request body, project it to a `WorkloadManifest` **iff** it is a\n * `ManagedAgentProfile`. Any other input (Workload / Revision / junk)\n * is returned verbatim so the existing manifest parser handles it\n * (including `MANIFEST_UNSUPPORTED_KIND` for unknown kinds).\n *\n * Profile validation failures throw `WorkloadManifestValidationError`,\n * which the route already catches and renders.\n */\nexport function normalizeManagedAgentProfileInput(input: unknown): unknown {\n if (\n typeof input === \"object\" &&\n input !== null &&\n !Array.isArray(input) &&\n (input as Record<string, unknown>).kind === MANAGED_AGENT_PROFILE_KIND\n ) {\n return projectManagedAgentProfileToWorkloadManifest(parseManagedAgentProfile(input));\n }\n return input;\n}\n","import { z } from \"zod\";\n\nimport { EnabledMcpEntryListSchema } from \"./mcp\";\nimport {\n RuntimeTemplateSnapshotSchema,\n SessionConfigValuesSchema,\n WorkerContractRefSchema,\n type WorkloadKind,\n WorkloadKindSchema,\n} from \"./pilot-v2-session\";\nimport { EnabledSkillEntryListSchema } from \"./skill\";\n\nconst RevisionWorkerContractRefSchema = WorkerContractRefSchema.pick({\n kind: true,\n name: true,\n version: true,\n}).strict();\n\nexport const PILOT_WORKLOAD_MANIFEST_API_VERSION = \"pilot.zhenguanyu.com/v0alpha1\";\nexport const PILOT_WORKLOAD_MANIFEST_LEGACY_API_VERSION = \"pilot.kanyun.ai/v0alpha1\";\nexport const PILOT_WORKLOAD_MANIFEST_API_VERSIONS = [\n PILOT_WORKLOAD_MANIFEST_API_VERSION,\n PILOT_WORKLOAD_MANIFEST_LEGACY_API_VERSION,\n] as const;\nexport const PilotWorkloadManifestApiVersionSchema = z.enum(PILOT_WORKLOAD_MANIFEST_API_VERSIONS);\nexport type PilotWorkloadManifestApiVersion = z.infer<typeof PilotWorkloadManifestApiVersionSchema>;\nexport const WORKLOAD_MANIFEST_NAME_MAX_LENGTH = 100;\nexport const WORKLOAD_MANIFEST_DISPLAY_NAME_MAX_LENGTH = 255;\nexport const WORKLOAD_MANIFEST_REF_NAME_MAX_LENGTH = 255;\n\nexport const WorkloadManifestErrorCodeSchema = z.enum([\n \"MANIFEST_UNSUPPORTED_API_VERSION\",\n \"MANIFEST_UNSUPPORTED_KIND\",\n \"MANIFEST_VALIDATION_ERROR\",\n \"WORKLOAD_KIND_UNSUPPORTED\",\n \"WORKLOAD_NOT_FOUND\",\n \"WORKLOAD_KIND_MISMATCH\",\n \"PROJECT_DEFAULT_RUNTIME_MISSING\",\n \"RUNTIME_TEMPLATE_NOT_FOUND\",\n \"REVISION_REGISTRATION_CONFLICT\",\n // Cross-project safety: thrown when `applyRevisionManifest` resolves a\n // workload and a runtime template that live in different projects.\n // Mirrors the `revisions_project_consistency` DB trigger; the\n // application-layer check exits early with a friendlier error code\n // before the trigger fires raw `check_violation` SQLSTATE 23514.\n // Plan: plans/admin-ui-project-namespacing.md §C2.\n \"REVISION_CROSS_PROJECT\",\n \"IMAGE_PROVENANCE_REQUIRED\",\n \"IMAGE_PROVENANCE_INVALID\",\n \"LEGACY_PROVENANCE_NOT_ALLOWED\",\n]);\nexport type WorkloadManifestErrorCode = z.infer<typeof WorkloadManifestErrorCodeSchema>;\n\nexport const ActiveWorkloadKindSchema = z.enum([\"managed_agent\", \"self_managed\"]);\nexport type ActiveWorkloadKind = z.infer<typeof ActiveWorkloadKindSchema>;\n\nexport const DeferredWorkloadKindSchema = z.enum([\"external_worker\", \"batch_task\"]);\nexport type DeferredWorkloadKind = z.infer<typeof DeferredWorkloadKindSchema>;\n\nconst DNS_LABEL_STYLE_PATTERN = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/;\n\nexport const WorkloadManifestNameSchema = z\n .string()\n .min(1)\n .max(WORKLOAD_MANIFEST_NAME_MAX_LENGTH)\n .regex(DNS_LABEL_STYLE_PATTERN, \"Name must be DNS-label-style\");\n\nexport const WorkloadManifestDisplayNameSchema = z\n .string()\n .min(1)\n .max(WORKLOAD_MANIFEST_DISPLAY_NAME_MAX_LENGTH);\n\nexport const WorkloadManifestRefNameSchema = z\n .string()\n .min(1)\n .max(WORKLOAD_MANIFEST_REF_NAME_MAX_LENGTH);\n\nexport const WorkloadManifestObjectRefSchema = z\n .object({\n name: WorkloadManifestRefNameSchema,\n })\n .strict();\nexport type WorkloadManifestObjectRef = z.infer<typeof WorkloadManifestObjectRefSchema>;\n\nconst WorkloadManifestMetadataBaseSchema = z\n .object({\n name: WorkloadManifestNameSchema,\n labels: z.record(z.string()).optional(),\n annotations: z.record(z.string()).optional(),\n })\n .strict();\n\nexport const WorkloadManifestMetadataSchema = WorkloadManifestMetadataBaseSchema.extend({\n displayName: WorkloadManifestDisplayNameSchema,\n}).strict();\nexport type WorkloadManifestMetadata = z.infer<typeof WorkloadManifestMetadataSchema>;\n\nexport const RevisionManifestMetadataSchema = WorkloadManifestMetadataBaseSchema.extend({\n workload: WorkloadManifestNameSchema,\n}).strict();\nexport type RevisionManifestMetadata = z.infer<typeof RevisionManifestMetadataSchema>;\n\nexport const WorkloadManifestCapabilityRefsSchema = z\n .object({\n modelRef: WorkloadManifestObjectRefSchema.optional(),\n toolRefs: z.array(WorkloadManifestObjectRefSchema).optional(),\n mcpRefs: z.array(WorkloadManifestObjectRefSchema).optional(),\n })\n .strict();\nexport type WorkloadManifestCapabilityRefs = z.infer<typeof WorkloadManifestCapabilityRefsSchema>;\n\nexport const WorkloadManifestPolicyRefsSchema = z\n .object({\n credentialPolicyRef: WorkloadManifestObjectRefSchema.optional(),\n readinessPolicyRef: WorkloadManifestObjectRefSchema.optional(),\n actionPolicyRef: WorkloadManifestObjectRefSchema.optional(),\n trafficPolicyRef: WorkloadManifestObjectRefSchema.optional(),\n })\n .strict();\nexport type WorkloadManifestPolicyRefs = z.infer<typeof WorkloadManifestPolicyRefsSchema>;\n\nexport const WorkloadManifestWorkerContractDefaultsSchema = z\n .object({\n name: WorkloadManifestRefNameSchema.optional(),\n version: z.string().min(1).max(WORKLOAD_MANIFEST_NAME_MAX_LENGTH).optional(),\n })\n .strict();\nexport type WorkloadManifestWorkerContractDefaults = z.infer<\n typeof WorkloadManifestWorkerContractDefaultsSchema\n>;\n\nexport const WORKLOAD_MANIFEST_MODEL_MAX_LENGTH = 255;\n\n/**\n * A workload-level **default model id** (real ModelGate model id, e.g.\n * `claude-opus-4-7`). Unlike the unconsumed `capabilityRefs.modelRef`\n * placeholder, this is persisted into `workloads.manifest_defaults_json`\n * and read at session creation as the default for\n * `sessions.metadata.model` when the caller does not pin one\n * (managed_agent profile Phase B; see\n * `specs/features/pilot-v2-managed-agent-profile.md` §\"Phase B\").\n */\nexport const WorkloadManifestModelSchema = z\n .string()\n .min(1)\n .max(WORKLOAD_MANIFEST_MODEL_MAX_LENGTH);\n\nexport const WORKLOAD_MANIFEST_SYSTEM_PROMPT_MAX_LENGTH = 32_768;\n\n/**\n * Workload-level **default system prompt** (managed_agent profile Phase D).\n * Persisted into `workloads.manifest_defaults_json` and seeded onto\n * `agents.system_prompt` at agent creation; control-worker then forwards it\n * as `PilotCoderRunConfigV1.systemPrompt` on each dispatch so agent-worker\n * uses it instead of the platform-level `SYSTEM_PROMPT` fallback. See\n * `specs/features/pilot-v2-managed-agent-profile.md` §\"Phase D\".\n */\nexport const WorkloadManifestSystemPromptSchema = z\n .string()\n .min(1)\n .max(WORKLOAD_MANIFEST_SYSTEM_PROMPT_MAX_LENGTH);\n\nexport const ManagedAgentProfileSnapshotSchema = z\n .object({\n model: WorkloadManifestModelSchema.optional(),\n systemPrompt: WorkloadManifestSystemPromptSchema.optional(),\n enabledSkills: EnabledSkillEntryListSchema.optional(),\n enabledMcpServers: EnabledMcpEntryListSchema.optional(),\n configValues: SessionConfigValuesSchema.optional(),\n })\n .strict();\nexport type ManagedAgentProfileSnapshot = z.infer<typeof ManagedAgentProfileSnapshotSchema>;\n\nexport const ManagedAgentOverridesSchema = z\n .object({\n model: WorkloadManifestModelSchema.nullable().optional(),\n systemPrompt: WorkloadManifestSystemPromptSchema.nullable().optional(),\n enabledSkills: EnabledSkillEntryListSchema.optional(),\n enabledMcpServers: EnabledMcpEntryListSchema.optional(),\n })\n .strict();\nexport type ManagedAgentOverrides = z.infer<typeof ManagedAgentOverridesSchema>;\n\nexport const WorkloadManifestDefaultsSchema = z\n .object({\n runtimeTemplateRef: WorkloadManifestObjectRefSchema.optional(),\n workerContract: WorkloadManifestWorkerContractDefaultsSchema.optional(),\n capabilityRefs: WorkloadManifestCapabilityRefsSchema.optional(),\n configValues: SessionConfigValuesSchema.optional(),\n model: WorkloadManifestModelSchema.optional(),\n /**\n * Workload-level **default system prompt** (managed_agent profile\n * Phase D). Seeded onto `agents.system_prompt` at agent creation and\n * forwarded per-run as `PilotCoderRunConfigV1.systemPrompt`. See\n * `specs/features/pilot-v2-managed-agent-profile.md` §\"Phase D\".\n */\n systemPrompt: WorkloadManifestSystemPromptSchema.optional(),\n /**\n * Workload-level **default enabled skills** (managed_agent profile\n * Phase C). Persisted into `workloads.manifest_defaults_json` and\n * seeded into `agents.enabled_skills` at agent creation when the\n * caller does not supply explicit skills. Accepts the snapshot-or-ref\n * union (same write contract as `projects.enabled_skills`); the\n * `POST /api/workloads` route resolves any refs into full\n * `EnabledSkill` snapshots via the rush registry before persisting so\n * the workload default is self-contained (no per-user install\n * dependency). See `specs/features/pilot-v2-managed-agent-profile.md`\n * §\"Phase C\".\n */\n enabledSkills: EnabledSkillEntryListSchema.optional(),\n /**\n * Workload-level **default enabled MCP servers** (managed_agent\n * profile Phase C2). Persisted into `workloads.manifest_defaults_json`\n * and seeded into `agents.enabled_mcp_servers` at agent creation when\n * the caller does not supply explicit MCP servers. Accepts the\n * snapshot-or-ref union (same write contract as\n * `projects.enabled_mcp_servers`); the `POST /api/workloads` route\n * resolves any refs into full `EnabledMcpServer` snapshots via the\n * rush registry before persisting so the workload default is\n * self-contained.\n *\n * Resolution at `POST /api/workloads` produces a mix:\n * - **credential-free** MCP (rush `requiredVars` empty, Phase C2) →\n * frozen `EnabledMcpServer` snapshot (self-contained, cross-user\n * identical).\n * - **credentialed** MCP (rush `requiredVars` non-empty, Phase C3) →\n * bare `EnabledMcpRef { rushMcpId }`; the credential is NOT frozen\n * here, it resolves per running user from `user_mcp_installs` at\n * bootstrap (ref-resolver), with per-MCP failure isolation when an\n * install is missing (`mcp-and-skills.md` §4.2).\n *\n * Inline plaintext credentials (`extraConfigValues` /\n * `extraConfigValuesOverride`) are rejected at resolution — a\n * cross-user workload default never stores one user's secret. See\n * `specs/features/pilot-v2-managed-agent-profile.md` §\"Phase C\".\n */\n enabledMcpServers: EnabledMcpEntryListSchema.optional(),\n })\n .strict();\nexport type WorkloadManifestDefaults = z.infer<typeof WorkloadManifestDefaultsSchema>;\n\nexport const WORKLOAD_MANIFEST_UI_DISPLAY_NAME_MAX_LENGTH = 255;\nexport const WORKLOAD_MANIFEST_UI_PROMPT_PLACEHOLDER_MAX_LENGTH = 500;\n\n/**\n * Optional portal UI rendering hints for the Managed-Agent default\n * Web UI (P4 task 4.1; consumed by the components under\n * `apps/web/app/(portal)/w/_components/`).\n *\n * All fields are optional, and the hint as a whole is optional on\n * `WorkloadManifestSchema.spec` — legacy manifests without it must\n * continue to parse unchanged. The UI layer reads each field with a\n * documented default so absence is always safe.\n *\n * Fields:\n * - `displayName` — portal-facing name override (falls back to\n * `metadata.displayName` when absent).\n * - `promptPlaceholder` — composer placeholder text (falls back to\n * a generic \"Type a message…\").\n * - `enableAttachments` — when `true`, the composer renders an\n * attachment picker. Default `false` (no attachments in P1).\n * - `artifactsView` — `\"none\"` (hide tab; default) or `\"panel\"`\n * (render the artifacts panel alongside the chat).\n *\n * Strict mode rejects any other key — this guards against typo\n * silently disabling a hint (`enableAttachemnts: true` MUST error,\n * not silently parse as `enableAttachments: undefined`).\n */\nexport const WorkloadManifestUiHintSchema = z\n .object({\n displayName: z.string().min(1).max(WORKLOAD_MANIFEST_UI_DISPLAY_NAME_MAX_LENGTH).optional(),\n promptPlaceholder: z\n .string()\n .min(1)\n .max(WORKLOAD_MANIFEST_UI_PROMPT_PLACEHOLDER_MAX_LENGTH)\n .optional(),\n enableAttachments: z.boolean().optional(),\n artifactsView: z.enum([\"none\", \"panel\"]).optional(),\n })\n .strict();\nexport type WorkloadManifestUiHint = z.infer<typeof WorkloadManifestUiHintSchema>;\n\nexport const WorkloadManifestSchema = z\n .object({\n apiVersion: PilotWorkloadManifestApiVersionSchema,\n kind: z.literal(\"Workload\"),\n metadata: WorkloadManifestMetadataSchema,\n spec: z\n .object({\n contract: z\n .object({\n kind: WorkloadKindSchema,\n })\n .strict(),\n defaults: WorkloadManifestDefaultsSchema.optional(),\n policyRefs: WorkloadManifestPolicyRefsSchema.optional(),\n ui: WorkloadManifestUiHintSchema.optional(),\n })\n .strict(),\n })\n .strict();\nexport type WorkloadManifest = z.infer<typeof WorkloadManifestSchema>;\n\n/**\n * Result of `resolveWorkloadUiHint()` — every documented field has a\n * concrete value so UI callers can render unconditionally without\n * repeating `?? false / ?? \"none\"` at every branch.\n *\n * Field semantics match `WorkloadManifestUiHintSchema`. `displayName`\n * is the only field with a fallback chain: manifest `ui.displayName`\n * → caller-supplied `fallbackDisplayName` (typically the workload's\n * `metadata.displayName` already loaded server-side).\n *\n * `promptPlaceholder` keeps `undefined` semantics so the UI can use\n * its own component-default rather than embedding placeholder copy\n * in this layer.\n */\nexport interface ResolvedWorkloadUiHint {\n displayName: string;\n promptPlaceholder: string | undefined;\n enableAttachments: boolean;\n artifactsView: \"none\" | \"panel\";\n}\n\nexport interface ResolveWorkloadUiHintOptions {\n /**\n * Required fallback for `displayName` — typically the workload row's\n * `metadata.displayName` already loaded at the call site. The helper\n * cannot reach into the workload metadata itself; it only sees the\n * `spec.ui` slice.\n */\n fallbackDisplayName: string;\n}\n\n/**\n * Resolve a portal UI rendering hint with documented defaults applied\n * (P4 task 4.2; consumed by `apps/web/app/(portal)/w/_components/`).\n *\n * `hint` may be `undefined` for legacy manifests that pre-date\n * `spec.ui`; in that case every UI field falls back to its documented\n * default (`enableAttachments: false`, `artifactsView: \"none\"`,\n * `promptPlaceholder: undefined`, `displayName: options.fallbackDisplayName`).\n *\n * Centralizing the fallback chain here keeps the documented defaults\n * (plan §5 P2 \"P2 → P4 依赖说明\") in one place — any future schema\n * default change ships through this function rather than scattered\n * `?? false` expressions.\n */\nexport function resolveWorkloadUiHint(\n hint: WorkloadManifestUiHint | undefined,\n options: ResolveWorkloadUiHintOptions,\n): ResolvedWorkloadUiHint {\n return {\n displayName: hint?.displayName ?? options.fallbackDisplayName,\n promptPlaceholder: hint?.promptPlaceholder,\n enableAttachments: hint?.enableAttachments ?? false,\n artifactsView: hint?.artifactsView ?? \"none\",\n };\n}\n\nexport const RevisionManifestStartupSchema = z\n .object({\n requiredGates: z.array(z.string().min(1)).optional(),\n optionalGates: z.array(z.string().min(1)).optional(),\n })\n .strict();\nexport type RevisionManifestStartup = z.infer<typeof RevisionManifestStartupSchema>;\n\nexport const RevisionManifestPublishSchema = z\n .object({\n setDefault: z.boolean().default(true),\n })\n .strict();\nexport type RevisionManifestPublish = z.infer<typeof RevisionManifestPublishSchema>;\n\nexport const RevisionRuntimeEnvironmentInputSchema = RuntimeTemplateSnapshotSchema.omit({\n defaultWorkerEndpoint: true,\n}).strict();\nexport type RevisionRuntimeEnvironmentInput = z.infer<typeof RevisionRuntimeEnvironmentInputSchema>;\n\nexport const RevisionRuntimeEnvironmentOverridesSchema =\n RevisionRuntimeEnvironmentInputSchema.partial().strict();\nexport type RevisionRuntimeEnvironmentOverrides = z.infer<\n typeof RevisionRuntimeEnvironmentOverridesSchema\n>;\n\nexport const RevisionRuntimeSchema = z\n .object({\n /**\n * Complete publish-time Runtime Environment input. Control-plane resolves\n * and freezes this into `revisions.runtime_template_snapshot_json`; DB\n * compatibility still records a runtime source/profile id separately.\n */\n environment: RevisionRuntimeEnvironmentInputSchema.optional(),\n /**\n * Runtime source/profile reference. During the RuntimeTemplate\n * compatibility window this maps to `runtime_templates.name`.\n */\n profileRef: WorkloadManifestObjectRefSchema.optional(),\n /**\n * Publish-time overrides applied to `profileRef`'s resolved environment.\n */\n overrides: RevisionRuntimeEnvironmentOverridesSchema.optional(),\n })\n .strict()\n .superRefine((runtime, ctx) => {\n if (!runtime.environment && !runtime.profileRef) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"environment\"],\n message: \"runtime must provide environment or profileRef\",\n });\n }\n if (runtime.environment && runtime.overrides) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"overrides\"],\n message: \"runtime.overrides is only allowed with runtime.profileRef\",\n });\n }\n if (runtime.overrides && !runtime.profileRef) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"profileRef\"],\n message: \"runtime.profileRef is required when runtime.overrides is provided\",\n });\n }\n });\nexport type RevisionRuntime = z.infer<typeof RevisionRuntimeSchema>;\n\nconst RevisionManifestSpecSchema = z\n .object({\n runtimeTemplateRef: WorkloadManifestObjectRefSchema.optional(),\n runtime: RevisionRuntimeSchema.optional(),\n workerContract: RevisionWorkerContractRefSchema,\n capabilityRefs: WorkloadManifestCapabilityRefsSchema.optional(),\n startup: RevisionManifestStartupSchema.optional(),\n publish: RevisionManifestPublishSchema.default({ setDefault: true }),\n configValues: SessionConfigValuesSchema.optional(),\n policyRefs: WorkloadManifestPolicyRefsSchema.optional(),\n managedAgentProfileSnapshot: ManagedAgentProfileSnapshotSchema.optional(),\n })\n .strict()\n .superRefine((spec, ctx) => {\n const profileRefName = spec.runtime?.profileRef?.name;\n const legacyRuntimeTemplateRefName = spec.runtimeTemplateRef?.name;\n if (\n profileRefName &&\n legacyRuntimeTemplateRefName &&\n profileRefName !== legacyRuntimeTemplateRefName\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"runtimeTemplateRef\"],\n message:\n \"runtimeTemplateRef must match runtime.profileRef when both compatibility refs are provided\",\n });\n }\n\n if (\n spec.managedAgentProfileSnapshot !== undefined &&\n spec.workerContract.kind !== \"managed_agent\"\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"managedAgentProfileSnapshot\"],\n message: \"managedAgentProfileSnapshot is only allowed for managed_agent revisions\",\n });\n }\n });\n\nexport const RevisionManifestSchema = z\n .object({\n apiVersion: PilotWorkloadManifestApiVersionSchema,\n kind: z.literal(\"Revision\"),\n metadata: RevisionManifestMetadataSchema,\n spec: RevisionManifestSpecSchema,\n })\n .strict();\nexport type RevisionManifest = z.infer<typeof RevisionManifestSchema>;\n\nexport const PilotWorkloadManifestSchema = z.discriminatedUnion(\"kind\", [\n WorkloadManifestSchema,\n RevisionManifestSchema,\n]);\nexport type PilotWorkloadManifest = z.infer<typeof PilotWorkloadManifestSchema>;\n\nexport interface ParsePilotWorkloadManifestOptions {\n validateForApply?: boolean;\n}\n\nexport interface WorkloadManifestValidationIssue {\n path: Array<string | number>;\n message: string;\n}\n\nexport class WorkloadManifestValidationError extends Error {\n readonly code: WorkloadManifestErrorCode;\n readonly issues: WorkloadManifestValidationIssue[];\n\n constructor(\n code: WorkloadManifestErrorCode,\n message: string,\n issues: WorkloadManifestValidationIssue[] = [],\n ) {\n super(message);\n this.name = \"WorkloadManifestValidationError\";\n this.code = code;\n this.issues = issues;\n }\n}\n\nexport function isActiveWorkloadKind(kind: WorkloadKind): kind is ActiveWorkloadKind {\n return ActiveWorkloadKindSchema.safeParse(kind).success;\n}\n\nexport function isDeferredWorkloadKind(kind: WorkloadKind): kind is DeferredWorkloadKind {\n return DeferredWorkloadKindSchema.safeParse(kind).success;\n}\n\nexport function assertManifestUsesActiveWorkloadKind(manifest: PilotWorkloadManifest): void {\n const kind =\n manifest.kind === \"Workload\" ? manifest.spec.contract.kind : manifest.spec.workerContract.kind;\n\n if (isDeferredWorkloadKind(kind)) {\n throw new WorkloadManifestValidationError(\n \"WORKLOAD_KIND_UNSUPPORTED\",\n `Workload kind ${kind} is reserved for a future Pilot v2 implementation`,\n [{ path: workloadKindPathForManifest(manifest), message: \"Workload kind is not supported\" }],\n );\n }\n}\n\nexport function parsePilotWorkloadManifest(\n input: unknown,\n options: Pick<ParsePilotWorkloadManifestOptions, \"validateForApply\"> = {},\n): PilotWorkloadManifest {\n assertTopLevelManifestFacts(input);\n\n const result = PilotWorkloadManifestSchema.safeParse(input);\n if (!result.success) {\n throw zodManifestValidationError(result.error);\n }\n\n if (options.validateForApply) {\n assertManifestUsesActiveWorkloadKind(result.data);\n }\n\n return result.data;\n}\n\nexport function parseWorkloadManifest(\n input: unknown,\n options: Pick<ParsePilotWorkloadManifestOptions, \"validateForApply\"> = {},\n): WorkloadManifest {\n const manifest = parsePilotWorkloadManifest(input, options);\n if (manifest.kind !== \"Workload\") {\n throw new WorkloadManifestValidationError(\"MANIFEST_UNSUPPORTED_KIND\", \"Expected Workload\");\n }\n return manifest;\n}\n\nexport function parseRevisionManifest(\n input: unknown,\n options: Pick<ParsePilotWorkloadManifestOptions, \"validateForApply\"> = {},\n): RevisionManifest {\n const manifest = parsePilotWorkloadManifest(input, options);\n if (manifest.kind !== \"Revision\") {\n throw new WorkloadManifestValidationError(\"MANIFEST_UNSUPPORTED_KIND\", \"Expected Revision\");\n }\n return manifest;\n}\n\nexport function parsePilotWorkloadManifestJson(\n source: string,\n options: Pick<ParsePilotWorkloadManifestOptions, \"validateForApply\"> = {},\n): PilotWorkloadManifest {\n const raw = parseJsonManifest(source);\n return parsePilotWorkloadManifest(raw, options);\n}\n\nfunction parseJsonManifest(source: string): unknown {\n try {\n return JSON.parse(source);\n } catch (error) {\n throw new WorkloadManifestValidationError(\n \"MANIFEST_VALIDATION_ERROR\",\n error instanceof Error ? error.message : \"Invalid JSON manifest\",\n );\n }\n}\n\nfunction assertTopLevelManifestFacts(input: unknown): asserts input is Record<string, unknown> {\n if (!isRecord(input)) {\n throw new WorkloadManifestValidationError(\n \"MANIFEST_VALIDATION_ERROR\",\n \"Manifest must be an object\",\n );\n }\n\n const issues: WorkloadManifestValidationIssue[] = [];\n\n if (!PilotWorkloadManifestApiVersionSchema.safeParse(input.apiVersion).success) {\n issues.push({ path: [\"apiVersion\"], message: \"Unsupported manifest apiVersion\" });\n }\n\n if (input.kind !== \"Workload\" && input.kind !== \"Revision\") {\n issues.push({ path: [\"kind\"], message: \"Unsupported manifest kind\" });\n }\n\n const hasUnsupportedApiVersion = issues.some((issue) => issue.path[0] === \"apiVersion\");\n if (hasUnsupportedApiVersion) {\n throw new WorkloadManifestValidationError(\n \"MANIFEST_UNSUPPORTED_API_VERSION\",\n `Manifest apiVersion must be one of ${PILOT_WORKLOAD_MANIFEST_API_VERSIONS.join(\", \")}`,\n issues,\n );\n }\n\n if (issues.length > 0) {\n throw new WorkloadManifestValidationError(\n \"MANIFEST_UNSUPPORTED_KIND\",\n \"Manifest kind must be Workload or Revision\",\n issues,\n );\n }\n}\n\nfunction zodManifestValidationError(error: z.ZodError): WorkloadManifestValidationError {\n return new WorkloadManifestValidationError(\n \"MANIFEST_VALIDATION_ERROR\",\n error.issues[0]?.message ?? \"Manifest validation failed\",\n error.issues.map((issue) => ({\n path: issue.path,\n message: issue.message,\n })),\n );\n}\n\nfunction workloadKindPathForManifest(manifest: PilotWorkloadManifest): Array<string | number> {\n if (manifest.kind === \"Workload\") return [\"spec\", \"contract\", \"kind\"];\n return [\"spec\", \"workerContract\", \"kind\"];\n}\n\nfunction isRecord(input: unknown): input is Record<string, unknown> {\n return typeof input === \"object\" && input !== null && !Array.isArray(input);\n}\n","import { z } from \"zod\";\n\nimport { EnabledMcpEntryListSchema } from \"./mcp\";\nimport {\n CreateSessionRequestSchema,\n CreateSessionResponseSchema,\n SessionConfigValuesSchema,\n SessionStatusSchema,\n} from \"./pilot-v2-session\";\nimport {\n ActiveWorkloadKindSchema,\n ManagedAgentProfileSnapshotSchema,\n PILOT_WORKLOAD_MANIFEST_API_VERSION,\n PILOT_WORKLOAD_MANIFEST_API_VERSIONS,\n PILOT_WORKLOAD_MANIFEST_LEGACY_API_VERSION,\n RevisionManifestPublishSchema,\n RevisionManifestSchema,\n RevisionRuntimeSchema,\n WorkloadManifestDisplayNameSchema,\n WorkloadManifestNameSchema,\n WorkloadManifestRefNameSchema,\n WorkloadManifestSchema,\n WorkloadManifestUiHintSchema,\n WorkloadManifestWorkerContractDefaultsSchema,\n} from \"./pilot-v2-workload-manifest\";\nimport { EnabledSkillEntryListSchema } from \"./skill\";\n\nexport {\n PILOT_WORKLOAD_MANIFEST_API_VERSION,\n PILOT_WORKLOAD_MANIFEST_API_VERSIONS,\n PILOT_WORKLOAD_MANIFEST_LEGACY_API_VERSION,\n};\n\nexport const PlatformProjectSchema = z\n .object({\n id: z.string().uuid(),\n slug: WorkloadManifestNameSchema,\n displayName: WorkloadManifestDisplayNameSchema,\n description: z.string().nullable().optional(),\n defaultRuntimeTemplateRefName: WorkloadManifestRefNameSchema.nullable().optional(),\n createdAt: z.string().optional(),\n updatedAt: z.string().optional(),\n })\n .strict();\nexport type PlatformProject = z.infer<typeof PlatformProjectSchema>;\n\nexport const CreatePlatformProjectRequestSchema = z\n .object({\n slug: WorkloadManifestNameSchema,\n displayName: WorkloadManifestDisplayNameSchema,\n description: z.string().max(2_000).optional(),\n defaultRuntimeTemplateRefName: WorkloadManifestRefNameSchema.optional(),\n })\n .strict();\nexport type CreatePlatformProjectRequest = z.infer<typeof CreatePlatformProjectRequestSchema>;\n\nexport const ListPlatformProjectsResponseSchema = z\n .object({\n projects: z.array(PlatformProjectSchema),\n })\n .strict();\nexport type ListPlatformProjectsResponse = z.infer<typeof ListPlatformProjectsResponseSchema>;\n\nconst PlatformWorkloadDefaultsSchema = z\n .object({\n workerContract: WorkloadManifestWorkerContractDefaultsSchema.optional(),\n configValues: SessionConfigValuesSchema.optional(),\n model: z.string().min(1).max(255).optional(),\n systemPrompt: z.string().min(1).max(32_768).optional(),\n enabledSkills: EnabledSkillEntryListSchema.optional(),\n enabledMcpServers: EnabledMcpEntryListSchema.optional(),\n })\n .strict();\nexport type PlatformWorkloadDefaults = z.infer<typeof PlatformWorkloadDefaultsSchema>;\n\nexport const CreatePlatformWorkloadRequestSchema = z\n .object({\n projectId: z.string().uuid(),\n slug: WorkloadManifestNameSchema,\n displayName: WorkloadManifestDisplayNameSchema,\n kind: ActiveWorkloadKindSchema,\n defaults: PlatformWorkloadDefaultsSchema.optional(),\n ui: WorkloadManifestUiHintSchema.optional(),\n })\n .strict();\nexport type CreatePlatformWorkloadRequest = z.infer<typeof CreatePlatformWorkloadRequestSchema>;\n\nexport const PlatformWorkloadSchema = z\n .object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n slug: WorkloadManifestNameSchema,\n displayName: WorkloadManifestDisplayNameSchema,\n kind: ActiveWorkloadKindSchema,\n defaultRevisionId: z.string().uuid().nullable().optional(),\n createdAt: z.string().optional(),\n updatedAt: z.string().optional(),\n })\n .strict();\nexport type PlatformWorkload = z.infer<typeof PlatformWorkloadSchema>;\n\nconst PublishPlatformRevisionWorkerContractSchema = z\n .object({\n kind: ActiveWorkloadKindSchema,\n name: WorkloadManifestRefNameSchema.optional(),\n version: z.string().min(1).max(100).optional(),\n })\n .strict();\n\nexport const PublishPlatformRevisionRequestSchema = z\n .object({\n projectId: z.string().uuid(),\n workloadSlug: WorkloadManifestNameSchema,\n version: WorkloadManifestNameSchema,\n workerContract: PublishPlatformRevisionWorkerContractSchema,\n setDefault: z.boolean().default(true),\n startup: z\n .object({\n requiredGates: z.array(z.string().min(1)).optional(),\n optionalGates: z.array(z.string().min(1)).optional(),\n })\n .strict()\n .optional(),\n configValues: SessionConfigValuesSchema.optional(),\n managedAgentProfileSnapshot: ManagedAgentProfileSnapshotSchema.optional(),\n runtime: RevisionRuntimeSchema.optional(),\n })\n .strict();\nexport type PublishPlatformRevisionRequest = z.infer<typeof PublishPlatformRevisionRequestSchema>;\n\nexport const PlatformRevisionSchema = z\n .object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n workloadId: z.string().uuid(),\n workloadSlug: WorkloadManifestNameSchema.optional(),\n version: WorkloadManifestNameSchema,\n runtimeSnapshotHash: z.string().nullable().optional(),\n createdAt: z.string().optional(),\n })\n .strict();\nexport type PlatformRevision = z.infer<typeof PlatformRevisionSchema>;\n\nexport const GetPlatformSessionResponseSchema = z\n .object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n workloadId: z.string().uuid(),\n revisionId: z.string().uuid(),\n status: SessionStatusSchema,\n createdAt: z.string().optional(),\n updatedAt: z.string().optional(),\n })\n .strict();\nexport type GetPlatformSessionResponse = z.infer<typeof GetPlatformSessionResponseSchema>;\n\nexport const CreatePlatformSessionRequestSchema = CreateSessionRequestSchema;\nexport type CreatePlatformSessionRequest = z.infer<typeof CreatePlatformSessionRequestSchema>;\nexport const CreatePlatformSessionResponseSchema = CreateSessionResponseSchema;\nexport type CreatePlatformSessionResponse = z.infer<typeof CreatePlatformSessionResponseSchema>;\n\nexport function platformWorkloadCreateToManifest(\n input: CreatePlatformWorkloadRequest,\n): z.infer<typeof WorkloadManifestSchema> {\n const defaults = input.defaults ? omitUndefined(input.defaults) : undefined;\n\n return WorkloadManifestSchema.parse({\n apiVersion: PILOT_WORKLOAD_MANIFEST_API_VERSION,\n kind: \"Workload\",\n metadata: {\n name: input.slug,\n displayName: input.displayName,\n },\n spec: {\n contract: { kind: input.kind },\n ...(defaults ? { defaults } : {}),\n ...(input.ui ? { ui: input.ui } : {}),\n },\n });\n}\n\nfunction omitUndefined<T extends Record<string, unknown>>(input: T): Partial<T> {\n return Object.fromEntries(\n Object.entries(input).filter((entry): entry is [string, unknown] => entry[1] !== undefined),\n ) as Partial<T>;\n}\n\nexport function platformRevisionPublishToManifest(\n input: PublishPlatformRevisionRequest,\n): z.infer<typeof RevisionManifestSchema> {\n return RevisionManifestSchema.parse({\n apiVersion: PILOT_WORKLOAD_MANIFEST_API_VERSION,\n kind: \"Revision\",\n metadata: {\n name: input.version,\n workload: input.workloadSlug,\n },\n spec: {\n ...(input.runtime ? { runtime: input.runtime } : {}),\n workerContract: input.workerContract,\n publish: RevisionManifestPublishSchema.parse({ setDefault: input.setDefault }),\n ...(input.startup ? { startup: input.startup } : {}),\n ...(input.configValues ? { configValues: input.configValues } : {}),\n ...(input.managedAgentProfileSnapshot\n ? { managedAgentProfileSnapshot: input.managedAgentProfileSnapshot }\n : {}),\n },\n });\n}\n","/**\n * Pilot Coder business payload schemas — JSON-encoded into the v2\n * `WorkerProtocolPromptRequest.promptText` / `WorkerProtocolFollowupRequest.followupText`\n * / `WorkerProtocolRestoreRequest.replayCursor` opaque pass-through field\n * (R-WP-04). Lives in `@pilot/contracts` so dispatcher (control-worker) and\n * handler (apps/agent-worker) share the single source of truth.\n *\n * Why this lives here, not in `apps/agent-worker`:\n *\n * - v2 envelope is intentionally narrow (idempotencyKey/session/text/trace/deadline)\n * so the substrate stays business-agnostic.\n * - Pilot Coder still needs ~12 per-prompt fields (provider/model/mcpServers/\n * triggerContext/attachments/workspace…) — they MUST be carried somewhere.\n * - Option A (chosen, see plans/p2-pilot-coder-v2-migration-mvp.md):\n * business owns the `*Text` payload schema; dispatcher encodes, handler decodes.\n * Substrate (sdk-worker) stays oblivious.\n *\n * The `schemaVersion` literal lets us roll forward without coordinating an\n * envelope change. Bumping to `\"v2\"` happens in a future commit when fields\n * are added/removed; both sides parse strictly so unknown fields fail loud.\n *\n * Abort dispatch has no business payload — `WorkerProtocolAbortRequestSchema`\n * already carries `turnId` + `reason`, which is all the handler needs.\n */\n\nimport { z } from \"zod\";\nimport { ProjectKindSchema } from \"./project\";\nimport { McpServersMapSchema } from \"./recovery\";\nimport { AttachmentMetaSchema, ProviderTypeSchema, TriggerSourceSchema } from \"./run\";\nimport { EnabledSkillSchema } from \"./skill\";\nimport { WebhookTriggerContextSchema } from \"./webhook-context\";\n\n/**\n * Per-run skill install hints, populated by control-plane and consumed\n * by the agent-worker in-sandbox skill installer. Tokens are short-lived\n * (resolved at dispatch time) and only sent to the hosts they apply to —\n * see `@pilot/skills` `ensureSkillsInstalled` host allowlist enforcement.\n *\n * Optional / nullable across the board because:\n * - `gitlabDomain` is unset for github-only deployments\n * - tokens are unset when the host requires no auth (public repos)\n * - the whole object is omitted when no skills are scheduled for the run\n */\nexport const PilotCoderSkillsInstallSchema = z\n .object({\n gitlabDomain: z.string().optional(),\n gitlabToken: z.string().optional(),\n githubToken: z.string().optional(),\n })\n .strict();\nexport type PilotCoderSkillsInstall = z.infer<typeof PilotCoderSkillsInstallSchema>;\n\n/**\n * P3 L3.3 — Extensible discriminated union of trigger references shipped to\n * the worker so delivery (PR / MR / Jira reverse-comment) has structured\n * info instead of re-parsing `runs.trigger_ref` opaque strings.\n *\n * Variants intentionally only carry the *issue / PR identifiers* (not repo\n * info — repo info comes from `repoUrl` separately). `opaque` is the\n * forward-compatibility escape hatch: control-worker uses it whenever the\n * raw `runs.trigger_ref` doesn't match any of the known shapes, so a future\n * trigger source (e.g. lark notifications) doesn't immediately break the\n * wire schema before this enum is widened.\n *\n * The 5-arm reference set the plan calls out (`jira_issue` etc.) is\n * preserved literally; adding a 6th variant later is non-breaking on the\n * worker because the matching is `switch (type)` with a default no-op.\n */\nexport const PilotCoderTriggerRefSchema = z.discriminatedUnion(\"type\", [\n z\n .object({\n type: z.literal(\"github_issue\"),\n number: z.number().int().positive(),\n commentId: z.number().int().positive().optional(),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"github_pr\"),\n number: z.number().int().positive(),\n commentId: z.number().int().positive().optional(),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"gitlab_issue\"),\n iid: z.number().int().positive(),\n noteId: z.number().int().positive().optional(),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"gitlab_mr\"),\n iid: z.number().int().positive(),\n noteId: z.number().int().positive().optional(),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"jira_issue\"),\n key: z.string().min(1),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"schedule\"),\n scheduleId: z.string().min(1),\n })\n .strict(),\n z\n .object({\n type: z.literal(\"opaque\"),\n value: z.string().min(1),\n })\n .strict(),\n]);\nexport type PilotCoderTriggerRef = z.infer<typeof PilotCoderTriggerRefSchema>;\n\n/**\n * Run-scoped configuration shared by prompt / followup / restore payloads.\n * Maps directly from v1 `PromptRequestSchema` fields that the agent-worker\n * needs to spin up an AI provider + tools + workspace.\n *\n * `agentId` / `runId` are echoed back into business events so control-plane\n * can correlate the v2 Worker Protocol path to its v1-era run/agent records.\n */\nexport const PilotCoderRunConfigV1Schema = z\n .object({\n runId: z.string().min(1),\n agentId: z.string().min(1),\n provider: ProviderTypeSchema.optional(),\n model: z.string().optional(),\n /**\n * Phase D — per-agent system prompt. Sourced by control-worker from\n * `agents.system_prompt` (seeded from a managed_agent profile's\n * `spec.systemPrompt` workload default). When present, agent-worker\n * uses it verbatim as the LLM `system` prompt **instead of** the\n * platform-level `SYSTEM_PROMPT` / `SYSTEM_PROMPT_GENERAL` fallback\n * (`getSystemPrompt(projectKind)`); when absent the platform default\n * is used, so v1 payloads stay backward-compatible.\n *\n * Routed per-run via the dispatch payload (not worker env) so multiple\n * workloads sharing a pod stay cleanly isolated. Deployment ordering:\n * contracts ship first (both control-worker and agent-worker must\n * recognize this key before control-worker starts populating it), since\n * `PilotCoderRunConfigV1Schema` is `.strict()`.\n */\n systemPrompt: z.string().min(1).optional(),\n workspacePath: z.string().optional(),\n mcpConfigDir: z.string().optional(),\n attachments: z.array(AttachmentMetaSchema).max(5).optional(),\n triggerContext: WebhookTriggerContextSchema.optional(),\n mcpServers: McpServersMapSchema.optional(),\n env: z.record(z.string(), z.string()).optional(),\n projectKind: ProjectKindSchema.optional(),\n /**\n * v2-only — resolved skill artifact list, populated by\n * control-plane `v2McpResolve` (see `apps/control-worker/src/worker.ts`).\n * Each entry MUST be fully resolved (i.e. the legacy `EnabledSkill`\n * shape with `resolvedArtifact`) — refs (`EnabledSkillRef`) are\n * lookup-time-only and never travel on the wire.\n *\n * Agent-worker `run-agent-loop.ts` consumes this list and invokes\n * `@pilot/skills` `ensureSkillsInstalled` to materialize each\n * skill under `$HOME/.claude/skills/<dir>/` (claude-code provider)\n * or `$HOME/.codex/skills/<dir>/` (codex provider) before the LLM\n * loop spins up.\n *\n * In v1 this work was done by `mcpSkillsBootstrap` against the\n * sandbox SDK; v2 sandboxes live in a separate namespace and that\n * SDK 404s on them, so installation moved into the in-sandbox\n * agent-worker process. See `specs/features/pilot-v2-sdk-worker-substrate-api.md`\n * for the namespace rationale.\n */\n skills: z.array(EnabledSkillSchema).optional(),\n skillsInstall: PilotCoderSkillsInstallSchema.optional(),\n /**\n * P3 L3.3 — delivery-related fields populated by control-worker from\n * `runs.*` / `agents.*` columns so the worker delivery loop can act\n * without re-querying control-plane. All fields are optional: v1\n * payloads predate L3.3 and senders without delivery (e.g. interactive\n * chat sessions) MUST still encode successfully.\n *\n * `repoUrl` mirrors `runs.repo_url` (nullable; omitted when null).\n * `baseBranch` is the PR/MR target branch (sourced from\n * `agents.base_ref` or `runs.target_ref` per dispatch site choice).\n * `triggerSource` mirrors `runs.trigger_source`. `triggerRef` is the\n * structured / parsed form of `runs.trigger_ref`. `prTitle` /\n * `prTemplate` are user / trigger-source specified overrides for the\n * delivery PR description; if neither column / setting exists yet on\n * the v1 data model, the dispatcher omits them (forward-compat).\n */\n repoUrl: z.string().min(1).optional(),\n baseBranch: z.string().min(1).optional(),\n triggerSource: TriggerSourceSchema.optional(),\n triggerRef: PilotCoderTriggerRefSchema.optional(),\n prTitle: z.string().min(1).optional(),\n prTemplate: z.string().min(1).optional(),\n })\n .strict();\nexport type PilotCoderRunConfigV1 = z.infer<typeof PilotCoderRunConfigV1Schema>;\n\nexport const PilotCoderPromptPayloadV1Schema = z\n .object({\n schemaVersion: z.literal(\"v1\"),\n kind: z.literal(\"prompt\"),\n prompt: z.string().min(1),\n config: PilotCoderRunConfigV1Schema,\n })\n .strict();\nexport type PilotCoderPromptPayloadV1 = z.infer<typeof PilotCoderPromptPayloadV1Schema>;\n\nexport const PilotCoderFollowupPayloadV1Schema = z\n .object({\n schemaVersion: z.literal(\"v1\"),\n kind: z.literal(\"followup\"),\n message: z.string().min(1),\n config: PilotCoderRunConfigV1Schema,\n expectedMessagesHash: z.string().optional(),\n expectedMessagesCount: z.number().int().nonnegative().optional(),\n })\n .strict();\nexport type PilotCoderFollowupPayloadV1 = z.infer<typeof PilotCoderFollowupPayloadV1Schema>;\n\nexport const PilotCoderRestorePayloadV1Schema = z\n .object({\n schemaVersion: z.literal(\"v1\"),\n kind: z.literal(\"restore\"),\n config: PilotCoderRunConfigV1Schema,\n messages: z.array(z.unknown()),\n messagesHash: z.string().min(1),\n lastEventId: z.number().int().nonnegative().optional(),\n pendingToolCalls: z.array(z.unknown()).optional(),\n workspaceHydrationRef: z.string().optional(),\n runtimeProfileSnapshot: z.record(z.unknown()).optional(),\n degradedRecovery: z.boolean().optional(),\n })\n .strict();\nexport type PilotCoderRestorePayloadV1 = z.infer<typeof PilotCoderRestorePayloadV1Schema>;\n\n// ---------------------------------------------------------------------------\n// Encode / decode helpers\n//\n// Encoders are total functions over their input type. Decoders take untrusted\n// bytes from the wire envelope and return a discriminated error when parsing\n// fails so call sites can map to `wp_invalid_envelope` / `wp_handler_error`\n// failure reasons (R-MAH spec) without throwing into the framework's\n// auto-emit guard.\n// ---------------------------------------------------------------------------\n\nexport type PilotCoderDecodeErrorCode =\n | \"INVALID_JSON\"\n | \"SCHEMA_MISMATCH\"\n | \"UNSUPPORTED_SCHEMA_VERSION\";\n\nexport class PilotCoderPayloadDecodeError extends Error {\n readonly code: PilotCoderDecodeErrorCode;\n readonly issues?: z.ZodIssue[];\n\n constructor(code: PilotCoderDecodeErrorCode, message: string, issues?: z.ZodIssue[]) {\n super(message);\n this.name = \"PilotCoderPayloadDecodeError\";\n this.code = code;\n this.issues = issues;\n }\n}\n\n/**\n * Recognized payload schema versions. When we add `v2`, this is the only\n * union we mutate — `decode*` keep working for older versions until the\n * cutover.\n */\nexport const PILOT_CODER_PAYLOAD_SCHEMA_VERSIONS = [\"v1\"] as const;\nexport type PilotCoderPayloadSchemaVersion = (typeof PILOT_CODER_PAYLOAD_SCHEMA_VERSIONS)[number];\n\nfunction parseAsJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch (err) {\n throw new PilotCoderPayloadDecodeError(\n \"INVALID_JSON\",\n `Pilot Coder payload is not valid JSON: ${(err as Error).message}`,\n );\n }\n}\n\nfunction checkSchemaVersion(parsed: unknown): void {\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n !(\"schemaVersion\" in parsed) ||\n typeof (parsed as { schemaVersion: unknown }).schemaVersion !== \"string\"\n ) {\n throw new PilotCoderPayloadDecodeError(\n \"SCHEMA_MISMATCH\",\n \"Pilot Coder payload is missing required string field `schemaVersion`\",\n );\n }\n const version = (parsed as { schemaVersion: string }).schemaVersion;\n if (!(PILOT_CODER_PAYLOAD_SCHEMA_VERSIONS as readonly string[]).includes(version)) {\n throw new PilotCoderPayloadDecodeError(\n \"UNSUPPORTED_SCHEMA_VERSION\",\n `Pilot Coder payload schemaVersion '${version}' is not supported by this SDK. Supported: ${PILOT_CODER_PAYLOAD_SCHEMA_VERSIONS.join(\", \")}.`,\n );\n }\n}\n\nfunction zodParseOrThrow<T extends z.ZodTypeAny>(\n schema: T,\n parsed: unknown,\n label: string,\n): z.infer<T> {\n const result = schema.safeParse(parsed);\n if (!result.success) {\n throw new PilotCoderPayloadDecodeError(\n \"SCHEMA_MISMATCH\",\n `Pilot Coder ${label} payload failed schema validation: ${result.error.message}`,\n result.error.issues,\n );\n }\n return result.data;\n}\n\nexport function encodePilotCoderPromptPayloadV1(payload: PilotCoderPromptPayloadV1): string {\n return JSON.stringify(PilotCoderPromptPayloadV1Schema.parse(payload));\n}\n\nexport function decodePilotCoderPromptPayloadV1(text: string): PilotCoderPromptPayloadV1 {\n const parsed = parseAsJson(text);\n checkSchemaVersion(parsed);\n return zodParseOrThrow(PilotCoderPromptPayloadV1Schema, parsed, \"prompt\");\n}\n\nexport function encodePilotCoderFollowupPayloadV1(payload: PilotCoderFollowupPayloadV1): string {\n return JSON.stringify(PilotCoderFollowupPayloadV1Schema.parse(payload));\n}\n\nexport function decodePilotCoderFollowupPayloadV1(text: string): PilotCoderFollowupPayloadV1 {\n const parsed = parseAsJson(text);\n checkSchemaVersion(parsed);\n return zodParseOrThrow(PilotCoderFollowupPayloadV1Schema, parsed, \"followup\");\n}\n\nexport function encodePilotCoderRestorePayloadV1(payload: PilotCoderRestorePayloadV1): string {\n return JSON.stringify(PilotCoderRestorePayloadV1Schema.parse(payload));\n}\n\nexport function decodePilotCoderRestorePayloadV1(text: string): PilotCoderRestorePayloadV1 {\n const parsed = parseAsJson(text);\n checkSchemaVersion(parsed);\n return zodParseOrThrow(PilotCoderRestorePayloadV1Schema, parsed, \"restore\");\n}\n","/**\n * Pilot v2 Gateway — stable error code schema (PR-2 of #518 implementation).\n *\n * Authoritative source: `specs/features/pilot-v2-gateway-mcp-proxy.md` §6\n * (Gateway error codes stable enum).\n *\n * These codes are stable — never rename or remove once shipped.\n * HTTP status mappings are defined in the spec §6 error code matrix;\n * this module only carries the Zod schema + TypeScript type.\n */\nimport { z } from \"zod\";\n\nexport const GatewayErrorCodeSchema = z.enum([\n \"gateway_invalid_session_token\",\n \"gateway_session_not_found\",\n \"gateway_missing_mcp_target\",\n \"gateway_invalid_mcp_target\",\n \"gateway_invalid_mcp_method\",\n \"gateway_not_a_mcp_path\",\n \"gateway_mcp_target_not_allowed\",\n \"gateway_vault_unreachable\",\n \"gateway_credential_refresh_failed\",\n \"gateway_credential_refresh_timeout\",\n \"gateway_upstream_unreachable\",\n \"gateway_upstream_error\",\n \"gateway_upstream_timeout\",\n \"gateway_request_too_large\",\n \"gateway_response_too_large\",\n]);\nexport type GatewayErrorCode = z.infer<typeof GatewayErrorCodeSchema>;\n","/**\n * Contracts for outbound webhooks (Issue #444).\n *\n * Subscription management API:\n *\n * POST /api/webhook-subscriptions\n * GET /api/webhook-subscriptions?projectId=...\n * PATCH /api/webhook-subscriptions/:id\n * DELETE /api/webhook-subscriptions/:id\n * POST /api/webhook-subscriptions/:id/rotate-secret\n * Authorization: Bearer <PILOT_PLATFORM_TOKEN>\n *\n * Authoritative behavior: `specs/features/pilot-v2-outbound-webhooks.md`.\n *\n * Delivery protocol (consumer-facing):\n * - at-least-once, NO ordering guarantee — consumers MUST be idempotent\n * keyed on `event_id`.\n * - id-only payload: no business data crosses the webhook boundary;\n * consumers call the Platform API (`GET /api/agents/:id`,\n * `GET /api/sessions/:id`, artifacts routes) to fetch current state.\n * - HMAC-SHA256 signature header (see `OUTBOUND_WEBHOOK_SIGNATURE_HEADER`).\n *\n * Event-type namespace note: `WebhookEventTypeSchema` is an INDEPENDENT\n * external protocol enum. It intentionally reuses the\n * `session.status_ready` / `session.status_failed` literals from the\n * internal event taxonomy (`specs/features/pilot-v2-event-taxonomy.md`)\n * but is NOT the same enum as `session_events.event_type` — the\n * webhook surface only ever exposes the members below, and the\n * `run.*` domain exists only on this external surface.\n */\n\nimport { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Event types\n// ---------------------------------------------------------------------------\n\nexport const WebhookEventTypeSchema = z.enum([\n /** v1/v2 Run reached terminal `completed`. */\n \"run.completed\",\n /** v1/v2 Run reached terminal `failed`. */\n \"run.failed\",\n /** v2 Session startup reached terminal `ready`. */\n \"session.status_ready\",\n /** v2 Session startup reached terminal `failed`. */\n \"session.status_failed\",\n /** v2 Session post-ready lifecycle entered `idle`. */\n \"session.lifecycle_idle\",\n /** v2 Session post-ready lifecycle entered `terminating`. */\n \"session.lifecycle_terminating\",\n /** v2 Session post-ready lifecycle reached `terminated`. */\n \"session.lifecycle_terminated\",\n]);\nexport type WebhookEventType = z.infer<typeof WebhookEventTypeSchema>;\n\nexport const WEBHOOK_EVENT_TYPES = WebhookEventTypeSchema.options;\n\n// ---------------------------------------------------------------------------\n// Delivery payload (id-only)\n// ---------------------------------------------------------------------------\n\n/**\n * The JSON body POSTed to the subscriber endpoint. Deliberately carries\n * identifiers only; `event_id` is deterministic\n * (`run:{runId}:{status}` / `session:{sessionId}:{status}`) so replays\n * of the same logical transition produce the same id.\n */\nexport const WebhookEventPayloadSchema = z\n .object({\n event_id: z.string().min(1).max(255),\n event_type: WebhookEventTypeSchema,\n /** ISO-8601 instant at which the transition was recorded. */\n occurred_at: z.string(),\n project_id: z.string().uuid(),\n run_id: z.string().uuid().optional(),\n agent_id: z.string().uuid().optional(),\n session_id: z.string().uuid().optional(),\n lifecycle_phase: z.enum([\"idle\", \"terminating\", \"terminated\"]).optional(),\n lifecycle_transition_id: z.string().uuid().optional(),\n idle_since: z.string().optional(),\n grace_deadline: z.string().optional(),\n reason: z.string().optional(),\n terminate_deadline: z.string().optional(),\n })\n .strict();\nexport type WebhookEventPayload = z.infer<typeof WebhookEventPayloadSchema>;\n\n// ---------------------------------------------------------------------------\n// Signature protocol\n// ---------------------------------------------------------------------------\n\n/**\n * Header carrying the request signature, in the form:\n *\n * X-Pilot-Webhook-Signature: t=<unix_seconds>,v1=<hex>\n *\n * where `<hex>` = HMAC_SHA256(secret, `${t}.${rawBody}`). Consumers MUST\n * verify with a constant-time comparison and SHOULD reject timestamps\n * older than 5 minutes to bound replay windows.\n */\nexport const OUTBOUND_WEBHOOK_SIGNATURE_HEADER = \"x-pilot-webhook-signature\";\n\n/** Prefix of every server-generated webhook secret (aids leak scanning). */\nexport const WEBHOOK_SECRET_PREFIX = \"pilot_whsec_\";\n\n// ---------------------------------------------------------------------------\n// Subscription CRUD\n// ---------------------------------------------------------------------------\n\nexport const WebhookSubscriptionStatusSchema = z.enum([\"active\", \"disabled\"]);\nexport type WebhookSubscriptionStatus = z.infer<typeof WebhookSubscriptionStatusSchema>;\n\nexport const CreateWebhookSubscriptionRequestSchema = z\n .object({\n projectId: z.string().uuid(),\n /** Subscriber endpoint. https required outside dev; SSRF-validated. */\n url: z.string().url().max(1024),\n /** Event types to deliver. At least one. */\n events: z.array(WebhookEventTypeSchema).min(1).max(WEBHOOK_EVENT_TYPES.length),\n /** Optional operator note shown in list responses. */\n description: z.string().max(512).optional(),\n })\n .strict();\nexport type CreateWebhookSubscriptionRequest = z.infer<\n typeof CreateWebhookSubscriptionRequestSchema\n>;\n\nexport const UpdateWebhookSubscriptionRequestSchema = z\n .object({\n url: z.string().url().max(1024).optional(),\n events: z.array(WebhookEventTypeSchema).min(1).max(WEBHOOK_EVENT_TYPES.length).optional(),\n description: z.string().max(512).nullable().optional(),\n /**\n * `active` re-enables a subscription that was auto-disabled after\n * consecutive failures (resets the failure counter); `disabled`\n * pauses delivery without deleting history.\n */\n status: WebhookSubscriptionStatusSchema.optional(),\n })\n .strict()\n .refine(\n (data) =>\n data.url !== undefined ||\n data.events !== undefined ||\n data.description !== undefined ||\n data.status !== undefined,\n { message: \"At least one of url / events / description / status MUST be provided\" },\n );\nexport type UpdateWebhookSubscriptionRequest = z.infer<\n typeof UpdateWebhookSubscriptionRequestSchema\n>;\n\n/** Public projection of a subscription row. Never includes the secret. */\nexport const WebhookSubscriptionSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n url: z.string(),\n events: z.array(WebhookEventTypeSchema),\n description: z.string().nullable(),\n status: WebhookSubscriptionStatusSchema,\n consecutiveFailures: z.number().int().nonnegative(),\n createdBy: z.string(),\n createdAt: z.string(),\n updatedAt: z.string(),\n});\nexport type WebhookSubscription = z.infer<typeof WebhookSubscriptionSchema>;\n\n/**\n * Create / rotate-secret response — the ONLY places the plaintext secret\n * is ever returned. It is stored encrypted at rest and cannot be read\n * back; rotation generates a new secret that takes effect immediately\n * (no dual-secret grace window — see spec).\n */\nexport const WebhookSubscriptionWithSecretSchema = z.object({\n subscription: WebhookSubscriptionSchema,\n secret: z.string(),\n});\nexport type WebhookSubscriptionWithSecret = z.infer<typeof WebhookSubscriptionWithSecretSchema>;\n\n// ---------------------------------------------------------------------------\n// Error codes\n// ---------------------------------------------------------------------------\n\nexport const WebhookSubscriptionErrorCodeSchema = z.enum([\n // 400\n \"VALIDATION_ERROR\",\n /** URL failed SSRF policy (non-https, private/loopback/link-local IP…). */\n \"WEBHOOK_URL_FORBIDDEN\",\n // 404\n \"SUBSCRIPTION_NOT_FOUND\",\n \"PROJECT_NOT_FOUND\",\n // 409\n \"SUBSCRIPTION_LIMIT_EXCEEDED\",\n // 500\n \"INTERNAL_ERROR\",\n]);\nexport type WebhookSubscriptionErrorCode = z.infer<typeof WebhookSubscriptionErrorCodeSchema>;\n\nexport const WEBHOOK_SUBSCRIPTION_ERROR_STATUS: Record<WebhookSubscriptionErrorCode, number> = {\n VALIDATION_ERROR: 400,\n WEBHOOK_URL_FORBIDDEN: 400,\n SUBSCRIPTION_NOT_FOUND: 404,\n PROJECT_NOT_FOUND: 404,\n SUBSCRIPTION_LIMIT_EXCEEDED: 409,\n INTERNAL_ERROR: 500,\n};\n\n/** Per-project cap on active+disabled subscriptions (MVP guard rail). */\nexport const MAX_WEBHOOK_SUBSCRIPTIONS_PER_PROJECT = 10;\n","import { z } from \"zod\";\n\nexport const SessionPrewarmingIdentitySchema = z\n .object({\n projectIdGenerator: z.literal(\"nanoid\"),\n claimNameTemplate: z.string().min(1),\n idempotencyScopePrefix: z.string().min(1),\n })\n .strict();\n\nexport const SessionPrewarmingSessionTemplateSchema = z\n .object({\n configValues: z.record(z.string(), z.string()),\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n .strict();\n\nexport const BusinessReadyProbeSchema = z\n .object({\n endpointName: z.enum([\"api\", \"preview\"]),\n path: z.string().min(1),\n successCodes: z.array(z.number().int().min(100).max(599)).min(1),\n timeoutMs: z.number().int().min(500).max(30_000),\n })\n .strict();\n\nexport const SessionPrewarmingSpecSchema = z\n .object({\n targetReadyCount: z.number().int().min(1).max(50),\n reVerifyIntervalSeconds: z.number().int().min(60).max(3600),\n warmingTimeoutSeconds: z.number().int().min(60).max(600),\n claimingLeaseTtlSeconds: z.number().int().min(10).max(120),\n replenishIntervalSeconds: z.number().int().min(5).max(300),\n maxConcurrentWarming: z.number().int().min(1).max(10),\n identity: SessionPrewarmingIdentitySchema,\n sessionTemplate: SessionPrewarmingSessionTemplateSchema,\n businessReadyProbe: BusinessReadyProbeSchema.optional(),\n })\n .strict();\n\nexport type SessionPrewarmingSpec = z.infer<typeof SessionPrewarmingSpecSchema>;\nexport type BusinessReadyProbe = z.infer<typeof BusinessReadyProbeSchema>;\n\nexport const POOL_SLOT_STATUSES = [\n \"warming\",\n \"ready\",\n \"claiming\",\n \"acquired\",\n \"released\",\n \"failed\",\n \"expired\",\n] as const;\n\nexport type PoolSlotStatus = (typeof POOL_SLOT_STATUSES)[number];\n\nexport const AcquireSessionRequestSchema = z\n .object({\n workloadId: z.string().uuid(),\n clientMutationId: z.string().min(1).max(255),\n })\n .strict();\n\nexport type AcquireSessionRequest = z.infer<typeof AcquireSessionRequestSchema>;\n\nexport const AcquireSessionResponseSchema = z\n .object({\n leaseToken: z.string().min(1),\n leaseExpiresAt: z.string().datetime(),\n sessionId: z.string().uuid(),\n projectId: z.string().min(1),\n runtimeClaimName: z.string().min(1),\n configValues: z.record(z.string(), z.string()),\n apiUrl: z.string().url(),\n previewUrl: z.string().url().optional(),\n })\n .strict();\n\nexport type AcquireSessionResponse = z.infer<typeof AcquireSessionResponseSchema>;\n\nexport const FinalizeAcquireRequestSchema = z\n .object({\n leaseToken: z.string().min(1),\n sessionId: z.string().uuid(),\n clientMutationId: z.string().min(1).max(255).optional(),\n })\n .strict();\n\nexport type FinalizeAcquireRequest = z.infer<typeof FinalizeAcquireRequestSchema>;\n\nexport const AbortAcquireRequestSchema = z\n .object({\n leaseToken: z.string().min(1),\n sessionId: z.string().uuid(),\n })\n .strict();\n\nexport type AbortAcquireRequest = z.infer<typeof AbortAcquireRequestSchema>;\n\nexport interface PoolStatusEntry {\n workloadId: string;\n workloadSlug: string;\n fdcEnabled: boolean;\n generation: number;\n runtimeFingerprint: string;\n target: number;\n counts: {\n ready: number;\n warming: number;\n claiming: number;\n acquired: number;\n released: number;\n failed: number;\n expired: number;\n };\n oldestReadyAge: string | null;\n activeLeasesCount: number;\n failedReasons: Array<{ reason: string; count: number }>;\n timing: {\n lastReplenishAt: string | null;\n lastAcquireAt: string | null;\n lastFinalizeAt: string | null;\n lastDrainAt: string | null;\n lastReclaimAt: string | null;\n };\n queuedWarmingJobs: number;\n unreclaimedTerminalSlots: number;\n}\n","import { z } from \"zod\";\n\nexport const DEFAULT_MANAGED_AGENT_IDLE_ENABLED = true;\nexport const DEFAULT_SELF_MANAGED_IDLE_ENABLED = false;\nexport const DEFAULT_IDLE_AFTER_SECONDS = 1_800;\nexport const DEFAULT_IDLE_GRACE_SECONDS = 300;\nexport const DEFAULT_MAX_SESSION_LIFETIME_MS = 86_400_000;\n\nexport const WorkloadLifecycleKindSchema = z.enum([\"managed_agent\", \"self_managed\"]);\nexport type WorkloadLifecycleKind = z.infer<typeof WorkloadLifecycleKindSchema>;\n\nexport const WorkloadLifecycleConfigSchema = z\n .object({\n idleEnabled: z.boolean().nullable(),\n idleAfterSeconds: z.number().int().min(300).max(86_400).nullable(),\n idleGraceSeconds: z.number().int().min(60).max(3_600).nullable(),\n maxSessionLifetimeMs: z.number().int().min(3_600_000).max(604_800_000).nullable(),\n })\n .strict();\n\nexport type WorkloadLifecycleConfig = z.infer<typeof WorkloadLifecycleConfigSchema>;\n\nexport const WorkloadLifecycleConfigUpdateSchema = WorkloadLifecycleConfigSchema.partial().strict();\nexport type WorkloadLifecycleConfigUpdate = z.infer<typeof WorkloadLifecycleConfigUpdateSchema>;\n\nexport const EffectiveWorkloadLifecycleConfigSchema = z\n .object({\n idleEnabled: z.boolean(),\n idleAfterSeconds: z.number().int().min(300).max(86_400),\n idleGraceSeconds: z.number().int().min(60).max(3_600),\n maxSessionLifetimeMs: z.number().int().min(3_600_000).max(604_800_000),\n })\n .strict();\n\nexport type EffectiveWorkloadLifecycleConfig = z.infer<\n typeof EffectiveWorkloadLifecycleConfigSchema\n>;\n\nexport const WorkloadLifecycleConfigResponseSchema = z\n .object({\n workloadId: z.string().uuid(),\n kind: WorkloadLifecycleKindSchema,\n config: WorkloadLifecycleConfigSchema,\n effective: EffectiveWorkloadLifecycleConfigSchema,\n })\n .strict();\n\nexport type WorkloadLifecycleConfigResponse = z.infer<typeof WorkloadLifecycleConfigResponseSchema>;\n\nexport function resolveWorkloadLifecycleConfig(\n kind: WorkloadLifecycleKind,\n config: WorkloadLifecycleConfig,\n): EffectiveWorkloadLifecycleConfig {\n return {\n idleEnabled:\n config.idleEnabled ??\n (kind === \"self_managed\"\n ? DEFAULT_SELF_MANAGED_IDLE_ENABLED\n : DEFAULT_MANAGED_AGENT_IDLE_ENABLED),\n idleAfterSeconds: config.idleAfterSeconds ?? DEFAULT_IDLE_AFTER_SECONDS,\n idleGraceSeconds: config.idleGraceSeconds ?? DEFAULT_IDLE_GRACE_SECONDS,\n maxSessionLifetimeMs: config.maxSessionLifetimeMs ?? DEFAULT_MAX_SESSION_LIFETIME_MS,\n };\n}\n","import { z } from \"zod\";\n\nconst UuidSchema = z.string().uuid();\n\nconst NonEmptyUuidArraySchema = z.array(UuidSchema).min(1).max(200);\n\nconst CleanupPrefixSchema = z\n .string()\n .trim()\n .min(5)\n .max(128)\n .regex(\n /^(?:e2e|tmp|test|cc)-[A-Za-z0-9][A-Za-z0-9._:-]*$/,\n \"prefix must start with an allowed cleanup namespace: e2e-, tmp-, test-, or cc-\",\n );\n\nexport const SessionTerminateRequestSchema = z\n .object({\n reason: z.string().trim().min(1).max(50).default(\"api\"),\n deadlineAt: z.string().datetime().optional(),\n requireNoActiveWork: z.boolean().default(true),\n })\n .strict();\nexport type SessionTerminateRequest = z.infer<typeof SessionTerminateRequestSchema>;\n\nexport const ResourceCleanupSelectorSchema = z\n .object({\n projectId: UuidSchema,\n prefix: CleanupPrefixSchema.optional(),\n workloadIds: NonEmptyUuidArraySchema.optional(),\n runtimeTemplateIds: NonEmptyUuidArraySchema.optional(),\n sessionIds: NonEmptyUuidArraySchema.optional(),\n })\n .strict()\n .superRefine((value, ctx) => {\n if (\n !value.prefix &&\n !value.workloadIds?.length &&\n !value.runtimeTemplateIds?.length &&\n !value.sessionIds?.length\n ) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"cleanup selector must include prefix or explicit ids\",\n path: [\"prefix\"],\n });\n }\n });\nexport type ResourceCleanupSelector = z.infer<typeof ResourceCleanupSelectorSchema>;\n\nexport const ResourceCleanupPlanRequestSchema = z\n .object({\n selector: ResourceCleanupSelectorSchema,\n })\n .strict();\nexport type ResourceCleanupPlanRequest = z.infer<typeof ResourceCleanupPlanRequestSchema>;\n\nexport const ResourceCleanupExecuteRequestSchema = z\n .object({\n selector: ResourceCleanupSelectorSchema,\n expectedCleanupId: z.string().min(16).max(64),\n confirm: z.literal(true),\n terminateActiveSessions: z.boolean().default(true),\n requireNoActiveWork: z.boolean().default(true),\n })\n .strict();\nexport type ResourceCleanupExecuteRequest = z.infer<typeof ResourceCleanupExecuteRequestSchema>;\n\nexport const ResourceCleanupResourceTypeSchema = z.enum([\n \"agents_session_refs\",\n \"runs_session_refs\",\n \"session_pool_slots\",\n \"session_pool_configs\",\n \"worker_protocol_jobs\",\n \"schedule_triggers\",\n \"schedule_definitions\",\n \"session_vault_bindings\",\n \"session_config_values\",\n \"session_tokens\",\n \"session_events\",\n \"session_startup_jobs\",\n \"session_failure_reasons\",\n \"startup_gate_conditions\",\n \"runtime_bindings\",\n \"sessions\",\n \"revision_config_values\",\n \"revisions\",\n \"workloads\",\n \"runtime_templates\",\n]);\nexport type ResourceCleanupResourceType = z.infer<typeof ResourceCleanupResourceTypeSchema>;\n\nexport const ResourceCleanupBlockerSchema = z\n .object({\n code: z.string(),\n resourceType: z.string(),\n resourceId: z.string(),\n message: z.string(),\n })\n .strict();\nexport type ResourceCleanupBlocker = z.infer<typeof ResourceCleanupBlockerSchema>;\n\nexport const ResourceCleanupStepSchema = z\n .object({\n resourceType: ResourceCleanupResourceTypeSchema,\n action: z.enum([\"delete\", \"update_null\"]),\n count: z.number().int().nonnegative(),\n ids: z.array(z.string()),\n })\n .strict();\nexport type ResourceCleanupStep = z.infer<typeof ResourceCleanupStepSchema>;\n\nexport const ResourceCleanupResourceIdsSchema = z\n .object({\n workloadIds: z.array(UuidSchema),\n runtimeTemplateIds: z.array(UuidSchema),\n revisionIds: z.array(UuidSchema),\n sessionIds: z.array(UuidSchema),\n runtimeBindingIds: z.array(UuidSchema),\n sessionPoolSlotIds: z.array(UuidSchema),\n sessionPoolConfigWorkloadIds: z.array(UuidSchema),\n scheduleDefinitionIds: z.array(UuidSchema),\n scheduleTriggerIds: z.array(UuidSchema),\n runSessionRefIds: z.array(UuidSchema),\n agentSessionRefIds: z.array(UuidSchema),\n workerProtocolJobIds: z.array(UuidSchema),\n })\n .strict();\nexport type ResourceCleanupResourceIds = z.infer<typeof ResourceCleanupResourceIdsSchema>;\n\nexport const ResourceCleanupPlanSchema = z\n .object({\n cleanupId: z.string(),\n generatedAt: z.string().datetime(),\n selector: ResourceCleanupSelectorSchema,\n resources: ResourceCleanupResourceIdsSchema,\n counts: z.record(ResourceCleanupResourceTypeSchema, z.number().int().nonnegative()),\n steps: z.array(ResourceCleanupStepSchema),\n blockers: z.array(ResourceCleanupBlockerSchema),\n })\n .strict();\nexport type ResourceCleanupPlan = z.infer<typeof ResourceCleanupPlanSchema>;\n\nexport const ResourceCleanupExecuteResultSchema = z\n .object({\n cleanupId: z.string(),\n deletedCounts: z.record(ResourceCleanupResourceTypeSchema, z.number().int().nonnegative()),\n updatedCounts: z.record(ResourceCleanupResourceTypeSchema, z.number().int().nonnegative()),\n terminatedSessions: z.array(UuidSchema),\n readback: ResourceCleanupPlanSchema,\n })\n .strict();\nexport type ResourceCleanupExecuteResult = z.infer<typeof ResourceCleanupExecuteResultSchema>;\n","export interface PilotPlatformApiErrorOptions {\n status: number;\n code: string;\n message?: string;\n requestId?: string;\n cause?: unknown;\n}\n\nexport class PilotPlatformApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly requestId?: string;\n\n constructor(options: PilotPlatformApiErrorOptions) {\n super(options.message ?? `${options.code} (HTTP ${options.status})`, {\n cause: options.cause,\n });\n this.name = \"PilotPlatformApiError\";\n this.status = options.status;\n this.code = options.code;\n this.requestId = options.requestId;\n }\n}\n\nexport class PilotPlatformUnauthenticatedError extends PilotPlatformApiError {\n constructor(options: Omit<PilotPlatformApiErrorOptions, \"status\">) {\n super({ ...options, status: 401 });\n this.name = \"PilotPlatformUnauthenticatedError\";\n }\n}\n\nexport class PilotPlatformForbiddenError extends PilotPlatformApiError {\n constructor(options: Omit<PilotPlatformApiErrorOptions, \"status\">) {\n super({ ...options, status: 403 });\n this.name = \"PilotPlatformForbiddenError\";\n }\n}\n\nexport class PilotPlatformNotFoundError extends PilotPlatformApiError {\n constructor(options: Omit<PilotPlatformApiErrorOptions, \"status\">) {\n super({ ...options, status: 404 });\n this.name = \"PilotPlatformNotFoundError\";\n }\n}\n\nexport class PilotPlatformServerError extends PilotPlatformApiError {\n constructor(options: PilotPlatformApiErrorOptions) {\n super(options);\n this.name = \"PilotPlatformServerError\";\n }\n}\n\nexport function pilotPlatformErrorFromResponse(params: {\n status: number;\n body: unknown;\n requestId?: string;\n}): PilotPlatformApiError {\n const parsed = extractErrorBody(params.body);\n const code = parsed.code ?? defaultCodeForStatus(params.status);\n const message = parsed.message ?? parsed.error;\n const base = { code, message, requestId: params.requestId };\n\n if (params.status === 401) return new PilotPlatformUnauthenticatedError(base);\n if (params.status === 403) return new PilotPlatformForbiddenError(base);\n if (params.status === 404) return new PilotPlatformNotFoundError(base);\n if (params.status >= 500 && params.status < 600) {\n return new PilotPlatformServerError({ ...base, status: params.status });\n }\n return new PilotPlatformApiError({ ...base, status: params.status });\n}\n\nfunction extractErrorBody(body: unknown): {\n error?: string;\n code?: string;\n message?: string;\n} {\n if (!body || typeof body !== \"object\") return {};\n const record = body as Record<string, unknown>;\n return {\n error: typeof record.error === \"string\" ? record.error : undefined,\n code: typeof record.code === \"string\" ? record.code : undefined,\n message: typeof record.message === \"string\" ? record.message : undefined,\n };\n}\n\nfunction defaultCodeForStatus(status: number): string {\n if (status === 401) return \"UNAUTHENTICATED\";\n if (status === 403) return \"FORBIDDEN\";\n if (status === 404) return \"NOT_FOUND\";\n if (status >= 500) return \"SERVER_ERROR\";\n return \"REQUEST_FAILED\";\n}\n","import {\n type CreatePlatformProjectRequest,\n CreatePlatformProjectRequestSchema,\n ListPlatformProjectsResponseSchema,\n type PlatformProject,\n PlatformProjectSchema,\n} from \"@pilot/contracts\";\n\nimport type { PilotPlatformClient } from \"../client\";\n\nexport class ProjectsResource {\n constructor(private readonly client: PilotPlatformClient) {}\n\n async create(\n request: CreatePlatformProjectRequest,\n options: { signal?: AbortSignal } = {},\n ): Promise<PlatformProject> {\n const body = CreatePlatformProjectRequestSchema.parse(request);\n const response = await this.client.request<unknown>(\"/api/projects\", {\n method: \"POST\",\n body,\n signal: options.signal,\n });\n return PlatformProjectSchema.parse(response);\n }\n\n async list(options: { signal?: AbortSignal } = {}): Promise<PlatformProject[]> {\n const response = await this.client.request<unknown>(\"/api/projects\", {\n method: \"GET\",\n signal: options.signal,\n });\n return ListPlatformProjectsResponseSchema.parse(response).projects;\n }\n\n async get(projectId: string, options: { signal?: AbortSignal } = {}): Promise<PlatformProject> {\n const response = await this.client.request<unknown>(\n `/api/projects/${encodeURIComponent(projectId)}`,\n {\n method: \"GET\",\n signal: options.signal,\n cache: \"no-store\",\n },\n );\n return PlatformProjectSchema.parse(response);\n }\n}\n","import {\n type CreatePlatformSessionRequest,\n CreatePlatformSessionRequestSchema,\n type CreatePlatformSessionResponse,\n CreatePlatformSessionResponseSchema,\n} from \"@pilot/contracts\";\n\nimport type { PilotPlatformClient } from \"../client\";\nimport { PilotPlatformApiError } from \"../errors\";\n\nexport interface SessionSnapshotResponse {\n session?: {\n id?: string;\n status?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\nexport interface WaitForSessionOptions {\n intervalMs?: number;\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport class SessionsResource {\n constructor(private readonly client: PilotPlatformClient) {}\n\n async create(\n request: CreatePlatformSessionRequest,\n options: { signal?: AbortSignal } = {},\n ): Promise<CreatePlatformSessionResponse> {\n const body = CreatePlatformSessionRequestSchema.parse(request);\n const envelope = await this.client.request<{ data?: unknown }>(\"/api/sessions\", {\n method: \"POST\",\n body,\n signal: options.signal,\n });\n return CreatePlatformSessionResponseSchema.parse(envelope?.data);\n }\n\n async get(\n sessionId: string,\n options: { signal?: AbortSignal } = {},\n ): Promise<SessionSnapshotResponse> {\n const envelope = await this.client.request<{ data?: unknown }>(\n `/api/sessions/${encodeURIComponent(sessionId)}`,\n {\n method: \"GET\",\n signal: options.signal,\n cache: \"no-store\",\n headers: {\n \"Cache-Control\": \"no-cache\",\n Pragma: \"no-cache\",\n },\n },\n );\n if (!envelope?.data || typeof envelope.data !== \"object\") {\n throw new PilotPlatformApiError({\n status: 0,\n code: \"MALFORMED_SESSION_RESPONSE\",\n message: \"GET /api/sessions/:id did not return a {data: ...} envelope.\",\n });\n }\n return envelope.data as SessionSnapshotResponse;\n }\n\n async wait(\n sessionId: string,\n options: WaitForSessionOptions = {},\n ): Promise<SessionSnapshotResponse> {\n const intervalMs = options.intervalMs ?? 1_000;\n const timeoutMs = options.timeoutMs ?? 120_000;\n const startedAt = Date.now();\n\n while (true) {\n if (options.signal?.aborted) throw options.signal.reason;\n const snapshot = await this.get(sessionId, { signal: options.signal });\n const status = snapshot.session?.status;\n if (status === \"ready\") return snapshot;\n if (status === \"failed\") {\n throw new PilotPlatformApiError({\n status: 0,\n code: \"SESSION_FAILED\",\n message: `Session ${sessionId} failed while waiting for readiness.`,\n });\n }\n if (Date.now() - startedAt >= timeoutMs) {\n throw new PilotPlatformApiError({\n status: 0,\n code: \"SESSION_WAIT_TIMEOUT\",\n message: `Timed out waiting for session ${sessionId} to become ready.`,\n });\n }\n await sleep(intervalMs, options.signal);\n }\n }\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n { once: true },\n );\n });\n}\n","import {\n type CreatePlatformWorkloadRequest,\n CreatePlatformWorkloadRequestSchema,\n PublishPlatformRevisionRequestSchema,\n type RevisionManifest,\n type WorkloadManifest,\n} from \"@pilot/contracts\";\nimport type { z } from \"zod\";\n\nimport type { PilotPlatformClient, PilotPlatformRequestInit } from \"../client\";\nimport { PilotPlatformApiError } from \"../errors\";\n\nexport type WorkloadManifestInput = WorkloadManifest | { yaml: string } | { json: string };\nexport type RevisionManifestInput = RevisionManifest | { yaml: string } | { json: string };\n\nexport interface ApplyManifestOptions {\n projectId: string;\n dryRun?: boolean;\n signal?: AbortSignal;\n}\n\nexport interface ApplyWorkloadManifestOptions extends ApplyManifestOptions {\n manifest: WorkloadManifestInput;\n}\n\nexport interface ApplyRevisionManifestOptions extends ApplyManifestOptions {\n workloadSlug: string;\n manifest: RevisionManifestInput;\n}\n\nexport type PublishPlatformRevisionRequestInput = z.input<\n typeof PublishPlatformRevisionRequestSchema\n>;\n\nexport interface WorkloadApplyResult {\n mode: \"dry_run\" | \"applied\";\n status: \"would_create\" | \"would_update\" | \"created\" | \"updated\";\n workloadId?: string;\n workload: {\n slug: string;\n displayName: string;\n kind: string;\n [key: string]: unknown;\n };\n}\n\nexport interface RevisionApplyResult {\n mode: \"dry_run\" | \"applied\";\n status: \"would_create\" | \"created\" | \"existing\";\n workloadId: string;\n revisionId?: string;\n runtimeTemplateId: string;\n resolved: {\n workloadId: string;\n workloadSlug: string;\n workloadKind: string;\n version: string;\n runtimeTemplateId: string;\n runtimeTemplateName: string;\n setDefault: boolean;\n [key: string]: unknown;\n };\n}\n\nexport class WorkloadsResource {\n constructor(private readonly client: PilotPlatformClient) {}\n\n async create(\n request: CreatePlatformWorkloadRequest,\n options: { signal?: AbortSignal; dryRun?: boolean } = {},\n ): Promise<WorkloadApplyResult> {\n const body = CreatePlatformWorkloadRequestSchema.parse(request);\n const envelope = await this.client.request<{ data?: WorkloadApplyResult }>(\"/api/workloads\", {\n method: \"POST\",\n body,\n signal: options.signal,\n query: options.dryRun ? { dryRun: true } : undefined,\n });\n return unwrapEnvelope(envelope, \"POST /api/workloads\", [\"status\", \"workload\"]);\n }\n\n async publishRevision(\n request: PublishPlatformRevisionRequestInput,\n options: { signal?: AbortSignal; dryRun?: boolean } = {},\n ): Promise<RevisionApplyResult> {\n const body = PublishPlatformRevisionRequestSchema.parse(request);\n const path = `/api/workloads/${encodeURIComponent(body.workloadSlug)}/revisions`;\n const envelope = await this.client.request<{ data?: RevisionApplyResult }>(path, {\n method: \"POST\",\n body,\n signal: options.signal,\n query: options.dryRun ? { dryRun: true } : undefined,\n });\n return unwrapEnvelope(envelope, `POST ${path}`, [\n \"status\",\n \"workloadId\",\n \"runtimeTemplateId\",\n \"resolved\",\n ]);\n }\n\n async applyManifest(options: ApplyWorkloadManifestOptions): Promise<WorkloadApplyResult> {\n const envelope = await this.client.request<{ data?: WorkloadApplyResult }>(\n \"/api/workloads\",\n buildManifestRequest(options.manifest, options),\n );\n return unwrapEnvelope(envelope, \"POST /api/workloads\", [\"status\", \"workload\"]);\n }\n\n async applyRevisionManifest(options: ApplyRevisionManifestOptions): Promise<RevisionApplyResult> {\n const path = `/api/workloads/${encodeURIComponent(options.workloadSlug)}/revisions`;\n const envelope = await this.client.request<{ data?: RevisionApplyResult }>(\n path,\n buildManifestRequest(options.manifest, options),\n );\n return unwrapEnvelope(envelope, `POST ${path}`, [\n \"status\",\n \"workloadId\",\n \"runtimeTemplateId\",\n \"resolved\",\n ]);\n }\n}\n\nfunction buildManifestRequest(\n manifest: WorkloadManifestInput | RevisionManifestInput,\n options: ApplyManifestOptions,\n): PilotPlatformRequestInit {\n const init: PilotPlatformRequestInit = {\n method: \"POST\",\n signal: options.signal,\n query: {\n projectId: options.projectId,\n ...(options.dryRun ? { dryRun: true } : {}),\n },\n };\n\n if (isYamlInput(manifest)) {\n init.rawBody = manifest.yaml;\n init.headers = { \"Content-Type\": \"application/yaml\" };\n } else if (isJsonStringInput(manifest)) {\n init.rawBody = manifest.json;\n init.headers = { \"Content-Type\": \"application/json\" };\n } else {\n init.body = manifest;\n }\n\n return init;\n}\n\nfunction isYamlInput(value: unknown): value is { yaml: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"yaml\" in value &&\n typeof (value as { yaml?: unknown }).yaml === \"string\"\n );\n}\n\nfunction isJsonStringInput(value: unknown): value is { json: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"json\" in value &&\n typeof (value as { json?: unknown }).json === \"string\"\n );\n}\n\nfunction unwrapEnvelope<T extends object>(\n envelope: { data?: T } | undefined,\n routeLabel: string,\n requiredKeys: (keyof T)[],\n): T {\n const data = envelope?.data;\n if (!data) {\n throw new PilotPlatformApiError({\n status: 0,\n code: \"MALFORMED_PLATFORM_RESPONSE\",\n message: `${routeLabel} did not return a {data: ...} envelope.`,\n });\n }\n for (const key of requiredKeys) {\n if (!(key in data)) {\n throw new PilotPlatformApiError({\n status: 0,\n code: \"MALFORMED_PLATFORM_RESPONSE\",\n message: `${routeLabel} response is missing required field '${String(key)}'.`,\n });\n }\n }\n return data;\n}\n","import type { PilotApiVersion } from \"@pilot/contracts\";\nimport { X_PILOT_API_VERSION_HEADER } from \"@pilot/contracts\";\n\nimport {\n PilotPlatformApiError,\n PilotPlatformUnauthenticatedError,\n pilotPlatformErrorFromResponse,\n} from \"./errors\";\nimport { ProjectsResource } from \"./resources/projects\";\nimport { SessionsResource } from \"./resources/sessions\";\nimport { WorkloadsResource } from \"./resources/workloads\";\n\nexport interface PilotPlatformClientConfig {\n controlPlaneUrl?: string;\n token?: string;\n fetch?: typeof fetch;\n signal?: AbortSignal;\n defaultHeaders?: Record<string, string>;\n userAgent?: string;\n pilotApiVersion?: PilotApiVersion;\n}\n\nexport interface PilotPlatformRequestInit {\n method?: \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\" | \"PUT\";\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n rawBody?: string;\n headers?: Record<string, string>;\n signal?: AbortSignal;\n cache?: RequestCache;\n raw?: boolean;\n}\n\nexport const AGENTHUB_SDK_USER_AGENT = \"@kanyun-ai-infra/agenthub/0.1.0\";\n\nexport class PilotPlatformClient {\n readonly #token: string;\n\n readonly controlPlaneUrl: string;\n private readonly fetchImpl: typeof fetch;\n private readonly defaultHeaders: Record<string, string>;\n private readonly defaultSignal?: AbortSignal;\n private readonly userAgent: string;\n private readonly pilotApiVersion: PilotApiVersion;\n\n readonly projects: ProjectsResource;\n readonly workloads: WorkloadsResource;\n readonly sessions: SessionsResource;\n\n constructor(config: PilotPlatformClientConfig = {}) {\n const controlPlaneUrl =\n config.controlPlaneUrl ??\n readEnv(\"PILOT_CONTROL_PLANE_URL\") ??\n readEnv(\"KANYUN_PILOT_CONTROL_PLANE_URL\");\n const token = config.token ?? readEnv(\"PILOT_TOKEN\");\n if (!controlPlaneUrl) {\n throw new PilotPlatformApiError({\n status: 0,\n code: \"CONFIG_MISSING_CONTROL_PLANE_URL\",\n message: \"PilotPlatformClient requires `controlPlaneUrl` or PILOT_CONTROL_PLANE_URL.\",\n });\n }\n if (!token) {\n throw new PilotPlatformUnauthenticatedError({\n code: \"CONFIG_MISSING_TOKEN\",\n message: \"PilotPlatformClient requires `token` or PILOT_TOKEN.\",\n });\n }\n\n const normalizedControlPlaneUrl = stripTrailingSlash(controlPlaneUrl);\n try {\n const parsed = new URL(normalizedControlPlaneUrl);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new Error(`Unsupported protocol: ${parsed.protocol}`);\n }\n } catch (error) {\n throw new PilotPlatformApiError({\n status: 0,\n code: \"CONFIG_INVALID_CONTROL_PLANE_URL\",\n message: `controlPlaneUrl is not a valid http(s) URL: ${controlPlaneUrl}`,\n cause: error,\n });\n }\n\n this.controlPlaneUrl = normalizedControlPlaneUrl;\n this.#token = token;\n this.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);\n this.defaultHeaders = { ...(config.defaultHeaders ?? {}) };\n this.defaultSignal = config.signal;\n this.userAgent = config.userAgent ?? AGENTHUB_SDK_USER_AGENT;\n this.pilotApiVersion = config.pilotApiVersion ?? \"v2\";\n\n this.projects = new ProjectsResource(this);\n this.workloads = new WorkloadsResource(this);\n this.sessions = new SessionsResource(this);\n }\n\n async request<T>(path: string, init: PilotPlatformRequestInit = {}): Promise<T> {\n const res = await this.rawRequest(path, init);\n if (init.raw) return res as unknown as T;\n const text = await res.text();\n if (!text) return undefined as T;\n try {\n return JSON.parse(text) as T;\n } catch (error) {\n throw new PilotPlatformApiError({\n status: res.status,\n code: \"INVALID_JSON_RESPONSE\",\n message: `Control Plane returned non-JSON body: ${text.slice(0, 200)}`,\n requestId: res.headers.get(\"x-request-id\") ?? undefined,\n cause: error,\n });\n }\n }\n\n async rawRequest(path: string, init: PilotPlatformRequestInit = {}): Promise<Response> {\n if (init.rawBody !== undefined && init.body !== undefined) {\n throw new PilotPlatformApiError({\n status: 0,\n code: \"INVALID_REQUEST_BODY\",\n message: \"body and rawBody are mutually exclusive.\",\n });\n }\n\n const headers = new Headers();\n addHeaders(headers, { Accept: \"application/json\", \"User-Agent\": this.userAgent });\n addHeaders(headers, this.defaultHeaders);\n addHeaders(headers, init.headers);\n headers.delete(\"authorization\");\n headers.set(\"Authorization\", `Bearer ${this.#token}`);\n headers.set(X_PILOT_API_VERSION_HEADER, this.pilotApiVersion);\n\n let body: BodyInit | undefined;\n if (init.rawBody !== undefined) {\n body = init.rawBody;\n } else if (init.body !== undefined) {\n body = JSON.stringify(init.body);\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n let res: Response;\n const url = this.composeUrl(path, init.query);\n try {\n res = await this.fetchImpl(url, {\n method: init.method ?? \"GET\",\n headers,\n body,\n signal: mergeSignals(this.defaultSignal, init.signal),\n cache: init.cache,\n });\n } catch (error) {\n if (isAbortError(error)) throw error;\n throw new PilotPlatformApiError({\n status: 0,\n code: \"NETWORK_ERROR\",\n message: `Request to ${url} failed: ${(error as Error)?.message ?? String(error)}`,\n cause: error,\n });\n }\n\n if (res.ok) return res;\n\n const text = await res.text();\n let parsed: unknown = undefined;\n if (text) {\n try {\n parsed = JSON.parse(text);\n } catch {\n parsed = { error: text };\n }\n }\n throw pilotPlatformErrorFromResponse({\n status: res.status,\n body: parsed,\n requestId: res.headers.get(\"x-request-id\") ?? undefined,\n });\n }\n\n private composeUrl(path: string, query?: PilotPlatformRequestInit[\"query\"]): string {\n const base = new URL(`${this.controlPlaneUrl}/`);\n const normalized =\n path.startsWith(\"//\") || /^[a-z][a-z0-9+.-]*:/i.test(path)\n ? path\n : path.startsWith(\"/\")\n ? path\n : `/${path}`;\n let full: URL;\n try {\n full = new URL(normalized, base);\n } catch (error) {\n throw new PilotPlatformApiError({\n status: 0,\n code: \"INVALID_REQUEST_URL\",\n message: `Could not resolve path \"${path}\" against controlPlaneUrl.`,\n cause: error,\n });\n }\n if (full.origin !== base.origin) {\n throw new PilotPlatformApiError({\n status: 0,\n code: \"CROSS_ORIGIN_REQUEST_BLOCKED\",\n message: `Refusing to send Bearer token to foreign origin ${full.origin}.`,\n });\n }\n if (query) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined || value === null) continue;\n full.searchParams.set(key, String(value));\n }\n }\n return full.toString();\n }\n}\n\nfunction stripTrailingSlash(url: string): string {\n return url.endsWith(\"/\") ? url.slice(0, -1) : url;\n}\n\nfunction addHeaders(target: Headers, source: Record<string, string> | undefined): void {\n if (!source) return;\n for (const [key, value] of Object.entries(source)) {\n if (value === undefined || value === null) continue;\n target.set(key, value);\n }\n}\n\nfunction readEnv(key: string): string | undefined {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n const value = env?.[key];\n return value && value.length > 0 ? value : undefined;\n}\n\nfunction isAbortError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"AbortError\" || (error as { code?: string }).code === \"ABORT_ERR\")\n );\n}\n\nfunction mergeSignals(...signals: (AbortSignal | undefined)[]): AbortSignal | undefined {\n const active = signals.filter((signal): signal is AbortSignal => !!signal);\n if (active.length === 0) return undefined;\n if (active.length === 1) return active[0];\n const anyFn = (AbortSignal as { any?: (signals: AbortSignal[]) => AbortSignal }).any;\n if (typeof anyFn === \"function\") return anyFn(active);\n const controller = new AbortController();\n for (const signal of active) {\n if (signal.aborted) {\n controller.abort(signal.reason);\n break;\n }\n signal.addEventListener(\"abort\", () => controller.abort(signal.reason), { once: true });\n }\n return controller.signal;\n}\n"],"mappings":";;;;;;;;;AAAA,IAAI,YAAY,OAAO;AACvB,IAAI,aAAa,OAAO;AACxB,IAAI,oBAAoB,OAAO;AAC/B,IAAI,sBAAsB,OAAO;AACjC,IAAI,eAAe,OAAO,UAAU;AACpC,IAAI,eAAe,OAAO,UAAU;AACpC,IAAI,kBAAkB,CAAC,KAAK,KAAK,UAAU,OAAO,MAAM,UAAU,KAAK,KAAK,EAAE,YAAY,MAAM,cAAc,MAAM,UAAU,MAAM,MAAM,CAAC,IAAI,IAAI,GAAG,IAAI;AAC1J,IAAI,iBAAiB,CAAC,GAAG,MAAM;AAC7B,WAAS,QAAQ,MAAM,IAAI,CAAC;AAC1B,QAAI,aAAa,KAAK,GAAG,IAAI;AAC3B,sBAAgB,GAAG,MAAM,EAAE,IAAI,CAAC;AACpC,MAAI;AACF,aAAS,QAAQ,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