{"version":3,"sources":["../src/agent-types.ts"],"sourcesContent":["/**\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n//\n// IMPORTANT: Please keep schema/type definitions in sync with\n//   genkit-tools/common/src/types/agent.ts\n//\n// This file is the single home for the agent/session wire schemas (and their\n// types) shared between the JS runtime and the canonical tools definitions. It\n// mirrors the order and shape of the tools file so the two stay easy to diff.\n//\n// Two intentional differences from the tools file:\n//\n//   1. The runtime variants of `SessionState`, `SessionSnapshot`, `AgentInit`,\n//      and `AgentOutput` are generic interfaces (`<S>`) so callers can type the\n//      custom session state, rather than the tools file's non-generic\n//      `z.infer` aliases.\n//   2. The structured error shape is defined here as `RuntimeErrorSchema`\n//      (the JS runtime has no shared error-types module to import it from).\n//\n\nimport { z } from '@genkit-ai/core';\nimport {\n  MessageSchema,\n  ModelResponseChunkSchema,\n  PartSchema,\n  type MessageData,\n} from './model-types.mjs';\nimport { ToolRequestPartSchema, ToolResponsePartSchema } from './parts.mjs';\n\n/**\n * Schema for the canonical Genkit error wire shape (`{status, message,\n * details}`). This is the form runtimes use when an error travels as data\n * inside another value (e.g. agent outputs and session snapshots).\n */\nexport const RuntimeErrorSchema = z.object({\n  /** Canonical status name (e.g. `INTERNAL`, `FAILED_PRECONDITION`). */\n  status: z.string().optional(),\n  /** Human-readable error message. */\n  message: z.string(),\n  /** Optional structured details describing the failure. */\n  details: z.any().optional(),\n});\n/** Structured error carried as data inside agent outputs and snapshots. */\nexport type RuntimeError = z.infer<typeof RuntimeErrorSchema>;\n\n/**\n * Schema for tracking persistent artifacts generated during a session turn.\n */\nexport const ArtifactSchema = z.object({\n  /** Name identifies the artifact (e.g., \"generated_code.go\", \"diagram.png\"). */\n  name: z.string().optional(),\n  /** Parts contains the artifact content (text, media, etc.). */\n  parts: z.array(PartSchema),\n  /** Metadata contains additional artifact-specific data. */\n  metadata: z.record(z.any()).optional(),\n});\n\n/**\n * Artifact generated during a session turn.\n */\nexport type Artifact = z.infer<typeof ArtifactSchema>;\n\n/**\n * Schema for a snapshot's lifecycle status.\n *\n * - `pending`: a detached invocation is still processing the queued inputs.\n *   The snapshot's state is empty until the background work finishes, at\n *   which point it is rewritten with the cumulative final state and a\n *   terminal status.\n * - `completed`: the snapshot captures a settled state.\n * - `aborted`: the snapshot's invocation was aborted via the `abort` companion\n *   action while detached.\n * - `failed`: the invocation terminated with an error. The snapshot's `error`\n *   field describes the failure and resume is rejected with that same error.\n * - `expired`: a `pending` snapshot whose detached background worker is\n *   presumed dead because its heartbeat went stale. Computed on read from a\n *   stale `heartbeatAt`; never persisted (the dead worker can no longer write\n *   a terminal status itself).\n */\nexport const SnapshotStatusSchema = z.enum([\n  'pending',\n  'completed',\n  'aborted',\n  'failed',\n  'expired',\n]);\n\n/**\n * Lifecycle status of a session snapshot.\n */\nexport type SnapshotStatus = z.infer<typeof SnapshotStatusSchema>;\n\n/**\n * Reason an agent turn (or whole invocation) finished.\n *\n * The first group mirrors the model-level `FinishReason` so a turn backed by a\n * single `generate` call can forward its reason verbatim. The remaining values\n * are agent-specific outcomes with no `generate`-level equivalent: `aborted`\n * (the turn/invocation was aborted), `detached` (the turn was moved to the\n * background), and `failed` (the turn ended in an error).\n */\nexport const AgentFinishReasonSchema = z.enum([\n  // Mirror of generate's FinishReason:\n  'stop',\n  'length',\n  'blocked',\n  'interrupted',\n  'other',\n  'unknown',\n  // Agent-specific additions:\n  'aborted',\n  'detached',\n  'failed',\n]);\n\n/**\n * Reason an agent turn (or whole invocation) finished.\n */\nexport type AgentFinishReason = z.infer<typeof AgentFinishReasonSchema>;\n\n/**\n * Schema for session execution state.\n */\nexport const SessionStateSchema = z.object({\n  sessionId: z.string().optional(),\n  messages: z.array(MessageSchema).optional(),\n  custom: z.any().optional(),\n  artifacts: z.array(ArtifactSchema).optional(),\n});\n\n/**\n * State persisted for a session across turns.\n *\n * Runtime variant of {@link SessionStateSchema}, generic over the custom state\n * type `S` so callers can type `custom`.\n */\nexport interface SessionState<S = unknown> {\n  sessionId?: string;\n  messages?: MessageData[];\n  custom?: S;\n  artifacts?: Artifact[];\n}\n\n/**\n * Schema for agent input messages and commands.\n */\nexport const AgentInputSchema = z.object({\n  /** User's input message for this turn. */\n  message: MessageSchema.optional(),\n  /** Options for resuming an interrupted generation. */\n  resume: z\n    .object({\n      respond: z.array(ToolResponsePartSchema).optional(),\n      restart: z.array(ToolRequestPartSchema).optional(),\n    })\n    .optional(),\n  detach: z.boolean().optional(),\n});\n\n/**\n * Input received by an agent turn.\n */\nexport type AgentInput = z.infer<typeof AgentInputSchema>;\n\n/**\n * Schema for initializing an agent turn.\n */\nexport const AgentInitSchema = z.object({\n  snapshotId: z.string().optional(),\n  sessionId: z.string().optional(),\n  state: SessionStateSchema.optional(),\n});\n\n/**\n * Initialization options for an agent turn.\n *\n * For server-managed agents (with a `store`) provide a `snapshotId` (resume an\n * exact snapshot, required for branching/snapshotting clients) and/or a\n * `sessionId` (resume the session's latest snapshot - the simple case used by\n * `useChat`-style clients). When both are provided, `snapshotId` selects the\n * snapshot to resume and `sessionId` acts as an ownership guard: the snapshot\n * must belong to that session. For client-managed agents (no store) provide\n * the full `state`.\n *\n * Runtime variant of {@link AgentInitSchema}, generic over the custom state\n * type `S`.\n */\nexport interface AgentInit<S = unknown> {\n  snapshotId?: string;\n  sessionId?: string;\n  state?: SessionState<S>;\n}\n\n/**\n * Schema for final results of an agent execution.\n */\nexport const AgentResultSchema = z.object({\n  message: MessageSchema.optional(),\n  artifacts: z.array(ArtifactSchema).optional(),\n  /** The reason the whole invocation finished (e.g. `stop`, `interrupted`). */\n  finishReason: AgentFinishReasonSchema.optional(),\n});\n\n/**\n * Result returned upon completing an agent execution.\n */\nexport type AgentResult = z.infer<typeof AgentResultSchema>;\n\n/**\n * Schema for output returned at turn completion.\n */\nexport const AgentOutputSchema = z.object({\n  /**\n   * ID of the session this invocation belongs to, assigned by the framework\n   * when the invocation starts.\n   */\n  sessionId: z.string().optional(),\n  snapshotId: z.string().optional(),\n  state: SessionStateSchema.optional(),\n  message: MessageSchema.optional(),\n  artifacts: z.array(ArtifactSchema).optional(),\n  /** The reason the invocation finished (e.g. `stop`, `interrupted`). */\n  finishReason: AgentFinishReasonSchema.optional(),\n  /**\n   * Present when `finishReason` is `failed`. Carries the original error\n   * details (RuntimeError shape; the runtime resolves gracefully instead of\n   * throwing). The accompanying `state`/`snapshotId` hold the last-good state -\n   * the state the failed turn started with.\n   */\n  error: RuntimeErrorSchema.optional(),\n});\n\n/**\n * Output returned at turn completion.\n *\n * Runtime variant of {@link AgentOutputSchema}, generic over the custom state\n * type `S`.\n */\nexport interface AgentOutput<S = unknown> {\n  sessionId?: string;\n  artifacts?: Artifact[];\n  message?: MessageData;\n  snapshotId?: string;\n  state?: SessionState<S>;\n  finishReason?: AgentFinishReason;\n  /**\n   * Present when `finishReason` is `failed`. Carries the original error\n   * details (RuntimeError shape); `state`/`snapshotId` hold the last-good state.\n   */\n  error?: RuntimeError;\n}\n\n/**\n * Schema identifying a turn termination event.\n */\nexport const TurnEndSchema = z.object({\n  snapshotId: z.string().optional(),\n  /** The reason this turn finished (e.g. `stop`, `interrupted`). */\n  finishReason: AgentFinishReasonSchema.optional(),\n});\n\n/**\n * Identifies a turn termination event.\n */\nexport type TurnEnd = z.infer<typeof TurnEndSchema>;\n\n/**\n * Schema for the operation kind of a JSON Patch operation (RFC 6902).\n */\nexport const JsonPatchOpSchema = z.enum([\n  'add',\n  'remove',\n  'replace',\n  'move',\n  'copy',\n  'test',\n]);\n\n/**\n * Operation kind of a JSON Patch (RFC 6902) operation.\n */\nexport type JsonPatchOp = z.infer<typeof JsonPatchOpSchema>;\n\n/**\n * Schema for a single RFC 6902 (JSON Patch) operation.\n */\nexport const JsonPatchOperationSchema = z.object({\n  op: JsonPatchOpSchema,\n  /** A JSON Pointer (RFC 6901) to the target location, e.g. `\"/agentStatus\"`. */\n  path: z.string(),\n  /** Source pointer; required for `move` and `copy`. */\n  from: z.string().optional(),\n  /** New value; required for `add`, `replace`, and `test`. */\n  value: z.any().optional(),\n});\n\n/**\n * Schema for an RFC 6902 JSON Patch: an ordered list of operations.\n */\nexport const JsonPatchSchema = z.array(JsonPatchOperationSchema);\n\n/**\n * Schema for stream chunks emitted during agent execution.\n */\nexport const AgentStreamChunkSchema = z.object({\n  modelChunk: ModelResponseChunkSchema.optional(),\n  /**\n   * An RFC 6902 JSON Patch describing a delta applied to the session's\n   * `custom` state. The runtime auto-emits these whenever custom state is\n   * mutated during a turn; clients apply them to keep their tracked custom\n   * state live mid-stream.\n   */\n  customPatch: JsonPatchSchema.optional(),\n  artifact: ArtifactSchema.optional(),\n  turnEnd: TurnEndSchema.optional(),\n});\n\n/**\n * Streamed chunk emitted during agent execution.\n */\nexport type AgentStreamChunk = z.infer<typeof AgentStreamChunkSchema>;\n\n/**\n * Zod schema mirroring {@link SessionSnapshot}. Used as the output schema for\n * the `getSnapshot` companion action so the snapshot shape is discoverable in\n * the registry (rather than an opaque `z.any()`).\n */\nexport const SessionSnapshotSchema = z.object({\n  snapshotId: z.string(),\n  sessionId: z.string().optional(),\n  parentId: z.string().optional(),\n  createdAt: z.string(),\n  updatedAt: z.string().optional(),\n  heartbeatAt: z.string().optional(),\n  status: SnapshotStatusSchema.optional(),\n  finishReason: AgentFinishReasonSchema.optional(),\n  error: RuntimeErrorSchema.optional(),\n  state: SessionStateSchema.optional(),\n});\n\n/**\n * Saved snapshot of a session's state at a given event point.\n *\n * Runtime variant of {@link SessionSnapshotSchema}, generic over the custom\n * state type `S`.\n */\nexport interface SessionSnapshot<S = unknown> {\n  snapshotId: string;\n\n  /**\n   * ID of the session this snapshot belongs to. Assigned by the agent\n   * framework when the conversation's first invocation starts and stamped on\n   * every later snapshot in the chain, including across resumed invocations.\n   * Stores preserve it across rewrites; rows written without one (data from\n   * before session IDs existed) belong to no session.\n   */\n  sessionId?: string;\n\n  /**\n   * ID of the previous snapshot in this timeline. Informational lineage (for\n   * debugging and UI history trees); plays no part in resolving a session's\n   * latest snapshot.\n   */\n  parentId?: string;\n  createdAt: string;\n  /** When the snapshot was last written (RFC 3339). Equals `createdAt` until rewritten. */\n  updatedAt?: string;\n\n  /**\n   * Heartbeat timestamp (RFC 3339) refreshed periodically while a detached\n   * (background) turn is in flight. Used to detect a dead background worker:\n   * if a `pending` snapshot's heartbeat goes stale (older than the configured\n   * timeout), reads surface its status as `expired` (the dead process can no\n   * longer persist a terminal status itself).\n   */\n  heartbeatAt?: string;\n  status?: SnapshotStatus;\n\n  /**\n   * Semantic reason the turn/invocation finished (e.g. `interrupted`,\n   * `stop`). Distinct from `status`, which tracks the persistence lifecycle.\n   */\n  finishReason?: AgentFinishReason;\n\n  /**\n   * Structured failure information (RuntimeError shape). `status` is the\n   * canonical error category (e.g. `INTERNAL`, `FAILED_PRECONDITION`).\n   */\n  error?: RuntimeError;\n\n  /**\n   * Conversation state captured at this point. Empty on a pending snapshot\n   * (the live state is not yet committed); populated on terminal snapshots\n   * with the cumulative final state.\n   */\n  state?: SessionState<S>;\n}\n\n/**\n * Schema for the input of an agent's `getSnapshot` companion action. Provide\n * exactly one of `snapshotId` or `sessionId`.\n */\nexport const GetSnapshotRequestSchema = z.object({\n  snapshotId: z.string().optional(),\n  sessionId: z.string().optional(),\n});\n\n/**\n * Input identifying which snapshot to fetch.\n */\nexport type GetSnapshotRequest = z.infer<typeof GetSnapshotRequestSchema>;\n\n/**\n * Schema for the input of the `abort` companion action.\n */\nexport const AgentAbortRequestSchema = z.object({\n  snapshotId: z.string(),\n});\n\n/**\n * Input identifying which snapshot's invocation to abort.\n */\nexport type AgentAbortRequest = z.infer<typeof AgentAbortRequestSchema>;\n\n/**\n * Schema for the output of the `abort` companion action.\n */\nexport const AgentAbortResponseSchema = z.object({\n  snapshotId: z.string(),\n  status: SnapshotStatusSchema.optional(),\n});\n\n/**\n * Result of an abort attempt.\n */\nexport type AgentAbortResponse = z.infer<typeof AgentAbortResponseSchema>;\n\n/**\n * Schema for who owns session state for an agent.\n *\n * - `server`: a session store is configured and snapshots are persisted\n *   server-side.\n * - `client`: no store; state flows through the agent's invocation init and\n *   output payloads.\n */\nexport const AgentStateManagementSchema = z.enum(['server', 'client']);\n\n/**\n * Who owns session state for an agent.\n */\nexport type AgentStateManagement = z.infer<typeof AgentStateManagementSchema>;\n\n/**\n * Schema for the agent capability metadata placed under `metadata.agent` on an\n * agent's action descriptor. Lets the Dev UI and other reflective callers\n * render the right surface (e.g. hide the Abort button when the configured\n * store doesn't support it) without round-tripping through the reflection API.\n */\nexport const AgentMetadataSchema = z.object({\n  /** Who owns session state for this agent. */\n  stateManagement: AgentStateManagementSchema,\n  /**\n   * Whether the agent's invocations can be aborted. True only when the\n   * configured store implements the abort lifecycle.\n   */\n  abortable: z.boolean(),\n  /**\n   * JSON schema for the agent's custom session state (the `custom` field of\n   * `SessionState`), inferred from the agent's state type. Omitted when the\n   * state type carries no schema to infer.\n   */\n  stateSchema: z.record(z.any()).optional(),\n});\n\n/**\n * Agent capability metadata placed under `metadata.agent`.\n */\nexport type AgentMetadata = z.infer<typeof AgentMetadataSchema>;\n"],"mappings":"AAkCA,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,uBAAuB,8BAA8B;AAOvD,MAAM,qBAAqB,EAAE,OAAO;AAAA;AAAA,EAEzC,QAAQ,EAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAE5B,SAAS,EAAE,OAAO;AAAA;AAAA,EAElB,SAAS,EAAE,IAAI,EAAE,SAAS;AAC5B,CAAC;AAOM,MAAM,iBAAiB,EAAE,OAAO;AAAA;AAAA,EAErC,MAAM,EAAE,OA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