Source: https://docs.cumuluslabs.io/sdk-reference/agent
Content version: 25ff7728

# Agent authoring reference

Define an agent as ordinary TypeScript data. Composition helpers return frozen serializable definitions; compileAgent resolves graph references and environment bindings without making requests. The authoring workflow previews remote state, applies revision-checked draft edits, validates with Cumulus and publishes an immutable version.

Import from `@cumulus/sdk/agent`. This page documents SDK 0.3.4. Follow the [agent authoring guide](/docs/sdk-definitions) for a worked workflow.

## Define an agent {#example}

Save this as `agent.ts`. It exports the graph, environment, integration and project used in the publication example below. The integration’s number alias is applied separately when you choose to route a published agent.

```typescript
import {
  defineAgent, defineNode, defineEdge, defineComponent,
  defineProject, defineIntegration, defineEnvironment, compileAgent,
} from "@cumulus/sdk/agent";

const greet = defineNode({ key: "greet", kind: "conversation",
  instruction: { type: "prompt", text: "Ask how you can help." } });
const done = defineNode({ key: "done", kind: "end" });
export const agent = defineAgent({
  key: "support", name: "Support", startNode: greet, nodes: [greet, done],
  edges: [defineEdge({ from: greet, to: done, slot: "edges",
    condition: { type: "prompt", prompt: "The caller is finished." } })],
});
export const integration = defineIntegration({
  key: "support_line", agent, outbound: { callerIdBinding: "support" },
});
export const project = defineProject({ key: "service_desk", agents: [agent],
  integrations: [integration] });
export const environment = defineEnvironment({ numbers: { support: "number-id" } });
export const compiled = compileAgent(agent, environment, integration);

// A reusable component is its own scoped graph; attach it to an agent as needed.
export const goodbye = defineComponent({ key: "goodbye", startNode: done,
  nodes: [done] });
```

## Preview, review, then publish

Download the [complete authoring example](/docs-assets/examples/sdk-authoring.zip). It contains this definition, the two files below and a storage helper. Save this helper as `publish.ts`. It accepts a saved plan that you have reviewed; it never creates a fresh preview. It checks the current source, bindings, integration and project against that plan before applying its exact revision and publishing a test-only version.

```typescript
import { Cumulus } from "@cumulus/sdk";
import { authoring, compileAgent, definitionHash, DraftConflict,
  type AgentDefinition, type EnvironmentBindings, type AuthoringPreview,
  type ApplyReceipt, type PreviewOptions } from "@cumulus/sdk/agent";

// sourceHash is review metadata for this example, not an SDK request field.
export type ReviewedPlan = AuthoringPreview & { sourceHash: string };
export function reviewedSourceHash(agent: AgentDefinition, bindings: EnvironmentBindings,
  options: PreviewOptions = {}) {
  return definitionHash({ agent, bindings, integration: options.integration ?? null,
    projectKey: options.projectKey ?? options.receipt?.projectKey ?? agent.key });
}

export async function publishAgent(client: Cumulus, agent: AgentDefinition,
  bindings: EnvironmentBindings, plan: ReviewedPlan,
  save: (receipt: ApplyReceipt) => Promise<void>, options: PreviewOptions = {}) {
  const current = compileAgent(agent, bindings, options.integration);
  const projectKey = options.projectKey ?? options.receipt?.projectKey ?? agent.key;
  const agentId = options.agentId ?? options.receipt?.agentId;
  if (plan.projectKey !== projectKey || definitionHash(current) !== plan.definitionHash ||
      reviewedSourceHash(agent, bindings, options) !== plan.sourceHash ||
      (agentId && plan.agentId !== agentId)) {
    throw new DraftConflict("Source or management scope changed; preview and review again");
  }
  const receipt = await authoring.apply(client, plan, {
    expectedRevision: plan.baseRevision, onCheckpoint: save,
  });
  const validation = await authoring.validate(client, receipt);
  if (!validation.ok) return { ok: false as const, diagnostics: validation.diagnostics };
  const published = await authoring.publish(client, receipt, {
    live: false, onCheckpoint: save,
  });
  await save(published);
  return { ok: true as const, publication: published.publication };
}
```

### Run the two steps separately

The example’s `authoring.ts` entrypoint passes `project.key`, `integration` and the previous receipt into preview. Its storage helper saves the full plan and durably checkpoints later edits; the helper is application code included in the download.

```typescript
import { pathToFileURL } from "node:url";
import { Cumulus } from "@cumulus/sdk";
import { authoring, effectiveTenant } from "@cumulus/sdk/agent";
import { agent, project, environment, integration } from "./agent.js";
import { publishAgent, reviewedSourceHash } from "./publish.js";
import { openAuthoringStore } from "./authoring-store.js";

export async function runAuthoring(command: "preview" | "publish") {
  const baseUrl = process.env.CUMULUS_API_URL;
  const apiKey = process.env.CUMULUS_API_KEY;
  if (!baseUrl || !apiKey) throw new Error("Set CUMULUS_API_URL and CUMULUS_API_KEY");
  const client = new Cumulus({ baseUrl, apiKey });
  const tenant = await effectiveTenant(client);
  const store = await openAuthoringStore(tenant, project.key, agent.key);
  const receipt = await store.readReceipt();
  if (receipt?.pendingBatch || receipt?.pendingPublication) {
    throw new Error("Reconcile the interrupted operation in receipt.json first");
  }
  const options = { projectKey: project.key, integration, receipt };
  if (command === "preview") {
    const plan = await authoring.preview(client, agent, environment, options);
    await store.savePlan({ ...plan, sourceHash: reviewedSourceHash(agent, environment, options) });
    console.log({ tenant: plan.tenantId, revision: plan.baseRevision, changes: plan.changes });
    console.log("Review the full plan at " + store.directory + "/preview.json");
    return; // No draft edit or publication has been sent.
  }
  const plan = await store.readPlan();
  if (!plan) throw new Error("Run preview and review preview.json before publishing");
  const result = await publishAgent(client, agent, environment, plan, store.saveReceipt, options);
  console.log(result);
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const command = process.argv[2];
  if (command !== "preview" && command !== "publish") throw new Error("Use preview or publish");
  await runAuthoring(command);
}
```

After installing SDK 0.3.4 in the downloaded example and setting `CUMULUS_API_URL` and `CUMULUS_API_KEY`, run:

```sh
npm run build
npm run preview
```

Preview prints the effective tenant, draft revision and proposed changes, then exits without editing or publishing. Open the printed `preview.json` path and review its complete definition and edits. Keep the file unchanged. When you approve that saved plan, run:

```sh
npm run publish
```

Publish reads that saved plan rather than calculating another one. A source, binding or integration change requires another preview and review. The SDK also checks the target tenant and draft revision before applying. `sourceHash` is extra review metadata used by this example; it is not a Cumulus request field. This command creates a test-only publication and does not route numbers or place calls.

Later previews load `receipt.json` to continue managing the same agent under the same tenant and project. The support helper stores private plan and receipt files under `.cumulus/<tenant>/<project>/<agent>/`. Keep them across builds and out of version control. A pending edit or publication stops the command so you can [reconcile the interrupted operation](/docs/sdk-lifecycle#recover-an-interrupted-apply-or-publication).

If someone changes the draft in Studio, [export and backport the intended change](/docs/sdk-lifecycle#backport-a-studio-change) before explicitly adopting its reviewed revision. Run one authoring process per managed agent.

## Compose an agent {#compose-an-agent}

### defineAgent {#defineagent}

Give a graph a stable agent key, display name and start node. The helper freezes a serializable copy; compileAgent checks the graph and native configuration.

Related types and helpers: [AgentDefinition](/docs/sdk-reference/agent#agentdefinition).

```typescript-declaration
export declare function defineAgent<const T extends AgentDefinition>(v: T): T;
```

### defineNode {#definenode}

Define one native conversation, tool, branch, extraction, transfer, end, component, verification or tokenization node. key becomes its native ID within its graph scope.

Related types and helpers: [NodeDefinition](/docs/sdk-reference/agent#nodedefinition).

```typescript-declaration
export declare function defineNode<const T extends NodeDefinition>(v: T): T;
```

### defineEdge {#defineedge}

Connect nodes by object reference or stable key. Set the native transition slot and condition. compileAgent verifies both endpoints exist in the same graph scope.

Related types and helpers: [EdgeDefinition](/docs/sdk-reference/agent#edgedefinition).

```typescript-declaration
export declare function defineEdge<const T extends EdgeDefinition>(v: T): T;
```

### defineComponent {#definecomponent}

Define a reusable subgraph with its own start node and node scope. Instantiate separate component keys when reusing a factory in one agent.

Related types and helpers: [ComponentDefinition](/docs/sdk-reference/agent#componentdefinition).

```typescript-declaration
export declare function defineComponent<const T extends ComponentDefinition>(v: T): T;
```

### defineTool {#definetool}

Declare the customer-hosted HTTP contract: input/output JSON schemas, endpoint binding, timeout and idempotency policy. JSON schemas are validated immediately; handler functions remain in your backend.

Related types and helpers: [JSONSchema](/docs/sdk-reference/agent#jsonschema) · [ToolDefinition](/docs/sdk-reference/agent#tooldefinition).

```typescript-declaration
export declare function defineTool<const I extends JSONSchema, const O extends JSONSchema>(v: ToolDefinition<I, O>): ToolDefinition<I, O>;
```

### defineIntegration {#defineintegration}

Associate an agent with inbound/outbound number aliases and optional event delivery. compileAgent resolves context and notification configuration; assignIntegration applies number routing separately.

Related types and helpers: [IntegrationDefinition](/docs/sdk-reference/agent#integrationdefinition).

```typescript-declaration
export declare function defineIntegration<const T extends IntegrationDefinition>(v: T): T;
```

### defineProject {#defineproject}

Group agent and integration definitions in a portable project. Its key identifies source management scope; applying agents remains an explicit workflow.

Related types and helpers: [ProjectDefinition](/docs/sdk-reference/agent#projectdefinition).

```typescript-declaration
export declare function defineProject<const T extends ProjectDefinition>(v: T): T;
```

### defineEnvironment {#defineenvironment}

Keep deployment-specific endpoint, number and event-destination bindings separate from portable agent source. Return a frozen serializable binding object.

Related types and helpers: [EnvironmentBindings](/docs/sdk-reference/agent#environmentbindings).

```typescript-declaration
export declare function defineEnvironment<const T extends EnvironmentBindings>(v: T): T;
```

### compileAgent {#compileagent}

Resolve tools, components, graph references and environment bindings into a native CompiledDefinition. Reject missing bindings, conflicting identities and invalid native edits. Defaults: phone channel, English, agent starts, empty global prompt/settings/variables, strict tool calls. Tool defaults: failure_edge on uncertainty, required response mappings and no automatic speech after execution. No network request is made.

Related types and helpers: [AgentDefinition](/docs/sdk-reference/agent#agentdefinition) · [EnvironmentBindings](/docs/sdk-reference/agent#environmentbindings) · [IntegrationDefinition](/docs/sdk-reference/agent#integrationdefinition) · [CompiledDefinition](/docs/sdk-reference/agent#compileddefinition).

```typescript-declaration
export declare function compileAgent(agent: AgentDefinition, bindings?: EnvironmentBindings, integration?: IntegrationDefinition): CompiledDefinition;
```

## Review and publish changes {#review-and-publish-changes}

### authoring {#authoring}

The authoring workflow object exposes the same preview, apply, validate, publish, promote and exportDraft functions exported individually below.

Related types and helpers: [preview](/docs/sdk-reference/agent#preview) · [apply](/docs/sdk-reference/agent#apply) · [validate](/docs/sdk-reference/agent#validate) · [publish](/docs/sdk-reference/agent#publish) · [promote](/docs/sdk-reference/agent#promote) · [exportDraft](/docs/sdk-reference/agent#exportdraft).

```typescript-declaration
export declare const authoring: {
    preview: typeof preview;
    apply: typeof apply;
    validate: typeof validate;
    publish: typeof publish;
    promote: typeof promote;
    exportDraft: typeof exportDraft;
};
```

### preview {#preview}

Compile the definition and read the effective tenant, draft and publication head. Return planned edits and their revision/fingerprint baseline without opening a draft or placing a call. A changed remote draft needs explicit acceptRemoteRevision after review/backport.

Pass `projectKey` to name the source project, `integration` to include that agent’s context and notification configuration, and the saved `receipt` when continuing to manage an agent. The receipt supplies its agent ID and baseline. You can supply `agentId` directly when adopting an existing agent; review/export its draft first.

The project defaults to `receipt.projectKey`, then `agent.key`. A receipt must match the effective tenant, agent key and selected project. `acceptRemoteRevision` explicitly adopts the exact remote revision you reviewed and backported; it does not disable future revision checks. See the complete invocation above.

Related types and helpers: [Cumulus](/docs/sdk-reference/client#cumulus) · [AgentDefinition](/docs/sdk-reference/agent#agentdefinition) · [EnvironmentBindings](/docs/sdk-reference/agent#environmentbindings) · [PreviewOptions](/docs/sdk-reference/agent#previewoptions) · [AuthoringPreview](/docs/sdk-reference/agent#authoringpreview).

```typescript-declaration
export declare function preview(client: Cumulus, agent: AgentDefinition, bindings?: EnvironmentBindings, options?: PreviewOptions): Promise<AuthoringPreview>;
```

### apply {#apply}

Apply exactly the reviewed preview. expectedRevision must equal plan.baseRevision. Creates a blank agent when needed, applies native edits in batches of at most 100, and calls onCheckpoint before each batch. Returns an ApplyReceipt; a partial failure carries its last checkpoint in PartialApplyError. Does not publish.

Related types and helpers: [Cumulus](/docs/sdk-reference/client#cumulus) · [AuthoringPreview](/docs/sdk-reference/agent#authoringpreview) · [ApplyOptions](/docs/sdk-reference/agent#applyoptions) · [ApplyReceipt](/docs/sdk-reference/agent#applyreceipt).

```typescript-declaration
export declare function apply(client: Cumulus, plan: AuthoringPreview, options: ApplyOptions): Promise<ApplyReceipt>;
```

### validate {#validate}

Ask Cumulus to validate the receipt’s draft ID and revision and include the execution plan. Read ok and diagnostics before publication.

Related types and helpers: [Cumulus](/docs/sdk-reference/client#cumulus) · [ApplyReceipt](/docs/sdk-reference/agent#applyreceipt) · [components](/docs/sdk-reference/client#components).

```typescript-declaration
export declare function validate(client: Cumulus, receipt: ApplyReceipt): Promise<{
    ok: boolean;
    version: number;
    digest: string | null;
    diagnostics: components["schemas"]["Diagnostic"][];
    plan?: components["schemas"]["PublicationPlan"];
}>;
```

### publish {#publish}

Re-read and fingerprint the draft, validate it, then publish its immutable version. Defaults to live:false and keep_draft:true. onCheckpoint records pending publication before sending, allowing the original publication request to be reconciled after interruption.

Related types and helpers: [Cumulus](/docs/sdk-reference/client#cumulus) · [ApplyReceipt](/docs/sdk-reference/agent#applyreceipt).

```typescript-declaration
export declare function publish(client: Cumulus, receipt: ApplyReceipt, options?: {
    live?: boolean;
    onCheckpoint?: (receipt: ApplyReceipt) => void | Promise<void>;
}): Promise<ApplyReceipt>;
```

### promote {#promote}

Move the current head to receipt.publication.version using the expected head version and draft ID. Requires a publication in the receipt; promotion does not change that publication’s test/live mode.

Related types and helpers: [Cumulus](/docs/sdk-reference/client#cumulus) · [ApplyReceipt](/docs/sdk-reference/agent#applyreceipt).

```typescript-declaration
export declare function promote(client: Cumulus, receipt: ApplyReceipt): Promise<ApplyReceipt>;
```

### exportDraft {#exportdraft}

Return the current public draft, revision and semantic fingerprint for review or backport into source. This is a canonical public view, not reconstructed TypeScript.

`exportDraft(client, agentId)`

The resolved object contains `schemaVersion`, `kind`, `agentId`, `revision`, `draftHash`, `draft` and `note`. The `draft` property is the [current draft response](/docs/reference/drafts.get#responses).

Use `Awaited<ReturnType<typeof exportDraft>>` for the exact inferred result type in your application. [Full TypeScript declaration](/docs-assets/sdk-reference/declarations/agent-exportDraft.txt).

Related types and helpers: [Cumulus](/docs/sdk-reference/client#cumulus) · [draftHash](/docs/sdk-reference/agent#drafthash) · [components](/docs/sdk-reference/client#components).

## Define private workflows {#define-private-workflows}

### defineVerification {#defineverification}

Build a verify_identity node with matched and declined exits. The successful native receipt sets rpc_confirmed; the language model does not select this trust decision.

Related types and helpers: [Cumulus](/docs/sdk-reference/client#cumulus) · [VerificationPolicy](/docs/sdk-reference/agent#verificationpolicy) · [NodeDefinition](/docs/sdk-reference/agent#nodedefinition).

```typescript-declaration
/** Cumulus selects these exits from verified private evidence. A model cannot grant verification. */
export declare function defineVerification(v: {
    key: string;
    policy: VerificationPolicy;
    matched: Destination;
    declined: Destination;
}): NodeDefinition;
```

### defineTokenization {#definetokenization}

Build a tokenize_private node with tokenized and declined exits. Require a tokenization-purpose POST tool using effect_key idempotency; the policy’s tool identity is filled from the tool definition.

Related types and helpers: [TokenizationPolicy](/docs/sdk-reference/agent#tokenizationpolicy) · [ToolDefinition](/docs/sdk-reference/agent#tooldefinition) · [NodeDefinition](/docs/sdk-reference/agent#nodedefinition).

```typescript-declaration
/** Capture is phone-only and requires matching native verification and keypad consent. */
export declare function defineTokenization(v: {
    key: string;
    policy: Omit<TokenizationPolicy, "toolId">;
    tool: ToolDefinition;
    tokenized: Destination;
    declined: Destination;
}): NodeDefinition;
```

## Resolve identities and bindings {#resolve-identities-and-bindings}

### keyOf {#keyof}

Read a stable key from a definition object or return a supplied string key. Useful in graph factories that accept either form.

```typescript-declaration
export declare function keyOf(v: string | {
    key: string;
}): string;
```

### secretReference {#secretreference}

Convert server SecretMetadata into its opaque id and current_version pair. This pins the secret version used by a published endpoint binding.

Related types and helpers: [components](/docs/sdk-reference/client#components).

```typescript-declaration
/** Pin the opaque server-issued secret identity, not the human-readable URL/name used to provision it. */
export declare function secretReference(metadata: components["schemas"]["SecretMetadata"]): {
    id: string;
    version: string;
};
```

### resolveEndpoint {#resolveendpoint}

Resolve an absolute tool path against a credential-free HTTPS endpoint. Require port 443, no query/fragment and the same origin; return the absolute URL.

```typescript-declaration
export declare function resolveEndpoint(base: string, path: string): string;
```

### effectiveTenant {#effectivetenant}

Resolve the API client’s current effective tenant. The result scopes authoring receipts and guards against applying a plan to another tenant.

Related types and helpers: [Cumulus](/docs/sdk-reference/client#cumulus).

```typescript-declaration
export declare function effectiveTenant(client: Cumulus): Promise<string>;
```

### definitionHash {#definitionhash}

Return a SHA-256 identity for canonical serializable definition data. Object key order does not change the identity.

```typescript-declaration
export declare const definitionHash: (value: unknown) => string;
```

### draftHash {#drafthash}

Fingerprint a draft’s semantic definition while excluding state, layout and flow version. Used to detect remote configuration changes around authoring operations.

```typescript-declaration
export declare function draftHash(draft: Draft): string;
```

## Handle authoring failures {#handle-authoring-failures}

### DefinitionError {#definitionerror}

A definition, binding or schema is invalid. code is definition_invalid; diagnostics contains path/message pairs when available.

```typescript-declaration
export declare class DefinitionError extends Error {
    readonly diagnostics: readonly {
        path: string;
        message: string;
    }[];
    readonly code = "definition_invalid";
    constructor(message: string, diagnostics?: readonly {
        path: string;
        message: string;
    }[]);
}
```

### DraftConflict {#draftconflict}

The reviewed draft, tenant or source baseline changed. code is draft_conflict; remote may contain the current public draft for reconciliation.

```typescript-declaration
export declare class DraftConflict extends Error {
    readonly remote?: Draft | undefined;
    readonly code = "draft_conflict";
    constructor(message: string, remote?: Draft | undefined);
}
```

### PartialApplyError {#partialapplyerror}

Draft application stopped after partial progress. code is partial_apply; receipt contains the last checkpoint and cause retains the underlying error. Inspect/export the remote draft before resuming.

Related types and helpers: [ApplyReceipt](/docs/sdk-reference/agent#applyreceipt).

```typescript-declaration
export declare class PartialApplyError extends Error {
    readonly receipt: ApplyReceipt;
    readonly cause: unknown;
    readonly code = "partial_apply";
    constructor(receipt: ApplyReceipt, cause: unknown);
}
```

## Types and declarations {#types}

### Action {#action}

The native customer HTTP action contract generated from a ToolDefinition and EndpointBinding.

Related types and helpers: [DraftEdit](/docs/sdk-reference/agent#draftedit).

```typescript-declaration
export type Action = Extract<DraftEdit, {
    type: "action.put";
}>["action"];
```

### AgentDefinition {#agentdefinition}

Portable source graph: stable key/name, start node, nodes and optional edges/components/tools/settings. edits carries explicit native domain edits after generated graph changes.

Related types and helpers: [NodeDefinition](/docs/sdk-reference/agent#nodedefinition) · [EdgeDefinition](/docs/sdk-reference/agent#edgedefinition) · [components](/docs/sdk-reference/client#components) · [ComponentDefinition](/docs/sdk-reference/agent#componentdefinition) · [ToolDefinition](/docs/sdk-reference/agent#tooldefinition) · [NativeNode](/docs/sdk-reference/agent#nativenode) · [DraftEdit](/docs/sdk-reference/agent#draftedit).

```typescript-declaration
export interface AgentDefinition {
    key: string;
    name: string;
    channels?: ("phone" | "cloud")[];
    languages?: ("en" | "es")[];
    startNode: NodeDefinition | string;
    nodes: NodeDefinition[];
    edges?: EdgeDefinition[];
    components?: ComponentDefinition[];
    tools?: ToolDefinition[];
    settings?: Settings;
    prompt?: string;
    startSpeaker?: "agent" | "user";
    variables?: Record<string, string>;
    contextVariables?: string[];
    modelChoice?: NativeNode["modelChoice"];
    toolCallStrictMode?: boolean;
    /** Native domain edits expose the full configuration contract. Applied after generated graph edits. */
    edits?: DraftEdit[];
}
```

### ApplyOptions {#applyoptions}

Require the reviewed base revision, optionally record sourceCommit, and persist onCheckpoint receipts before consequential network steps.

Related types and helpers: [ApplyReceipt](/docs/sdk-reference/agent#applyreceipt).

```typescript-declaration
export interface ApplyOptions {
    expectedRevision: number | null;
    sourceCommit?: string;
    onCheckpoint?: (receipt: ApplyReceipt) => void | Promise<void>;
}
```

### ApplyReceipt {#applyreceipt}

Persisted management checkpoint identifying tenant, agent, draft revision, fingerprints and managed definition. pendingBatch/pendingPublication record unfinished operations; publication identifies a published version.

Related types and helpers: [definitionHash](/docs/sdk-reference/agent#definitionhash) · [CompiledDefinition](/docs/sdk-reference/agent#compileddefinition) · [draftHash](/docs/sdk-reference/agent#drafthash) · [components](/docs/sdk-reference/client#components) · [DraftEdit](/docs/sdk-reference/agent#draftedit).

```typescript-declaration
export interface ApplyReceipt {
    schemaVersion: 1;
    projectKey: string;
    agentKey: string;
    agentId: string;
    tenantId: string;
    draftId: string;
    revision: number;
    headVersion: number | null;
    definitionHash: string;
    definition: CompiledDefinition;
    draftHash: string;
    sourceCommit?: string;
    publication?: {
        agent_id: string;
        version: number;
        digest: string;
    };
    pendingPublication?: components["schemas"]["PublicationsPublishRequest"];
    pendingBatch?: {
        expectedRevision: number;
        edits: DraftEdit[];
    };
}
```

### AuthoringPreview {#authoringpreview}

The immutable proposed change: compiled definition, effective tenant, remote draft/head baseline, create key and edit summary. Pass it unchanged to apply.

Related types and helpers: [CompiledDefinition](/docs/sdk-reference/agent#compileddefinition) · [definitionHash](/docs/sdk-reference/agent#definitionhash) · [DraftEdit](/docs/sdk-reference/agent#draftedit).

```typescript-declaration
export interface AuthoringPreview {
    schemaVersion: 1;
    projectKey: string;
    definition: CompiledDefinition;
    definitionHash: string;
    agentId?: string;
    tenantId: string;
    baseRevision: number | null;
    draftId: string | null;
    baseHash: string | null;
    headVersion: number | null;
    createKey: string;
    edits: DraftEdit[];
    changes: {
        operation: string;
        target: string;
    }[];
}
```

### CompiledDefinition {#compileddefinition}

The immutable, serializable native output of compileAgent: nodes, components, actions, flow, settings and explicit edits.

Related types and helpers: [NativeNode](/docs/sdk-reference/agent#nativenode) · [components](/docs/sdk-reference/client#components) · [DraftEdit](/docs/sdk-reference/agent#draftedit).

```typescript-declaration
export interface CompiledDefinition {
    schemaVersion: 1;
    key: string;
    name: string;
    channels: ("phone" | "cloud")[];
    languages: ("en" | "es")[];
    nodes: NativeNode[];
    components: {
        id: string;
        startNodeId: string;
        nodes: NativeNode[];
        tools: any[];
        flexMode?: boolean;
    }[];
    actions: Extract<DraftEdit, {
        type: "action.put";
    }>[];
    flow: Extract<DraftEdit, {
        type: "flow.configure";
    }>["changes"];
    settings: Settings;
    edits: DraftEdit[];
}
```

### ComponentDefinition {#componentdefinition}

A scoped graph with a start node, nodes and optional edges/tools. flexMode is the native component flexibility option.

Related types and helpers: [NodeDefinition](/docs/sdk-reference/agent#nodedefinition) · [EdgeDefinition](/docs/sdk-reference/agent#edgedefinition) · [ToolDefinition](/docs/sdk-reference/agent#tooldefinition).

```typescript-declaration
export interface ComponentDefinition {
    key: string;
    startNode: NodeDefinition | string;
    nodes: NodeDefinition[];
    edges?: EdgeDefinition[];
    tools?: ToolDefinition[];
    flexMode?: boolean;
}
```

### DraftEdit {#draftedit}

The full discriminated union of native authoring edits. Use agent.edits or environment.edits when a native setting has no dedicated composition helper.

Related types and helpers: [components](/docs/sdk-reference/client#components).

```typescript-declaration
export type DraftEdit = components["schemas"]["DraftEdit"];
```

### EdgeDefinition {#edgedefinition}

A native transition with source from/to references and optional key. slot and condition keep their native graph meanings.

Related types and helpers: [NativeEdge](/docs/sdk-reference/agent#nativeedge) · [NodeDefinition](/docs/sdk-reference/agent#nodedefinition).

```typescript-declaration
export type EdgeDefinition = Omit<NativeEdge, "id" | "destinationNodeId"> & {
    key?: string;
    from: NodeDefinition | string;
    to?: NodeDefinition | string;
};
```

### EndpointBinding {#endpointbinding}

A deployed HTTPS base URL, native authentication policy and optional non-secret headers. Credentials are pinned secret references.

Related types and helpers: [Action](/docs/sdk-reference/agent#action).

```typescript-declaration
export interface EndpointBinding {
    baseUrl: string;
    auth: Action["auth"];
    headers?: Record<string, string>;
}
```

### EnvironmentBindings {#environmentbindings}

Maps portable endpoint, phone number and notification aliases to one deployment’s resources; optional edits adds native environment configuration.

Related types and helpers: [EndpointBinding](/docs/sdk-reference/agent#endpointbinding) · [SecretRef](/docs/sdk-reference/agent#secretref) · [DraftEdit](/docs/sdk-reference/agent#draftedit).

```typescript-declaration
export interface EnvironmentBindings {
    endpoints?: Record<string, EndpointBinding>;
    numbers?: Record<string, string>;
    notifications?: Record<string, {
        url: string;
        secretRef: SecretRef;
    }>;
    edits?: DraftEdit[];
}
```

### InferSchema {#inferschema}

Infer common JSON Schema primitives, enum/const, objects, arrays and unions. Other valid patterns remain unknown at the TypeScript level.

```typescript-declaration
/** Inference covers primitives, objects, arrays, enums and unions. Other valid schemas remain unknown. */
export type InferSchema<S> = S extends {
    enum: readonly (infer V)[];
} ? V : S extends {
    const: infer V;
} ? V : S extends {
    anyOf: readonly (infer U)[];
} ? InferSchema<U> : S extends {
    oneOf: readonly (infer U)[];
} ? InferSchema<U> : S extends {
    type: "string";
} ? string : S extends {
    type: "number" | "integer";
} ? number : S extends {
    type: "boolean";
} ? boolean : S extends {
    type: "null";
} ? null : S extends {
    type: "array";
    items: infer I;
} ? InferSchema<I>[] : S extends {
    type: "object";
} ? {
    [K in keyof Properties<S> as K extends RequiredKeys<S> ? K : never]: InferSchema<Properties<S>[K]>;
} & {
    [K in keyof Properties<S> as K extends RequiredKeys<S> ? never : K]?: InferSchema<Properties<S>[K]>;
} : unknown;
```

### IntegrationDefinition {#integrationdefinition}

The agent plus optional inbound context, caller-ID binding and semantic-event subscriptions.

Related types and helpers: [AgentDefinition](/docs/sdk-reference/agent#agentdefinition).

```typescript-declaration
export interface IntegrationDefinition {
    key: string;
    agent: AgentDefinition;
    inbound?: {
        numberBinding: string;
        contextResolver?: string;
        contextOutputs?: string[];
    };
    outbound?: {
        callerIdBinding: string;
    };
    events?: {
        destinationBinding: string;
        subscriptions: ("run.admitted" | "run.ended" | "recording.updated" | "analysis.updated")[];
    };
}
```

### JSONSchema {#jsonschema}

A JSON Schema object used for tool contracts. The SDK validates supported schema structure at runtime.

```typescript-declaration
export type JSONSchema = {
    readonly [keyword: string]: unknown;
};
```

### NativeEdge {#nativeedge}

The native transition contract shared by node edges and EdgeDefinition.

Related types and helpers: [NativeNode](/docs/sdk-reference/agent#nativenode).

```typescript-declaration
export type NativeEdge = NativeNode["edges"][number];
```

### NativeNode {#nativenode}

The complete native node union extracted from node.create. NodeDefinition adapts it for source references.

Related types and helpers: [DraftEdit](/docs/sdk-reference/agent#draftedit).

```typescript-declaration
export type NativeNode = Extract<DraftEdit, {
    type: "node.create";
}>["node"];
```

### NodeDefinition {#nodedefinition}

A native node with a source key instead of ID. tool and component accept source objects or keys; native IDs can also be supplied explicitly.

Related types and helpers: [NativeNode](/docs/sdk-reference/agent#nativenode) · [NativeEdge](/docs/sdk-reference/agent#nativeedge) · [ToolDefinition](/docs/sdk-reference/agent#tooldefinition) · [ComponentDefinition](/docs/sdk-reference/agent#componentdefinition).

```typescript-declaration
export type NodeDefinition = Omit<NativeNode, "id" | "edges" | "toolId" | "componentId"> & {
    key: string;
    edges?: NativeEdge[];
    tool?: ToolDefinition | string;
    component?: ComponentDefinition | string;
    toolId?: string;
    componentId?: string;
};
```

### PreviewOptions {#previewoptions}

Choose an existing agent, management project and previous receipt. acceptRemoteRevision explicitly adopts a remote draft revision after reviewing/backporting it.

`projectKey` names your source management scope. `receipt` identifies the managed agent and last applied baseline. `integration` selects the context and notification connections to compile. `agentId` explicitly selects an existing agent; it takes precedence over the receipt’s agent ID. `acceptRemoteRevision` adopts only that reviewed draft revision. Forward these options to `authoring.preview` when writing your own deployment helper.

Related types and helpers: [ApplyReceipt](/docs/sdk-reference/agent#applyreceipt) · [IntegrationDefinition](/docs/sdk-reference/agent#integrationdefinition).

```typescript-declaration
export interface PreviewOptions {
    projectKey?: string;
    agentId?: string;
    receipt?: ApplyReceipt;
    integration?: IntegrationDefinition;
    /** Explicitly adopt this remote revision after review/backport. Never use an implicit force overwrite. */
    acceptRemoteRevision?: number;
}
```

### ProjectDefinition {#projectdefinition}

A stable project key with optional arrays of agents and integrations.

Related types and helpers: [AgentDefinition](/docs/sdk-reference/agent#agentdefinition) · [IntegrationDefinition](/docs/sdk-reference/agent#integrationdefinition).

```typescript-declaration
export interface ProjectDefinition {
    key: string;
    agents?: AgentDefinition[];
    integrations?: IntegrationDefinition[];
}
```

### SecretRef {#secretref}

Opaque secret identity plus version. It references a provisioned credential; it contains no credential value.

```typescript-declaration
export type SecretRef = {
    id: string;
    version: string;
};
```

### TokenizationPolicy {#tokenizationpolicy}

The full native tokenize_private policy. defineTokenization fills its toolId from the selected tool.

Related types and helpers: [NativeNode](/docs/sdk-reference/agent#nativenode).

```typescript-declaration
export type TokenizationPolicy = NonNullable<NativeNode["tokenization"]>;
```

### ToolDefinition {#tooldefinition}

A portable tool schema and HTTP execution policy. responseVariables maps output JSON paths to native scalar variables; responseVariablePolicy selects required versus replace_available mapping.

Related types and helpers: [JSONSchema](/docs/sdk-reference/agent#jsonschema) · [Action](/docs/sdk-reference/agent#action).

```typescript-declaration
export interface ToolDefinition<I extends JSONSchema = JSONSchema, O extends JSONSchema = JSONSchema> {
    key: string;
    description: string;
    input: I;
    output: O;
    channels?: Action["channels"];
    purpose?: "tokenization";
    execution: {
        type: "http";
        binding: string;
        path: string;
        method: Action["method"];
        timeoutMs: number;
        idempotency: Action["idempotency"];
        onUncertain?: Action["on_uncertain"];
    };
    responseVariables?: Record<string, string>;
    responseVariablePolicy?: "required" | "replace_available";
    speakAfterExecution?: boolean;
}
```

### ToolInput {#toolinput}

Infer the application input type from a ToolDefinition’s JSON input schema.

Related types and helpers: [ToolDefinition](/docs/sdk-reference/agent#tooldefinition) · [InferSchema](/docs/sdk-reference/agent#inferschema).

```typescript-declaration
export type ToolInput<T extends ToolDefinition> = InferSchema<T["input"]>;
```

### ToolOutput {#tooloutput}

Infer the application output type from a ToolDefinition’s JSON output schema.

Related types and helpers: [ToolDefinition](/docs/sdk-reference/agent#tooldefinition) · [InferSchema](/docs/sdk-reference/agent#inferschema).

```typescript-declaration
export type ToolOutput<T extends ToolDefinition> = InferSchema<T["output"]>;
```

### VerificationPolicy {#verificationpolicy}

The full native verify_identity policy, including verification method and trust output rules.

Related types and helpers: [NativeNode](/docs/sdk-reference/agent#nativenode).

```typescript-declaration
export type VerificationPolicy = NonNullable<NativeNode["verification"]>;
```

## Supporting types {#supporting-types}

These local type expressions appear in the signatures above. They are not separate package exports.

```typescript-declaration
type Properties<S> = S extends {
    properties: infer P;
} ? P : {};

type RequiredKeys<S> = S extends {
    required: readonly (infer K)[];
} ? K : never;

type Settings = Extract<DraftEdit, {
    type: "agent.settings";
}>["values"];

type Draft = components["schemas"]["DraftsGetResponse200"];

type Destination = NodeDefinition | string;
```

## Export index {#exports}

- **Compose an agent:** [defineAgent](#defineagent) · [defineNode](#definenode) · [defineEdge](#defineedge) · [defineComponent](#definecomponent) · [defineTool](#definetool) · [defineIntegration](#defineintegration) · [defineProject](#defineproject) · [defineEnvironment](#defineenvironment) · [compileAgent](#compileagent)
- **Review and publish changes:** [authoring](#authoring) · [preview](#preview) · [apply](#apply) · [validate](#validate) · [publish](#publish) · [promote](#promote) · [exportDraft](#exportdraft)
- **Define private workflows:** [defineVerification](#defineverification) · [defineTokenization](#definetokenization)
- **Resolve identities and bindings:** [keyOf](#keyof) · [secretReference](#secretreference) · [resolveEndpoint](#resolveendpoint) · [effectiveTenant](#effectivetenant) · [definitionHash](#definitionhash) · [draftHash](#drafthash)
- **Handle authoring failures:** [DefinitionError](#definitionerror) · [DraftConflict](#draftconflict) · [PartialApplyError](#partialapplyerror)
- **Types:** [Action](#action) · [AgentDefinition](#agentdefinition) · [ApplyOptions](#applyoptions) · [ApplyReceipt](#applyreceipt) · [AuthoringPreview](#authoringpreview) · [CompiledDefinition](#compileddefinition) · [ComponentDefinition](#componentdefinition) · [DraftEdit](#draftedit) · [EdgeDefinition](#edgedefinition) · [EndpointBinding](#endpointbinding) · [EnvironmentBindings](#environmentbindings) · [InferSchema](#inferschema) · [IntegrationDefinition](#integrationdefinition) · [JSONSchema](#jsonschema) · [NativeEdge](#nativeedge) · [NativeNode](#nativenode) · [NodeDefinition](#nodedefinition) · [PreviewOptions](#previewoptions) · [ProjectDefinition](#projectdefinition) · [SecretRef](#secretref) · [TokenizationPolicy](#tokenizationpolicy) · [ToolDefinition](#tooldefinition) · [ToolInput](#toolinput) · [ToolOutput](#tooloutput) · [VerificationPolicy](#verificationpolicy)
