length-extrapolating-architecture-data / dev /code_qwen-code-dev-bot__oh-my-cli.txt
ag2003's picture
Upload folder using huggingface_hub
5b48487 verified
Raw History Blame Contribute Delete
112 kB
# ===== file: src/accessibility-semantics.ts ===== // Read-only accessibility semantics: defines color roles, reduced-color // fallbacks, and reduced-motion preferences for activity rendering. // // Color roles expose semantic name, full-color value, reduced-color // fallback (symbol/glyph), and contrast ratio. Reduced-motion preferences // disable animation hints. The model supports screen-reader label // generation. The view is read-only and never renders actual UI, executes // commands, or modifies preferences. export const ACCESSIBILITY_SEMANTICS_SCHEMA = "oh-my-cli.accessibility-semantics"; export const ACCESSIBILITY_SEMANTICS_VERSION = 1; // --- types ------------------------------------------------------------------ export type ColorRole = | "status-running" | "status-success" | "status-failure" | "status-waiting" | "emphasis" | "warning" | "error" | "muted"; export interface ColorDefinition { role: ColorRole; /** Semantic meaning description. */ meaning: string; /** Full-color hex value. */ fullColor: string; /** Reduced-color fallback glyph/symbol. */ reducedGlyph: string; /** WCAG contrast ratio against the background (approximate). */ contrastRatio: number; /** Screen-reader label. */ screenReaderLabel: string; } export interface MotionPreference { /** Whether animations are enabled. */ animationsEnabled: boolean; /** Static alternative for spinner/progress. */ staticSpinner: string; /** Static alternative for progress bar. */ staticProgress: string; } export interface AccessibilityProfile { /** Whether reduced-color mode is active. */ reducedColor: boolean; /** Whether reduced-motion mode is active. */ reducedMotion: boolean; /** Color definitions. */ colors: ColorDefinition[]; /** Motion preferences. */ motion: MotionPreference; } // --- default definitions ---------------------------------------------------- const DEFAULT_COLORS: ColorDefinition[] = [ { role: "status-running", meaning: "Active/running process", fullColor: "#3B82F6", reducedGlyph: "▶", contrastRatio: 4.5, screenReaderLabel: "Running" }, { role: "status-success", meaning: "Successful completion", fullColor: "#22C55E", reducedGlyph: "✓", contrastRatio: 4.6, screenReaderLabel: "Succeeded" }, { role: "status-failure", meaning: "Failed operation", fullColor: "#EF4444", reducedGlyph: "✗", contrastRatio: 4.5, screenReaderLabel: "Failed" }, { role: "status-waiting", meaning: "Waiting for input or dependency", fullColor: "#F59E0B", reducedGlyph: "○", contrastRatio: 4.5, screenReaderLabel: "Waiting" }, { role: "emphasis", meaning: "Emphasized content", fullColor: "#8B5CF6", reducedGlyph: "★", contrastRatio: 4.6, screenReaderLabel: "Emphasis" }, { role: "warning", meaning: "Warning condition", fullColor: "#F97316", reducedGlyph: "⚠", contrastRatio: 4.5, screenReaderLabel: "Warning" }, { role: "error", meaning: "Error condition", fullColor: "#DC2626", reducedGlyph: "⛔", contrastRatio: 5.0, screenReaderLabel: "Error" }, { role: "muted", meaning: "De-emphasized content", fullColor: "#6B7280", reducedGlyph: "·", contrastRatio: 4.5, screenReaderLabel: "Muted" }, ]; const DEFAULT_MOTION: MotionPreference = { animationsEnabled: true, staticSpinner: "[working]", staticProgress: "[=====> ]", }; const REDUCED_MOTION: MotionPreference = { animationsEnabled: false, staticSpinner: "[working]", staticProgress: "[=====> ]", }; // --- profile builder -------------------------------------------------------- export function buildAccessibilityProfile(opts: { reducedColor?: boolean; reducedMotion?: boolean; } = {}): AccessibilityProfile { return { reducedColor: opts.reducedColor ?? false, reducedMotion: opts.reducedMotion ?? false, colors: DEFAULT_COLORS, motion: opts.reducedMotion ? REDUCED_MOTION : DEFAULT_MOTION, }; } // --- rendering helpers (pure, no actual UI) --------------------------------- // Render a status indicator for a given role, respecting the profile. export function renderStatusIndicator(role: ColorRole, profile: AccessibilityProfile): string { const color = profile.colors.find((c) => c.role === role); if (!color) return "?"; if (profile.reducedColor) { return color.reducedGlyph; } return `${color.reducedGlyph}`; // In a real TUI, this would use ANSI colors. } // Generate a screen-reader label for an activity state. export function screenReaderLabel(role: ColorRole, detail: string, profile: AccessibilityProfile): string { const color = profile.colors.find((c) => c.role === role); const label = color?.screenReaderLabel ?? role; return `${label}: ${detail}`; } // Render a spinner/progress respecting motion preferences. export function renderProgress(pct: number, profile: AccessibilityProfile): string { if (!profile.motion.animationsEnabled) { return profile.motion.staticProgress; } const width = 20; // Issue #808: clamp the fill into [0, width] so an out-of-range pct // (over-100 or negative) renders a clamped bar instead of throwing a // RangeError from a negative repeat count. In-range output is unchanged. const filled = Math.max(0, Math.min(width, Math.round((pct / 100) * width))); return `[${"=".repeat(filled)}>${" ".repeat(width - filled)}]`; } // --- formatting ------------------------------------------------------------- export function formatAccessibilityProfile(profile: AccessibilityProfile): string { const lines: string[] = []; lines.push("Accessibility Semantics"); lines.push("═".repeat(50)); lines.push(`Reduced color: ${profile.reducedColor ? "YES" : "no"} Reduced motion: ${profile.reducedMotion ? "YES" : "no"}`); lines.push(""); lines.push("Color roles:"); for (const color of profile.colors) { const display = profile.reducedColor ? color.reducedGlyph : `${color.reducedGlyph} (${color.fullColor})`; lines.push(` ${display} ${color.role} — ${color.meaning} [${color.contrastRatio}:1] "${color.screenReaderLabel}"`); } lines.push(""); lines.push(`Motion: animations ${profile.motion.animationsEnabled ? "enabled" : "disabled"}`); lines.push(` Spinner: ${profile.motion.staticSpinner}`); lines.push(` Progress: ${profile.motion.staticProgress}`); lines.push(""); lines.push("Read-only: no UI rendered, no preferences modified."); return lines.join("\n"); } # ===== file: src/activity-render.ts ===== // Activity rendering: render the #306 presented activity event stream as // progressive-disclosure cards for the mission-control TUI view (Issue #307, the // TUI activity-rendering child of #291). Each card shows a status glyph, the // event kind, its summary, elapsed time, and a liveness marker; expanding a card // reveals its bounded detail. The rendering is a pure function of the presented // events plus a small view state (which cards are expanded, follow-mode, and an // unread count), so the same events and view state always render the same view, // and expanding/collapsing never loses the underlying events. // // This module returns plain text lines (no ANSI); the TUI panel in tui-shell.ts // applies color/style around them, exactly as the mission lifecycle (#314) and // background-task panels style their bodies. Keeping rendering pure and // style-free makes it unit-testable against fixture event streams and reusable by // the Desktop canvas (#318). Reduced-color/no-color degrades to the glyphs and // plain text without losing information. // // Trust boundary: the rendering reads only already-presented events (sanitized by // the #306 mapper); it executes nothing and adds no untrusted content. import type { PresentedEvent, EventStatus } from "./event-presentation.js"; // A stable glyph per activity status, so a card communicates status at a glance // without relying on color alone. const STATUS_GLYPHS: Record<EventStatus, string> = { pending: "○", active: "◆", completed: "✓", failed: "✕", waiting: "◇", cancelled: "⊘", }; export function activityGlyph(status: EventStatus): string { return STATUS_GLYPHS[status] ?? "?"; } // Compact human elapsed time: seconds under a minute, minutes under an hour, // hours otherwise. export function formatElapsed(ms: number): string { const seconds = Math.max(0, Math.floor(ms / 1000)); if (seconds >= 3600) return `${Math.floor(seconds / 3600)}h`; if (seconds >= 60) return `${Math.floor(seconds / 60)}m`; return `${seconds}s`; } // A liveness marker: a filled dot while the event is live, blank otherwise. export function livenessMarker(live: boolean): string { return live ? "●" : "·"; } // Render one activity card. Collapsed shows a single summary line; expanded adds // the bounded detail (with a truncation note when the #306 mapper bounded it). export function renderActivityCard(event: PresentedEvent, expanded: boolean): string[] { const summary = event.summary || event.kind; const head = `${activityGlyph(event.status)} ${event.kind} · ${summary} · ${formatElapsed( event.elapsedMs, )} ${livenessMarker(event.live)} ${event.status}`; if (!expanded) return [head]; const detail = event.detail === "" ? [" (no detail)"] : event.detail.split("\n").map((l) => ` ${l}`); const truncated = event.detailTruncated ? [" … (detail truncated)"] : []; return [head, ...detail, ...truncated]; } // The activity view state: which card indices are expanded, whether follow-mode // is on (auto-track the latest event), and how many events arrived since the view // was last read. Immutable; transitions return new states. export interface ActivityViewState { expanded: ReadonlySet<number>; followMode: boolean; unread: number; } export function initialActivityViewState(): ActivityViewState { return { expanded: new Set<number>(), followMode: true, unread: 0 }; } // Toggle whether one card index is expanded. export function toggleExpand(state: ActivityViewState, index: number): ActivityViewState { const expanded = new Set(state.expanded); if (expanded.has(index)) expanded.delete(index); else expanded.add(index); return { ...state, expanded }; } // Expand every card (when count > 0 and not all already expanded) or collapse all // otherwise — a simple toggle-all for the panel's expand/collapse gesture. export function toggleExpandAll(state: ActivityViewState, count: number): ActivityViewState { const allExpanded = count > 0 && state.expanded.size >= count; const expanded = allExpanded ? new Set<number>() : new Set<number>(Array.from({ length: count }, (_, i) => i)); return { ...state, expanded }; } export function setFollowMode(state: ActivityViewState, on: boolean): ActivityViewState { return { ...state, followMode: on }; } export function markRead(state: ActivityViewState): ActivityViewState { return { ...state, unread: 0 }; } export function bumpUnread(state: ActivityViewState, n: number): ActivityViewState { return { ...state, unread: state.unread + Math.max(0, Math.floor(n)) }; } // Render the whole activity stream as progressive-disclosure cards (in event // order), expanding the cards whose indices are in the view state. Empty stream // renders a single placeholder line. export function renderActivityStream( events: readonly PresentedEvent[], state: ActivityViewState, ): string[] { if (events.length === 0) return ["(no activity)"]; const lines: string[] = []; events.forEach((event, index) => { lines.push(...renderActivityCard(event, state.expanded.has(index))); }); return lines; } // Render the full read-only activity view: a header (counts + follow-mode + // unread), the card stream, and a hint line. Pure and deterministic. export function formatActivityView( events: readonly PresentedEvent[], state: ActivityViewState, ): string[] { const active = events.filter((e) => e.live).length; const header = `Activity (read-only) · events ${events.length} · live ${active} · ` + `follow ${state.followMode ? "on" : "off"} · unread ${state.unread}`; return [header, "", ...renderActivityStream(events, state)]; } # ===== file: src/agent.ts ===== import type { Config } from "./config.js"; import type { SessionMessage } from "./session.js"; import type { ToolDef, ToolResult, ShellFailureDetail } from "./tools.js"; import { createTools, toolSchemasForOpenAI } from "./tools.js"; import { streamChat, backoffDelayMs, RETRY_MAX_ATTEMPTS, isQuotaExhausted, quotaExhaustedGuidance, classifyTransient, } from "./provider.js"; import type { StreamProvider } from "./provider.js"; import { redactEndpointHost } from "./permission-impact.js"; import type { Workspace } from "./workspace.js"; import type { ApprovalMode } from "./approval.js"; import { needsApproval, promptApproval } from "./approval.js"; import { evaluateCommandPolicy, policyDenialMessage } from "./command-policy.js"; import { evaluatePreToolUseHooks, type PreToolUseHook } from "./hook-contract.js"; import { folderTrustDenialMessage } from "./folder-trust.js"; import { estimateCostUsd, lookupModelPrice, formatCostUsd } from "./cost.js"; import { computeMessageTiming, formatMessageUsageLine } from "./message-usage.js"; import { buildEffectiveSystemPrompt, composeAppendedSystemPrompt } from "./instruction-context.js"; import { promptWithTextAttachments } from "./text-attachment.js"; import type { LoadedTextAttachment } from "./text-attachment.js"; import { compactMessages, buildCompactedTranscript } from "./compaction.js"; import type { LoadedImage } from "./image-input.js"; import type { TurnImageCollector } from "./turn-checkpoint.js"; import type { BottleneckCollector } from "./run-bottleneck.js"; import type { FailureTaxonomyCollector } from "./run-failure-taxonomy.js"; const MAX_ROUNDS = 30; // Transcript content for a tool call cancelled before execution (Issue #550). // A bounded, secret-free placeholder that keeps the transcript resume-valid: // every tool_call_id keeps exactly one tool message. session-stats derives // deterministic cancellation counts by matching this exact content. export const CANCELLED_TOOL_CONTENT = "[cancelled: turn cancelled before this tool ran]"; // Bounded wait between empty-completion recovery attempts (#244). Mirrors the // provider's own bounded backoff so an unattended run can never loop or overspend // indefinitely waiting for a non-empty answer. function sleep(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); } export interface AgentOptions { config: Config; workspace: Workspace; approvalMode: ApprovalMode; sessionId: string; onMessage: (msg: SessionMessage) => void; sink?: AgentSink; // Optional spend budget in USD. When the running cost estimate reaches this // cap, the loop stops before issuing further provider calls. Null disables it. budgetUsd?: number | null; // Optional operator turn cap (Issue #515). When set, the loop stops before // the (n+1)th provider round at the round boundary — never mid-tool-call and // never mid-stream. Null disables it. maxTurns?: number | null; // Optional operator wall-time cap in milliseconds (Issue #515). When set, the // loop stops the first round that would start at or after this much wall // time has elapsed since the run began — at the round boundary only. Null // disables it. maxWallTimeMs?: number | null; // Optional operator tool-call cap (Issue #517). When set, the loop stops at // the first round boundary after the cumulative processed tool-call count // reaches it — every tool call the round emitted already has its result, so // the transcript stays complete. Null disables it. maxToolCalls?: number | null; // Run-scoped user instructions (Issue #789): appended as a labeled section // after the built-in system prompt when a fresh session is seeded here. // Validated at the dispatch boundary (bounded, non-empty, fresh sessions // only); the agent trusts what it receives. Undefined disables it. appendSystemPrompt?: string; // Folder-trust enforcement. When false, every mutating tool (file or shell) // fails closed before approval is even considered, regardless of approvalMode // (so yolo cannot widen the boundary). Defaults to true (no enforcement) so // callers that do not opt in keep the existing behaviour. mutatingAllowed?: boolean; // Context-pressure threshold in tokens. When the most recent provider call's // prompt size reaches this, the in-memory transcript is compacted before the // next provider call (the on-disk transcript is untouched). Undefined or <= 0 // disables auto-compaction. compactThreshold?: number; // Image attachments for the initial user prompt. They are sent to the provider // as multimodal content parts; only a non-secret reference is persisted (the // data URL never reaches the session log). images?: LoadedImage[]; // Text-file attachments for the initial user prompt (Issue #797): pinned // verbatim into the next user message as delimited, path-labeled sections. // One-shot: the surface consumes its pending attachments when the turn // submits. textAttachments?: LoadedTextAttachment[]; // Optional collector for safe turn undo/redo. When present, the pre-image of // each file a mutating-file tool touches is captured before the tool runs, so // the turn's workspace mutations can later be reversed without a Git reset. turnImages?: TurnImageCollector; // User-owned PreToolUse hooks (resolved from the user settings scope by the // caller). Each matching hook runs as a deny-only gate before a tool executes; // a hook can only block a call, never approve it. Empty/undefined ⇒ no hooks. preToolUseHooks?: readonly PreToolUseHook[]; // Optional wall-time bottleneck collector. When present, the loop records each // tool's execution wall-time and each approval gate's wait wall-time so the // caller can build a privacy-safe bottleneck report. Undefined ⇒ no collection. bottleneck?: BottleneckCollector; // Optional failure-taxonomy collector. When present, the loop records the cause // of each failed tool call (policy/hook/approval denial, path escape, tool // error, unknown tool, folder-trust denial) so the caller can build a // privacy-safe failure-taxonomy report. Undefined ⇒ no collection. failureTaxonomy?: FailureTaxonomyCollector; // Optional shell failure receipt sink (Issue #574). When present, every // non-zero/killed/timed-out shell execution reports its structured failure // descriptor so the caller can persist a bounded, redacted receipt. The sink // is best-effort: a recording failure never changes tool results, approval // behavior, or turn outcomes. Undefined ⇒ no capture. onShellFailure?: (detail: ShellFailureDetail) => void; // Optional provider stream override. Defaults to the network `streamChat`; // the deterministic task-fixture replay (#224) supplies a scripted provider so // the same fixture always produces the same run. Undefined ⇒ network provider. streamProvider?: StreamProvider; // Read-only mode (#234): restrict the run to read-only tools and refuse any // mutating tool fail-closed, regardless of approval mode or folder trust, so // parallel investigators can safely share one workspace. Defaults to false. readOnly?: boolean; // Injectable wall-clock for per-message timing (TTFT / tok/s). Defaults to // Date.now; tests supply a deterministic clock so responsiveness metrics are // reproducible. Undefined ⇒ Date.now. now?: () => number; // Injectable wall-time clock for the operator wall-time cap (Issue #515). // Deliberately distinct from `now` (per-message timing) so capping a run // never shifts TTFT clock sequences. Defaults to Date.now. Undefined ⇒ // Date.now. runClock?: () => number; // One-shot fallback model (Issue #590). When set and the primary model's // request fails with a retryable (transient) provider error BEFORE producing // any output, the run degrades at most once to this model for the remainder // of the run; a subsequent failure never re-degrades. Null/undefined // disables fallback entirely and keeps existing behavior. Callers driving a // scripted provider (task-fixture replay) must never set this — a scripted // run cannot degrade truthfully. fallbackModel?: string | null; // Cooperative cancellation (#489). Polled before the first provider call, at // every round boundary, and between streamed events. When it returns true the // loop stops as soon as the current event is handled: any streamed assistant // text is persisted as one interrupted turn (never lost, never reported as a // completed answer) and the run ends with reason "cancelled". Undefined ⇒ the // run cannot be cancelled. cancelRequested?: () => boolean; // Retry support (#489). When false the run does NOT create or persist a user // message — the caller has already persisted the turn's user message and it is // present in existingMessages, so a retry reuses one request identity instead // of duplicating the user turn. Defaults to true. Attachments belong to the // original turn and are never re-attached on retry. appendUserMessage?: boolean; } // Cumulative usage and cost reported after each round. `estimatedCostUsd` is an // estimate (never authoritative billing); `costKnown` reports whether the model // price was found in the bundled table. `budgetReached` is true once the running // estimate has met or exceeded `budgetUsd`. export interface AgentUsage { round: number; tokens: { prompt: number; completion: number; total: number }; estimatedCostUsd: number; costKnown: boolean; budgetUsd: number | null; budgetReached: boolean; // Per-message responsiveness for this turn (#241): time-to-first-token and // output throughput. Null when the provider did not stream text tokens or did // not report usage/timing — omitted downstream rather than guessed. ttftMs: number | null; tokensPerSecond: number | null; } // A transient provider failure is being retried within a round. Metadata only — // which attempt, the transient reason class, and the scheduled wait — so a // consumer can observe resilience without seeing error text or secrets. export interface AgentRetry { round: number; attempt: number; maxAttempts: number; reasonClass: string; delayMs: number; } // The in-memory transcript was compacted to relieve context pressure. Metadata // only — how many messages were summarized and how many completed-action // receipts were retained — so a consumer can observe the event without seeing // content or secrets. export interface AgentCompaction { round: number; summarizedMessages: number; receipts: number; promptTokens: number; } // The run degraded from the primary model to the configured one-shot fallback // after a retryable provider failure produced no output (Issue #590). Metadata // only — model identifiers and the transient reason class — never error text, // request bodies, or secrets. export interface AgentFallback { round: number; fromModel: string; toModel: string; reasonClass: string; } // Output sink for the agent loop. The default console sink reproduces the // existing terminal behaviour; the headless sink (see headless-protocol.ts) // renders the same lifecycle as a versioned JSON event stream. export interface AgentSink { assistantDelta(delta: string): void; // `interrupted` is true when the turn's provider stream failed after emitting // text (#243): the text is preserved but the turn is incomplete. Absent/false // for normal turns. assistantTurn(text: string, round: number, opts: { final: boolean; interrupted?: boolean }): void; // `args` carries the tool's parsed arguments so a sink can render structured // detail (e.g. a file diff) without re-parsing; optional so existing sinks are // unaffected. toolStart(info: { id: string; name: string; round: number; args?: Record<string, unknown> }): void; toolResult(info: { id: string; name: string; result: ToolResult; round: number }): void; providerError(message: string): void; // Cumulative token usage and cost estimate, reported once per round. usage(info: AgentUsage): void; // A transient provider failure is being retried (bounded backoff). retry(info: AgentRetry): void; // The run degraded to the one-shot fallback model (Issue #590). Optional so // existing sinks are unaffected. fallback?(info: AgentFallback): void; // The in-memory transcript was compacted to relieve context pressure. compaction?(info: AgentCompaction): void; // A tool requires approval before executing. Optional: when present the sink // owns the prompt (e.g. the full-screen shell coordinates it within its own // raw-mode input model); when absent the agent falls back to the terminal // prompt. Returning false denies the tool exactly like a "no" at the prompt. requestApproval?(info: { name: string; args: Record<string, unknown> }): Promise<boolean>; } export function createConsoleSink(opts?: { messageUsage?: boolean }): AgentSink { const messageUsage = opts?.messageUsage ?? false; return { assistantDelta: (delta) => { process.stdout.write(delta); }, assistantTurn: (_text, _round, opts) => { if (opts.interrupted) { // Terminate the partial line and show a plain-text (non-color-only) // interruption indicator. The emitted text stays visible on stdout; the // marker goes to stderr like the other run-level notes (#243). process.stdout.write("\n"); process.stderr.write("[interrupted: incomplete response; the partial answer above was preserved]\n"); return; } if (opts.final) process.stdout.write("\n"); }, toolStart: () => {}, toolResult: () => {}, providerError: (message) => { process.stderr.write(`\nProvider error: ${message}\n`); }, usage: (info) => { // Opt-in per-message usage line (#241): a redacted turn-level readout of // tokens, estimated cost, TTFT, and throughput. Off by default so normal // conversation output is unchanged; written to stderr like the other // run-level notes so it never interleaves with assistant text on stdout. if (messageUsage) { process.stderr.write( `\n${formatMessageUsageLine({ round: info.round, promptTokens: info.tokens.prompt, completionTokens: info.tokens.completion, totalTokens: info.tokens.total, estimatedCostUsd: info.estimatedCostUsd, costKnown: info.costKnown, ttftMs: info.ttftMs, tokensPerSecond: info.tokensPerSecond, })}\n`, ); } // Keep normal output uncluttered; surface only the actionable budget stop. if (info.budgetReached && info.budgetUsd !== null) { process.stderr.write( `\nSpend budget reached: estimated ${formatCostUsd(info.estimatedCostUsd)} ` + `>= ${formatCostUsd(info.budgetUsd)}; stopping before further provider calls.\n`, ); } }, retry: (info) => { // A brief stderr note so the wait is visible without polluting stdout. process.stderr.write( `\nProvider retry ${info.attempt}/${info.maxAttempts} after ${info.reasonClass} ` + `(waiting ${info.delayMs}ms).\n`, ); }, fallback: (info) => { // The degrade is a material change of model for the rest of the run; it // goes to stderr like the other run-level notes, never into stdout. process.stderr.write( `\nProvider fallback: model "${info.fromModel}" failed transiently (${info.reasonClass}); ` + `degrading this run to fallback model "${info.toModel}".\n`, ); }, compaction: (info) => { // Surface the compaction so the context reduction is observable. process.stderr.write( `\nContext compacted: summarized ${info.summarizedMessages} message(s) ` + `(${info.receipts} completed-action receipt(s)) after ${info.promptTokens} prompt tokens.\n`, ); }, }; } export interface AgentResult { text: string; ok: boolean; // `empty_response` is the terminal anomaly when the provider keeps returning a // stream with no assistant text and no valid tool call and the bounded // empty-completion recovery is exhausted (#244). `max_turns_reached`, // `wall_time_reached`, and `tool_call_budget_reached` are operator run-cap // stops (Issues #515, #517): bounded, round-boundary halts distinct from // failures. reason: | "completed" | "provider_error" | "max_rounds" | "budget_reached" | "max_turns_reached" | "wall_time_reached" | "tool_call_budget_reached" | "empty_response" | "cancelled"; rounds: number; // Total transient provider retries across the run (0 when the provider never // failed transiently). Lets a consumer distinguish "exhausted retries" // (retries > 0, then provider_error) from "non-retryable" (retries 0). retries: number; // Bounded per-tool activity counts for the whole run. Each processed tool // call — executed (with or without error) or cancelled before execution — // is counted exactly once (no double-counted retries). stats: { toolCalls: Record<string, number>; toolFailures: Record<string, number>; // Calls cancelled before execution (#550); a subset of toolCalls that is // never counted in toolFailures. toolCancellations: Record<string, number>; }; // Aggregated token totals across all rounds, or null when the provider never // reported usage. tokens: { prompt: number; completion: number; total: number } | null; // Prompt size of the most recent provider call in this run (Issue #721) — // the exact input the context-pressure auto-compaction gate compares // against. Null when no call has reported usage yet (including right after // an auto-compaction reset, until the next call reports). lastCallPromptTokens: number | null; // Estimated provider cost (USD) across the run, or null when the provider // never reported usage. An estimate, not authoritative billing. estimatedCostUsd: number | null; // Whether the model price was found in the bundled table (false ⇒ the // conservative fallback rate was used). costKnown: boolean; // One-shot fallback degrade (Issue #590): true when the run degraded from // the primary model to the configured fallback; `fallbackModel` is the model // the run degraded to (null when no degrade happened). fellBack: boolean; fallbackModel: string | null; } export async function runAgent( userPrompt: string, existingMessages: SessionMessage[], opts: AgentOptions, ): Promise<AgentResult> { const sink = opts.sink ?? createConsoleSink(); // Wall-clock used for per-message timing; injectable for deterministic tests. const now = opts.now ?? Date.now; // Approval is owned by the sink when it offers a handler (the full-screen shell // coordinates the prompt within its raw-mode input model); otherwise the agent // falls back to the terminal prompt so non-interactive callers are unchanged. const requestApproval = sink.requestApproval ? (name: string, args: Record<string, unknown>): Promise<boolean> => sink.requestApproval!({ name, args }) : promptApproval; const tools = createTools(); const toolMap = new Map(tools.map((t) => [t.name, t])); const schemas = toolSchemasForOpenAI(tools); const preToolUseHooks = opts.preToolUseHooks ?? []; // Provider stream: the network `streamChat` by default, or a deterministic // scripted provider for task-fixture replay (#224). const stream = opts.streamProvider ?? streamChat; const messages: SessionMessage[] = [...existingMessages]; if (messages.length === 0) { // Fresh session: seed with the effective repository instruction context // (bounded identity + Git state + trusted instruction hierarchy) instead of // a generic prompt. Resumed sessions keep their original system message. const { text } = buildEffectiveSystemPrompt({ workspace: opts.workspace.root }); // Run-scoped user instructions (Issue #789): appended as a labeled section // after the built-in prompt — the built-in text is a byte-for-byte prefix, // never modified. Validated at the dispatch boundary. const systemText = opts.appendSystemPrompt ? composeAppendedSystemPrompt(text, opts.appendSystemPrompt) : text; const system: SessionMessage = { role: "system", content: systemText }; messages.push(system); opts.onMessage(system); } if (opts.appendUserMessage !== false) { // Text attachments (Issue #797) ride inside the message content itself — // unlike image bytes there is no out-of-band channel, and what the model // sees is exactly what the session persists. No attachments → the prompt // is used byte-for-byte. const userMsg: SessionMessage = { role: "user", content: promptWithTextAttachments(userPrompt, opts.textAttachments ?? []), }; if (opts.images && opts.images.length > 0) { // In-memory copy carries the data URLs the provider needs. userMsg.images = opts.images.map((img) => ({ name: img.name, mediaType: img.mediaType, bytes: img.bytes, dataUrl: img.dataUrl, })); } messages.push(userMsg); // Persist a privacy-safe copy: the data URL (raw image bytes) never reaches // the session log; only the non-secret reference (name, type, size) is kept. opts.onMessage( userMsg.images ? { ...userMsg, images: userMsg.images.map(({ name, mediaType, bytes }) => ({ name, mediaType, bytes })) } : userMsg, ); } let finalText = ""; const toolCalls: Record<string, number> = {}; const toolFailures: Record<string, number> = {}; const toolCancellations: Record<string, number> = {}; const tokens = { prompt: 0, completion: 0, total: 0 }; let hasUsage = false; // Total transient provider retries observed across the run. let retries = 0; // Running cost estimate (USD) across the run. Recomputed from cumulative // tokens each round; null in snapshots until the provider reports usage. let costUsd = 0; // One-shot fallback degrade (Issue #590). `activeConfig` is the provider // config the current round runs under; the degrade swaps its model once for // the remainder of the run. Cost accounting splits at the degrade so tokens // streamed under the primary keep the primary's price — with no degrade the // baselines stay 0 and the math reduces to whole-run pricing. const fallbackModel = typeof opts.fallbackModel === "string" && opts.fallbackModel.trim() !== "" ? opts.fallbackModel.trim() : null; let activeConfig = opts.config; let fellBack = false; let costBaselineUsd = 0; let baselinePromptTokens = 0; let baselineCompletionTokens = 0; let costKnown = lookupModelPrice(opts.config.model).known; const budgetUsd = opts.budgetUsd ?? null; // Operator run caps (Issue #515): same round-boundary semantics as the spend // budget. The wall-time cap measures real elapsed time through a dedicated // injectable clock (`runClock`), kept distinct from the per-message `now` // clock so capping never shifts TTFT timing sequences. const maxTurns = typeof opts.maxTurns === "number" && opts.maxTurns > 0 ? opts.maxTurns : null; const maxWallTimeMs = typeof opts.maxWallTimeMs === "number" && opts.maxWallTimeMs >= 0 ? opts.maxWallTimeMs : null; // Tool-call cap (Issue #517): counts every tool call the loop processes // (including denied attempts, which also consume rounds and can loop), via // the same per-tool counters that back the run stats. const maxToolCalls = typeof opts.maxToolCalls === "number" && opts.maxToolCalls > 0 ? opts.maxToolCalls : null; const runClock = opts.runClock ?? Date.now; const runStartedAt = runClock(); // Context-pressure auto-compaction. Null disables it. `lastPromptTokens` is the // most recent provider call's prompt size — the live context pressure that // drives compaction at the next round boundary. const compactThreshold = typeof opts.compactThreshold === "number" && opts.compactThreshold > 0 ? opts.compactThreshold : null; let lastPromptTokens = 0; const bump = (map: Record<string, number>, name: string) => { map[name] = (map[name] ?? 0) + 1; }; const statsSnapshot = () => ({ toolCalls: { ...toolCalls }, toolFailures: { ...toolFailures }, toolCancellations: { ...toolCancellations }, }); const tokensSnapshot = () => (hasUsage ? { ...tokens } : null); const costSnapshot = () => (hasUsage ? costUsd : null); // Issue #721: the auto-compaction gate input, surfaced for the /context // view. 0 means "no call has reported usage (yet)" — including right after // the gate resets the counter on compaction — and maps to null. const lastCallPromptTokensSnapshot = () => lastPromptTokens > 0 ? lastPromptTokens : null; const budgetReached = () => budgetUsd !== null && costUsd >= budgetUsd; const totalToolCalls = () => Object.values(toolCalls).reduce((sum, n) => sum + n, 0); for (let round = 0; round < MAX_ROUNDS; round++) { // Cooperative cancellation (#489): checked before any provider call in this // round, so a cancel issued while queued or between rounds stops the loop // without another billable call. Nothing has been streamed at a round // boundary, so there is no partial turn to persist here. if (opts.cancelRequested?.()) { return { text: finalText, ok: false, reason: "cancelled", rounds: round, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } // Spend budget gate: once the running estimate has reached the cap, stop // before issuing a new provider call so no further billable calls are made. if (budgetReached()) { return { text: finalText, ok: false, reason: "budget_reached", rounds: round, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } // Operator run-cap gates (Issue #515): the same round-boundary semantics as // the spend budget — stop before the next provider call, never mid-tool and // never mid-stream, so no partial turn or orphan tool call is produced. if (maxTurns !== null && round >= maxTurns) { return { text: finalText, ok: false, reason: "max_turns_reached", rounds: round, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } if (maxWallTimeMs !== null && runClock() - runStartedAt >= maxWallTimeMs) { return { text: finalText, ok: false, reason: "wall_time_reached", rounds: round, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } // Tool-call cap gate (Issue #517): stop at the first round boundary after // the cumulative processed tool-call count reaches the cap. The boundary // guarantees every tool call emitted by prior rounds has its result, so // the persisted transcript stays complete (no orphan tool_call). if (maxToolCalls !== null && totalToolCalls() >= maxToolCalls) { return { text: finalText, ok: false, reason: "tool_call_budget_reached", rounds: round, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } // Context-pressure gate: when the most recent provider call's prompt size has // reached the threshold, compact the in-memory transcript before the next // provider call. Only the live `messages` window is replaced with a bounded // summary; the on-disk transcript is untouched (every message was already // persisted via onMessage). This runs at a round boundary where every prior // tool call already has its result, so no orphan tool_call is produced. The // threshold is reset so we do not re-compact until the context grows again. if (compactThreshold !== null && lastPromptTokens >= compactThreshold && messages.length > 1) { const triggeredAt = lastPromptTokens; const { summary } = compactMessages(messages); const compacted = buildCompactedTranscript(messages, summary); messages.length = 0; messages.push(...compacted); lastPromptTokens = 0; sink.compaction?.({ round, summarizedMessages: summary.messageCount, receipts: summary.receipts.length, promptTokens: triggeredAt, }); } let assistantText = ""; let assistantToolCalls: Array<{ id: string; name: string; arguments: string }> = []; // Per-message timing (#241): the wall-clock just before the request, the // first streamed text token (for TTFT), and the turn's own completion tokens // (for throughput). firstTokenAt stays null for a turn that streams no text // (e.g. a pure tool-call turn), which omits TTFT downstream. These are // (re)assigned at the start of each attempt below; the placeholders here // satisfy definite-assignment without consuming a clock read. let roundStart = 0; let firstTokenAt: number | null = null; let roundCompletionTokens: number | null = null; // Bounded empty-completion recovery (#244): a stream that ends with neither // assistant text nor a valid tool call is an anomaly, not a completed answer. // Re-invoke the provider up to the fixed retry cap, charging each attempt's // usage to the budget and exposing each retry through the retry event path. let emptyAttempts = 0; let exhaustedEmpty = false; while (true) { assistantText = ""; assistantToolCalls = []; roundStart = now(); firstTokenAt = null; roundCompletionTokens = null; try { for await (const event of stream(activeConfig, messages, { tools: schemas })) { if (event.type === "text") { if (firstTokenAt === null) firstTokenAt = now(); assistantText += event.delta; sink.assistantDelta(event.delta); } else if (event.type === "tool_call") { assistantToolCalls.push({ id: event.id, name: event.name, arguments: event.arguments }); } else if (event.type === "usage") { hasUsage = true; tokens.prompt += event.promptTokens; tokens.completion += event.completionTokens; tokens.total += event.totalTokens; lastPromptTokens = event.promptTokens; roundCompletionTokens = event.completionTokens; } else if (event.type === "retry") { retries++; sink.retry({ round, attempt: event.attempt, maxAttempts: event.maxAttempts, reasonClass: event.reasonClass, delayMs: event.delayMs, }); } // Cooperative cancellation (#489): polled between streamed events so a // cancel takes effect at the next event boundary. Partial tool calls // are never persisted; only emitted assistant text survives, as one // interrupted turn. if (opts.cancelRequested?.()) { if (assistantText.length > 0) { const partial: SessionMessage = { role: "assistant", content: assistantText, interrupted: true, }; messages.push(partial); opts.onMessage(partial); sink.assistantTurn(assistantText, round, { final: false, interrupted: true }); } return { text: assistantText, ok: false, reason: "cancelled", rounds: round, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } } } catch (err: unknown) { // One-shot fallback degrade (Issue #590): when the active model's // request fails transiently BEFORE producing any output (no text, no // tool calls) and a fallback is configured and not yet used, swap to // the fallback for the rest of the run and re-invoke the provider for // this round. The provider's own bounded retries already ran inside // streamChat; this is a degrade, not another retry of the same model. // A failure after any output, a non-retryable failure, or any failure // once already degraded falls through to the terminal path below. const transient = classifyTransient(err); if ( fallbackModel !== null && !fellBack && transient !== null && assistantText.length === 0 && assistantToolCalls.length === 0 ) { if (hasUsage) { costBaselineUsd = estimateCostUsd(activeConfig.model, { prompt: tokens.prompt, completion: tokens.completion, }).usd; } baselinePromptTokens = tokens.prompt; baselineCompletionTokens = tokens.completion; const fromModel = activeConfig.model; activeConfig = { ...activeConfig, model: fallbackModel }; costKnown = costKnown && lookupModelPrice(fallbackModel).known; fellBack = true; sink.fallback?.({ round, fromModel, toModel: fallbackModel, reasonClass: transient.reasonClass, }); continue; } const rawMsg = err instanceof Error ? err.message : String(err); // Surface a stable, secret-safe quota-exhausted guidance instead of raw // provider prose when the failure is an exhausted quota (#247); other // failures keep their existing message. const msg = isQuotaExhausted(err) ? quotaExhaustedGuidance({ model: activeConfig.model, redactedHost: redactEndpointHost(activeConfig.baseUrl), }) : rawMsg; // Preserve a partial answer (#243): when the stream fails after emitting // text, persist exactly one interrupted assistant turn carrying only the // emitted text — never partial tool calls, raw provider errors, or // credentials — and surface it to the sink BEFORE the terminal failure so // consumers observe the partial record first. A failure before any text // persists nothing (no empty entry). The run still terminates as // provider_error with a non-zero exit; the partial turn is never reported // as completed, and the no-retry-after-output invariant is unchanged. if (assistantText.length > 0) { const partial: SessionMessage = { role: "assistant", content: assistantText, interrupted: true, }; messages.push(partial); opts.onMessage(partial); sink.assistantTurn(assistantText, round, { final: false, interrupted: true }); } sink.providerError(msg); return { text: assistantText, ok: false, reason: "provider_error", rounds: round, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } // Charge this attempt's usage to the running cost estimate so every empty // attempt is accounted before any retry. Tokens streamed before a // fallback degrade (Issue #590) keep the earlier model's price via the // baseline; with no degrade the baseline is 0 and this is whole-run // pricing under the primary model. if (hasUsage) { costUsd = costBaselineUsd + estimateCostUsd(activeConfig.model, { prompt: tokens.prompt - baselinePromptTokens, completion: tokens.completion - baselineCompletionTokens, }).usd; } // A valid completion has at least one non-empty text delta or at least one // complete tool call; anything else is an empty completion to recover from. if (assistantText.length > 0 || assistantToolCalls.length > 0) break; emptyAttempts++; // The spend budget can prevent the next attempt. if (budgetReached()) { return { text: finalText, ok: false, reason: "budget_reached", rounds: round, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } if (emptyAttempts >= RETRY_MAX_ATTEMPTS) { exhaustedEmpty = true; break; } const delayMs = backoffDelayMs(emptyAttempts, null); retries++; sink.retry({ round, attempt: emptyAttempts + 1, maxAttempts: RETRY_MAX_ATTEMPTS, reasonClass: "empty_response", delayMs, }); await sleep(delayMs); } if (exhaustedEmpty) { // Persistent empty completions: a truthful terminal failure with a non-zero // exit. No assistant turn (empty or otherwise) is persisted. sink.providerError( "provider returned an empty completion (no assistant text or tool call) after bounded retries", ); return { text: "", ok: false, reason: "empty_response", rounds: round, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } // Per-message responsiveness for this turn (#241), derived from the captured // timestamps; degrades to nulls when the provider gave no text token or usage. const timing = computeMessageTiming({ requestStartMs: roundStart, firstTokenMs: firstTokenAt, generationEndMs: now(), completionTokens: roundCompletionTokens, }); sink.usage({ round, tokens: { ...tokens }, estimatedCostUsd: costUsd, costKnown, budgetUsd, budgetReached: budgetReached(), ttftMs: timing.ttftMs, tokensPerSecond: timing.tokensPerSecond, }); const final = assistantToolCalls.length === 0; sink.assistantTurn(assistantText, round, { final }); if (final) { // Final answer finalText = assistantText; const assistantMsg: SessionMessage = { role: "assistant", content: assistantText }; messages.push(assistantMsg); opts.onMessage(assistantMsg); return { text: finalText, ok: true, reason: "completed", rounds: round + 1, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } // Record assistant message with tool calls const assistantMsg: SessionMessage = { role: "assistant", content: assistantText || null, tool_calls: assistantToolCalls.map((tc) => ({ id: tc.id, type: "function", function: { name: tc.name, arguments: tc.arguments }, })), }; messages.push(assistantMsg); opts.onMessage(assistantMsg); // Execute each tool call. Cooperative cancellation (#489, refined by #550) // is polled before each call in the batch: the call in flight is never // killed, but once a cancel is requested the remaining calls are never // executed and each gets a transcript-valid cancelled placeholder, so the // transcript stays resume-valid and the record distinguishes cancelled // calls from executed ones. for (let i = 0; i < assistantToolCalls.length; i++) { const tc = assistantToolCalls[i]; if (opts.cancelRequested?.()) { for (const pending of assistantToolCalls.slice(i)) { bump(toolCalls, pending.name); bump(toolCancellations, pending.name); sink.toolStart({ id: pending.id, name: pending.name, round, args: {} }); sink.toolResult({ id: pending.id, name: pending.name, result: { content: CANCELLED_TOOL_CONTENT, isError: true }, round, }); const cancelledMsg: SessionMessage = { role: "tool", content: CANCELLED_TOOL_CONTENT, tool_call_id: pending.id, }; messages.push(cancelledMsg); opts.onMessage(cancelledMsg); } return { text: finalText, ok: false, reason: "cancelled", rounds: round, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } // Parse the arguments once so the sink can render structured detail (e.g. a // file diff); a malformed payload degrades to no args rather than throwing. let parsedArgs: Record<string, unknown> = {}; try { const p = JSON.parse(tc.arguments); if (p && typeof p === "object") parsedArgs = p as Record<string, unknown>; } catch { /* leave parsedArgs empty */ } sink.toolStart({ id: tc.id, name: tc.name, round, args: parsedArgs }); const result = await executeToolCall( tc, toolMap, opts.approvalMode, opts.workspace, opts.mutatingAllowed ?? true, requestApproval, preToolUseHooks, opts.bottleneck, opts.failureTaxonomy, opts.readOnly ?? false, opts.turnImages, opts.onShellFailure, ); sink.toolResult({ id: tc.id, name: tc.name, result, round }); bump(toolCalls, tc.name); if (result.isError) bump(toolFailures, tc.name); const toolMsg: SessionMessage = { role: "tool", content: result.content, tool_call_id: tc.id, }; messages.push(toolMsg); opts.onMessage(toolMsg); } } return { text: finalText, ok: false, reason: "max_rounds", rounds: MAX_ROUNDS, retries, stats: statsSnapshot(), tokens: tokensSnapshot(), lastCallPromptTokens: lastCallPromptTokensSnapshot(), estimatedCostUsd: costSnapshot(), costKnown, fellBack, fallbackModel: fellBack ? fallbackModel : null, }; } // Resolve a single tool call to its result, applying approval gating and // uniform error handling. Approval is sought only when required; a denial or an // unknown tool yields an error result rather than throwing. async function executeToolCall( tc: { id: string; name: string; arguments: string }, toolMap: Map<string, ToolDef>, approvalMode: ApprovalMode, workspace: Workspace, mutatingAllowed: boolean, requestApproval: (name: string, args: Record<string, unknown>) => Promise<boolean>, preToolUseHooks: readonly PreToolUseHook[], bottleneck: BottleneckCollector | undefined, failureTaxonomy: FailureTaxonomyCollector | undefined, readOnly: boolean, turnImages?: TurnImageCollector, onShellFailure?: (detail: ShellFailureDetail) => void, ): Promise<ToolResult> { const tool = toolMap.get(tc.name); if (!tool) { failureTaxonomy?.record("unknown_tool"); return { content: `Error: unknown tool "${tc.name}"`, isError: true }; } // Read-only mode (e.g. parallel investigation, #234) restricts the run to // read-only tools and refuses any mutating tool fail-closed, regardless of // approval mode or folder-trust state — yolo cannot widen it. This is what lets // several investigators share one workspace safely without isolation. if (readOnly && tool.category !== "read") { failureTaxonomy?.record("read_only_denied"); return { content: "Tool execution denied: read-only mode allows only read-only tools (list, glob, grep, read)", isError: true, }; } // Folder-trust enforcement runs first and regardless of approval mode, so an // untrusted workspace fails closed for every mutating tool — yolo cannot widen // the boundary. Read-only tools (list/glob/grep/read) are always permitted. if (!mutatingAllowed && tool.category !== "read") { failureTaxonomy?.record("folder_trust_denied"); return { content: folderTrustDenialMessage(), isError: true }; } // Deterministic command policy runs before approval and regardless of mode, // so a known-dangerous shape is denied even under yolo. Commands that pass // keep the existing approval/yolo behaviour unchanged. if (tool.category === "mutate-shell") { let command = ""; try { const parsed = JSON.parse(tc.arguments); if (typeof parsed.command === "string") command = parsed.command; } catch { /* ignore */ } const decision = evaluateCommandPolicy(command, { provenance: "repository", workspace: workspace.root, }); if (!decision.allowed) { failureTaxonomy?.record("policy_denied"); return { content: policyDenialMessage(decision), isError: true }; } } // PreToolUse hook gate (user-owned, deny-only): a matching hook may block the // call before approval is considered; silence leaves the normal approval flow // unchanged. A hook can only ever deny, never approve. A hook timeout or spawn // failure fails closed (the call is blocked) before any tool side effect. if (preToolUseHooks.length > 0) { let hookArgs: Record<string, unknown> = {}; try { const parsed = JSON.parse(tc.arguments); if (parsed && typeof parsed === "object") hookArgs = parsed as Record<string, unknown>; } catch { /* leave hookArgs empty */ } const decision = await evaluatePreToolUseHooks( preToolUseHooks, { toolName: tc.name, toolInput: hookArgs }, { cwd: workspace.root }, ); if (decision.denied) { failureTaxonomy?.record("hook_denied"); return { content: decision.reason ? `Tool call denied by a user PreToolUse hook: ${decision.reason}` : "Tool call denied by a user PreToolUse hook", isError: true, }; } } if (needsApproval(approvalMode, tool.category)) { let parsed: Record<string, unknown> = {}; try { parsed = JSON.parse(tc.arguments); } catch { /* ignore */ } // Time the approval gate separately from the tool's own execution so a long // human-approval wait surfaces as an `approval` bottleneck, not a tool one. const approvalStartedAt = Date.now(); const approved = await requestApproval(tc.name, parsed); bottleneck?.recordApproval(tc.name, Date.now() - approvalStartedAt); if (!approved) { failureTaxonomy?.record("approval_denied"); return { content: "Tool execution denied by user", isError: true }; } } // Detects a path escape so a thrown escape is categorized distinctly from a // generic tool error in the failure taxonomy. let pathEscape = false; try { const parsed = JSON.parse(tc.arguments); // Capture the file's pre-image before a mutating-file tool overwrites it, so // the turn's workspace change can later be undone without a Git reset. Only // the first touch per path is recorded (the state before the turn); an // unresolvable path is left for the tool itself to reject. if (turnImages && tool.category === "mutate-file" && typeof parsed.path === "string") { try { turnImages.capture(workspace.resolveSafe(parsed.path)); } catch { /* path escape is the tool's own error to surface */ } } if (failureTaxonomy && tool.category === "mutate-file" && typeof parsed.path === "string") { try { workspace.resolveSafe(parsed.path); } catch { pathEscape = true; } } // Time only the tool's own execution (approval/policy/hook gates are measured // or rejected above); recorded even when the tool throws via the finally. const executeStartedAt = Date.now(); try { const result = await tool.execute(parsed, workspace); // A tool that reports an error result without throwing is still a failed // call; categorize it (a detected path escape takes precedence). if (result.isError) { failureTaxonomy?.record(pathEscape ? "path_escape" : "tool_error"); } // Shell failure receipt capture (Issue #574): best-effort, and a // recording failure never changes the result the turn observes. if (result.shellFailure && onShellFailure) { try { onShellFailure(result.shellFailure); } catch { /* best-effort evidence capture */ } } return result; } catch (err: unknown) { failureTaxonomy?.record(pathEscape ? "path_escape" : "tool_error"); const msg = err instanceof Error ? err.message : String(err); return { content: `Tool error: ${msg}`, isError: true }; } finally { bottleneck?.recordTool(tc.name, Date.now() - executeStartedAt); } } catch (err: unknown) { // A failure outside the tool's own execution (e.g. malformed arguments). failureTaxonomy?.record("tool_error"); const msg = err instanceof Error ? err.message : String(err); return { content: `Tool error: ${msg}`, isError: true }; } } # ===== file: src/answer-routing.ts ===== // Answer routing: routes user answers to the waiting Goal instead of // creating an unrelated conversation turn. // // When a Goal is waiting for user input, the user's response is associated // with the waiting Goal revision and attempt. Answer routes are bounded // (max 50), redacted, and deterministic. import { redactSecrets } from "./permission-impact.js"; import { safeCutEnd } from "./text-cut.js"; export const ANSWER_ROUTING_SCHEMA = "oh-my-cli.answer-routing"; export const ANSWER_ROUTING_VERSION = 1; // --- types ------------------------------------------------------------------ export interface AnswerRoute { /** Route identifier. */ id: string; /** The user's answer text (bounded, redacted). */ answerText: string; /** Goal revision the answer is routed to. */ goalRevision: number; /** Attempt the answer is routed to. */ attempt: number; /** When the answer was received (epoch ms). */ receivedAt: number; /** Whether the answer has been consumed by the Goal. */ consumed: boolean; /** When the answer was consumed (epoch ms). */ consumedAt?: number; } // --- bounds ----------------------------------------------------------------- const MAX_ROUTES = 50; const MAX_ANSWER_LENGTH = 500; function safeAnswer(value: string): string { const terminalSafe = value .replace(/[\u0000-\u001f\u007f]+/g, " ") .replace(/[\u200b-\u200f\u202a-\u202e\u2060-\u206f\ufeff]/g, "") .replace(/\s+/g, " ") .trim(); const redacted = redactSecrets(terminalSafe).text; return redacted.length <= MAX_ANSWER_LENGTH ? redacted : `${redacted.slice(0, safeCutEnd(redacted, MAX_ANSWER_LENGTH - 1))}…`; } // --- answer router ---------------------------------------------------------- export class AnswerRouter { private readonly routes: AnswerRoute[] = []; private nextId = 1; /** Route a user answer to a waiting Goal. */ routeAnswer( answerText: string, goalRevision: number, attempt: number, receivedAt: number = Date.now(), ): AnswerRoute | null { if (this.routes.length >= MAX_ROUTES) { return null; // At capacity. } const route: AnswerRoute = { id: `answer-${this.nextId++}`, answerText: safeAnswer(answerText), goalRevision, attempt, receivedAt, consumed: false, }; this.routes.push(route); return { ...route }; } /** Get all pending (unconsumed) answer routes. */ getPendingAnswerRoutes(): AnswerRoute[] { return this.routes .filter((r) => !r.consumed) .map((r) => ({ ...r })); } /** Get all answer routes for a specific revision. */ getRoutesForRevision(goalRevision: number): AnswerRoute[] { return this.routes .filter((r) => r.goalRevision === goalRevision) .map((r) => ({ ...r })); } /** Consume an answer route (mark as consumed). */ consumeAnswer(routeId: string, consumedAt: number = Date.now()): AnswerRoute | null { const route = this.routes.find((r) => r.id === routeId); if (!route || route.consumed) return null; route.consumed = true; route.consumedAt = consumedAt; return { ...route }; } /** Number of routes. */ get size(): number { return this.routes.length; } /** Number of pending routes. */ get pendingCount(): number { return this.routes.filter((r) => !r.consumed).length; } } // --- formatting ------------------------------------------------------------- export function formatAnswerRouter(router: AnswerRouter): string { const pending = router.getPendingAnswerRoutes(); const lines: string[] = []; lines.push("Answer Routes"); lines.push("═".repeat(50)); lines.push(`Total: ${router.size} Pending: ${router.pendingCount}`); lines.push(""); for (const route of pending) { lines.push(` ○ ${route.id} → rev ${route.goalRevision}, attempt ${route.attempt}`); lines.push(` "${route.answerText}"`); } if (pending.length === 0) { lines.push(" No pending answers."); } lines.push(""); lines.push("Read-only: no conversation turns managed."); return lines.join("\n"); } # ===== file: src/approval-inbox.ts ===== // Read-only approval inbox inspection: shows pending and decided approval // requests with action context, risk, expiry, and decision trail. // // Approval entries expose id, action summary, risk level, requested-by, // expiry, head SHA, decision state, decided-by, and decided-at. Expired // approvals are flagged when current time exceeds expiry. Stale-head // detection flags approvals where the head SHA has changed. The view is // read-only and never grants approvals, executes actions, or modifies // the inbox. export const APPROVAL_INBOX_SCHEMA = "oh-my-cli.approval-inbox"; export const APPROVAL_INBOX_VERSION = 1; // --- types ------------------------------------------------------------------ export type RiskLevel = "low" | "medium" | "high" | "critical"; export type ApprovalState = "pending" | "approved" | "rejected" | "expired"; export interface ApprovalEntry { /** Stable approval identifier. */ id: string; /** Summary of the action requiring approval. */ actionSummary: string; riskLevel: RiskLevel; /** Who requested the approval. */ requestedBy: string; /** Epoch ms of the request. */ requestedAt: number; /** Epoch ms when the approval expires. */ expiresAt: number; /** Head SHA at the time of the request. */ headSha: string; /** Current decision state. */ state: ApprovalState; /** Who made the decision (when decided). */ decidedBy?: string; /** Epoch ms of the decision (when decided). */ decidedAt?: number; /** Whether the head SHA has changed since the request. */ staleHead: boolean; } // --- approval inbox --------------------------------------------------------- export class ApprovalInbox { private readonly entries: ApprovalEntry[] = []; /** Add an approval request. */ request(opts: { id: string; actionSummary: string; riskLevel: RiskLevel; requestedBy: string; requestedAt: number; expiresAt: number; headSha: string; }): ApprovalEntry { const entry: ApprovalEntry = { ...opts, state: "pending", staleHead: false, }; this.entries.push(entry); return entry; } /** Record an approval decision (read-only model: records, does not execute). */ decide(id: string, decision: "approved" | "rejected", decidedBy: string, decidedAt: number): void { const entry = this.entries.find((e) => e.id === id); if (!entry || entry.state !== "pending") return; entry.state = decision; entry.decidedBy = decidedBy; entry.decidedAt = decidedAt; } /** Refresh expiry and staleness state. */ refresh(now: number, currentHeadSha: string): void { for (const entry of this.entries) { if (entry.state === "pending" && now > entry.expiresAt) { entry.state = "expired"; } entry.staleHead = entry.headSha !== currentHeadSha; } } get(id: string): ApprovalEntry | undefined { return this.entries.find((e) => e.id === id); } list(): ApprovalEntry[] { return [...this.entries]; } getPending(): ApprovalEntry[] { return this.entries.filter((e) => e.state === "pending"); } getDecided(): ApprovalEntry[] { return this.entries.filter((e) => e.state === "approved" || e.state === "rejected"); } getExpired(): ApprovalEntry[] { return this.entries.filter((e) => e.state === "expired"); } getStaleHead(): ApprovalEntry[] { return this.entries.filter((e) => e.staleHead); } get size(): number { return this.entries.length; } } // --- inbox view ------------------------------------------------------------- export interface ApprovalInboxView { schema: typeof APPROVAL_INBOX_SCHEMA; v: typeof APPROVAL_INBOX_VERSION; entries: ApprovalEntry[]; totalCount: number; pendingCount: number; decidedCount: number; expiredCount: number; staleHeadCount: number; hasStaleHead: boolean; snapshotAt: number; } export function assembleInboxView(inbox: ApprovalInbox): ApprovalInboxView { const entries = inbox.list(); return { schema: APPROVAL_INBOX_SCHEMA, v: APPROVAL_INBOX_VERSION, entries, totalCount: entries.length, pendingCount: inbox.getPending().length, decidedCount: inbox.getDecided().length, expiredCount: inbox.getExpired().length, staleHeadCount: inbox.getStaleHead().length, hasStaleHead: inbox.getStaleHead().length > 0, snapshotAt: Date.now(), }; } // --- formatting ------------------------------------------------------------- export function formatApprovalEntry(entry: ApprovalEntry): string { const icon = stateIcon(entry.state); const risk = riskIcon(entry.riskLevel); const stale = entry.staleHead ? " ⚠STALE HEAD" : ""; const lines: string[] = []; lines.push(`${icon} ${entry.actionSummary} [${entry.riskLevel}]${stale}`); lines.push(` Requested by ${entry.requestedBy} Expires: ${new Date(entry.expiresAt).toISOString()}`); lines.push(` Head: ${entry.headSha.slice(0, 12)}`); if (entry.state !== "pending") { lines.push(` Decision: ${entry.state} by ${entry.decidedBy ?? "system"} at ${entry.decidedAt ? new Date(entry.decidedAt).toISOString() : "N/A"}`); } return lines.join("\n"); } export function formatInboxSummary(inbox: ApprovalInbox): string { const lines: string[] = []; lines.push("Approval Inbox"); lines.push("═".repeat(50)); lines.push(`Total: ${inbox.size} Pending: ${inbox.getPending().length} Decided: ${inbox.getDecided().length} Expired: ${inbox.getExpired().length}`); if (inbox.getStaleHead().length > 0) { lines.push("⚠ Stale-head approvals detected (head SHA changed)"); } for (const entry of inbox.list()) { lines.push(""); lines.push(formatApprovalEntry(entry)); } lines.push(""); lines.push("Read-only: no approvals granted, no actions executed."); return lines.join("\n"); } function stateIcon(state: ApprovalState): string { switch (state) { case "pending": return "○"; case "approved": return "✓"; case "rejected": return "✗"; case "expired": return "⏰"; } } function riskIcon(risk: RiskLevel): string { switch (risk) { case "low": return "▽"; case "medium": return "◆"; case "high": return "▲"; case "critical": return "⚠"; } } # ===== file: src/approval-mode-switch.ts ===== // Runtime approval-mode switching (Issue #715): the pure decision model behind // the interactive `/approval-mode` command. The palette used to advertise three // multi-word stubs that could never resolve from typed input and changed // nothing from palette selection; this model makes the advertised control real // and honest: report the effective mode, reject invalid input naming the valid // modes, apply a de-escalation (tighter gating) immediately, and apply an // escalation (looser gating) only through an explicit two-step confirmation. // // The decision is pure and shared by both interactive surfaces so the // full-screen shell and the plain readline REPL render identical outcomes. The // approval plane itself (needsApproval/promptApproval) is untouched — it // consumes the effective mode as input. import type { ApprovalMode } from "./approval.js"; export const APPROVAL_MODES: readonly ApprovalMode[] = ["default", "auto-edit", "yolo"]; // Permission rank: lower is stricter. De-escalation moves toward 0, // escalation away from it. const MODE_RANK: Record<ApprovalMode, number> = { default: 0, "auto-edit": 1, yolo: 2, }; export function parseApprovalMode(text: string): ApprovalMode | null { const trimmed = text.trim().toLowerCase(); const match = APPROVAL_MODES.find((mode) => mode.toLowerCase() === trimmed); return match ?? null; } export type ApprovalModeCommandDecision = // No argument: report the effective mode and the command shape. | { kind: "report"; mode: ApprovalMode } // Unknown mode or trailing form: nothing changes; the notice names the // valid modes / usage. | { kind: "invalid"; requested: string } // Requested mode equals the effective one: nothing changes, said plainly. | { kind: "unchanged"; mode: ApprovalMode } // Strictly tighter gating: applies immediately. | { kind: "de-escalate"; mode: ApprovalMode } // Looser gating: NOT applied. The caller records the pending escalation and // shows the warning; only the explicit confirm form applies it. | { kind: "escalation-needs-confirm"; mode: ApprovalMode } // `confirm` was given but there is no matching pending escalation: nothing // changes, and the notice says exactly that. | { kind: "escalation-unconfirmed"; mode: ApprovalMode } // `confirm` matches the pending escalation: applies. | { kind: "escalation-confirmed"; mode: ApprovalMode }; export function approvalModeCommandDecision( current: ApprovalMode, args: string, pendingEscalation: ApprovalMode | null, ): ApprovalModeCommandDecision { const parts = args.trim().split(/\s+/).filter(Boolean); if (parts.length === 0) return { kind: "report", mode: current }; const mode = parseApprovalMode(parts[0]); if (mode === null) return { kind: "invalid", requested: parts[0] }; const rest = parts.slice(1); if (rest.length > 0 && rest.join(" ").toLowerCase() !== "confirm") { return { kind: "invalid", requested: rest.join(" ") }; } const confirmed = rest.length > 0; if (mode === current) return { kind: "unchanged", mode }; if (MODE_RANK[mode] < MODE_RANK[current]) return { kind: "de-escalate", mode }; // Escalation from here on: never applied without the explicit confirm form // matching a pending request for exactly this mode. if (!confirmed) return { kind: "escalation-needs-confirm", mode }; if (pendingEscalation !== mode) return { kind: "escalation-unconfirmed", mode }; return { kind: "escalation-confirmed", mode }; } // Does the decision apply a new effective mode? export function decisionAppliesMode( decision: ApprovalModeCommandDecision, ): decision is | { kind: "de-escalate"; mode: ApprovalMode } | { kind: "escalation-confirmed"; mode: ApprovalMode } { return decision.kind === "de-escalate" || decision.kind === "escalation-confirmed"; } // What pending escalation the caller should hold after this decision: an // escalation request replaces it; every other outcome clears it, so a stale // confirmation can never apply a request the user moved away from. export function nextPendingEscalation( decision: ApprovalModeCommandDecision, ): ApprovalMode | null { return decision.kind === "escalation-needs-confirm" ? decision.mode : null; } const ESCALATION_CONSEQUENCE: Record<ApprovalMode, string> = { default: "", "auto-edit": "file edits will run without approval; shell commands still require it", yolo: "all mutating tools will run without approval", }; // One shared renderer so both interactive surfaces (and the tests) show the // same honest outcome. Never implies approval for any pending request. export function formatApprovalModeNotice(decision: ApprovalModeCommandDecision): string { switch (decision.kind) { case "report": return ( `Approval mode: ${decision.mode}. ` + `Change with /approval-mode <${APPROVAL_MODES.join("|")}>; loosening requires an explicit confirm.` ); case "invalid": return ( `Unknown approval mode or form "${decision.requested}". ` + `Valid modes: ${APPROVAL_MODES.join(", ")}. Usage: /approval-mode [mode [confirm]].` ); case "unchanged": return `Approval mode is already ${decision.mode}.`; case "de-escalate": return `Approval mode set to ${decision.mode} (tighter). Subsequent turns are gated by it.`; case "escalation-needs-confirm": return ( `Escalating to ${decision.mode} loosens tool gating: ${ESCALATION_CONSEQUENCE[decision.mode]}. ` + `Not applied — run /approval-mode ${decision.mode} confirm to apply.` ); case "escalation-unconfirmed": return ( `Nothing confirmed — there is no pending escalation to ${decision.mode}. ` + `Run /approval-mode ${decision.mode} first, then /approval-mode ${decision.mode} confirm.` ); case "escalation-confirmed": return `Approval mode set to ${decision.mode} (looser, explicitly confirmed). Subsequent turns are gated by it.`; } } # ===== file: src/approval.ts ===== import readline from "node:readline"; import { analyzeImpact, formatImpact } from "./permission-impact.js"; export type ApprovalMode = "default" | "auto-edit" | "yolo"; export type ToolCategory = "read" | "mutate-file" | "mutate-shell"; export function needsApproval(mode: ApprovalMode, category: ToolCategory): boolean { if (category === "read") return false; if (mode === "yolo") return false; if (mode === "auto-edit" && category === "mutate-file") return false; return true; } export async function promptApproval(toolName: string, args: Record<string, unknown>): Promise<boolean> { if (!process.stdin.isTTY) { return false; } const rl = readline.createInterface({ input: process.stdin, output: process.stderr }); const summary = formatImpact(analyzeImpact(toolName, args)); return new Promise((resolve) => { rl.question(`\n⚠ Tool "${toolName}" requires approval.\n${summary}\nAllow? (y/N) `, (answer) => { rl.close(); resolve(answer.toLowerCase() === "y"); }); }); } # ===== file: src/archive-stale.ts ===== // Archive-stale executor (Issue #702): the retention story's action half. // The stale-sessions report (#626, strict-gated by #680) detects archive // candidates; this surface acts on exactly those candidates. // // Dry run is the default: resolve the same candidates the stale-sessions // report shows and print them with a trailing note, mutating nothing. // --apply opts into the mutation, and the mutation is bounded by design: // archiving writes the existing archived marker (via the same primitive as // --archive-session), never deletes, never touches transcripts or any // other sidecar, and is reversible with --unarchive-session. Pinned and // already-archived sessions are protected by the builder and never become // candidates, so they can never be re-archived here either. import type { SessionStore } from "./session.js"; import { buildStaleSessionsReport, type StaleSessionsRecord, } from "./stale-sessions.js"; import { archiveSession } from "./session-archive.js"; export const ARCHIVE_STALE_SCHEMA = "oh-my-cli.archive-stale" as const; export const ARCHIVE_STALE_VERSION = 1 as const; export type ArchiveStaleMode = "dry-run" | "apply"; /** Versioned machine-readable record of an archive-stale run (Issue #702). */ export interface ArchiveStaleRecord { schema: typeof ARCHIVE_STALE_SCHEMA; v: typeof ARCHIVE_STALE_VERSION; thresholdDays: number; mode: ArchiveStaleMode; /** Sessions resolved as archive candidates, oldest first. */ candidates: Array<{ sessionId: string; shortId: string }>; /** Session ids archived by this run; empty in dry-run mode. */ archivedIds: string[]; protectedPinned: number; protectedArchived: number; } export interface ArchiveStaleOutcome { /** The resolved stale report — reused verbatim for the dry-run text. */ report: StaleSessionsRecord; record: ArchiveStaleRecord; } /** * Execute an archive-stale run (Issue #702). In dry-run mode the store is * never touched; in apply mode exactly the resolved candidates receive the * archived marker via the shared archiveSession primitive (idempotent — * a session that is already archived is reported as such, never rewritten). */ export function executeArchiveStale( store: SessionStore, opts: { thresholdDays: number; apply: boolean }, ): ArchiveStaleOutcome { const report = buildStaleSessionsReport(store, { thresholdDays: opts.thresholdDays }); const candidates = report.candidates.map((c) => ({ sessionId: c.sessionId, shortId: c.shortId, })); const archivedIds: string[] = []; if (opts.apply) { for (const candidate of candidates) { const result = archiveSession(store, candidate.sessionId); if (result.ok && !result.alreadyArchived) { archivedIds.push(candidate.sessionId); } } } return { report, record: { schema: ARCHIVE_STALE_SCHEMA, v: ARCHIVE_STALE_VERSION, thresholdDays: opts.thresholdDays, mode: opts.apply ? "apply" : "dry-run", candidates, archivedIds, protectedPinned: report.protectedPinned, protectedArchived: report.protectedArchived, }, }; } /** * Render the apply-mode result as lines (Issue #702). Dry-run text is the * stale-sessions report itself plus a trailing note (rendered by the * caller), so its "Advisory only — nothing is archived" footer stays true. */ export function formatArchiveStale(record: ArchiveStaleRecord): string[] { const lines: string[] = []; lines.push(`Archive stale sessions — threshold ${record.thresholdDays} day(s)`); lines.push("─".repeat(40)); lines.push(""); if (record.candidates.length === 0) { lines.push("No stale archive candidates at this threshold."); } else { lines.push("Archived:"); for (const candidate of record.candidates) { lines.push(` ${candidate.shortId}`); } } lines.push( `Protected (older than threshold): ${record.protectedPinned} pinned · ${record.protectedArchived} archived.`, ); lines.push(""); lines.push( `Archived ${record.archivedIds.length} session(s). Nothing was deleted; restore any with --unarchive-session ${record.candidates.length > 0 ? record.candidates[0].shortId : "<id>"}.`, ); return lines; } /** The trailing note appended to the dry-run rendering (Issue #702). */ export const ARCHIVE_STALE_DRY_RUN_NOTE = "Dry run: nothing archived (re-run with --apply to archive the sessions above)."; # ===== file: src/artifact-history.ts ===== // Read-only artifact history: links produced artifacts to producing turns // and file diffs when real evidence exists. // // Artifact entries expose stable identity, kind, producing turn, session, // content hash, timestamp, and associated file paths. History is ordered by // production time and bounded. Attribution is present only when real // evidence exists; absent evidence reports "no attribution". The view is // read-only and never creates, modifies, or deletes artifacts. export const ARTIFACT_HISTORY_SCHEMA = "oh-my-cli.artifact-history"; export const ARTIFACT_HISTORY_VERSION = 1; // --- bounds ----------------------------------------------------------------- const DEFAULT_MAX_ENTRIES = 100; // --- artifact types --------------------------------------------------------- export type ArtifactKind = "html" | "image" | "screenshot" | "export" | "document" | "other"; export type AttributionState = "attributed" | "no-attribution"; export interface ArtifactEntry { /** Stable, unique identifier. */ id: string; kind: ArtifactKind; /** Display label. */ label: string; /** SHA-256 hex digest of the artifact content. */ contentHash: string; /** Session that produced this artifact. */ sessionId: string; /** Turn that produced this artifact (when known). */ turnId?: string; /** Associated file paths (when known). */ filePaths: string[]; /** Epoch ms of production. */ producedAt: number; /** Size in bytes. */ sizeBytes: number; /** Whether turn/file attribution is based on real evidence. */ attributionState: AttributionState; } // --- artifact history ------------------------------------------------------- export class ArtifactHistory { private readonly entries: ArtifactEntry[] = []; private readonly maxEntries: number; constructor(maxEntries: number = DEFAULT_MAX_ENTRIES) { this.maxEntries = maxEntries; } /** Record a produced artifact. */ record(opts: { id: string; kind: ArtifactKind; label: string; contentHash: string; sessionId: string; turnId?: string; filePaths?: string[]; producedAt: number; sizeBytes: number; }): ArtifactEntry { const entry: ArtifactEntry = { ...opts, filePaths: opts.filePaths ?? [], attributionState: (opts.turnId || (opts.filePaths && opts.filePaths.length > 0)) ? "attributed" : "no-attribution", }; this.entries.push(entry); // Bound the history. if (this.entries.length > this.maxEntries) { this.entries.shift(); // Remove oldest. } return entry; } /** Get all entries ordered by production time (newest first). */ list(): ArtifactEntry[] { return [...this.entries].sort((a, b) => b.producedAt - a.producedAt); } /** Get entries for a specific session. */ getBySession(sessionId: string): ArtifactEntry[] { return this.list().filter((e) => e.sessionId === sessionId); } /** Get entries for a specific turn. */ getByTurn(turnId: string): ArtifactEntry[] { return this.list().filter((e) => e.turnId === turnId); } /** Get entries with no attribution. */ getUnattributed(): ArtifactEntry[] { return this.list().filter((e) => e.attributionState === "no-attribution"); } get size(): number { return this.entries.length; } } // --- history view ----------------------------------------------------------- export interface ArtifactHistoryView { schema: typeof ARTIFACT_HISTORY_SCHEMA; v: typeof ARTIFACT_HISTORY_VERSION; entries: ArtifactEntry[]; totalCount: number; attributedCount: number; unattributedCount: number; /** Counts by kind. */ kindCounts: Partial<Record<ArtifactKind, number>>; snapshotAt: number; } // Assemble a read-only history view. export function assembleArtifactHistoryView(history: ArtifactHistory): ArtifactHistoryView { const entries = history.list(); const kindCounts: Partial<Record<ArtifactKind, number>> = {}; let attributedCount = 0; let unattributedCount = 0; for (const e of entries) { kindCounts[e.kind] = (kindCounts[e.kind] ?? 0) + 1; if (e.attributionState === "attributed") attributedCount++; else unattributedCount++; } return { schema: ARTIFACT_HISTORY_SCHEMA, v: ARTIFACT_HISTORY_VERSION, entries, totalCount: entries.length, attributedCount, unattributedCount, kindCounts, snapshotAt: Date.now(), }; } // --- formatting ------------------------------------------------------------- // Format a history view as a compact TUI view. export function formatArtifactHistoryView(view: ArtifactHistoryView): string { const lines: string[] = []; lines.push("Artifact History"); lines.push("═".repeat(50)); lines.push(`Total: ${view.totalCount} Attributed: ${view.attributedCount} Unattributed: ${view.unattributedCount}`); const kinds = Object.entries(view.kindCounts); if (kinds.length > 0) { lines.push(`Kinds: ${kinds.map(([k, v]) => `${k}:${v}`).join(" ")}`); } for (const entry of view.entries.slice(0, 10)) { const icon = kindIcon(entry.kind); const turn = entry.turnId ? ` turn:${entry.turnId}` : " turn:(no attribution)"; const files = entry.filePaths.length > 0 ? ` files:[${entry.filePaths.join(", ")}]` : ""; lines.push(`${icon} ${entry.label} [${entry.id}]${turn}${files}`); lines.push(` ${entry.kind} ${entry.sizeBytes}B hash:${entry.contentHash.slice(0, 12)}…`); } if (view.entries.length > 10) { lines.push(`… ${view.entries.length - 10} more artifacts`); } lines.push(""); lines.push("Read-only: no artifacts created, modified, or deleted."); return lines.join("\n"); } function kindIcon(kind: ArtifactKind): string { switch (kind) { case "html": return "◆"; case "image": return "▣"; case "screenshot": return "▣"; case "export": return "◇"; case "document": return "▤"; case "other": return "·"; } } # ===== file: src/artifact-preview.ts ===== // Safe static HTML artifact preview. // // Accepts a local HTML artifact reference, resolves it within the trusted // workspace, and produces an inspectable preview with scripts, network, // navigation, and filesystem access disabled by default. The preview policy // is fail-closed: anything not explicitly allowed is blocked, and every // blocked item is reported with a reason. Preview evidence is attributable // to the active session and exact artifact content hash. // // The module is surface-independent: the same artifact produces the same // sanitized output and policy report for both the TUI and a future Desktop // pane. import crypto from "node:crypto"; import fs from "node:fs"; import path from "node:path"; import type { Workspace } from "./workspace.js"; import { safeCutEnd } from "./text-cut.js"; export const ARTIFACT_PREVIEW_SCHEMA = "oh-my-cli.artifact-preview"; export const ARTIFACT_PREVIEW_VERSION = 1; // --- bounds ----------------------------------------------------------------- const MAX_ARTIFACT_BYTES = 5 * 1_048_576; // 5 MiB const MAX_PREVIEW_LINES = 500; const SNIFF_BYTES = 8_000; // --- preview policy --------------------------------------------------------- // The security policy applied to every artifact preview. All capabilities // are disabled by default; the struct records what was enforced. export interface PreviewPolicy { scripts: "disabled"; network: "disabled"; navigation: "disabled"; filesystem: "disabled"; forms: "disabled"; } export const DEFAULT_PREVIEW_POLICY: PreviewPolicy = Object.freeze({ scripts: "disabled", network: "disabled", navigation: "disabled", filesystem: "disabled", forms: "disabled", }); // --- blocked content -------------------------------------------------------- export type BlockedReason = | "script-tag" | "event-handler" | "remote-url" | "iframe" | "form" | "meta-refresh" | "object-embed" | "javascript-uri"; export interface BlockedContent { reason: BlockedReason; /** 1-based line number where the content was found. */ line: number; /** Truncated preview of the blocked line. */ preview: string; } // --- artifact identity ------------------------------------------------------ export interface ArtifactIdentity { /** Workspace-relative path. */ path: string; /** SHA-256 hex digest of the raw artifact content. */ contentHash: string; /** Size in bytes. */ sizeBytes: number; } // --- preview result --------------------------------------------------------- export type RenderStatus = "ok" | "refused"; export interface ArtifactPreview { schema: typeof ARTIFACT_PREVIEW_SCHEMA; v: typeof ARTIFACT_PREVIEW_VERSION; identity: ArtifactIdentity; policy: PreviewPolicy; renderStatus: RenderStatus; /** Sanitized HTML lines (scripts/network/navigation removed). */ sanitizedLines: string[]; /** Total lines in the original artifact. */ totalLines: number; /** Whether the preview was truncated to MAX_PREVIEW_LINES. */ truncated: boolean; /** Content that was blocked, with reasons. */ blocked: BlockedContent[]; /** Whether any content was blocked. */ hasBlockedContent: boolean; } export interface ArtifactRefusal { renderStatus: "refused"; reason: "untrusted" | "oversized" | "unreadable" | "binary" | "outside-workspace" | "not-html"; detail: string; } export type ArtifactPreviewResult = ArtifactPreview | ArtifactRefusal; // --- detection patterns ----------------------------------------------------- const SCRIPT_TAG_RE = /<script[\s>]/i; const EVENT_HANDLER_RE = /\bon\w+\s*=/i; const REMOTE_URL_RE = /(?:src|href|action|data|poster)\s*=\s*["']?https?:\/\//i; const IFRAME_RE = /<iframe[\s>]/i; const FORM_RE = /<form[\s>]/i; const META_REFRESH_RE = /<meta[^>]+http-equiv\s*=\s*["']?refresh/i; const OBJECT_EMBED_RE = /<(?:object|embed)[\s>]/i; const JAVASCRIPT_URI_RE = /(?:href|src|action)\s*=\s*["']?\s*javascript:/i; const DETECTION_RULES: Array<{ re: RegExp; reason: BlockedReason }> = [ { re: SCRIPT_TAG_RE, reason: "script-tag" }, { re: EVENT_HANDLER_RE, reason: "event-handler" }, { re: REMOTE_URL_RE, reason: "remote-url" }, { re: IFRAME_RE, reason: "iframe" }, { re: FORM_RE, reason: "form" }, { re: META_REFRESH_RE, reason: "meta-refresh" }, { re: OBJECT_EMBED_RE, reason: "object-embed" }, { re: JAVASCRIPT_URI_RE, reason: "javascript-uri" }, ]; // --- sanitization ----------------------------------------------------------- // Sanitize a single HTML line by neutralizing dangerous content. The line // is returned with blocked patterns replaced by safe placeholders, and the // blocked items are recorded. function sanitizeLine(line: string, lineNum: number, blocked: BlockedContent[]): string { let sanitized = line; for (const { re, reason } of DETECTION_RULES) { if (re.test(sanitized)) { blocked.push({ reason, line: lineNum, preview: truncate(line.trim(), 120), }); // Neutralize: replace the dangerous content with a safe comment. sanitized = neutralize(sanitized, reason); } } return sanitized; } // Replace dangerous HTML constructs with safe, visible placeholders. function neutralize(line: string, reason: BlockedReason): string { switch (reason) { case "script-tag": return line.replace(/<script[\s\S]*?<\/script>/gi, `<!-- [BLOCKED: script] -->`) .replace(/<script[\s>][^>]*>/gi, `<!-- [BLOCKED: script] -->`); case "event-handler": return line.replace(/\bon\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "data-blocked-handler"); case "remote-url": return line.replace(/((?:src|href|action|data|poster)\s*=\s*["']?)https?:\/\/[^"'\s>]*/gi, "$1about:blank"); case "iframe": return line.replace(/<iframe[\s\S]*?<\/iframe>/gi, `<!-- [BLOCKED: iframe] -->`) .replace(/<iframe[^>]*\/?>/gi, `<!-- [BLOCKED: iframe] -->`); case "form": return line.replace(/<form([^>]*)>/gi, "<div data-blocked-form$1>") .replace(/<\/form>/gi, "</div>"); case "meta-refresh": return line.replace(/<meta[^>]+http-equiv\s*=\s*["']?refresh[^>]*>/gi, `<!-- [BLOCKED: meta-refresh] -->`); case "object-embed": return line.replace(/<(?:object|embed)[\s\S]*?<\/(?:object|embed)>/gi, `<!-- [BLOCKED: object/embed] -->`) .replace(/<(?:object|embed)[^>]*\/?>/gi, `<!-- [BLOCKED: object/embed] -->`); case "javascript-uri": return line.replace(/((?:href|src|action)\s*=\s*["']?\s*)javascript:[^"'\s>]*/gi, "$1about:blank"); default: return line; } } function truncate(s: string, max: number): string { if (s.length <= max) return s; return s.slice(0, safeCutEnd(s, max - 1)) + "…"; } // --- binary detection ------------------------------------------------------- function looksBinary(buf: Buffer): boolean { const limit = Math.min(buf.length, SNIFF_BYTES); for (let i = 0; i < limit; i++) { if (buf[i] === 0) return true; } return false; } // --- preview ---------------------------------------------------------------- export interface PreviewOptions { /** Whether the workspace is trusted. Defaults to true. */ trusted?: boolean; /** Maximum artifact size in bytes. */ maxBytes?: number; } // Default deliverable path for an exported artifact (Issue #803): strip one // trailing .html/.htm extension from the basename and append ".safe.html", // keeping the file beside the original. Pure: no filesystem access. export function defaultDeliverablePath(relPath: string): string { const dir = path.dirname(relPath); const base = path.basename(relPath).replace(/\.(html|htm)$/i, ""); const name = `${base}.safe.html`; return dir === "." ? name : path.join(dir, name); } // Produce a safe static preview of a local HTML artifact. The artifact is // resolved within the workspace, validated, sanitized (scripts, network, // navigation, forms disabled), and returned with a full policy report and // blocked-content inventory. Fails closed with explicit recovery guidance. export function previewArtifact( workspace: Workspace, relPath: string, opts: PreviewOptions = {}, ): ArtifactPreviewResult { const trusted = opts.trusted ?? true; const maxBytes = opts.maxBytes ?? MAX_ARTIFACT_BYTES; // Trust gate. if (!trusted) { return { renderStatus: "refused", reason: "untrusted", detail: "Workspace is untrusted. Trust it with --trust or add it to the trust store." }; } // Path safety. if (relPath.startsWith("/") || relPath.split("/").includes("..")) { return { renderStatus: "refused", reason: "outside-workspace", detail: "Path is absolute or contains ... Use a workspace-relative path." }; } // Extension check. const ext = path.extname(relPath).toLowerCase(); if (ext !== ".html" && ext !== ".htm") { return { renderStatus: "refused", reason: "not-html", detail: `Extension "${ext}" is not HTML. Only .html and .htm files can be previewed.` }; } // Resolve within workspace. let abs: string; try { abs = workspace.resolve(relPath); } catch { return { renderStatus: "refused", reason: "outside-workspace", detail: "Path escapes the workspace. Use a path within the project root." }; } // Read and validate. let stat: fs.Stats; try { stat = fs.statSync(abs); } catch { return { renderStatus: "refused", reason: "unreadable", detail: "File does not exist or is not readable. Check the path and permissions." }; } if (stat.size > maxBytes) { return { renderStatus: "refused", reason: "oversized", detail: `File is ${stat.size} bytes (limit ${maxBytes}). Reduce the artifact size.` }; } let buf: Buffer; try { buf = fs.readFileSync(abs); } catch { return { renderStatus: "refused", reason: "unreadable", detail: "Read failed. Check permissions." }; } if (looksBinary(buf)) { return { renderStatus: "refused", reason: "binary", detail: "Content contains NUL bytes. Only text HTML files can be previewed." }; } const content = buf.toString("utf-8"); const contentHash = crypto.createHash("sha256").update(buf).digest("hex"); const allLines = content.split("\n"); const totalLines = allLines.length; // Sanitize. const blocked: BlockedContent[] = []; const limit = Math.min(totalLines, MAX_PREVIEW_LINES); const sanitizedLines: string[] = []; for (let i = 0; i < limit; i++) { sanitizedLines.push(sanitizeLine(allLines[i], i + 1, blocked)); } return { schema: ARTIFACT_PREVIEW_SCHEMA, v: ARTIFACT_PREVIEW_VERSION, identity: { path: relPath, contentHash, sizeBytes: stat.size, }, policy: DEFAULT_PREVIEW_POLICY, renderStatus: "ok", sanitizedLines, totalLines, truncated: totalLines > MAX_PREVIEW_LINES, blocked, hasBlockedContent: blocked.length > 0, }; } // --- formatting ------------------------------------------------------------- // Format a preview result as a compact, color-independent summary for the // TUI. Shows artifact identity, policy, render status, blocked content, // and safe actions. export function formatArtifactPreview(result: ArtifactPreviewResult): string { if ("reason" in result) { const lines = [ "Artifact Preview — REFUSED", "─".repeat(40), `Reason: ${result.reason}`, `Detail: ${result.detail}`, ]; return lines.join("\n"); } const lines: string[] = []; lines.push("Artifact Preview"); lines.push("─".repeat(40)); lines.push(`Path: ${result.identity.path}`); lines.push(`Hash: ${result.identity.contentHash.slice(0, 16)}…`); lines.push(`Size: ${result.identity.sizeBytes} bytes`); lines.push(`Status: ${result.renderStatus}`); lines.push(`Lines: ${result.sanitizedLines.length} / ${result.totalLines}${result.truncated ? " (truncated)" : ""}`); lines.push(""); lines.push("Policy:"); lines.push(` Scripts: ${result.policy.scripts}`); lines.push(` Network: ${result.policy.network}`); lines.push(` Navigation: ${result.policy.navigation}`); lines.push(` Filesystem: ${result.policy.filesystem}`); lines.push(` Forms: ${result.policy.forms}`); if (result.blocked.length > 0) { lines.push(""); lines.push(`Blocked content (${result.blocked.length}):`); for (const b of result.blocked) { lines.push(` ✗ L${b.line} [${b.reason}] ${b.preview}`); } } else { lines.push(""); lines.push("Blocked content: none"); } lines.push(""); lines.push("Actions: open (safe) · export sanitized"); return lines.join("\n"); } # ===== file: src/artifact-retention.ts ===== // Artifact retention: defines retention and cleanup rules for completed // Goal execution artifacts. // // RetentionPolicy defines max age (days) and max count. ArtifactInventory // tracks artifact type, creation time, and size. evaluateRetention determines // cleanup eligibility. Read-only evaluation (does not delete anything). // Deterministic. export const ARTIFACT_RETENTION_SCHEMA = "oh-my-cli.artifact-retention"; export const ARTIFACT_RETENTION_VERSION = 1; // --- types ------------------------------------------------------------------ export type ArtifactType = | "audit-event" | "cancelled-attempt" | "completion-summary" | "failure-summary" | "execution-outline" | "answer-route"; export interface ArtifactRecord { /** Artifact identifier. */ id: string; type: ArtifactType; /** When the artifact was created (epoch ms). */ createdAt: number; /** Size in bytes (approximate). */ sizeBytes: number; /** Goal revision this artifact belongs to. */ goalRevision: number; } export interface RetentionPolicy { /** Maximum age in days. Artifacts older than this are eligible for cleanup. */ maxAgeDays: number; /** Maximum count per Goal revision. Excess artifacts are eligible for cleanup. */ maxCountPerRevision: number; } export interface RetentionEvaluation { /** Artifacts that should be retained. */ retained: ArtifactRecord[]; /** Artifacts eligible for cleanup. */ eligibleForCleanup: ArtifactRecord[]; /** Reason for each cleanup eligibility. */ cleanupReasons: Map<string, string>; /** Total size of retained artifacts. */ retainedSizeBytes: number; /** Total size of cleanup-eligible artifacts. */ cleanupSizeBytes: number; } // --- default policy --------------------------------------------------------- export const DEFAULT_RETENTION_POLICY: RetentionPolicy = { maxAgeDays: 7, maxCountPerRevision: 50, }; // --- retention evaluation --------------------------------------------------- const MS_PER_DAY = 86_400_000; // Evaluate retention for a set of artifacts. export function evaluateRetention( artifacts: ArtifactRecord[], policy: RetentionPolicy = DEFAULT_RETENTION_POLICY, now: number = Date.now(), ): RetentionEvaluation { const retained: ArtifactRecord[] = []; const eligibleForCleanup: ArtifactRecord[] = []; const cleanupReasons = new Map<string, string>(); const maxAgeMs = policy.maxAgeDays * MS_PER_DAY; // Group by revision for count-based evaluation. const byRevision = new Map<number, ArtifactRecord[]>(); for (const artifact of artifacts) { const group = byRevision.get(artifact.goalRevision) ?? []; group.push(artifact); byRevision.set(artifact.goalRevision, group); } // Count-based ranking: sort each revision group once (newest first) and // record each artifact's rank. This replaces the previous per-artifact // re-sort + linear indexOf scan with one sort per revision plus an O(1) rank // lookup, turning count evaluation from O(n² log n) into O(n log n) (#852). // Behavior is unchanged: same stable newest-first ordering and ranks. const indexByArtifact = new Map<ArtifactRecord, number>(); for (const group of byRevision.values()) { const sorted = [...group].sort((a, b) => b.createdAt - a.createdAt); sorted.forEach((artifact, index) => indexByArtifact.set(artifact, index)); } for (const artifact of artifacts) { const ageMs = now - artifact.createdAt; const isTooOld = ageMs > maxAgeMs; const indexInRevision = indexByArtifact.get(artifact)!; const isExcess = indexInRevision >= policy.maxCountPerRevision; if (isTooOld) { eligibleForCleanup.push(artifact); cleanupReasons.set(artifact.id, `Age ${Math.floor(ageMs / MS_PER_DAY)}d exceeds max ${policy.maxAgeDays}d`); } else if (isExcess) { eligibleForCleanup.push(artifact); cleanupReasons.set(artifact.id, `Count ${indexInRevision + 1} exceeds max ${policy.maxCountPerRevision} per revision`); } else { retained.push(artifact); } } const retainedSizeBytes = retained.reduce((sum, a) => sum + a.sizeBytes, 0); const cleanupSizeBytes = eligibleForCleanup.reduce((sum, a) => sum + a.sizeBytes, 0); return { retained, eligibleForCleanup, cleanupReasons, retainedSizeBytes, cleanupSizeBytes, }; } // --- formatting ------------------------------------------------------------- export function formatRetentionReport(evaluation: RetentionEvaluation): string { const lines: string[] = []; lines.push("Artifact Retention Report"); lines.push("═".repeat(50)); lines.push(`Retained: ${evaluation.retained.length} (${formatBytes(evaluation.retainedSizeBytes)})`); lines.push(`Eligible for cleanup: ${evaluation.eligibleForCleanup.length} (${formatBytes(evaluation.cleanupSizeBytes)})`); if (evaluation.eligibleForCleanup.length > 0) { lines.push(""); lines.push("Eligible for cleanup:"); for (const artifact of evaluation.eligibleForCleanup.slice(0, 10)) { const reason = evaluation.cleanupReasons.get(artifact.id) ?? "unknown"; lines.push(` · ${artifact.id} [${artifact.type}] — ${reason}`); } if (evaluation.eligibleForCleanup.length > 10) { lines.push(` … ${evaluation.eligibleForCleanup.length - 10} more`); } } lines.push(""); lines.push("Read-only: no artifacts deleted."); return lines.join("\n"); } export function formatBytes(bytes: number): string { if (bytes < 1024) return `${bytes}B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`; // Issue #850: scale past MB as well, so multi-gigabyte footprints (session // stores, retention totals) render as GB/TB instead of thousands/millions of // MB (a 1 TB store previously printed "1048576.0MB"). if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)}MB`; if (bytes < 1024 * 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`; return `${(bytes / (1024 * 1024 * 1024 * 1024)).toFixed(1)}TB`; } # ===== file: src/ascii-output.ts ===== // ASCII-safe output mode for the read-only report/journal surfaces // (Issue #672), extended to the read-only session surfaces (Issue #674). // // The report/journal family renders with Unicode decoration — box-drawing // separators, middle dots, multiplication signs, em dashes — and the // session surfaces additionally emit semantic marks (status checks, arrows, // ellipses); the health inventory adds warning/disabled status marks // (Issue #696). For screen readers, legacy terminals, C-locale pipelines, and // log scrapers these glyphs are noise or breakage. `--ascii` maps the // glyphs to ASCII equivalents while keeping all content and structure // identical: decorative glyphs map to their nearest ASCII shape; semantic // marks map to readable ASCII that preserves the mark's meaning. // // The transformation is a pure, deterministic per-line substitution applied // only to the known glyphs; user content (note text, goal objectives) is // never rewritten. JSON output is untouched — it is already ASCII-safe data. /** * Glyphs emitted by the in-scope surfaces, mapped to ASCII. Semantic marks * (Issue #674) map to readable ASCII preserving the mark's meaning; * decorative glyphs map to their nearest ASCII shape. */ export const ASCII_GLYPH_MAP: Readonly<Record<string, string>> = { "\u2500": "-", // ─ box-drawing separator "\u00b7": "|", // · middle-dot field separator "\u00d7": "x", // × count multiplier "\u2014": "-", // — em dash "\u2026": "...", // … ellipsis "\u2192": "->", // → arrow "\u2194": "<->", // ↔ bidirectional arrow
# ===== file: src/accessibility-semantics.ts =====
// Read-only accessibility semantics: defines color roles, reduced-color
// fallbacks, and reduced-motion preferences for activity rendering.
//
// Color roles expose semantic name, full-color value, reduced-color
// fallback (symbol/glyph), and contrast ratio. Reduced-motion preferences
// disable animation hints. The model supports screen-reader label
// generation. The view is read-only and never renders actual UI, executes
// commands, or modifies preferences.
export const ACCESSIBILITY_SEMANTICS_SCHEMA = "oh-my-cli.accessibility-semantics";
export const ACCESSIBILITY_SEMANTICS_VERSION = 1;
// --- types ------------------------------------------------------------------
export type ColorRole =
| "status-running"
| "status-success"
| "status-failure"
| "status-waiting"
| "emphasis"
| "warning"
| "error"
| "muted";
export interface ColorDefinition {
role: ColorRole;
/** Semantic meaning description. */
meaning: string;
/** Full-color hex value. */
fullColor: string;
/** Reduced-color fallback glyph/symbol. */
reducedGlyph: string;
/** WCAG contrast ratio against the background (approximate). */
contrastRatio: number;
/** Screen-reader label. */
screenReaderLabel: string;
}
export interface MotionPreference {
/** Whether animations are enabled. */
animationsEnabled: boolean;
/** Static alternative for spinner/progress. */
staticSpinner: string;
/** Static alternative for progress bar. */
staticProgress: string;
}
export interface AccessibilityProfile {
/** Whether reduced-color mode is active. */
reducedColor: boolean;
/** Whether reduced-motion mode is active. */
reducedMotion: boolean;
/** Color definitions. */
colors: ColorDefinition[];
/** Motion preferences. */
motion: MotionPreference;
}
// --- default definitions ----------------------------------------------------
const DEFAULT_COLORS: ColorDefinition[] = [
{ role: "status-running", meaning: "Active/running process", fullColor: "#3B82F6", reducedGlyph: "▶", contrastRatio: 4.5, screenReaderLabel: "Running" },
{ role: "status-success", meaning: "Successful completion", fullColor: "#22C55E", reducedGlyph: "✓", contrastRatio: 4.6, screenReaderLabel: "Succeeded" },
{ role: "status-failure", meaning: "Failed operation", fullColor: "#EF4444", reducedGlyph: "✗", contrastRatio: 4.5, screenReaderLabel: "Failed" },
{ role: "status-waiting", meaning: "Waiting for input or dependency", fullColor: "#F59E0B", reducedGlyph: "○", contrastRatio: 4.5, screenReaderLabel: "Waiting" },
{ role: "emphasis", meaning: "Emphasized content", fullColor: "#8B5CF6", reducedGlyph: "★", contrastRatio: 4.6, screenReaderLabel: "Emphasis" },
{ role: "warning", meaning: "Warning condition", fullColor: "#F97316", reducedGlyph: "⚠", contrastRatio: 4.5, screenReaderLabel: "Warning" },
{ role: "error", meaning: "Error condition", fullColor: "#DC2626", reducedGlyph: "⛔", contrastRatio: 5.0, screenReaderLabel: "Error" },
{ role: "muted", meaning: "De-emphasized content", fullColor: "#6B7280", reducedGlyph: "·", contrastRatio: 4.5, screenReaderLabel: "Muted" },
];
const DEFAULT_MOTION: MotionPreference = {
animationsEnabled: true,
staticSpinner: "[working]",
staticProgress: "[=====> ]",
};
const REDUCED_MOTION: MotionPreference = {
animationsEnabled: false,
staticSpinner: "[working]",
staticProgress: "[=====> ]",
};
// --- profile builder --------------------------------------------------------
export function buildAccessibilityProfile(opts: {
reducedColor?: boolean;
reducedMotion?: boolean;
} = {}): AccessibilityProfile {
return {
reducedColor: opts.reducedColor ?? false,
reducedMotion: opts.reducedMotion ?? false,
colors: DEFAULT_COLORS,
motion: opts.reducedMotion ? REDUCED_MOTION : DEFAULT_MOTION,
};
}
// --- rendering helpers (pure, no actual UI) ---------------------------------