Tela SDK for JavaScript
    Preparing search index...

    Class CanvasExecution<TParams, TInput, TOutput>

    Manages the execution lifecycle of a canvas.

    Handles synchronous, asynchronous (with polling), and streaming execution modes. Automatically uploads TelaFile instances and validates results based on output schema.

    The execution status can be accessed via the status property and tracks the lifecycle:

    • Sync executions: succeeded or failed (set after validation completes)
    • Async executions: createdrunningsucceeded or failed (updated during polling)
    • Stream executions: streaming (set when stream starts)

    Status is set to failed when:

    • API request fails
    • Validation fails (for both sync and async)
    • Polling reports failure status

    Status is set to succeeded only after:

    • API request succeeds AND
    • Output validation passes (if schema provided)

    poll - Emitted during async polling with current status and output. Includes requestId from the polling request. (async executions only)

    success - Emitted when execution completes successfully with the final result. Includes requestId from the final request.

    error - Emitted when execution fails (only if error listeners are registered, otherwise throws)

    statusChange - Emitted when execution status transitions to a new state

    const execution = await canvas.execute({ query: 'test' }, { async: true })

    // Track status changes
    execution.on('statusChange', (status) => {
    console.log(`Status: ${status}`) // created → running → succeeded
    })

    // Access current status at any time
    console.log(execution.status) // 'running'

    const result = await execution.result
    console.log(execution.status) // 'succeeded'

    Type Parameters

    Hierarchy

    Index

    Constructors

    • Creates a new canvas execution instance.

      Type Parameters

      Parameters

      • variables: TInput

        Input variables to be passed to the canvas template.

      • params: TParams = ...

        Execution parameters controlling sync/async/stream behavior.

      • outputSchema:
            | Record<string, unknown>
            | ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

        Zod schema or object schema for validating/parsing output.

      • client: BaseClient

        HTTP client instance for making API requests.

      • isTask: boolean = false

      Returns CanvasExecution<TParams, TInput, TOutput>

    Accessors

    • get id(): string

      Gets the unique execution ID assigned by the server.

      Note: Streaming executions do not have an ID as they don't create a tracked execution on the server.

      Returns string

      The execution ID.

      If the execution has not been started yet.

      If called on a streaming execution (streams don't have IDs).

    • get isAsync(): boolean

      Checks if this execution is configured for asynchronous processing.

      Returns boolean

      True if async mode is enabled.

    • get isStream(): boolean

      Checks if this execution is configured for streaming responses.

      Returns boolean

      True if stream mode is enabled.

    • get isSync(): boolean

      Checks if this execution is configured for synchronous processing.

      Returns boolean

      True if sync mode is enabled (not async).

    • get params(): TParams

      Gets the execution parameters configured for this instance.

      Returns TParams

      The execution parameters or undefined.

    • get rawResult(): Promise<any>

      Gets the raw API response without any processing or validation. Automatically starts execution and waits for completion (including polling for async executions).

      For sync executions, returns the complete API response. For async executions, returns the polling response with status and output.

      Returns Promise<any>

      A promise resolving to the raw API result.

      If called on a streaming execution.

    • get requestId(): Promise<string>

      Gets the request ID from the x-request-id header of the execution creation request.

      This is the request ID from the initial POST /v2/chat/completions request that created the execution. Each API request has its own unique request ID.

      For async executions, different request IDs are available:

      • execution.requestId - ID from the execution creation request
      • pollResult.requestId - ID from each polling request (in poll events)
      • result.requestId - ID from the final successful polling request (in success events)

      Returns Promise<string>

      A promise that resolves to the request ID from the execution creation request.

      If the execution has not been started yet.

      const execution = await canvas.execute({ query: 'test' })
      const requestId = await execution.requestId
      console.log('Request ID:', requestId)
      const execution = await canvas.execute({ query: 'test' }, { async: true })

      // Request ID from execution creation
      const creationRequestId = await execution.requestId

      // Request IDs from polling
      execution.on('poll', (pollResult) => {
      console.log('Poll request ID:', pollResult.requestId)
      })

      // Request ID from final result
      execution.on('success', (result) => {
      console.log('Final request ID:', result.requestId)
      })

      execution.poll()
    • get status(): ExecutionStatus

      Gets the latest known status of the execution.

      Status values and transitions:

      • Sync: succeeded (after validation) or failed (on any error)
      • Async: createdrunningsucceeded or failed
      • Stream: streaming (once started)

      Important: Status is set to succeeded only after successful validation. If validation fails, status will be failed even if the API request succeeded.

      Use the statusChange event to track status transitions in real-time.

      Returns ExecutionStatus

      The current status of the execution.

      If the execution has not been started yet.

      const execution = await canvas.execute({ query: 'test' }, { async: true })
      console.log(execution.status) // 'created'

      await execution.result
      console.log(execution.status) // 'succeeded' or 'failed'
    • get task(): TaskDefinition | undefined

      Gets the task associated with this execution if it was created from an application.

      Returns TaskDefinition | undefined

      The task creation result or undefined.

    • get variables(): TInput

      Gets the input variables provided to this execution.

      Returns TInput

      The variables object.

    Methods

    • Cancels the ongoing execution by aborting all active requests and polling operations.

      Returns void

    • Starts polling for the execution result without waiting for the promise to resolve. This allows users to track execution progress via events rather than awaiting a promise.

      The following events will be emitted during polling:

      • statusChange: Emitted when the execution status changes (e.g., 'created' → 'running' → 'succeeded')
      • poll: Emitted on each polling attempt with the server response
      • success: Emitted when the execution completes successfully with the final result
      • error: Emitted if the execution fails

      Important: Events are only emitted while polling is active. You must either call poll() or await execution.result to start polling. Simply setting up event listeners without starting polling will not trigger any events.

      Note: If the execution has already completed (succeeded or failed) when fetched, the success and error events will not fire since no polling is needed. Check the status property and access the result directly for already-completed executions.

      Returns void

      If called on a non-async execution (sync or stream).

      If the execution has not been started yet (no ID assigned).

      const execution = await canvas.getExecution('execution-id')

      // Check if already completed
      if (execution.status === 'succeeded' || execution.status === 'failed') {
      // Access result directly - events won't fire
      const result = await execution.result
      console.log('Already completed:', result)
      } else {
      // Still running - set up events and start polling
      execution.on('statusChange', (status) => {
      console.log('Status:', status)
      })

      execution.on('success', (result) => {
      console.log('Completed:', result)
      })

      execution.on('error', (error) => {
      console.error('Failed:', error)
      })

      // Start polling without waiting
      execution.poll()
      }
    • Starts the execution based on configured parameters. Routes to the appropriate execution method (sync, async, or stream).

      Returns Promise<
          | CanvasExecutionResult<TParams, TOutput>
          | AsyncGenerator<Partial<TOutput>, any, any>
          | AsyncCompletionCreateResult & { requestId?: string }
          | Omit<
              {
                  approvedAt: any;
                  approvedBy: any;
                  completionRunId: string;
                  createdAt: string;
                  createdBy: string;
                  deletedAt: any;
                  id: string;
                  inputContent: any;
                  metadata: any;
                  name: string;
                  originalOutputContent: {
                      content: unknown;
                      functionCall: any;
                      role: "assistant";
                      toolCalls: any[];
                  };
                  outputContent: {
                      content: unknown;
                      functionCall: any;
                      role: "assistant";
                      toolCalls: any[];
                  };
                  promptApplicationId: string;
                  promptVersionId: string;
                  rawInput: {
                      applicationId: string;
                      async: boolean;
                      stream: boolean;
                      variables: Record<string, unknown>;
                  };
                  reference: number;
                  requestId: string;
                  status: | "created"
                  | "failed"
                  | "running"
                  | "validating"
                  | "completed"
                  | "cancelled";
                  tags: string[];
                  updatedAt: string;
                  workflowRunId: any;
                  workspaceId: string;
              },
              "outputContent"
              | "originalOutputContent",
          > & {
              originalOutputContent: {
                  content: unknown;
                  functionCall: any;
                  role: "assistant";
                  toolCalls: any[];
              };
              outputContent: {
                  content: unknown;
                  functionCall: any;
                  role: "assistant";
                  toolCalls: any[];
              };
          } & { requestId?: string },
      >

      A promise or async generator depending on execution mode.

    • Fetches an existing asynchronous execution by its ID.

      This method retrieves the current state of an async execution and creates a new CanvasExecution instance with the fetched data. Only async executions can be fetched, as they are the only ones with persistent UUIDs on the server.

      Type Parameters

      • TOutput = unknown

      Parameters

      • id: string

        The UUID of the async execution to fetch.

      • outputSchema:
            | Record<string, unknown>
            | ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>

        Zod schema or object schema for validating/parsing output.

      • client: BaseClient

        HTTP client instance for making API requests.

      • Optionaloptions: {
            isTask?: boolean;
            pollingInterval?: string | number;
            pollingTimeout?: string | number;
        }

        Optional configuration for polling behavior.

        • OptionalisTask?: boolean

          Whether the execution is a task of a workstation.

        • OptionalpollingInterval?: string | number

          Time in milliseconds between polling attempts (default: 1000).

        • OptionalpollingTimeout?: string | number

          Maximum time in milliseconds to wait for completion (default: 60000).

      Returns Promise<CanvasExecution<AsyncExecutionParams, unknown, TOutput>>

      A promise resolving to a CanvasExecution instance with the fetched state.

      If the provided ID is not a valid UUID.

      const execution = await CanvasExecution.fetch(
      'execution-uuid',
      z.object({ result: z.string() }),
      client,
      { pollingInterval: 2000, pollingTimeout: 120000 }
      )
      console.log(execution.status) // 'running' or 'succeeded' or 'failed'