import type { ThinkingLevel } from "@gajae-code/agent-core"; import type { Usage } from "@gajae-code/ai/core"; import type { FallbackTriggerClass } from "@gajae-code/ai/utils/fallback-transport"; import * as z from "zod/v4"; import { type AutoroutingReasonCode } from "../config/autorouting-contract"; import type { TaskResultReceipt } from "./receipt"; import type { SpawnRoiReconciliation } from "./roi-reconciliation"; import { type TaskSimpleMode } from "./simple-mode"; import type { SpawnPlanReceipt } from "./spawn-gate"; import type { NestedRepoPatch } from "./worktree"; /** Source of an agent definition */ export type AgentSource = "bundled" | "user" | "project"; export type ForkContextPolicy = "forbidden" | "allowed"; export type ForkContextMode = "none" | "receipt" | "last-turn" | "bounded" | "full"; /** Maximum output bytes per agent */ export declare const MAX_OUTPUT_BYTES: number; /** Maximum output lines per agent */ export declare const MAX_OUTPUT_LINES: number; /** EventBus channel for raw subagent events */ export declare const TASK_SUBAGENT_EVENT_CHANNEL = "task:subagent:event"; /** EventBus channel for aggregated subagent progress */ export declare const TASK_SUBAGENT_PROGRESS_CHANNEL = "task:subagent:progress"; /** EventBus channel for subagent lifecycle (start/end) */ export declare const TASK_SUBAGENT_LIFECYCLE_CHANNEL = "task:subagent:lifecycle"; /** Payload emitted on TASK_SUBAGENT_PROGRESS_CHANNEL */ export interface SubagentProgressPayload { index: number; agent: string; agentSource: AgentSource; task: string; assignment?: string; progress: AgentProgress; sessionFile?: string; } /** Payload emitted on TASK_SUBAGENT_LIFECYCLE_CHANNEL */ export interface SubagentLifecyclePayload { id: string; agent: string; agentSource: AgentSource; description?: string; status: "started" | "completed" | "failed" | "aborted" | "paused"; sessionFile?: string; index: number; } /** Single task item for parallel execution (default shape with context enabled). */ export declare const taskItemSchema: z.ZodObject<{ id: z.ZodString; description: z.ZodString; assignment: z.ZodString; tier: z.ZodOptional>; executionMode: z.ZodOptional>; inheritContext: z.ZodOptional>; repositoryBinding: z.ZodOptional; worktreeRoot: z.ZodString; commonDir: z.ZodNullable; relativeSubdir: z.ZodOptional; displayPath: z.ZodOptional; head: z.ZodOptional; branch: z.ZodOptional; }, z.core.$strict>>; duplicate_policy: z.ZodOptional>; }, z.core.$strip>; export type TaskItem = z.infer; export declare const taskSchema: z.ZodObject<{ agent: z.ZodString; tasks: z.ZodArray>; executionMode: z.ZodOptional>; inheritContext: z.ZodOptional>; repositoryBinding: z.ZodOptional; worktreeRoot: z.ZodString; commonDir: z.ZodNullable; relativeSubdir: z.ZodOptional; displayPath: z.ZodOptional; head: z.ZodOptional; branch: z.ZodOptional; }, z.core.$strict>>; duplicate_policy: z.ZodOptional>; }, z.core.$strip>>; spawnPlan: z.ZodOptional>; }, z.core.$strip>; export declare const taskSchemaNoIsolation: z.ZodObject<{ agent: z.ZodString; tasks: z.ZodArray>; executionMode: z.ZodOptional>; inheritContext: z.ZodOptional>; repositoryBinding: z.ZodOptional; worktreeRoot: z.ZodString; commonDir: z.ZodNullable; relativeSubdir: z.ZodOptional; displayPath: z.ZodOptional; head: z.ZodOptional; branch: z.ZodOptional; }, z.core.$strict>>; duplicate_policy: z.ZodOptional>; }, z.core.$strip>>; spawnPlan: z.ZodOptional>; }, z.core.$strip>; declare const ALL_TASK_SCHEMAS: readonly [z.ZodObject<{ agent: z.ZodString; tasks: z.ZodArray>; executionMode: z.ZodOptional>; inheritContext: z.ZodOptional>; repositoryBinding: z.ZodOptional; worktreeRoot: z.ZodString; commonDir: z.ZodNullable; relativeSubdir: z.ZodOptional; displayPath: z.ZodOptional; head: z.ZodOptional; branch: z.ZodOptional; }, z.core.$strict>>; duplicate_policy: z.ZodOptional>; }, z.core.$strip>>; spawnPlan: z.ZodOptional>; }, z.core.$strip>, z.ZodObject<{ agent: z.ZodString; tasks: z.ZodArray>; executionMode: z.ZodOptional>; inheritContext: z.ZodOptional>; repositoryBinding: z.ZodOptional; worktreeRoot: z.ZodString; commonDir: z.ZodNullable; relativeSubdir: z.ZodOptional; displayPath: z.ZodOptional; head: z.ZodOptional; branch: z.ZodOptional; }, z.core.$strict>>; duplicate_policy: z.ZodOptional>; }, z.core.$strip>>; spawnPlan: z.ZodOptional>; }, z.core.$strip>, z.ZodObject<{ agent: z.ZodString; tasks: z.ZodArray>; executionMode: z.ZodOptional>; inheritContext: z.ZodOptional>; repositoryBinding: z.ZodOptional; worktreeRoot: z.ZodString; commonDir: z.ZodNullable; relativeSubdir: z.ZodOptional; displayPath: z.ZodOptional; head: z.ZodOptional; branch: z.ZodOptional; }, z.core.$strict>>; duplicate_policy: z.ZodOptional>; }, z.core.$strip>>; spawnPlan: z.ZodOptional>; }, z.core.$strip>, z.ZodObject<{ agent: z.ZodString; tasks: z.ZodArray>; executionMode: z.ZodOptional>; inheritContext: z.ZodOptional>; repositoryBinding: z.ZodOptional; worktreeRoot: z.ZodString; commonDir: z.ZodNullable; relativeSubdir: z.ZodOptional; displayPath: z.ZodOptional; head: z.ZodOptional; branch: z.ZodOptional; }, z.core.$strict>>; duplicate_policy: z.ZodOptional>; }, z.core.$strip>>; spawnPlan: z.ZodOptional>; }, z.core.$strip>, z.ZodObject<{ agent: z.ZodString; tasks: z.ZodArray>; executionMode: z.ZodOptional>; inheritContext: z.ZodOptional>; repositoryBinding: z.ZodOptional; worktreeRoot: z.ZodString; commonDir: z.ZodNullable; relativeSubdir: z.ZodOptional; displayPath: z.ZodOptional; head: z.ZodOptional; branch: z.ZodOptional; }, z.core.$strict>>; duplicate_policy: z.ZodOptional>; }, z.core.$strip>>; spawnPlan: z.ZodOptional>; }, z.core.$strip>, z.ZodObject<{ agent: z.ZodString; tasks: z.ZodArray>; executionMode: z.ZodOptional>; inheritContext: z.ZodOptional>; repositoryBinding: z.ZodOptional; worktreeRoot: z.ZodString; commonDir: z.ZodNullable; relativeSubdir: z.ZodOptional; displayPath: z.ZodOptional; head: z.ZodOptional; branch: z.ZodOptional; }, z.core.$strict>>; duplicate_policy: z.ZodOptional>; }, z.core.$strip>>; spawnPlan: z.ZodOptional>; }, z.core.$strip>]; type DynamicTaskSchema = (typeof ALL_TASK_SCHEMAS)[number]; export type TaskSchema = typeof taskSchema; /** Active task tool parameter schema for the current simple-mode / isolation flags */ export type TaskToolSchemaInstance = DynamicTaskSchema; export declare function getTaskSchema(options: { isolationEnabled: boolean; simpleMode: TaskSimpleMode; }): DynamicTaskSchema; export interface TaskParams { agent: string; context?: string; schema?: string; spawnPlan?: SpawnPlanReceipt; tasks: TaskItem[]; isolated?: boolean; duplicate_policy?: "warn" | "supersede"; } /** A code review finding reported by the reviewer agent */ export interface ReviewFinding { title: string; body: string; priority: number; confidence: number; file_path: string; line_start: number; line_end: number; } /** Durable full-fidelity review findings artifact associated with a task result. */ export interface ReviewFindingsArtifactRef { uri: `artifact://${string}`; sizeBytes: number; sha256: string; findingCount: number; } /** Review summary submitted by the reviewer agent */ export interface ReviewSummary { overall_correctness: "correct" | "incorrect"; explanation: string; confidence: number; } /** Structured review data extracted from reviewer agent */ export interface ReviewData { findings: ReviewFinding[]; summary?: ReviewSummary; } /** Agent definition (bundled or discovered) */ export interface AgentDefinition { name: string; description: string; systemPrompt: string; tools?: string[]; spawns?: string[] | "*"; model?: string[]; thinkingLevel?: ThinkingLevel; output?: unknown; blocking?: boolean; autoloadSkills?: string[]; hide?: boolean; forkContext?: ForkContextPolicy; bashAllowedPrefixes?: string[]; source: AgentSource; filePath?: string; } export interface ModelSubstitutionWarning { requested: string; effective: string; reason: "auth_unavailable" | "assistant_model_mismatch"; } /** Progress tracking for a single agent */ export interface AgentProgress { index: number; id: string; agent: string; agentSource: AgentSource; status: "pending" | "running" | "completed" | "failed" | "aborted" | "paused"; task: string; assignment?: string; description?: string; lastIntent?: string; currentTool?: string; currentToolArgs?: string; currentToolStartMs?: number; recentTools: Array<{ tool: string; args: string; endMs: number; }>; recentOutput: string[]; toolCount: number; /** Cumulative input + output + cacheWrite tokens across all turns. Excludes cacheRead (re-reads cached context every turn, making cumulative sum misleading). */ tokens: number; /** * Current per-turn context size: latest assistant message's `usage.totalTokens`. * This is the number to compare against `contextWindow` — what compaction * decides on, what the user typically reads as "how full is the context". * Distinct from `tokens`, which is a lifetime billing-volume counter. */ contextTokens?: number; /** Model's context window in tokens, when known. Lets the UI render `/` gauges. */ contextWindow?: number; /** Cumulative billing cost in USD, accumulated incrementally from message_end events. */ cost: number; durationMs: number; modelOverride?: string | string[]; modelSubstitutionWarning?: ModelSubstitutionWarning; /** Whether the resolved subagent model runs under the effective fast service tier. */ fastMode?: boolean; /** Data extracted by registered subprocess tool handlers (keyed by tool name) */ extractedToolData?: Record; /** * Auto-retry state when the subagent is sleeping between provider retries * (e.g. 429 rate-limit with retry-after). Cleared when the retry resolves * or fails. Surfacing this to the parent prevents the task tool from * looking indefinitely "in progress" when a child is actually blocked on * provider quota. */ retryState?: { attempt: number; maxAttempts: number; unbounded?: boolean; kind: "first_event_timeout" | "idle_stream_stall" | "provider_error"; provider?: string; lastProviderProgressAtMs?: number; delayMs: number; errorMessage: string; startedAtMs: number; }; /** * Terminal retry failure surfaced once the subagent gave up retrying * (e.g. retry-after exceeded the cap, or all attempts exhausted). Carries * the final error so the parent UI can render "blocked: rate-limited" * instead of waiting for a status that never arrives. */ retryFailure?: { attempt: number; errorMessage: string; }; /** Safe diagnostic retained in terminal progress when setup fails before the first LLM request. */ setupFailure?: SetupFailureSummary; /** * Snapshot of the most recent `task` tool call's in-flight `TaskToolDetails`, * captured from `tool_execution_update`. Lets the parent UI surface live * nested-subagent progress while this agent is still inside its own `task` * call. Cleared when the call ends — finalized data lives in * `extractedToolData.task` after that. */ inflightTaskDetails?: TaskToolDetails; } /** Bounded diagnostic retained when subagent setup fails before an LLM request starts. */ export interface SetupFailureSummary { summary: string; } /** Create a bounded diagnostic that preserves a setup failure's cause without exposing credentials or local paths. */ export declare function createSetupFailureSummary(error: unknown): SetupFailureSummary; /** Bounded, redaction-safe summary of a terminal local (non-provider) subagent failure. */ export interface LocalErrorSummary { kind: string; summary: string; } /** * Runtime-validate a structured overflow diagnostic at the consuming trust * boundary. Presence on an `AssistantMessage` is NOT authenticity: a foreign * provider/stream payload could set the field, so every value is checked — * closed `stage`/`exceeded` literals and finite non-negative integer counters. * Returns `undefined` for anything that fails, and the caller then degrades to * a fixed neutral sentence instead of interpolating untrusted values (#4618). */ export declare function validateLocalOverflowShape(overflow: unknown): { stage: string; exceeded: "events" | "bytes" | "both"; stagedEventCount: number; stagedBytes: number; incomingEventBytes: number; maxStagedEvents: number; maxStagedBytes: number; } | undefined; /** * Render the parent-facing summary of a validated overflow diagnostic. Built * ONLY from the closed-vocabulary stage/exceeded literals and the numeric * counters — no producer-controlled text participates, so a hostile or buggy * child can inject nothing through this path (#4618). */ export declare function formatBufferOverflowSummary(overflow: { stage: string; exceeded: "events" | "bytes" | "both"; stagedEventCount: number; stagedBytes: number; incomingEventBytes: number; maxStagedEvents: number; maxStagedBytes: number; }): string; /** * Build the safe parent-facing summary for a terminal local failure. * * Trust boundary: the structured `bufferOverflow` shape is runtime-validated * (`validateLocalOverflowShape`) before any value is interpolated — closed * literals and checked integers only. A shape that fails validation, or an * overflow kind with no shape at all, degrades to a fixed neutral sentence. * `local_snapshot_failure` uses a fixed sentence too: regex redaction cannot * make arbitrary child message text safe to embed in a parent receipt. */ export declare function createLocalErrorSummary(kind: unknown, _message: string | undefined, overflow?: unknown): LocalErrorSummary; /** Whether an assistant terminal message carries a known local (non-provider) failure kind. */ export declare function isAssistantLocalErrorKind(kind: unknown): kind is "local_buffer_overflow" | "local_snapshot_failure"; export interface TaskRecoveryArtifactRef { uri: string; sizeBytes: number; sha256: string; /** Recovery artifacts remain readable for the parent session lifetime. */ durability: "session"; } /** Bounded duplicate-launch disposition carried into task receipts. */ export interface DuplicateDisposition { action: "warned" | "superseded"; predecessorIds: string[]; } export interface TaskPersistenceResult { outcome: "applied" | "no_changes" | "recovery_available"; ownerWorktreeApplied: boolean; recoveryRef?: TaskRecoveryArtifactRef; } export type RoutingSubstitution = "auth_substituted" | "assistant_model_mismatch"; /** A typed failure observed while an autorouting candidate is still before the real provider fence. */ export type AutoroutingPreflightFailure = { kind: "local"; op: "auth_resolve" | "session_open" | "tool_bootstrap" | "preflight_validation"; transient: boolean; } | { kind: "transport"; class: FallbackTriggerClass; }; export type AutoroutingAttemptCode = "probe_passed" | "accepted" | "spawn_transient_retry" | "credential_unavailable" | "config_invalid_terminal" | "post_acceptance_failure" | "unclassified_terminal"; export type AutoroutingAttempt = { selector: string; phase: "probe" | "durable"; code: AutoroutingAttemptCode; }; export type AutoroutingSkip = { selector: string; code: AutoroutingReasonCode; }; export interface TaskRoutingEvidence { tier: "fast" | "balanced" | "strong"; requestedTier?: "fast" | "balanced" | "strong"; defaultTierApplied?: true; requestedSelector: string; authResolvedModel?: string; effectiveModel?: string; notExecuted?: true; substitutions: RoutingSubstitution[]; manualFallbackReason?: "tier_unmatched" | "tier_missing_in_map"; freshOnResume?: true; note?: string; skips?: AutoroutingSkip[]; omittedSkipCount?: number; omittedByCode?: Partial>; attempts?: AutoroutingAttempt[]; terminal?: "preflight_exhausted" | "all_candidates_skipped"; } export declare function assertRoutingEvidenceInvariant(evidence: TaskRoutingEvidence): void; /** Result from a single agent execution */ export interface SingleResult { index: number; id: string; agent: string; agentSource: AgentSource; task: string; assignment?: string; description?: string; lastIntent?: string; exitCode: number; output: string; stderr: string; truncated: boolean; durationMs: number; /** Cumulative input + output + cacheWrite tokens across all turns. Excludes cacheRead (re-reads cached context every turn, making cumulative sum misleading). */ tokens: number; /** Latest per-turn context size at task completion. See `AgentProgress.contextTokens`. */ contextTokens?: number; /** Model's context window in tokens, when known. */ contextWindow?: number; routing?: TaskRoutingEvidence; modelOverride?: string | string[]; modelSubstitutionWarning?: ModelSubstitutionWarning; /** Whether the resolved subagent model ran under the effective fast service tier. */ fastMode?: boolean; error?: string; /** Safe summary of a terminal local (non-provider) failure kind, e.g. `local_buffer_overflow`. */ localErrorSummary?: LocalErrorSummary; /** Safe diagnostic for a failure before the subagent sent its first LLM request. */ setupFailure?: SetupFailureSummary; /** Internal typed autorouting preflight outcome; receipt sanitization omits this field. */ preflightFailure?: AutoroutingPreflightFailure; preflightFenceCrossed?: boolean; preflightProbeAccepted?: boolean; preflightCommitFailure?: boolean; aborted?: boolean; abortReason?: string; duplicateDisposition?: DuplicateDisposition; paused?: boolean; /** Aggregated usage from the subprocess, accumulated incrementally from message_end events. */ usage?: Usage; /** True only when every usage-contributing assistant supplied a complete, non-negative raw cost breakdown. */ usageCostBreakdownComplete?: true; /** Output path for the task result */ outputPath?: string; /** Patch path for isolated worktree output */ patchPath?: string; /** Branch name for isolated branch-mode output */ branchName?: string; /** Nested repo patches to apply after parent merge */ nestedPatches?: NestedRepoPatch[]; /** Whether isolated execution produced a non-empty root or nested patch. */ producedChanges?: boolean; /** Receipt-safe owner-worktree persistence result for isolated execution. */ persistence?: TaskPersistenceResult; /** Identity-bound patch artifact captured before isolation cleanup. */ recoveryRef?: TaskRecoveryArtifactRef; /** Data extracted by registered subprocess tool handlers (keyed by tool name) */ extractedToolData?: Record; /** Full wrapper-owned review evidence, kept separate from caller completion data. */ reviewFindingsRef?: ReviewFindingsArtifactRef; /** * Terminal retry failure, when the subagent exited because the auto-retry * loop gave up (retry-after exceeded the cap, or all attempts exhausted). * Lets the parent task tool surface a "blocked: rate-limited" outcome * instead of a generic failure. */ retryFailure?: { attempt: number; errorMessage: string; }; /** Output metadata for agent:// URL integration */ outputMeta?: { lineCount: number; charCount: number; byteSize?: number; sha256?: string; }; /** Fork-context seed accounting for this subagent, when inherited parent context was cloned. */ forkContext?: { mode: ForkContextMode; clonedTokens: number; }; /** * Advisory fork-context mode recommendation for this task (logged only; * never changes the actual mode selection). */ forkContextAdvisory?: { recommendedMode: ForkContextMode; reasons: string[]; }; /** * Resolved repository identity used for this task after pre-discovery stamping * and fail-closed validation (#2901). */ repositoryBinding?: { schema: "gjc.repository_binding.v1"; worktreeRoot: string; commonDir: string | null; relativeSubdir?: string; displayPath?: string; head?: string; branch?: string; }; } /** True only for complete, factual five-bucket cost accounting. */ export declare function hasCompleteUsageCostBreakdown(usage: unknown): boolean; /** True only when every usage-contributing result has explicit, complete cost provenance. */ export declare function hasCompleteAggregateUsageCostBreakdown(results: readonly Pick[]): boolean; /** Tool details for TUI rendering */ export interface TaskToolDetails { projectAgentsDir: string | null; results: TaskResultReceipt[]; totalDurationMs: number; /** Aggregated usage across all subagents. */ usage?: Usage; /** True only when every usage-contributing subagent supplied a complete raw cost breakdown. */ usageCostBreakdownComplete?: true; /** Aggregate cloned tokens copied into fork-context seeds across subagents. */ forkContextClonedTokens?: number; roiSummary?: { childCount: number; totalTokens: number; totalCostTotal?: number; totalClonedTokens?: number; /** Advisory ids for terminal children that spent tokens without detectable output/review/changes. */ lowRoiChildIds: string[]; }; roiReconciliation?: SpawnRoiReconciliation; progress?: AgentProgress[]; async?: { state: "running" | "paused" | "queued" | "completed" | "failed"; jobId: string; type: "task"; }; } /** * Persisted per-turn / per-subagent token record (Phase 0 instrumentation). * * Additive: this does not alter any existing task result shape. It is the * durable, model-independent unit the deterministic orchestration-token * benchmark (`@gajae-code/orchestration-token-benchmark`) consumes to measure * token efficiency without any live-model calls. */ export interface TaskTokenLog { /** Subagent id, or "root" for the orchestrator's own turn. */ subagentId: string; /** Agent name for attribution, when known. */ agent?: string; /** 1-based turn index within the subagent's session. */ turn: number; /** ISO-8601 timestamp the turn completed. */ at: string; /** Cost-bearing input tokens (excludes cache reads), mirrors `Usage.input`. */ input: number; /** Total output tokens for the turn, mirrors `Usage.output`. */ output: number; /** Tokens read from the prompt cache, mirrors `Usage.cacheRead`. */ cacheRead: number; /** Tokens written to the prompt cache, mirrors `Usage.cacheWrite`. */ cacheWrite: number; /** input + output + cacheRead + cacheWrite. */ totalTokens: number; /** Latest per-turn context-window occupancy, when known. */ contextTokens?: number; /** Estimated USD cost for the turn, when known. */ cost?: number; /** Model id used for the turn, when known. */ model?: string; } /** * Deterministic aggregate token metrics computed from a set of `TaskTokenLog` * entries. The cache-hit-rate field is the primary prompt-cache signal called * out by the prefix-stability invariant (see the approved plan). */ export interface TaskTokenMetrics { /** Number of token-log entries aggregated. */ turns: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; totalTokens: number; /** cacheRead / (input + cacheRead); 0 when there is no input-class traffic. */ cacheHitRate: number; } export {};