@automatalabs/shared-types
v0.29.1
Published
> Internal package. The shared type contract every other `@automatalabs/*` package imports. > You normally consume these **transitively** via [`@automatalabs/workflows`](../workflows) — > you only depend on this package directly if you're **implementing a
Readme
@automatalabs/shared-types
Internal package. The shared type contract every other
@automatalabs/*package imports. You normally consume these transitively via@automatalabs/workflows— you only depend on this package directly if you're implementing a custom agent backend.
This is the one module both the workflow engine and the agent backend import (they never
import each other). It has zero ACP/MCP/engine deps — only typebox (type-level) plus the
runtime WorkflowError class, so instanceof checks hold across package boundaries.
The AgentRunner seam
AgentRunner is the single, frozen coupling point between the engine and any agent backend.
The engine calls exactly one method — run(prompt, options) — once per subagent:
import type { AgentRunner, RunOptions, AgentResult } from "@automatalabs/shared-types";
import type { TSchema } from "typebox";
interface AgentRunner {
run<S extends TSchema | undefined = undefined>(
prompt: string,
options?: RunOptions<S>,
): Promise<AgentResult<S>>;
}Contract, in brief:
promptis a positional string;optionsis one optional bag (defaults to{}).- Return is the RAW value, never an envelope:
schemapresent ⇒Static<schema>(a parsed + validated object); no schema ⇒ the assistant's final text (string). It must be JSON-serializable and stable, because the engine journals it verbatim and replays it on resume. - Usage is delivered out-of-band via
options.onUsage(usage)— it is not in the return. - On failure, throw — ideally a
WorkflowErrorfrom this package.recoverableerrors are retried then resolved tonull; non-recoverable ones halt the run. Timeout and abort are the engine's job (it races a timeout and passesoptions.signal); the runner should honor the signal but must not implement its own timeout.
The manager has two intentional exceptions to ordinary non-recoverable failure: it converts
PROVIDER_USAGE_LIMIT and AUTH_REQUIRED into persisted, resumable paused results. Direct
AgentRunner consumers still receive the thrown error.
A minimal custom backend:
import { WorkflowError, WorkflowErrorCode } from "@automatalabs/shared-types";
import type { AgentRunner, RunOptions, AgentResult } from "@automatalabs/shared-types";
import type { TSchema } from "typebox";
export const myRunner: AgentRunner = {
async run<S extends TSchema | undefined = undefined>(
prompt: string,
options: RunOptions<S> = {},
): Promise<AgentResult<S>> {
const text = await callMyBackend(prompt, { signal: options.signal });
options.onUsage?.({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, cost: 0 });
if (!options.schema) {
if (!text) {
throw new WorkflowError("no output", WorkflowErrorCode.AGENT_EMPTY_OUTPUT, {
recoverable: true,
});
}
return text as AgentResult<S>;
}
return parseAndValidate(text, options.schema) as AgentResult<S>; // Static<schema>
},
};Exported types
From src/index.ts:
The seam
AgentRunner— therun(prompt, options) => resultinterface above.RunOptions<S>— the options bag:label,schema,instructions,signal,model,mode,tier,cwd,toolNames,disallowedToolNames,maxSchemaRetries,mcpServers,images,runId,backends,meta,promptMeta, the Codex-onlybaseInstructions/developerInstructions,keepSession, and the out-of-band callbacksonUsage,onModelResolved,onModelFallback,onHistory,onSessionOpen. The resume-onlycontinueFromSessiondirective is advisory: a capable runner reopens that exact session and reports the attempt throughAgentResultProvenance.continuation; otherwise it runs fresh.onSessionOpenfires exactly once for whichever acquisition wins (fresh, resumed, or loaded).AgentResult<S>—S extends TSchema ? Static<S> : string.AgentUsage— per-run token/cost:input,output,cacheRead,cacheWrite,total,cost.AgentRunOptions/AgentRunResult— lift-compat aliases forRunOptions/AgentResult.
Errors (runtime, not just types)
WorkflowError(class) +WorkflowErrorCode(enum) +WorkflowErrorOptions.AGENT_TIMEOUTidentifies exhaustion of a recoverable total-wall-clock attempt cap. The engine retries only within its configured bound, then settles the call tonull; every retry gets a fresh clock.AGENT_CANCELLEDidentifies a host-selected in-flight call. The engine settles that call tonullwithout retrying or aborting the owning run; the failed row is observable but is not a replayable journal result.AuthErrorContext— the non-secret backend/method summary carried byAUTH_REQUIRED.ProviderUsageLimitContext— the backend/code and provider-derived reset instant carried byPROVIDER_USAGE_LIMIT.isWorkflowError,isProviderUsageLimit,isAuthRequired(guards).
Workflow result
WorkflowRunResult<T>— the public, host-facing run result (runId,status,meta,result,phases,agentCount,durationMs,tokenUsage?,logs,reason?,resetHint?,authContext?,agentSessions?,fallbacks?,checkpointsTaken?,calls?,resumeReport?,replayEligibility?,effectiveLimits?). Paused, failed, and aborted results additionally carry the optional redacted final-20logTail; completed results omit it andlogsremains the full compatibility array.WorkflowRunFallback—{ callIndex, label, phase?, requestedSpec, resolvedModel?, backendId?, kind: "model" | "modifier" | "continuation", message, continuation? }. Continuation notices carry either{ outcome: "reattached", method }or{ outcome: "skipped", reason }; the detail remains structurally optional for compatibility, while engine emissions always correlate it withkind: "continuation".WorkflowCheckpointTaken/WorkflowCheckpointSource— a resolved checkpoint's call index, kind, journaled decision, and provable source (live,headless-default,journal-replay, orinjected). These result-only arrays are absent when empty and never widenWorkflowRunStatus.RunStatus,WorkflowMeta,WorkflowMetaPhase,WorkflowBackendConfig,TokenUsage,JournalEntry,AgentSessionRef,AgentSessionRecord. Session refs include the optional persistedpoolKeyspawn identity used to reject a reattach to a changed custom backend.ResumePolicy,WorkflowResumeStrategy,WorkflowResumeMatch,WorkflowResumeSafety,WorkflowResumeFallbackReason,WorkflowResumeDisabledReason,WorkflowResumeCallLiveReason,WorkflowResumeCallFailedReason,WorkflowCallReplayProvenance,WorkflowResumeCallDecision,WorkflowResumeReport,WorkflowReplayOperationalOption,WorkflowReplayOperationalChange,WorkflowReplayProvenanceField,WorkflowReplayProvenanceChange,WorkflowReplayFirstNonReplay, andWorkflowReplayEligibility— the additive content-addressed new-run replay contract. Runtime reason arrays live in@automatalabs/workflow-engineand are re-exported by@automatalabs/workflows; see the incremental resume API. The Historical safety/world reason literals such ascrash-residueremain in the wire unions so old journals and consumers continue to parse. Current-format crash snapshots use identity matching even without a terminal-environment capture.inputs-format-legacyidentifies a source below input-fingerprint format 2 that uses hash-only positional replay. Producing/current engine versions and runtime/environment provenance changes are diagnostics inWorkflowReplayEligibilityand never gate replay.WorkflowCallRecord— the terminal call manifest, including optionalpath, agent/checkpointinputsHash, legacy diagnosticresumeSafety, and manager-owned replay provenance. Replay is determined by call correspondence, never this marker. Old object literals remain valid because every incremental-resume field is optional and omitted when unset.JournalCallMetadataand optionalJournalEntry.call— replay-neutral agent/checkpoint attribution (kind, label, phase, resolved model, actual backend). Legacy entries without it remain valid.WorkflowRunInspectionOptions,WorkflowLogTail,WorkflowRunCallStatus,WorkflowRunStatusTruncation, andWorkflowRunStatus— the shared bounded status contract used by SDK and MCP polling/inspection hosts. Agent call status can carry its resolved total-wall-clocktimeoutMsand terminalerrorCode, includingAGENT_TIMEOUTandAGENT_CANCELLEDfor recoverable calls that have no journal result. Resumed results/statuses can carryreplayEligibility, a bounded admission and progress summary with the predicted/observed prefix, first non-replay, engine/input-format diagnostics, and non-gating operational changes.WorkflowRunLimits— resolvedmaxAgents,tokenBudget,concurrency,agentRetries, and per-attemptagentTimeoutMs; it is returned asWorkflowRunResult.effectiveLimitsand asWorkflowRunStatus.limits(optional only for legacy persisted records).
MCP config
McpServerConfig(union) +McpStdioServerConfig,McpHttpServerConfig,McpSseServerConfig,McpAcpServerConfig,McpNameValue.
History & meta
AgentHistoryEntry,AgentHistoryRole,AgentHistoryKind(diagnostic, viaonHistory).META_KEYS,CODEX_META_KEYS,ClaudeCodeSessionMeta,ClaudeJsonSchemaOutputFormat.
License
Apache-2.0