/** * Taskflow runtime — the orchestration engine. * * Resolves the phase DAG into topological layers and executes each phase by * delegating to isolated subagents. Intermediate phase outputs live here (in * RunState) and never enter the host conversation's context window — only the * final phase output is returned to the caller. * * Supports resume: phases whose resolved input hash matches a cached completed * result are skipped. */ import type { AgentConfig } from "./agents.ts"; import type { SubagentRunner } from "./host/runner-types.ts"; /** The host-neutral subagent runner signature the engine drives. A host adapter * (pi, codex) injects a concrete `runTask` via `RuntimeDeps`. */ type RunTaskFn = SubagentRunner["runTask"]; export { PHASE_TIMEOUT_ABORT_GRACE_MS } from "./runner-core.ts"; import { type UsageStats } from "./usage.ts"; import { type CacheScope, type Phase, type Taskflow } from "./schema.ts"; import { type TaskflowVerifier } from "./verify.ts"; import { parseGateVerdict } from "./deterministic.ts"; export { parseTournamentWinner } from "./deterministic.ts"; import { type TraceSink } from "./trace.ts"; export { parseGateVerdict }; import { type PhaseState, type RunState } from "./store.ts"; import { CacheStore } from "./cache.ts"; import { type CwdBridgeMode, type DirectoryIdentity } from "./cwd-bridge.ts"; import { type ResolveOnlyPhaseBinding, type ResolveOnlyWorkspaceSession } from "./resources/execution.ts"; /** A human-in-the-loop approval request raised by an `approval` phase. */ export interface ApprovalRequest { phaseId: string; /** Interpolated prompt shown to the human. */ message: string; /** Output of the immediately-upstream phase, for context. */ upstream?: string; } /** The human's decision. `edit` carries guidance passed downstream as the phase output. */ export interface ApprovalDecision { decision: "approve" | "reject" | "edit"; note?: string; } export interface LoadedSavedFlow { def: Taskflow; /** Canonical loader-owned definition path. Omitted for legacy loaders. */ filePath?: string; /** Identity of the canonical definition directory, captured with the file. */ sourceDirIdentity?: DirectoryIdentity; } export interface RuntimeDeps { cwd: string; agents: AgentConfig[]; globalThinking?: string; /** Whether the host reports authoritative token/cost usage. A host that * cannot observe usage must reject every actually-executed budgeted flow, * including nested/dynamic flows, rather than silently bypassing the cap. */ usageAccounting?: "available" | "tokens-only" | "unavailable"; signal?: AbortSignal; /** Persist run state after each phase (for resume). */ persist?: (state: RunState) => void; /** Live progress callback for TUI streaming. */ onProgress?: (state: RunState) => void; /** Injectable task runner (defaults to spawning a real subagent). Enables testing. */ runTask?: RunTaskFn; /** Resolve an `approval` phase. Omit for non-interactive runs (auto-reject). */ requestApproval?: (req: ApprovalRequest) => Promise; /** Legacy definition-only loader. Prefer `loadSavedFlow` when file-backed * semantics such as `scriptCwd:"flow"` are available. */ loadFlow?: (name: string) => Taskflow | undefined; /** Atomically resolve a saved definition together with its trusted canonical * source path. Runtime snapshots the pair as one immutable capability. */ loadSavedFlow?: (name: string) => LoadedSavedFlow | undefined; /** Cross-run memoization store. Omit to construct a default one for `deps.cwd`. */ cacheStore?: CacheStore; /** Default cache scope for phases that don't specify one. */ cacheScopeDefault?: CacheScope; /** Deterministic-replay trace sink (best-effort, fail-open). When injected, * the runtime records each phase's subagent calls + its own decisions to an * append-only trace for offline replay. Absent → no-op (runs behave * identically to today). See `trace.ts`. */ trace?: TraceSink; /** * S2 strangler: when true, eligible flows run on `exec/driver` (event kernel). * Covers core kinds except `race`/`expand`; advanced features force imperative * fallback. Default false; also set `PI_TASKFLOW_EVENT_KERNEL=1`. */ eventKernel?: boolean; /** Caller-supplied zero-token verifiers (see verify.ts). Threaded into every * `verifyTaskflow` preflight the runtime performs — dynamic subflows (spawn + * inline `flow{def}`), the event-kernel path, and the top-level pre-execution * gate (which blocks only on error-severity plugin issues, leaving built-in * detectors advisory at the top level as before). A host embedding the engine * registers the verifiers it trusts here. Undefined ⇒ built-in detectors only. */ verifiers?: TaskflowVerifier[]; /** Internal: sub-flow call stack, for recursion detection. */ _stack?: string[]; /** Internal: pre-resolved Shared Context Tree dir for this run (sub-flows inherit the parent's). */ _ctxDir?: string; /** Internal: an isolated workspace dir override for the current phase (worktree isolation). */ _cwdOverride?: string; /** Host-owned 0.2.1 cwd bridge mode. Undefined is fail-closed. Flow data * cannot enable this; adapters may opt into the documented resolve-only mode. */ cwdBridgeMode?: CwdBridgeMode; /** Optional trusted control-plane location for workspace leases/journal/HMAC * state. Defaults outside the flow workspace under ~/.taskflow. */ workspaceControlDirectory?: string; /** Host-created W1a resolve-only session. Ordinarily constructed lazily from * cwdBridgeMode; injectable for delivery policy and conformance tests. */ workspaceSession?: ResolveOnlyWorkspaceSession; /** Internal: a cwd-bridge flow may mutate workspace state, so output-only * cache/resume reuse is disabled for the entire nested execution tree. */ _disableCache?: boolean; /** Internal host-only continuation of an exact durable approval checkpoint. * The host must first exclude the old writer and re-admit live authority. * Unlike cache reuse, already settled effects are never dispatched again. */ _approvalCheckpointContinuation?: { runId: string; }; /** Internal: execution originated from an LLM-authored flow{def}/ctx_spawn. * Resource-bearing fields remain denied through every nested frame. */ _dynamic?: boolean; /** Internal: canonical directory capability inherited from a cwd-bridge * phase. Nested phases may stay inside or narrow it, never escape it. */ _cwdBoundary?: string; /** Internal: only resource-selected execution trees opt into cwd-sensitive * cache keys. Ordinary legacy root phases retain their existing key format. */ _cacheCwdIdentity?: string; /** Internal: one immutable loader view per top-level execution. Saved-flow * definitions must not change between capability scan and execution. */ _flowLoaderSnapshot?: Map; /** Internal: a child-flow dispatch site has already run the plugin-verifier * preflight on the child's declared def, so executeTaskflow's top-level * preflight must NOT re-run it on re-entry (avoids verifying each child 2-3x * across the imperative path). Root/ctx_spawn entries leave this unset. */ _verifierPreflightDone?: boolean; /** Internal phase-scoped W1a execution binding inherited only by descendants * that remain inside the selected cwd capability. */ _workspaceBinding?: ResolveOnlyPhaseBinding; } type FlowLoaderSnapshotEntry = { ok: true; value: LoadedSavedFlow | undefined; } | { ok: false; error: unknown; }; export interface RuntimeResult { state: RunState; finalOutput: string; ok: boolean; totalUsage: UsageStats; /** The id of the PhaseState whose output supplied `finalOutput`. For the * normal case this is the (fallback) final phase that actually completed. * For gate/budget prefixes, it is retained when underlying partial output * is included (the blocking gate/approval phase, or the fallback final * phase for a budget halt); a failed final phase is attributed only when it * has an explicitly marked partial answer. `undefined` when no phase answer * is available. */ outputSourcePhaseId?: string; /** Incremental-reuse summary: how many phases were reused from cache vs. * freshly executed this run, and the cost the reused work would otherwise * have incurred (known only for within-run resume; cross-run hits zero * their usage so their original cost is not recoverable). Optional & * additive — callers that ignore it are unaffected. */ reuse?: ReuseSummary; } export { resolveFinalOutput, type FinalOutputBlockedCtx, type FinalOutputResolution, } from "./final-output.ts"; /** A run's incremental-reuse accounting (see RuntimeResult.reuse). */ export interface ReuseSummary { /** Phases that completed by executing a subagent this run. */ executed: number; /** Phases served from the within-run resume cache (no new tokens). */ reusedRunOnly: number; /** Phases restored from the cross-run store (no new tokens). */ reusedCrossRun: number; /** Total phases that reached `done` (executed + reused). */ done: number; /** USD the within-run-reused phases would have cost if re-executed (their * preserved prior usage). Cross-run hits are excluded (cost not recoverable). */ savedUSD: number; } /** Compute the incremental-reuse summary from a run's terminal phase states. * Pure, total, never throws. A phase is "reused" iff it carries a `cacheHit` * marker (set by `cachedPhase` for both within-run resume and cross-run hits). */ export declare function summarizeReuse(state: RunState): ReuseSummary; /** A conservative prompt-size warning threshold in estimated tokens. Crossed * → the phase records a `warnings` entry so an author notices they may be * approaching a model's context limit. Approximate (ceil(chars/4)), not a * real tokenizer count. Chosen conservatively well below typical 128K context * windows so the warning fires with ample headroom. */ export declare const PROMPT_SIZE_WARN_TOKENS = 32000; /** Compute durable prompt-size diagnostics for a resolved prompt string: * exact UTF-8 byte count, character count, and a documented approximate token * estimate (ceil(chars/4)). Never throws. */ export declare function promptSizeStats(text: string): { bytes: number; chars: number; estTokens: number; }; /** Resolve the effective idle-watchdog ms for a phase: phase overrides flow; * returns `undefined` when neither sets it (host default 300000 applies). * `0` is passed through (disables the watchdog — validation already ensured a * finite wall `timeout` exists in that case). */ export declare function resolveIdleTimeoutMs(phase: Phase, def: Taskflow): number | undefined; /** * Per-phase cache policy resolved once at the top of executePhase. Carries the * scope, optional TTL, and a pre-resolved fingerprint string so each phase-type * branch can fold it into its inputHash and consult the cross-run store uniformly. */ export interface PhaseCacheCtx { scope: CacheScope; ttlMs?: number; fingerprint: string; store: CacheStore; prior: PhaseState | undefined; phaseId: string; flowName: string; runId: string; /** Per-phase execution config that materially affects subagent output and * therefore must be part of the cache identity (else a config change could * silently serve a stale cross-run hit). */ thinking?: string; tools?: string[]; /** Resolved `context` pre-read content. Explicitly part of the cache identity * so a context-file change always invalidates the phase — independent of * whether a given branch happens to fold preRead into its task string * (previously this was only incidentally true via `fullTask`). */ preRead?: string; /** Flow-level semantics retained even by per-item cache contexts, which * deliberately omit phaseFp/flowDefHash for partial reuse. */ agentScope?: Taskflow["agentScope"]; contextSharing?: boolean; /** Resolved agent content/config. Same name+scope can still change prompt, * model, tools, or thinking and must invalidate cached output. */ agentDefinitions?: string; /** Canonical effective cwd. Required because a typed cwd arg can change the * resource selected without appearing in the task text or phase definition. */ executionCwd?: string; /** Content fingerprint of the desugared flow definition — folded into the * key so two structurally-different flows that share a name can never * collide, and a changed flow never serves a stale cross-run hit. */ flowDefHash?: string | "failed"; /** Per-phase structural sub-fingerprint (M6). When present, folds into the * key as `v3:phasefp:` so editing phase B invalidates only B + its * transitive dependents. When absent (sub-flow inner states, or a phase * for which per-phase soundness couldn't be guaranteed), `cacheKeys` * falls back to `flowDefHash` — preserving pre-M6 whole-flow behavior. */ phaseFp?: string; /** Force this phase to re-execute, ignoring the within-run prior AND the * cross-run store (M5 recompute seed). Downstream phases are NOT forced — * they re-evaluate naturally: if the seed's new output changed their * inputHash they miss and re-run, otherwise they hit (early cutoff). */ forceRerun?: boolean; } /** Stable cache identity for the fully resolved agent pool. File paths are * excluded: content/config, not installation location, determines output. */ export declare function agentDefinitionsIdentity(agents: readonly AgentConfig[]): string; /** Fold the phase fingerprint into the base hash parts to form the final cache key. */ /** A computed cache identity: the new (versioned) key plus the read-only * fallback keys used to honor entries written by older releases. The `key` * is what we WRITE under and what `PhaseState.inputHash` carries; the * `v2Key`/`bareKey` are consulted READ-ONLY on a miss. `legacyKey` is exposed * only for tooling/tests and is never read because it lacks structural * identity. See docs/internal/cache-migration.md. */ export interface CacheKeys { /** Current key: folds `v3:phasefp:` (the per-phase structural * sub-fingerprint; degrades to the whole-flow hash when per-phase * soundness couldn't be guaranteed). */ key: string; /** Pre-M6 key: `v2:flowdef:` (whole-flow fingerprint). * Read-only. */ v2Key: string; /** Bare (unversioned) `flowdef:` key — written by pre-H1 code that folded * the hash without a `v2:` prefix. Read-only. Removed in v0.1.0. */ bareKey: string; /** Pre-flowDefHash-era key: the flowdef line OMITTED entirely. Read-only. */ legacyKey: string; } /** Fold the phase fingerprint into the base hash parts to form the cache keys. * * Four keys are derived for tooling/backward compatibility (see * docs/internal/cache-migration.md): * - `key` : `v3:phasefp:` — the current write key (per-phase * structural sub-fingerprint; falls back to the whole-flow hash when * `cc.phaseFp` is absent). * - `v2Key` : `v2:flowdef:` — pre-M6 whole-flow key. * - `bareKey` : bare `flowdef:` (unversioned) — pre-H1 entries. * - `legacyKey`: the flowdef line omitted — pre-flowDefHash entries. * `cachedPhase` consults the first three safe tiers READ-ONLY on a miss; * `legacyKey` is never read because it has no structural identity. * `recordCache` writes only `key`. */ export declare function cacheKeys(cc: PhaseCacheCtx, baseParts: string[]): CacheKeys; /** * Execute a full taskflow. Mutates and persists `state` as it progresses. */ /** Result of a recompute: what was (or would be) re-executed vs reused. * `cutoff` is the prize — phases in the stale frontier whose inputHash did * NOT move, so they hit their cached result instead of re-running (early * cutoff). That is what makes recompute cheaper than a full re-run. */ export interface RecomputeReport { readonly dryRun: boolean; readonly aborted: boolean; readonly seeds: readonly string[]; /** Phases that were (dry-run: would be) re-executed, or whose result moved. */ readonly rerun: readonly string[]; /** Phases outside the frontier — untouched, reused verbatim. */ readonly reused: readonly string[]; /** Phases in the frontier whose inputHash did NOT move → cached result * reused, no re-execution (early cutoff). Empty in dry-run (unknowable). */ readonly cutoff: readonly string[]; /** Per-phase decision trace: WHY each phase was rerun / cut off / reused. * The "explainable reactivity" layer — like React DevTools telling you why * a component re-rendered. Additive; callers that ignore it are unaffected. */ readonly decisions: readonly RecomputeDecision[]; } /** Why a single phase landed in its recompute outcome. */ export interface RecomputeDecision { readonly phaseId: string; /** What happened (real run) or would happen (dry-run). */ readonly outcome: "rerun" | "cutoff" | "reused" | "failed"; /** Human-readable cause. */ readonly reason: string; /** The upstream phase(s) that caused this outcome, when applicable * (e.g. the changed upstreams that forced a rerun). */ readonly causedBy?: readonly string[]; } /** Recompute a completed run minimally: force-rerun the `seeds`, then walk * their stale frontier in topological order. The cache provides early cutoff * for free — a downstream whose inputHash didn't move (because the seed's new * output happened to equal the old) hits its prior and is reused rather than * re-executed. `dryRun` computes the worst-case frontier without spending a * token. Returns a fresh state + a report. Throws only when dryRun:false is * requested for a flow with unobserved dependencies; callers should surface * that as a user-facing error. */ export declare function recomputeTaskflow(state: RunState, deps: RuntimeDeps, seeds: readonly string[], opts?: { dryRun?: boolean; }): Promise<{ report: RecomputeReport; state: RunState; }>; export declare function executeTaskflow(state: RunState, deps: RuntimeDeps): Promise; //# sourceMappingURL=runtime.d.ts.map