@stackbone/sdk 0.1.0-alpha.5 → 0.1.0-alpha.6

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.
package/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AgentConnectionListResponse, InvokeConnectorActionResponse, PublishJobResponse, ScheduleJobResponse, UnscheduleJobResponse, ListSchedulesResponse, ContractResponse } from '@stackbone/validators';
2
- import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
3
2
  import { Sql } from 'postgres';
3
+ import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
4
4
  import { IngestJobWriter, IngestRequest, IngestResponse, RagIngestProgress, DeleteOptions, DeleteResponse, RetrieveRequest, RetrieveHit, ChunkOptions, ParseInput, ParseOptions } from '@stackbone/rag-core';
5
5
  export { ChunkOptions, ChunkStrategy, DeleteOptions, DeleteResponse, IngestChunk, IngestRequest, IngestRequestAutoEmbed, IngestRequestPrecomputed, IngestResponse, ParseInput, ParseOptions, RagIngestProgress, RetrieveHit, RetrieveRequest, RetrieveRequestAutoEmbed, RetrieveRequestPrecomputed } from '@stackbone/rag-core';
6
6
  import OpenAI from 'openai';
@@ -77,7 +77,7 @@ interface ClientConfig {
77
77
  * RAG-related defaults parsed from `agent.yaml.rag` by the CLI/orchestrator
78
78
  * and forwarded here. The SDK never reads `agent.yaml` itself — keeping
79
79
  * filesystem ownership in the CLI. Defaults follow ADR
80
- * `2026-05-10-rag-consolidation-on-client-database` (D2/D6).
80
+ * `2026-06-05-rag` (D2/D6).
81
81
  */
82
82
  rag?: {
83
83
  /**
@@ -483,6 +483,43 @@ declare class DatabaseModule {
483
483
  delete: DrizzleClient['delete'];
484
484
  execute: DrizzleClient['execute'];
485
485
  transaction: DrizzleClient['transaction'];
486
+ /**
487
+ * Cross-surface raw-SQL runner carrying the SAME cold-start resilience the
488
+ * query-builder verbs above get. Sibling agent-local surfaces (`approval`,
489
+ * `config`, `secrets`, `prompts`) that issue tagged-template queries over the
490
+ * shared postgres-js `Sql` MUST execute them through this instead of caching
491
+ * `shared().$client` once and calling it directly. Otherwise a dead pooled
492
+ * socket — Fly Machines suspending the Machine between invokes, or a
493
+ * WSL2/Docker localhost relay dropping an idle connection during a long LLM
494
+ * step — surfaces as an unretried `CONNECTION_ENDED`/`ECONNRESET`. That is
495
+ * exactly the asymmetry that let `client.approval.request` fail while the
496
+ * `client.database.insert` right before it recovered.
497
+ *
498
+ * `fn` receives a FRESH `$client` on each attempt, so the single retry runs
499
+ * against the rebuilt pool. Whole-operation granularity is replayed as a
500
+ * unit — pass a multi-statement `sql.begin(...)` transaction or a helper that
501
+ * fires several queries and the replay re-runs all of it; postgres-js never
502
+ * commits a half-applied tx, so that is safe. SQLSTATE application errors
503
+ * pass straight through without a retry. Like `shared()`/`raw()`, the
504
+ * contract gate is intentionally NOT consulted here — gating surfaces gate at
505
+ * their own call sites.
506
+ */
507
+ runShared<T>(fn: (sql: Sql) => Promise<T> | T): Promise<T>;
508
+ /**
509
+ * `Result`-shaped sibling of `runShared` for surfaces whose driver swallows
510
+ * the dead-socket error into a returned `Result.err.cause` instead of
511
+ * throwing it — today only `client.rag`, whose `RagPipeline` returns a
512
+ * `Result` rather than throwing. `attempt` runs once; if it comes back with a
513
+ * pool-terminated `cause`, the pool is rebuilt and `attempt` replays exactly
514
+ * once, then its result (success or the fresh error) is returned verbatim.
515
+ * The `Result` contract is preserved end to end: a still-dead socket on the
516
+ * replay surfaces as the surface's own `Result.err`, never as a raw throw.
517
+ */
518
+ runSharedResult<T extends {
519
+ error?: {
520
+ cause?: unknown;
521
+ } | null;
522
+ }>(attempt: () => Promise<T>): Promise<T>;
486
523
  /**
487
524
  * Canonical accessor for the **shared-handles pattern**. Returns the
488
525
  * process-wide Drizzle handle backing `client.database`. Cross-surface
@@ -949,7 +986,7 @@ interface IngestAsyncHandle {
949
986
  * Implementation note: `RagModule` is a thin facade over `RagPipeline`. The
950
987
  * pipeline owns parse → chunk → embed → persist; the facade resolves the
951
988
  * shared `client.database` pool, builds an `Embedder` on demand, and maps
952
- * configuration errors. See ADR `2026-05-10-rag-consolidation-on-client-database`.
989
+ * configuration errors. See ADR `2026-06-05-rag`.
953
990
  *
954
991
  * Connection ownership: this module never opens its own postgres pool. It
955
992
  * reaches the underlying `postgres-js` `Sql` through the **shared-handles
@@ -1738,6 +1775,22 @@ declare const createStructuredLogger: (opts?: StructuredLoggerOptions) => Logger
1738
1775
  * - `logger` is a child of the wrapper's structured logger already
1739
1776
  * bound to `invocationId` and `runId`, so the handler does not have to
1740
1777
  * pass them on every line. The actual JSON format lands in F6.
1778
+ * - `stream` is present **only** when the caller requested a streamed reply
1779
+ * (an SSE `/invoke`). The handler pushes incremental output through it —
1780
+ * `delta(text)` for token-by-token text and `event(name, data?)` for a
1781
+ * named structured event — and the wrapper relays each onto the open
1782
+ * socket as it is produced. On a plain (buffered) invoke `stream` is
1783
+ * `undefined`, so a handler that wants to stream guards on it and falls
1784
+ * back to returning its `output` normally.
1785
+ * - `progress` / `step` are the **live run progress** helpers (distinct from
1786
+ * token streaming): they record `run_steps` rows on the run so the Studio
1787
+ * runs timeline fills in as the handler works. `progress(message, data?)` is
1788
+ * a coarse, point-in-time note; `step({ type, name })` opens a span and
1789
+ * returns a handle whose `.finish()` closes it with a duration. Both are
1790
+ * runtime-injected and fire-and-forget — they are wired to the install's
1791
+ * Postgres by the wrapper, are absent (no-op) when no run writer is mounted
1792
+ * (e.g. plain unit tests), and the wrapper throttles `progress` so a hot
1793
+ * loop cannot flood the run with notes.
1741
1794
  */
1742
1795
  interface InvokeContext<I extends z.ZodType> {
1743
1796
  input: z.infer<I>;
@@ -1746,7 +1799,76 @@ interface InvokeContext<I extends z.ZodType> {
1746
1799
  runId: string;
1747
1800
  client: StackboneClient;
1748
1801
  logger: Logger;
1802
+ stream?: InvokeStream;
1803
+ progress?: InvokeProgress;
1804
+ step?: InvokeStepFn;
1805
+ }
1806
+ /**
1807
+ * The streaming sink handed to a handler as `ctx.stream` when the caller asked
1808
+ * for a streamed `/invoke`. Both methods are fire-and-forget — the handler
1809
+ * emits, the wrapper relays — so neither returns a promise the handler must
1810
+ * await.
1811
+ */
1812
+ interface InvokeStream {
1813
+ /** Emit an incremental chunk of text (e.g. a model token). */
1814
+ delta(text: string): void;
1815
+ /** Emit a named structured event with an optional JSON-serialisable payload. */
1816
+ event(name: string, data?: unknown): void;
1817
+ }
1818
+ /**
1819
+ * The closed set of step types `ctx.step` / `ctx.progress` may record. It
1820
+ * mirrors the CHECK constraint on `stackbone_platform.run_steps.type`; an
1821
+ * unknown type would be rejected by Postgres, so the contract enumerates the
1822
+ * allowed values at the type layer too. `agent` is the catch-all a coarse
1823
+ * `progress` note records under.
1824
+ */
1825
+ type RunStepType = 'agent' | 'llm_call' | 'db_query' | 'http_fetch' | 'queue_publish' | 'hitl_pause' | 'tool_call' | 'rag_query' | 'storage_op';
1826
+ /**
1827
+ * `ctx.progress` — a coarse, point-in-time note on the run, distinct from the
1828
+ * token-level `ctx.stream`. The wrapper writes one `run_steps` row (type
1829
+ * `agent`) per call, opened and closed in place, so it shows up immediately on
1830
+ * the Studio timeline. Fire-and-forget: it returns nothing the handler must
1831
+ * await, and the wrapper throttles calls to ~1/s so a hot loop cannot flood the
1832
+ * run. `data` is an optional JSON-serialisable payload stored on the row.
1833
+ */
1834
+ type InvokeProgress = (message: string, data?: unknown) => void;
1835
+ /** Opening descriptor for `ctx.step`. */
1836
+ interface StepOptions {
1837
+ /** One of the canonical `run_steps` types; defaults to `agent` when omitted. */
1838
+ type?: RunStepType;
1839
+ /** Human-readable label for the step (the `run_steps.name` column). */
1840
+ name: string;
1841
+ /** Optional JSON-serialisable payload stored on the opened row. */
1842
+ data?: unknown;
1843
+ }
1844
+ /** Closing descriptor for a `StepHandle.finish`. */
1845
+ interface StepFinishOptions {
1846
+ /** Terminal status; defaults to `ok`. */
1847
+ status?: 'ok' | 'error';
1848
+ /** Failure detail recorded on the row when the step errored. */
1849
+ error?: string;
1850
+ /** Optional JSON-serialisable payload merged onto the row at finish. */
1851
+ data?: unknown;
1749
1852
  }
1853
+ /**
1854
+ * Handle returned by `ctx.step`. The handler calls `.finish()` when the work the
1855
+ * step represents completes, which closes the open `run_steps` row with a
1856
+ * duration and terminal status. Calling `.finish()` more than once is a no-op —
1857
+ * the first close wins.
1858
+ */
1859
+ interface StepHandle {
1860
+ /** The id of the opened `run_steps` row (useful for nesting / correlation). */
1861
+ readonly id: string;
1862
+ /** Close the step. Idempotent: only the first call writes a terminal row. */
1863
+ finish(options?: StepFinishOptions): void;
1864
+ }
1865
+ /**
1866
+ * `ctx.step` — opens a span on the run and returns a handle to close it. The
1867
+ * wrapper writes a `run_steps` row in the `running` state on open and updates it
1868
+ * to `ok`/`error` with a duration on `.finish()`. Fire-and-forget like
1869
+ * `ctx.progress`; absent (no-op handle) when no run writer is mounted.
1870
+ */
1871
+ type InvokeStepFn = (options: StepOptions) => StepHandle;
1750
1872
  /**
1751
1873
  * The synchronous `invoke` capability. Mirrors the wrapper's three HTTP verbs
1752
1874
  * (`/invoke`, `/health`, `/schema`): `invoke` is the only request path, its
@@ -2120,4 +2242,4 @@ interface JsonSchemaDocument {
2120
2242
  */
2121
2243
  declare const analyzeAgentSchemas: (pair: AgentSchemaPair) => SchemaIntrospectionResult;
2122
2244
 
2123
- export { type AddMemoryRequest, type AgentSchemaPair, type AgentSpec, type AnyCapability, type ApprovalListOptions, type ApprovalListResult, type ApprovalRecord, type ApprovalRequest, type ApprovalRequestOptions, type ApprovalStatus, type ApprovalTool, type ApprovalToolSpec, type ApprovalTopic, type ApproverInfo, type ClientConfig, type CompilePromptResult, type ConsoleLike, type CreatePromptRequest, type Decision, type DecisionStatus, type DeleteAllMemoryRequest, type DeletePromptOptions, type DeletePromptResult, type EndSessionOptions, type EndSessionResult, type FatalConstruct, type GeneratedImage, type GetPromptOptions, INVOCATION_ID_HEADER, INVOKE_TIMEOUT_HARD_CAP_MS, type ImageGenerateParams, type ImagesResponse, type IngestAsyncHandle, type InstallConsoleCaptureOptions, type InvocationContext, type InvokeCapability, type InvokeContext, type InvokeEnvelopeError, type InvokeErrorEnvelope, type InvokeOptions, type InvokeRequest, type InvokeResponse, type InvokeSuccessEnvelope, type JobCapability, type JsonSchemaDocument, type ListMemoryRequest, type ListMemoryResult, type ListOptions, type ListPromptsOptions, type ListPromptsResult, type LoadSystemSecretsArgs, type LogSink, type Logger, type LoggerBindings, type MemoryContent, type MemoryHistoryEntry, type MemoryHistoryEvent, type MemoryHit, type MemoryItem, type MemoryScope, type ModelsListResponse, type OpenRouterModel, type Prompt, type PublishRequest, RESERVED_ERROR_CODES, RESERVED_HANDLER_NAMES, RUN_ID_HEADER, type ReservedErrorCode, type Result, STORED_TO_SDK_ENV, type ScheduleRequest, type SchemaDiagnostic, type SchemaHalf, type SchemaIntrospectionResult, type SdkError, type SdkErrorCode, type SearchMemoryOptions, type SignedUrl, type SignedUrlOptions, StackboneClient, type StorageBody, type StorageObject, type StructuredLoggerOptions, type SystemSecretRow, type SystemSecretsReader, type UnscheduleRequest, type UpdateMemoryOptions, type UpdatePromptOptions, type UploadOptions, type VerifyOptions, type WarnConstruct, analyzeAgentSchemas, createClient, createStructuredLogger, defineAgent, getInvocationContext, installInvocationConsoleCapture, invokeRequestSchema, isReservedErrorCode, isSdkErrorCode, loadSystemSecretsIntoEnv, rehydrateSystemSecretsRows, runWithInvocationContext };
2245
+ export { type AddMemoryRequest, type AgentSchemaPair, type AgentSpec, type AnyCapability, type ApprovalListOptions, type ApprovalListResult, type ApprovalRecord, type ApprovalRequest, type ApprovalRequestOptions, type ApprovalStatus, type ApprovalTool, type ApprovalToolSpec, type ApprovalTopic, type ApproverInfo, type ClientConfig, type CompilePromptResult, type ConsoleLike, type CreatePromptRequest, type Decision, type DecisionStatus, type DeleteAllMemoryRequest, type DeletePromptOptions, type DeletePromptResult, type EndSessionOptions, type EndSessionResult, type FatalConstruct, type GeneratedImage, type GetPromptOptions, INVOCATION_ID_HEADER, INVOKE_TIMEOUT_HARD_CAP_MS, type ImageGenerateParams, type ImagesResponse, type IngestAsyncHandle, type InstallConsoleCaptureOptions, type InvocationContext, type InvokeCapability, type InvokeContext, type InvokeEnvelopeError, type InvokeErrorEnvelope, type InvokeOptions, type InvokeProgress, type InvokeRequest, type InvokeResponse, type InvokeStepFn, type InvokeStream, type InvokeSuccessEnvelope, type JobCapability, type JsonSchemaDocument, type ListMemoryRequest, type ListMemoryResult, type ListOptions, type ListPromptsOptions, type ListPromptsResult, type LoadSystemSecretsArgs, type LogSink, type Logger, type LoggerBindings, type MemoryContent, type MemoryHistoryEntry, type MemoryHistoryEvent, type MemoryHit, type MemoryItem, type MemoryScope, type ModelsListResponse, type OpenRouterModel, type Prompt, type PublishRequest, RESERVED_ERROR_CODES, RESERVED_HANDLER_NAMES, RUN_ID_HEADER, type ReservedErrorCode, type Result, type RunStepType, STORED_TO_SDK_ENV, type ScheduleRequest, type SchemaDiagnostic, type SchemaHalf, type SchemaIntrospectionResult, type SdkError, type SdkErrorCode, type SearchMemoryOptions, type SignedUrl, type SignedUrlOptions, StackboneClient, type StepFinishOptions, type StepHandle, type StepOptions, type StorageBody, type StorageObject, type StructuredLoggerOptions, type SystemSecretRow, type SystemSecretsReader, type UnscheduleRequest, type UpdateMemoryOptions, type UpdatePromptOptions, type UploadOptions, type VerifyOptions, type WarnConstruct, analyzeAgentSchemas, createClient, createStructuredLogger, defineAgent, getInvocationContext, installInvocationConsoleCapture, invokeRequestSchema, isReservedErrorCode, isSdkErrorCode, loadSystemSecretsIntoEnv, rehydrateSystemSecretsRows, runWithInvocationContext };
package/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AgentConnectionListResponse, InvokeConnectorActionResponse, PublishJobResponse, ScheduleJobResponse, UnscheduleJobResponse, ListSchedulesResponse, ContractResponse } from '@stackbone/validators';
2
- import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
3
2
  import { Sql } from 'postgres';
3
+ import { PostgresJsDatabase } from 'drizzle-orm/postgres-js';
4
4
  import { IngestJobWriter, IngestRequest, IngestResponse, RagIngestProgress, DeleteOptions, DeleteResponse, RetrieveRequest, RetrieveHit, ChunkOptions, ParseInput, ParseOptions } from '@stackbone/rag-core';
5
5
  export { ChunkOptions, ChunkStrategy, DeleteOptions, DeleteResponse, IngestChunk, IngestRequest, IngestRequestAutoEmbed, IngestRequestPrecomputed, IngestResponse, ParseInput, ParseOptions, RagIngestProgress, RetrieveHit, RetrieveRequest, RetrieveRequestAutoEmbed, RetrieveRequestPrecomputed } from '@stackbone/rag-core';
6
6
  import OpenAI from 'openai';
@@ -77,7 +77,7 @@ interface ClientConfig {
77
77
  * RAG-related defaults parsed from `agent.yaml.rag` by the CLI/orchestrator
78
78
  * and forwarded here. The SDK never reads `agent.yaml` itself — keeping
79
79
  * filesystem ownership in the CLI. Defaults follow ADR
80
- * `2026-05-10-rag-consolidation-on-client-database` (D2/D6).
80
+ * `2026-06-05-rag` (D2/D6).
81
81
  */
82
82
  rag?: {
83
83
  /**
@@ -483,6 +483,43 @@ declare class DatabaseModule {
483
483
  delete: DrizzleClient['delete'];
484
484
  execute: DrizzleClient['execute'];
485
485
  transaction: DrizzleClient['transaction'];
486
+ /**
487
+ * Cross-surface raw-SQL runner carrying the SAME cold-start resilience the
488
+ * query-builder verbs above get. Sibling agent-local surfaces (`approval`,
489
+ * `config`, `secrets`, `prompts`) that issue tagged-template queries over the
490
+ * shared postgres-js `Sql` MUST execute them through this instead of caching
491
+ * `shared().$client` once and calling it directly. Otherwise a dead pooled
492
+ * socket — Fly Machines suspending the Machine between invokes, or a
493
+ * WSL2/Docker localhost relay dropping an idle connection during a long LLM
494
+ * step — surfaces as an unretried `CONNECTION_ENDED`/`ECONNRESET`. That is
495
+ * exactly the asymmetry that let `client.approval.request` fail while the
496
+ * `client.database.insert` right before it recovered.
497
+ *
498
+ * `fn` receives a FRESH `$client` on each attempt, so the single retry runs
499
+ * against the rebuilt pool. Whole-operation granularity is replayed as a
500
+ * unit — pass a multi-statement `sql.begin(...)` transaction or a helper that
501
+ * fires several queries and the replay re-runs all of it; postgres-js never
502
+ * commits a half-applied tx, so that is safe. SQLSTATE application errors
503
+ * pass straight through without a retry. Like `shared()`/`raw()`, the
504
+ * contract gate is intentionally NOT consulted here — gating surfaces gate at
505
+ * their own call sites.
506
+ */
507
+ runShared<T>(fn: (sql: Sql) => Promise<T> | T): Promise<T>;
508
+ /**
509
+ * `Result`-shaped sibling of `runShared` for surfaces whose driver swallows
510
+ * the dead-socket error into a returned `Result.err.cause` instead of
511
+ * throwing it — today only `client.rag`, whose `RagPipeline` returns a
512
+ * `Result` rather than throwing. `attempt` runs once; if it comes back with a
513
+ * pool-terminated `cause`, the pool is rebuilt and `attempt` replays exactly
514
+ * once, then its result (success or the fresh error) is returned verbatim.
515
+ * The `Result` contract is preserved end to end: a still-dead socket on the
516
+ * replay surfaces as the surface's own `Result.err`, never as a raw throw.
517
+ */
518
+ runSharedResult<T extends {
519
+ error?: {
520
+ cause?: unknown;
521
+ } | null;
522
+ }>(attempt: () => Promise<T>): Promise<T>;
486
523
  /**
487
524
  * Canonical accessor for the **shared-handles pattern**. Returns the
488
525
  * process-wide Drizzle handle backing `client.database`. Cross-surface
@@ -949,7 +986,7 @@ interface IngestAsyncHandle {
949
986
  * Implementation note: `RagModule` is a thin facade over `RagPipeline`. The
950
987
  * pipeline owns parse → chunk → embed → persist; the facade resolves the
951
988
  * shared `client.database` pool, builds an `Embedder` on demand, and maps
952
- * configuration errors. See ADR `2026-05-10-rag-consolidation-on-client-database`.
989
+ * configuration errors. See ADR `2026-06-05-rag`.
953
990
  *
954
991
  * Connection ownership: this module never opens its own postgres pool. It
955
992
  * reaches the underlying `postgres-js` `Sql` through the **shared-handles
@@ -1738,6 +1775,22 @@ declare const createStructuredLogger: (opts?: StructuredLoggerOptions) => Logger
1738
1775
  * - `logger` is a child of the wrapper's structured logger already
1739
1776
  * bound to `invocationId` and `runId`, so the handler does not have to
1740
1777
  * pass them on every line. The actual JSON format lands in F6.
1778
+ * - `stream` is present **only** when the caller requested a streamed reply
1779
+ * (an SSE `/invoke`). The handler pushes incremental output through it —
1780
+ * `delta(text)` for token-by-token text and `event(name, data?)` for a
1781
+ * named structured event — and the wrapper relays each onto the open
1782
+ * socket as it is produced. On a plain (buffered) invoke `stream` is
1783
+ * `undefined`, so a handler that wants to stream guards on it and falls
1784
+ * back to returning its `output` normally.
1785
+ * - `progress` / `step` are the **live run progress** helpers (distinct from
1786
+ * token streaming): they record `run_steps` rows on the run so the Studio
1787
+ * runs timeline fills in as the handler works. `progress(message, data?)` is
1788
+ * a coarse, point-in-time note; `step({ type, name })` opens a span and
1789
+ * returns a handle whose `.finish()` closes it with a duration. Both are
1790
+ * runtime-injected and fire-and-forget — they are wired to the install's
1791
+ * Postgres by the wrapper, are absent (no-op) when no run writer is mounted
1792
+ * (e.g. plain unit tests), and the wrapper throttles `progress` so a hot
1793
+ * loop cannot flood the run with notes.
1741
1794
  */
1742
1795
  interface InvokeContext<I extends z.ZodType> {
1743
1796
  input: z.infer<I>;
@@ -1746,7 +1799,76 @@ interface InvokeContext<I extends z.ZodType> {
1746
1799
  runId: string;
1747
1800
  client: StackboneClient;
1748
1801
  logger: Logger;
1802
+ stream?: InvokeStream;
1803
+ progress?: InvokeProgress;
1804
+ step?: InvokeStepFn;
1805
+ }
1806
+ /**
1807
+ * The streaming sink handed to a handler as `ctx.stream` when the caller asked
1808
+ * for a streamed `/invoke`. Both methods are fire-and-forget — the handler
1809
+ * emits, the wrapper relays — so neither returns a promise the handler must
1810
+ * await.
1811
+ */
1812
+ interface InvokeStream {
1813
+ /** Emit an incremental chunk of text (e.g. a model token). */
1814
+ delta(text: string): void;
1815
+ /** Emit a named structured event with an optional JSON-serialisable payload. */
1816
+ event(name: string, data?: unknown): void;
1817
+ }
1818
+ /**
1819
+ * The closed set of step types `ctx.step` / `ctx.progress` may record. It
1820
+ * mirrors the CHECK constraint on `stackbone_platform.run_steps.type`; an
1821
+ * unknown type would be rejected by Postgres, so the contract enumerates the
1822
+ * allowed values at the type layer too. `agent` is the catch-all a coarse
1823
+ * `progress` note records under.
1824
+ */
1825
+ type RunStepType = 'agent' | 'llm_call' | 'db_query' | 'http_fetch' | 'queue_publish' | 'hitl_pause' | 'tool_call' | 'rag_query' | 'storage_op';
1826
+ /**
1827
+ * `ctx.progress` — a coarse, point-in-time note on the run, distinct from the
1828
+ * token-level `ctx.stream`. The wrapper writes one `run_steps` row (type
1829
+ * `agent`) per call, opened and closed in place, so it shows up immediately on
1830
+ * the Studio timeline. Fire-and-forget: it returns nothing the handler must
1831
+ * await, and the wrapper throttles calls to ~1/s so a hot loop cannot flood the
1832
+ * run. `data` is an optional JSON-serialisable payload stored on the row.
1833
+ */
1834
+ type InvokeProgress = (message: string, data?: unknown) => void;
1835
+ /** Opening descriptor for `ctx.step`. */
1836
+ interface StepOptions {
1837
+ /** One of the canonical `run_steps` types; defaults to `agent` when omitted. */
1838
+ type?: RunStepType;
1839
+ /** Human-readable label for the step (the `run_steps.name` column). */
1840
+ name: string;
1841
+ /** Optional JSON-serialisable payload stored on the opened row. */
1842
+ data?: unknown;
1843
+ }
1844
+ /** Closing descriptor for a `StepHandle.finish`. */
1845
+ interface StepFinishOptions {
1846
+ /** Terminal status; defaults to `ok`. */
1847
+ status?: 'ok' | 'error';
1848
+ /** Failure detail recorded on the row when the step errored. */
1849
+ error?: string;
1850
+ /** Optional JSON-serialisable payload merged onto the row at finish. */
1851
+ data?: unknown;
1749
1852
  }
1853
+ /**
1854
+ * Handle returned by `ctx.step`. The handler calls `.finish()` when the work the
1855
+ * step represents completes, which closes the open `run_steps` row with a
1856
+ * duration and terminal status. Calling `.finish()` more than once is a no-op —
1857
+ * the first close wins.
1858
+ */
1859
+ interface StepHandle {
1860
+ /** The id of the opened `run_steps` row (useful for nesting / correlation). */
1861
+ readonly id: string;
1862
+ /** Close the step. Idempotent: only the first call writes a terminal row. */
1863
+ finish(options?: StepFinishOptions): void;
1864
+ }
1865
+ /**
1866
+ * `ctx.step` — opens a span on the run and returns a handle to close it. The
1867
+ * wrapper writes a `run_steps` row in the `running` state on open and updates it
1868
+ * to `ok`/`error` with a duration on `.finish()`. Fire-and-forget like
1869
+ * `ctx.progress`; absent (no-op handle) when no run writer is mounted.
1870
+ */
1871
+ type InvokeStepFn = (options: StepOptions) => StepHandle;
1750
1872
  /**
1751
1873
  * The synchronous `invoke` capability. Mirrors the wrapper's three HTTP verbs
1752
1874
  * (`/invoke`, `/health`, `/schema`): `invoke` is the only request path, its
@@ -2120,4 +2242,4 @@ interface JsonSchemaDocument {
2120
2242
  */
2121
2243
  declare const analyzeAgentSchemas: (pair: AgentSchemaPair) => SchemaIntrospectionResult;
2122
2244
 
2123
- export { type AddMemoryRequest, type AgentSchemaPair, type AgentSpec, type AnyCapability, type ApprovalListOptions, type ApprovalListResult, type ApprovalRecord, type ApprovalRequest, type ApprovalRequestOptions, type ApprovalStatus, type ApprovalTool, type ApprovalToolSpec, type ApprovalTopic, type ApproverInfo, type ClientConfig, type CompilePromptResult, type ConsoleLike, type CreatePromptRequest, type Decision, type DecisionStatus, type DeleteAllMemoryRequest, type DeletePromptOptions, type DeletePromptResult, type EndSessionOptions, type EndSessionResult, type FatalConstruct, type GeneratedImage, type GetPromptOptions, INVOCATION_ID_HEADER, INVOKE_TIMEOUT_HARD_CAP_MS, type ImageGenerateParams, type ImagesResponse, type IngestAsyncHandle, type InstallConsoleCaptureOptions, type InvocationContext, type InvokeCapability, type InvokeContext, type InvokeEnvelopeError, type InvokeErrorEnvelope, type InvokeOptions, type InvokeRequest, type InvokeResponse, type InvokeSuccessEnvelope, type JobCapability, type JsonSchemaDocument, type ListMemoryRequest, type ListMemoryResult, type ListOptions, type ListPromptsOptions, type ListPromptsResult, type LoadSystemSecretsArgs, type LogSink, type Logger, type LoggerBindings, type MemoryContent, type MemoryHistoryEntry, type MemoryHistoryEvent, type MemoryHit, type MemoryItem, type MemoryScope, type ModelsListResponse, type OpenRouterModel, type Prompt, type PublishRequest, RESERVED_ERROR_CODES, RESERVED_HANDLER_NAMES, RUN_ID_HEADER, type ReservedErrorCode, type Result, STORED_TO_SDK_ENV, type ScheduleRequest, type SchemaDiagnostic, type SchemaHalf, type SchemaIntrospectionResult, type SdkError, type SdkErrorCode, type SearchMemoryOptions, type SignedUrl, type SignedUrlOptions, StackboneClient, type StorageBody, type StorageObject, type StructuredLoggerOptions, type SystemSecretRow, type SystemSecretsReader, type UnscheduleRequest, type UpdateMemoryOptions, type UpdatePromptOptions, type UploadOptions, type VerifyOptions, type WarnConstruct, analyzeAgentSchemas, createClient, createStructuredLogger, defineAgent, getInvocationContext, installInvocationConsoleCapture, invokeRequestSchema, isReservedErrorCode, isSdkErrorCode, loadSystemSecretsIntoEnv, rehydrateSystemSecretsRows, runWithInvocationContext };
2245
+ export { type AddMemoryRequest, type AgentSchemaPair, type AgentSpec, type AnyCapability, type ApprovalListOptions, type ApprovalListResult, type ApprovalRecord, type ApprovalRequest, type ApprovalRequestOptions, type ApprovalStatus, type ApprovalTool, type ApprovalToolSpec, type ApprovalTopic, type ApproverInfo, type ClientConfig, type CompilePromptResult, type ConsoleLike, type CreatePromptRequest, type Decision, type DecisionStatus, type DeleteAllMemoryRequest, type DeletePromptOptions, type DeletePromptResult, type EndSessionOptions, type EndSessionResult, type FatalConstruct, type GeneratedImage, type GetPromptOptions, INVOCATION_ID_HEADER, INVOKE_TIMEOUT_HARD_CAP_MS, type ImageGenerateParams, type ImagesResponse, type IngestAsyncHandle, type InstallConsoleCaptureOptions, type InvocationContext, type InvokeCapability, type InvokeContext, type InvokeEnvelopeError, type InvokeErrorEnvelope, type InvokeOptions, type InvokeProgress, type InvokeRequest, type InvokeResponse, type InvokeStepFn, type InvokeStream, type InvokeSuccessEnvelope, type JobCapability, type JsonSchemaDocument, type ListMemoryRequest, type ListMemoryResult, type ListOptions, type ListPromptsOptions, type ListPromptsResult, type LoadSystemSecretsArgs, type LogSink, type Logger, type LoggerBindings, type MemoryContent, type MemoryHistoryEntry, type MemoryHistoryEvent, type MemoryHit, type MemoryItem, type MemoryScope, type ModelsListResponse, type OpenRouterModel, type Prompt, type PublishRequest, RESERVED_ERROR_CODES, RESERVED_HANDLER_NAMES, RUN_ID_HEADER, type ReservedErrorCode, type Result, type RunStepType, STORED_TO_SDK_ENV, type ScheduleRequest, type SchemaDiagnostic, type SchemaHalf, type SchemaIntrospectionResult, type SdkError, type SdkErrorCode, type SearchMemoryOptions, type SignedUrl, type SignedUrlOptions, StackboneClient, type StepFinishOptions, type StepHandle, type StepOptions, type StorageBody, type StorageObject, type StructuredLoggerOptions, type SystemSecretRow, type SystemSecretsReader, type UnscheduleRequest, type UpdateMemoryOptions, type UpdatePromptOptions, type UploadOptions, type VerifyOptions, type WarnConstruct, analyzeAgentSchemas, createClient, createStructuredLogger, defineAgent, getInvocationContext, installInvocationConsoleCapture, invokeRequestSchema, isReservedErrorCode, isSdkErrorCode, loadSystemSecretsIntoEnv, rehydrateSystemSecretsRows, runWithInvocationContext };